Skip to main content

gpui/
window.rs

1#[cfg(any(feature = "inspector", debug_assertions))]
2use crate::Inspector;
3use crate::{
4    Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
5    AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
6    Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
7    DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
8    EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
9    Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,
10    KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,
11    MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
12    PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
13    Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,
14    RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
15    SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
16    StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,
17    SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextRenderingMode, TextStyle,
18    TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
19    WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
20    WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, profiler, px, rems, size,
21    transparent_black,
22};
23
24use anyhow::{Context as _, Result, anyhow};
25use collections::{FxHashMap, FxHashSet};
26#[cfg(target_os = "macos")]
27use core_video::pixel_buffer::CVPixelBuffer;
28use derive_more::{Deref, DerefMut};
29use futures::FutureExt;
30use futures::channel::oneshot;
31use gpui_util::post_inc;
32use gpui_util::{ResultExt, measure};
33#[cfg(feature = "input-latency-histogram")]
34use hdrhistogram::Histogram;
35use itertools::FoldWhile::{Continue, Done};
36use itertools::Itertools;
37use parking_lot::RwLock;
38use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
39use refineable::Refineable;
40use scheduler::Instant;
41use slotmap::SlotMap;
42use smallvec::SmallVec;
43use std::{
44    any::{Any, TypeId},
45    borrow::Cow,
46    cell::{Cell, RefCell},
47    cmp,
48    fmt::{Debug, Display},
49    hash::{Hash, Hasher},
50    marker::PhantomData,
51    mem,
52    ops::{DerefMut, Range},
53    rc::Rc,
54    sync::{
55        Arc, Weak,
56        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
57    },
58    time::Duration,
59};
60use uuid::Uuid;
61
62pub(crate) mod a11y;
63mod prompts;
64
65pub use a11y::A11ySubtreeBuilder;
66
67use self::a11y::A11y;
68#[cfg(not(target_family = "wasm"))]
69use self::a11y::ROOT_NODE_ID;
70use crate::util::{
71    atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
72    round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
73};
74pub use prompts::*;
75
76/// Default window size used when no explicit size is provided.
77pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
78
79/// A 6:5 aspect ratio minimum window size to be used for functional,
80/// additional-to-main-Zed windows, like the settings and rules library windows.
81pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
82    width: Pixels(900.),
83    height: Pixels(750.),
84};
85
86/// Represents the two different phases when dispatching events.
87#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
88pub enum DispatchPhase {
89    /// After the capture phase comes the bubble phase, in which mouse event listeners are
90    /// invoked front to back and keyboard event listeners are invoked from the focused element
91    /// to the root of the element tree. This is the phase you'll most commonly want to use when
92    /// registering event listeners.
93    #[default]
94    Bubble,
95    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
96    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
97    /// is used for special purposes such as clearing the "pressed" state for click events. If
98    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
99    /// outside of the immediate region may rely on detecting non-local events during this phase.
100    Capture,
101}
102
103impl DispatchPhase {
104    /// Returns true if this represents the "bubble" phase.
105    #[inline]
106    pub fn bubble(self) -> bool {
107        self == DispatchPhase::Bubble
108    }
109
110    /// Returns true if this represents the "capture" phase.
111    #[inline]
112    pub fn capture(self) -> bool {
113        self == DispatchPhase::Capture
114    }
115}
116
117struct WindowInvalidatorInner {
118    pub dirty: bool,
119    pub draw_phase: DrawPhase,
120    pub dirty_views: FxHashSet<EntityId>,
121    pub update_count: usize,
122    pub frame_dirty: FrameDirtyAccumulator,
123}
124
125/// Per-frame invalidation bookkeeping, drained at draw time and emitted to the
126/// frame profiler. Tracks when the current frame first became dirty and how
127/// many invalidations were coalesced into it. Only populated while
128/// `profiler::frame_trace_enabled()` is set.
129#[derive(Default)]
130struct FrameDirtyAccumulator {
131    dirty_at: Option<Instant>,
132    invalidations: u64,
133}
134
135#[derive(Clone)]
136pub(crate) struct WindowInvalidator {
137    inner: Rc<RefCell<WindowInvalidatorInner>>,
138}
139
140impl WindowInvalidator {
141    pub fn new() -> Self {
142        WindowInvalidator {
143            inner: Rc::new(RefCell::new(WindowInvalidatorInner {
144                dirty: true,
145                draw_phase: DrawPhase::None,
146                dirty_views: FxHashSet::default(),
147                update_count: 0,
148                frame_dirty: FrameDirtyAccumulator::default(),
149            })),
150        }
151    }
152
153    pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
154        let mut inner = self.inner.borrow_mut();
155        inner.update_count += 1;
156        inner.dirty_views.insert(entity);
157        if inner.draw_phase == DrawPhase::None {
158            Self::record_frame_dirty(&mut inner);
159            inner.dirty = true;
160            cx.push_effect(Effect::Notify { emitter: entity });
161            true
162        } else {
163            false
164        }
165    }
166
167    pub fn is_dirty(&self) -> bool {
168        self.inner.borrow().dirty
169    }
170
171    pub fn set_dirty(&self, dirty: bool) {
172        let mut inner = self.inner.borrow_mut();
173        inner.dirty = dirty;
174        if dirty {
175            inner.update_count += 1;
176            Self::record_frame_dirty(&mut inner);
177        }
178    }
179
180    pub fn set_phase(&self, phase: DrawPhase) {
181        self.inner.borrow_mut().draw_phase = phase
182    }
183
184    pub fn update_count(&self) -> usize {
185        self.inner.borrow().update_count
186    }
187
188    fn record_frame_dirty(inner: &mut WindowInvalidatorInner) {
189        if profiler::frame_trace_enabled() {
190            inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
191            inner.frame_dirty.invalidations += 1;
192        }
193    }
194
195    fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
196        mem::take(&mut self.inner.borrow_mut().frame_dirty)
197    }
198
199    pub fn take_views(&self) -> FxHashSet<EntityId> {
200        mem::take(&mut self.inner.borrow_mut().dirty_views)
201    }
202
203    pub fn replace_views(&self, views: FxHashSet<EntityId>) {
204        self.inner.borrow_mut().dirty_views = views;
205    }
206
207    pub fn not_drawing(&self) -> bool {
208        self.inner.borrow().draw_phase == DrawPhase::None
209    }
210
211    #[track_caller]
212    pub fn debug_assert_paint(&self) {
213        debug_assert!(
214            matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
215            "this method can only be called during paint"
216        );
217    }
218
219    #[track_caller]
220    pub fn debug_assert_prepaint(&self) {
221        debug_assert!(
222            matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
223            "this method can only be called during request_layout, or prepaint"
224        );
225    }
226
227    #[track_caller]
228    pub fn debug_assert_paint_or_prepaint(&self) {
229        debug_assert!(
230            matches!(
231                self.inner.borrow().draw_phase,
232                DrawPhase::Paint | DrawPhase::Prepaint
233            ),
234            "this method can only be called during request_layout, prepaint, or paint"
235        );
236    }
237}
238
239type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
240
241pub(crate) type AnyWindowFocusListener =
242    Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
243
244pub(crate) struct WindowFocusEvent {
245    pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
246    pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
247}
248
249impl WindowFocusEvent {
250    pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
251        !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
252    }
253
254    pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
255        self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
256    }
257}
258
259/// This is provided when subscribing for `Context::on_focus_out` events.
260pub struct FocusOutEvent {
261    /// A weak focus handle representing what was blurred.
262    pub blurred: WeakFocusHandle,
263}
264
265slotmap::new_key_type! {
266    /// A globally unique identifier for a focusable element.
267    pub struct FocusId;
268}
269
270thread_local! {
271    /// Fallback arena used when no app-specific arena is active.
272    /// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena.
273    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
274
275    /// Points to the current App's element arena during draw operations.
276    /// This allows multiple test Apps to have isolated arenas, preventing
277    /// cross-session corruption when the scheduler interleaves their tasks.
278    static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
279}
280
281/// Whether a window draw is currently in progress on this thread.
282///
283/// This holds exactly while an `ElementArenaScope` is active: nested scopes
284/// restore the previous (still set) arena pointer, so `CURRENT_ELEMENT_ARENA`
285/// is `Some` from the outermost draw's start to its end.
286///
287/// The `on_request_frame` callback uses this to defer draw requests that
288/// arrive re-entrantly while a draw is already on the stack (e.g. via nested
289/// message pumping in the Windows window procedure), instead of running a
290/// nested draw or panicking on the already-borrowed App.
291fn draw_in_progress() -> bool {
292    CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
293}
294
295/// Allocates an element in the current arena. Uses the app-specific arena if one
296/// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA.
297pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
298    CURRENT_ELEMENT_ARENA.with(|current| {
299        if let Some(arena_ptr) = current.get() {
300            // SAFETY: The pointer is valid for the duration of the draw operation
301            // that set it, and we're being called during that same draw.
302            let arena_cell = unsafe { &*arena_ptr };
303            f(&mut arena_cell.borrow_mut())
304        } else {
305            ELEMENT_ARENA.with_borrow_mut(f)
306        }
307    })
308}
309
310/// Scope guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw
311/// operation and tracks the arena's scope depth, so that a nested draw's
312/// `ArenaClearNeeded::clear` is deferred rather than freeing memory the outer
313/// draw still references (see `Arena::clear`).
314///
315/// Call [`ElementArenaScope::exit`] with the same arena that was entered to
316/// obtain the [`ArenaClearNeeded`] token the draw now owes; requiring `exit`
317/// makes it impossible to request a clear before the scope has ended. The
318/// scope's teardown — restoring the thread-local and balancing `begin_scope`
319/// with `end_scope` — happens in `Drop`, so the arena's scope depth stays
320/// balanced on every path, including when a panic unwinds a draw before `exit`
321/// is reached. (If teardown lived only in `exit`, such a panic would leave the
322/// scope depth permanently elevated and defer every future clear, leaking
323/// memory unboundedly.)
324pub(crate) struct ElementArenaScope {
325    /// The entered arena: compared against the argument in `exit`, and
326    /// dereferenced in `Drop` to end its scope (see the SAFETY note there).
327    entered: *const RefCell<Arena>,
328    previous: Option<*const RefCell<Arena>>,
329    exited: bool,
330}
331
332impl ElementArenaScope {
333    /// Enter a scope where element allocations use the given arena.
334    pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
335        arena.borrow_mut().begin_scope();
336        let previous = CURRENT_ELEMENT_ARENA.with(|current| {
337            let prev = current.get();
338            current.set(Some(arena as *const RefCell<Arena>));
339            prev
340        });
341        Self {
342            entered: arena as *const RefCell<Arena>,
343            previous,
344            exited: false,
345        }
346    }
347
348    /// End the scope: restores the previously-current arena and ends the
349    /// arena's clear-deferral scope. Returns the token for the arena clear the
350    /// draw now owes; producing it here makes it impossible to request a clear
351    /// before the scope has ended (which would be silently deferred forever).
352    ///
353    /// Panics if passed a different arena than was entered: ending the scope
354    /// of the wrong arena would unbalance two arenas' scope depths, allowing
355    /// one of them to clear while a draw still references its memory.
356    pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
357        assert!(
358            std::ptr::eq(self.entered, arena),
359            "ElementArenaScope::exit called with a different arena than was entered"
360        );
361        self.exited = true;
362        // Teardown (restoring the thread-local and ending the arena's
363        // clear-deferral scope) runs in `Drop`, which fires both here — `self`
364        // is dropped as `exit` returns, before the token reaches the caller —
365        // and when a panic unwinds the draw before `exit` is reached.
366        ArenaClearNeeded::new(arena)
367    }
368}
369
370impl Drop for ElementArenaScope {
371    fn drop(&mut self) {
372        // Teardown lives here (rather than in `exit`) so it runs exactly once on
373        // every path: `exit` consumes and drops the guard on the normal path,
374        // and unwinding drops it on the panic path. Balancing `begin_scope` here
375        // keeps the arena's scope depth correct even when a draw panics; if this
376        // only happened in `exit`, a panic between `enter` and `exit` would leave
377        // the depth elevated and defer every future clear.
378        CURRENT_ELEMENT_ARENA.with(|current| {
379            current.set(self.previous);
380        });
381        // SAFETY: `entered` came from a `&RefCell<Arena>` in `enter`, and the
382        // arena (owned by the `App` being drawn) outlives this guard on both the
383        // normal and unwinding paths, since the guard is a local of the draw.
384        unsafe { &*self.entered }.borrow_mut().end_scope();
385        if !self.exited && !std::thread::panicking() {
386            debug_assert!(false, "ElementArenaScope dropped without calling exit()");
387            log::error!(
388                "ElementArenaScope dropped without calling exit(); \
389                 the arena clear for this draw was never requested"
390            );
391        }
392    }
393}
394
395/// Returned when the element arena has been used and so must be cleared before the next draw.
396#[must_use]
397pub struct ArenaClearNeeded {
398    /// Identity of the arena that was drawn into. Only ever compared against
399    /// another pointer in `clear`; never dereferenced.
400    arena: *const RefCell<Arena>,
401}
402
403impl ArenaClearNeeded {
404    /// Create a new ArenaClearNeeded token for the App whose arena was drawn
405    /// into. Private: the only way to obtain one is [`ElementArenaScope::exit`].
406    fn new(arena: &RefCell<Arena>) -> Self {
407        Self {
408            arena: arena as *const RefCell<Arena>,
409        }
410    }
411
412    /// Clear the element arena of the App the draw ran against. If an enclosing
413    /// draw is still in progress (this draw was nested inside it), the clear is
414    /// deferred to the enclosing draw's own `ArenaClearNeeded` so that its live
415    /// allocations aren't freed.
416    ///
417    /// Panics if passed a different App than the draw ran against, since
418    /// clearing another App's arena could free memory its draws still
419    /// reference.
420    pub fn clear(self, cx: &mut App) {
421        assert!(
422            std::ptr::eq(self.arena, &cx.element_arena),
423            "ArenaClearNeeded::clear called with a different App than the draw ran against"
424        );
425        cx.element_arena.borrow_mut().clear();
426    }
427}
428
429pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
430pub(crate) struct FocusRef {
431    pub(crate) ref_count: AtomicUsize,
432    pub(crate) tab_index: isize,
433    pub(crate) tab_stop: bool,
434}
435
436impl FocusId {
437    /// Obtains whether the element associated with this handle is currently focused.
438    pub fn is_focused(&self, window: &Window) -> bool {
439        window.focus == Some(*self)
440    }
441
442    /// Obtains whether the element associated with this handle contains the focused
443    /// element or is itself focused.
444    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
445        window
446            .focused(cx)
447            .is_some_and(|focused| self.contains(focused.id, window))
448    }
449
450    /// Obtains whether the element associated with this handle is contained within the
451    /// focused element or is itself focused.
452    pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
453        let focused = window.focused(cx);
454        focused.is_some_and(|focused| focused.id.contains(*self, window))
455    }
456
457    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
458    pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
459        window
460            .rendered_frame
461            .dispatch_tree
462            .focus_contains(*self, other)
463    }
464}
465
466/// A handle which can be used to track and manipulate the focused element in a window.
467pub struct FocusHandle {
468    pub(crate) id: FocusId,
469    handles: Arc<FocusMap>,
470    /// The index of this element in the tab order.
471    pub tab_index: isize,
472    /// Whether this element can be focused by tab navigation.
473    pub tab_stop: bool,
474}
475
476impl std::fmt::Debug for FocusHandle {
477    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
479    }
480}
481
482impl FocusHandle {
483    pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
484        let id = handles.write().insert(FocusRef {
485            ref_count: AtomicUsize::new(1),
486            tab_index: 0,
487            tab_stop: false,
488        });
489
490        Self {
491            id,
492            tab_index: 0,
493            tab_stop: false,
494            handles: handles.clone(),
495        }
496    }
497
498    pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
499        let lock = handles.read();
500        let focus = lock.get(id)?;
501        if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
502            return None;
503        }
504        Some(Self {
505            id,
506            tab_index: focus.tab_index,
507            tab_stop: focus.tab_stop,
508            handles: handles.clone(),
509        })
510    }
511
512    /// Sets the tab index of the element associated with this handle.
513    pub fn tab_index(mut self, index: isize) -> Self {
514        self.tab_index = index;
515        if let Some(focus) = self.handles.write().get_mut(self.id) {
516            focus.tab_index = index;
517        }
518        self
519    }
520
521    /// Sets whether the element associated with this handle is a tab stop.
522    ///
523    /// When `false`, the element will not be included in the tab order.
524    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
525        self.tab_stop = tab_stop;
526        if let Some(focus) = self.handles.write().get_mut(self.id) {
527            focus.tab_stop = tab_stop;
528        }
529        self
530    }
531
532    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
533    pub fn downgrade(&self) -> WeakFocusHandle {
534        WeakFocusHandle {
535            id: self.id,
536            handles: Arc::downgrade(&self.handles),
537        }
538    }
539
540    /// Moves the focus to the element associated with this handle.
541    pub fn focus(&self, window: &mut Window, cx: &mut App) {
542        window.focus(self, cx)
543    }
544
545    /// Obtains whether the element associated with this handle is currently focused.
546    pub fn is_focused(&self, window: &Window) -> bool {
547        self.id.is_focused(window)
548    }
549
550    /// Obtains whether the element associated with this handle contains the focused
551    /// element or is itself focused.
552    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
553        self.id.contains_focused(window, cx)
554    }
555
556    /// Obtains whether the element associated with this handle is contained within the
557    /// focused element or is itself focused.
558    pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
559        self.id.within_focused(window, cx)
560    }
561
562    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
563    pub fn contains(&self, other: &Self, window: &Window) -> bool {
564        self.id.contains(other.id, window)
565    }
566
567    /// Dispatch an action on the element that rendered this focus handle
568    pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
569        if let Some(node_id) = window
570            .rendered_frame
571            .dispatch_tree
572            .focusable_node_id(self.id)
573        {
574            window.dispatch_action_on_node(node_id, action, cx)
575        }
576    }
577}
578
579impl Clone for FocusHandle {
580    fn clone(&self) -> Self {
581        Self::for_id(self.id, &self.handles).unwrap()
582    }
583}
584
585impl PartialEq for FocusHandle {
586    fn eq(&self, other: &Self) -> bool {
587        self.id == other.id
588    }
589}
590
591impl Eq for FocusHandle {}
592
593impl Drop for FocusHandle {
594    fn drop(&mut self) {
595        self.handles
596            .read()
597            .get(self.id)
598            .unwrap()
599            .ref_count
600            .fetch_sub(1, SeqCst);
601    }
602}
603
604/// A weak reference to a focus handle.
605#[derive(Clone, Debug)]
606pub struct WeakFocusHandle {
607    pub(crate) id: FocusId,
608    pub(crate) handles: Weak<FocusMap>,
609}
610
611impl WeakFocusHandle {
612    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
613    pub fn upgrade(&self) -> Option<FocusHandle> {
614        let handles = self.handles.upgrade()?;
615        FocusHandle::for_id(self.id, &handles)
616    }
617}
618
619impl PartialEq for WeakFocusHandle {
620    fn eq(&self, other: &WeakFocusHandle) -> bool {
621        self.id == other.id
622    }
623}
624
625impl Eq for WeakFocusHandle {}
626
627impl PartialEq<FocusHandle> for WeakFocusHandle {
628    fn eq(&self, other: &FocusHandle) -> bool {
629        self.id == other.id
630    }
631}
632
633impl PartialEq<WeakFocusHandle> for FocusHandle {
634    fn eq(&self, other: &WeakFocusHandle) -> bool {
635        self.id == other.id
636    }
637}
638
639/// Focusable allows users of your view to easily
640/// focus it (using window.focus_view(cx, view))
641pub trait Focusable: 'static {
642    /// Returns the focus handle associated with this view.
643    fn focus_handle(&self, cx: &App) -> FocusHandle;
644}
645
646impl<V: Focusable> Focusable for Entity<V> {
647    fn focus_handle(&self, cx: &App) -> FocusHandle {
648        self.read(cx).focus_handle(cx)
649    }
650}
651
652/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
653/// where the lifecycle of the view is handled by another view.
654pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
655
656impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
657
658/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
659pub struct DismissEvent;
660
661type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
662
663pub(crate) type AnyMouseListener =
664    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
665
666#[derive(Clone)]
667pub(crate) struct CursorStyleRequest {
668    pub(crate) hitbox_id: Option<HitboxId>,
669    pub(crate) style: CursorStyle,
670}
671
672#[derive(Default, Eq, PartialEq)]
673pub(crate) struct HitTest {
674    pub(crate) ids: SmallVec<[HitboxId; 8]>,
675    pub(crate) hover_hitbox_count: usize,
676}
677
678/// A type of window control area that corresponds to the platform window.
679#[derive(Clone, Copy, Debug, Eq, PartialEq)]
680pub enum WindowControlArea {
681    /// An area that allows dragging of the platform window.
682    Drag,
683    /// An area that allows closing of the platform window.
684    Close,
685    /// An area that allows maximizing of the platform window.
686    Max,
687    /// An area that allows minimizing of the platform window.
688    Min,
689}
690
691/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
692#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
693pub struct HitboxId(u64);
694
695#[cfg(feature = "test-support")]
696impl HitboxId {
697    /// A placeholder HitboxId exclusively for integration testing API's that
698    /// need a hitbox but where the value of the hitbox does not matter. The
699    /// alternative is to make the Hitbox optional but that complicates the
700    /// implementation.
701    pub const fn placeholder() -> Self {
702        Self(0)
703    }
704}
705
706impl HitboxId {
707    /// Checks if the hitbox with this ID is currently hovered. Returns `false` during keyboard
708    /// input modality so that keyboard navigation suppresses hover highlights. Except when handling
709    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
710    /// events or paint hover styles.
711    ///
712    /// See [`Hitbox::is_hovered`] for details.
713    pub fn is_hovered(self, window: &Window) -> bool {
714        // If this hitbox has captured the pointer, it's always considered hovered
715        if window.captured_hitbox == Some(self) {
716            return true;
717        }
718        if window.last_input_was_keyboard() {
719            return false;
720        }
721        self.hit_test(window)
722    }
723
724    /// Checks if the hitbox with this ID is currently hovered, regardless of the last
725    /// input modality used.
726    ///
727    /// See [`HitboxId::is_hovered`] for more details.
728    pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
729        // If this hitbox has captured the pointer, it's always considered hovered
730        if window.captured_hitbox == Some(self) {
731            return true;
732        }
733        self.hit_test(window)
734    }
735
736    fn hit_test(self, window: &Window) -> bool {
737        let hit_test = &window.mouse_hit_test;
738        for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
739            if self == *id {
740                return true;
741            }
742        }
743        false
744    }
745
746    /// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
747    /// Typically this should only be used when handling `ScrollWheelEvent`, and otherwise
748    /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
749    /// this distinction.
750    pub fn should_handle_scroll(self, window: &Window) -> bool {
751        window.mouse_hit_test.ids.contains(&self)
752    }
753
754    fn next(mut self) -> HitboxId {
755        HitboxId(self.0.wrapping_add(1))
756    }
757}
758
759/// A rectangular region that potentially blocks hitboxes inserted prior.
760/// See [Window::insert_hitbox] for more details.
761#[derive(Clone, Debug, Deref)]
762pub struct Hitbox {
763    /// A unique identifier for the hitbox.
764    pub id: HitboxId,
765    /// The bounds of the hitbox.
766    #[deref]
767    pub bounds: Bounds<Pixels>,
768    /// The content mask when the hitbox was inserted.
769    pub content_mask: ContentMask<Pixels>,
770    /// Flags that specify hitbox behavior.
771    pub behavior: HitboxBehavior,
772}
773
774impl Hitbox {
775    /// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality
776    /// so that keyboard navigation suppresses hover highlights. Except when handling
777    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
778    /// events or paint hover styles.
779    ///
780    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
781    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
782    /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`),
783    /// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]).
784    ///
785    /// Handling of `ScrollWheelEvent` should typically use `should_handle_scroll` instead.
786    /// Concretely, this is due to use-cases like overlays that cause the elements under to be
787    /// non-interactive while still allowing scrolling. More abstractly, this is because
788    /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
789    /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
790    /// container.
791    pub fn is_hovered(&self, window: &Window) -> bool {
792        self.id.is_hovered(window)
793    }
794
795    /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
796    /// should only be used when handling `ScrollWheelEvent`, and otherwise `is_hovered` should be
797    /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
798    ///
799    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
800    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
801    pub fn should_handle_scroll(&self, window: &Window) -> bool {
802        self.id.should_handle_scroll(window)
803    }
804}
805
806/// How the hitbox affects mouse behavior.
807#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
808pub enum HitboxBehavior {
809    /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
810    #[default]
811    Normal,
812
813    /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
814    /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
815    /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
816    /// [`InteractiveElement::occlude`].
817    ///
818    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
819    /// bubble-phase handler for every mouse event type:
820    ///
821    /// ```ignore
822    /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
823    ///     if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
824    ///         cx.stop_propagation();
825    ///     }
826    /// })
827    /// ```
828    ///
829    /// This has effects beyond event handling - any use of hitbox checking, such as hover
830    /// styles and tooltips. These other behaviors are the main point of this mechanism. An
831    /// alternative might be to not affect mouse event handling - but this would allow
832    /// inconsistent UI where clicks and moves interact with elements that are not considered to
833    /// be hovered.
834    BlockMouse,
835
836    /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
837    /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
838    /// interaction except scroll events to be ignored - see the documentation of
839    /// [`Hitbox::is_hovered`] for details. This flag is set by
840    /// [`InteractiveElement::block_mouse_except_scroll`].
841    ///
842    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
843    /// bubble-phase handler for every mouse event type **except** `ScrollWheelEvent`:
844    ///
845    /// ```ignore
846    /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
847    ///     if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
848    ///         cx.stop_propagation();
849    ///     }
850    /// })
851    /// ```
852    ///
853    /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollWheelEvent` is
854    /// handled differently than other mouse events. If also blocking these scroll events is
855    /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
856    ///
857    /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
858    /// hover styles and tooltips. These other behaviors are the main point of this mechanism.
859    /// An alternative might be to not affect mouse event handling - but this would allow
860    /// inconsistent UI where clicks and moves interact with elements that are not considered to
861    /// be hovered.
862    BlockMouseExceptScroll,
863}
864
865/// An identifier for a tooltip.
866#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
867pub struct TooltipId(usize);
868
869impl TooltipId {
870    /// Checks if the tooltip is currently hovered.
871    pub fn is_hovered(&self, window: &Window) -> bool {
872        window
873            .tooltip_bounds
874            .as_ref()
875            .is_some_and(|tooltip_bounds| {
876                tooltip_bounds.id == *self
877                    && tooltip_bounds.bounds.contains(&window.mouse_position())
878            })
879    }
880}
881
882pub(crate) struct TooltipBounds {
883    id: TooltipId,
884    bounds: Bounds<Pixels>,
885}
886
887#[derive(Clone)]
888pub(crate) struct TooltipRequest {
889    id: TooltipId,
890    tooltip: AnyTooltip,
891}
892
893pub(crate) struct DeferredDraw {
894    current_view: EntityId,
895    priority: usize,
896    parent_node: DispatchNodeId,
897    element_id_stack: SmallVec<[ElementId; 32]>,
898    text_style_stack: Vec<TextStyleRefinement>,
899    content_mask: Option<ContentMask<Pixels>>,
900    rem_size: Pixels,
901    element: Option<AnyElement>,
902    absolute_offset: Point<Pixels>,
903    prepaint_range: Range<PrepaintStateIndex>,
904    paint_range: Range<PaintIndex>,
905}
906
907pub(crate) struct Frame {
908    pub(crate) focus: Option<FocusId>,
909    pub(crate) window_active: bool,
910    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
911    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
912    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
913    pub(crate) dispatch_tree: DispatchTree,
914    pub(crate) scene: Scene,
915    pub(crate) hitboxes: Vec<Hitbox>,
916    pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
917    pub(crate) deferred_draws: Vec<DeferredDraw>,
918    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
919    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
920    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
921    #[cfg(any(test, feature = "test-support"))]
922    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
923    #[cfg(any(feature = "inspector", debug_assertions))]
924    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
925    #[cfg(any(feature = "inspector", debug_assertions))]
926    pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
927    pub(crate) tab_stops: TabStopMap,
928}
929
930#[derive(Clone, Default)]
931pub(crate) struct PrepaintStateIndex {
932    hitboxes_index: usize,
933    tooltips_index: usize,
934    deferred_draws_index: usize,
935    dispatch_tree_index: usize,
936    accessed_element_states_index: usize,
937    line_layout_index: LineLayoutIndex,
938}
939
940#[derive(Clone, Default)]
941pub(crate) struct PaintIndex {
942    scene_index: usize,
943    mouse_listeners_index: usize,
944    input_handlers_index: usize,
945    cursor_styles_index: usize,
946    accessed_element_states_index: usize,
947    tab_handle_index: usize,
948    line_layout_index: LineLayoutIndex,
949}
950
951impl Frame {
952    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
953        Frame {
954            focus: None,
955            window_active: false,
956            element_states: FxHashMap::default(),
957            accessed_element_states: Vec::new(),
958            mouse_listeners: Vec::new(),
959            dispatch_tree,
960            scene: Scene::default(),
961            hitboxes: Vec::new(),
962            window_control_hitboxes: Vec::new(),
963            deferred_draws: Vec::new(),
964            input_handlers: Vec::new(),
965            tooltip_requests: Vec::new(),
966            cursor_styles: Vec::new(),
967
968            #[cfg(any(test, feature = "test-support"))]
969            debug_bounds: FxHashMap::default(),
970
971            #[cfg(any(feature = "inspector", debug_assertions))]
972            next_inspector_instance_ids: FxHashMap::default(),
973
974            #[cfg(any(feature = "inspector", debug_assertions))]
975            inspector_hitboxes: FxHashMap::default(),
976            tab_stops: TabStopMap::default(),
977        }
978    }
979
980    pub(crate) fn clear(&mut self) {
981        self.element_states.clear();
982        self.accessed_element_states.clear();
983        self.mouse_listeners.clear();
984        self.dispatch_tree.clear();
985        self.scene.clear();
986        self.input_handlers.clear();
987        self.tooltip_requests.clear();
988        self.cursor_styles.clear();
989        self.hitboxes.clear();
990        self.window_control_hitboxes.clear();
991        self.deferred_draws.clear();
992        self.tab_stops.clear();
993        self.focus = None;
994
995        #[cfg(any(test, feature = "test-support"))]
996        {
997            self.debug_bounds.clear();
998        }
999
1000        #[cfg(any(feature = "inspector", debug_assertions))]
1001        {
1002            self.next_inspector_instance_ids.clear();
1003            self.inspector_hitboxes.clear();
1004        }
1005    }
1006
1007    pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1008        self.cursor_styles
1009            .iter()
1010            .rev()
1011            .fold_while(None, |style, request| match request.hitbox_id {
1012                None => Done(Some(request.style)),
1013                Some(hitbox_id) => Continue(style.or_else(|| {
1014                    hitbox_id
1015                        .is_hovered_ignoring_last_input(window)
1016                        .then_some(request.style)
1017                })),
1018            })
1019            .into_inner()
1020    }
1021
1022    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1023        let mut set_hover_hitbox_count = false;
1024        let mut hit_test = HitTest::default();
1025        for hitbox in self.hitboxes.iter().rev() {
1026            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1027            if bounds.contains(&position) {
1028                hit_test.ids.push(hitbox.id);
1029                if !set_hover_hitbox_count
1030                    && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1031                {
1032                    hit_test.hover_hitbox_count = hit_test.ids.len();
1033                    set_hover_hitbox_count = true;
1034                }
1035                if hitbox.behavior == HitboxBehavior::BlockMouse {
1036                    break;
1037                }
1038            }
1039        }
1040        if !set_hover_hitbox_count {
1041            hit_test.hover_hitbox_count = hit_test.ids.len();
1042        }
1043        hit_test
1044    }
1045
1046    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1047        self.focus
1048            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1049            .unwrap_or_default()
1050    }
1051
1052    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1053        for element_state_key in &self.accessed_element_states {
1054            if let Some((element_state_key, element_state)) =
1055                prev_frame.element_states.remove_entry(element_state_key)
1056            {
1057                self.element_states.insert(element_state_key, element_state);
1058            }
1059        }
1060
1061        self.scene.finish();
1062    }
1063}
1064
1065#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1066enum InputModality {
1067    Mouse,
1068    Keyboard,
1069    Touch,
1070}
1071
1072/// Holds the state for a specific window.
1073pub struct Window {
1074    pub(crate) handle: AnyWindowHandle,
1075    pub(crate) invalidator: WindowInvalidator,
1076    pub(crate) removed: bool,
1077    pub(crate) platform_window: Box<dyn PlatformWindow>,
1078    display_id: Option<DisplayId>,
1079    is_resizable: bool,
1080    is_minimizable: bool,
1081    sprite_atlas: Arc<dyn PlatformAtlas>,
1082    text_system: Arc<WindowTextSystem>,
1083    text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1084    rem_size: Pixels,
1085    /// The stack of override values for the window's rem size.
1086    ///
1087    /// This is used by `with_rem_size` to allow rendering an element tree with
1088    /// a given rem size.
1089    rem_size_override_stack: SmallVec<[Pixels; 8]>,
1090    pub(crate) viewport_size: Size<Pixels>,
1091    layout_engine: Option<TaffyLayoutEngine>,
1092    pub(crate) root: Option<AnyView>,
1093    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
1094    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1095    pub(crate) rendered_entity_stack: Vec<EntityId>,
1096    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1097    pub(crate) element_opacity: f32,
1098    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1099    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1100    pub(crate) image_cache_stack: Vec<AnyImageCache>,
1101    pub(crate) rendered_frame: Frame,
1102    pub(crate) next_frame: Frame,
1103    next_hitbox_id: HitboxId,
1104    pub(crate) next_tooltip_id: TooltipId,
1105    pub(crate) tooltip_bounds: Option<TooltipBounds>,
1106    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1107    pub(crate) dirty_views: FxHashSet<EntityId>,
1108    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1109    pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1110    default_prevented: bool,
1111    mouse_position: Point<Pixels>,
1112    mouse_hit_test: HitTest,
1113    modifiers: Modifiers,
1114    capslock: Capslock,
1115    scale_factor: f32,
1116    pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1117    appearance: WindowAppearance,
1118    pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1119    pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1120    active: Rc<Cell<bool>>,
1121    hovered: Rc<Cell<bool>>,
1122    pub(crate) needs_present: Rc<Cell<bool>>,
1123    /// Tracks recent input event timestamps to determine if input is arriving at a high rate.
1124    /// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
1125    pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1126    #[cfg(feature = "input-latency-histogram")]
1127    input_latency_tracker: InputLatencyTracker,
1128    last_input_modality: InputModality,
1129    pub(crate) refreshing: bool,
1130    pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1131    pub(crate) focus: Option<FocusId>,
1132    focus_enabled: bool,
1133    /// Incremented every time focus moves. Used to invalidate a
1134    /// pending keyboard activation state when focus changes.
1135    pub(crate) focus_generation: u64,
1136    pending_input: Option<PendingInput>,
1137    pending_modifier: ModifierState,
1138    pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1139    prompt: Option<RenderablePromptHandle>,
1140    pub(crate) client_inset: Option<Pixels>,
1141    /// The hitbox that has captured the pointer, if any.
1142    /// While captured, mouse events route to this hitbox regardless of hit testing.
1143    captured_hitbox: Option<HitboxId>,
1144    #[cfg(any(feature = "inspector", debug_assertions))]
1145    inspector: Option<Entity<Inspector>>,
1146    pub(crate) a11y: A11y,
1147}
1148
1149#[derive(Clone, Debug, Default)]
1150struct ModifierState {
1151    modifiers: Modifiers,
1152    saw_other_input: bool,
1153}
1154
1155/// Tracks input event timestamps to determine if input is arriving at a high rate.
1156/// Used for selective VRR (Variable Refresh Rate) optimization.
1157#[derive(Clone, Debug)]
1158pub(crate) struct InputRateTracker {
1159    timestamps: Vec<Instant>,
1160    window: Duration,
1161    inputs_per_second: u32,
1162    sustain_until: Instant,
1163    sustain_duration: Duration,
1164}
1165
1166impl Default for InputRateTracker {
1167    fn default() -> Self {
1168        Self {
1169            timestamps: Vec::new(),
1170            window: Duration::from_millis(100),
1171            inputs_per_second: 60,
1172            sustain_until: Instant::now(),
1173            sustain_duration: Duration::from_secs(1),
1174        }
1175    }
1176}
1177
1178impl InputRateTracker {
1179    pub fn record_input(&mut self) {
1180        let now = Instant::now();
1181        self.timestamps.push(now);
1182        self.prune_old_timestamps(now);
1183
1184        let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1185        if self.timestamps.len() as u128 >= min_events {
1186            self.sustain_until = now + self.sustain_duration;
1187        }
1188    }
1189
1190    pub fn is_high_rate(&self) -> bool {
1191        Instant::now() < self.sustain_until
1192    }
1193
1194    fn prune_old_timestamps(&mut self, now: Instant) {
1195        self.timestamps
1196            .retain(|&t| now.duration_since(t) <= self.window);
1197    }
1198}
1199
1200/// A point-in-time snapshot of the input-latency histograms for a window,
1201/// suitable for external formatting.
1202#[cfg(feature = "input-latency-histogram")]
1203#[derive(Clone)]
1204pub struct InputLatencySnapshot {
1205    /// Histogram of input-to-frame latency samples, in nanoseconds.
1206    pub latency_histogram: Histogram<u64>,
1207    /// Histogram of input events coalesced per rendered frame.
1208    pub events_per_frame_histogram: Histogram<u64>,
1209    /// Count of input events that arrived mid-draw and were excluded from
1210    /// latency recording.
1211    pub mid_draw_events_dropped: u64,
1212}
1213
1214/// Records the time between when the first input event in a frame is dispatched
1215/// and when the resulting frame is presented, capturing worst-case latency when
1216/// multiple events are coalesced into a single frame.
1217#[cfg(feature = "input-latency-histogram")]
1218struct InputLatencyTracker {
1219    /// Timestamp of the first unrendered input event in the current frame;
1220    /// cleared when a frame is presented.
1221    first_input_at: Option<Instant>,
1222    /// Count of input events received since the last frame was presented.
1223    pending_input_count: u64,
1224    /// Histogram of input-to-frame latency samples, in nanoseconds.
1225    latency_histogram: Histogram<u64>,
1226    /// Histogram of input events coalesced per rendered frame.
1227    events_per_frame_histogram: Histogram<u64>,
1228    /// Count of input events that arrived mid-draw and were excluded from
1229    /// latency recording because their effects won't appear until the next frame.
1230    mid_draw_events_dropped: u64,
1231}
1232
1233#[cfg(feature = "input-latency-histogram")]
1234impl InputLatencyTracker {
1235    fn new() -> Result<Self> {
1236        Ok(Self {
1237            first_input_at: None,
1238            pending_input_count: 0,
1239            latency_histogram: Histogram::new(3)
1240                .map_err(|e| anyhow!("Failed to create input latency histogram: {e}"))?,
1241            events_per_frame_histogram: Histogram::new(3)
1242                .map_err(|e| anyhow!("Failed to create events per frame histogram: {e}"))?,
1243            mid_draw_events_dropped: 0,
1244        })
1245    }
1246
1247    /// Record that an input event was dispatched at the given time.
1248    /// Only the first event's timestamp per frame is retained (worst-case latency).
1249    fn record_input(&mut self, dispatch_time: Instant) {
1250        self.first_input_at.get_or_insert(dispatch_time);
1251        self.pending_input_count += 1;
1252    }
1253
1254    /// Record that an input event arrived during a draw phase and was excluded
1255    /// from latency tracking.
1256    fn record_mid_draw_input(&mut self) {
1257        self.mid_draw_events_dropped += 1;
1258    }
1259
1260    /// Record that a frame was presented, flushing pending latency and coalescing samples.
1261    fn record_frame_presented(&mut self) {
1262        if let Some(first_input_at) = self.first_input_at.take() {
1263            let latency_nanos = first_input_at.elapsed().as_nanos() as u64;
1264            self.latency_histogram.record(latency_nanos).ok();
1265        }
1266        if self.pending_input_count > 0 {
1267            self.events_per_frame_histogram
1268                .record(self.pending_input_count)
1269                .ok();
1270            self.pending_input_count = 0;
1271        }
1272    }
1273
1274    fn snapshot(&self) -> InputLatencySnapshot {
1275        InputLatencySnapshot {
1276            latency_histogram: self.latency_histogram.clone(),
1277            events_per_frame_histogram: self.events_per_frame_histogram.clone(),
1278            mid_draw_events_dropped: self.mid_draw_events_dropped,
1279        }
1280    }
1281}
1282
1283#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1284pub(crate) enum DrawPhase {
1285    None,
1286    Prepaint,
1287    Paint,
1288    Focus,
1289}
1290
1291#[derive(Default, Debug)]
1292struct PendingInput {
1293    keystrokes: SmallVec<[Keystroke; 1]>,
1294    focus: Option<FocusId>,
1295    timer: Option<Task<()>>,
1296    needs_timeout: bool,
1297    generation: Rc<()>,
1298}
1299
1300pub(crate) struct ElementStateBox {
1301    pub(crate) inner: Box<dyn Any>,
1302    #[cfg(debug_assertions)]
1303    pub(crate) type_name: &'static str,
1304}
1305
1306fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1307    // TODO, BUG: if you open a window with the currently active window
1308    // on the stack, this will erroneously fallback to `None`
1309    //
1310    // TODO these should be the initial window bounds not considering maximized/fullscreen
1311    let active_window_bounds = cx
1312        .active_window()
1313        .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1314
1315    const CASCADE_OFFSET: f32 = 25.0;
1316
1317    let display = display_id
1318        .map(|id| cx.find_display(id))
1319        .unwrap_or_else(|| cx.primary_display());
1320
1321    let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1322
1323    // Use visible_bounds to exclude taskbar/dock areas
1324    let display_bounds = display
1325        .as_ref()
1326        .map(|d| d.visible_bounds())
1327        .unwrap_or_else(default_placement);
1328
1329    let (
1330        Bounds {
1331            origin: base_origin,
1332            size: base_size,
1333        },
1334        window_bounds_ctor,
1335    ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1336        Some(bounds) => match bounds {
1337            WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1338            WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1339            WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1340        },
1341        None => (
1342            display
1343                .as_ref()
1344                .map(|d| d.default_bounds())
1345                .unwrap_or_else(default_placement),
1346            WindowBounds::Windowed,
1347        ),
1348    };
1349
1350    let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1351    let proposed_origin = base_origin + cascade_offset;
1352    let proposed_bounds = Bounds::new(proposed_origin, base_size);
1353
1354    let display_right = display_bounds.origin.x + display_bounds.size.width;
1355    let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1356    let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1357    let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1358
1359    let fits_horizontally = window_right <= display_right;
1360    let fits_vertically = window_bottom <= display_bottom;
1361
1362    let final_origin = match (fits_horizontally, fits_vertically) {
1363        (true, true) => proposed_origin,
1364        (false, true) => point(display_bounds.origin.x, base_origin.y),
1365        (true, false) => point(base_origin.x, display_bounds.origin.y),
1366        (false, false) => display_bounds.origin,
1367    };
1368    window_bounds_ctor(Bounds::new(final_origin, base_size))
1369}
1370
1371impl Window {
1372    pub(crate) fn new(
1373        handle: AnyWindowHandle,
1374        options: WindowOptions,
1375        cx: &mut App,
1376    ) -> Result<Self> {
1377        let WindowOptions {
1378            window_bounds,
1379            titlebar,
1380            focus,
1381            show,
1382            kind,
1383            is_movable,
1384            app_owns_titlebar_drag,
1385            is_resizable,
1386            is_minimizable,
1387            display_id,
1388            window_background,
1389            app_id,
1390            window_min_size,
1391            window_decorations,
1392            #[cfg_attr(
1393                not(any(target_os = "linux", target_os = "freebsd")),
1394                allow(unused_variables)
1395            )]
1396            icon,
1397            #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1398            tabbing_identifier,
1399        } = options;
1400
1401        let initial_window_title = titlebar
1402            .as_ref()
1403            .and_then(|titlebar| titlebar.title.clone());
1404
1405        let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1406        let mut platform_window = cx.platform.open_window(
1407            handle,
1408            WindowParams {
1409                bounds: window_bounds.get_bounds(),
1410                titlebar,
1411                kind,
1412                is_movable,
1413                app_owns_titlebar_drag,
1414                is_resizable,
1415                is_minimizable,
1416                focus,
1417                show,
1418                display_id,
1419                window_min_size,
1420                app_id: app_id.clone(),
1421                icon,
1422                #[cfg(target_os = "macos")]
1423                tabbing_identifier,
1424            },
1425        )?;
1426
1427        let tab_bar_visible = platform_window.tab_bar_visible();
1428        SystemWindowTabController::init_visible(cx, tab_bar_visible);
1429        if let Some(tabs) = platform_window.tabbed_windows() {
1430            SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1431        }
1432
1433        let display_id = platform_window.display().map(|display| display.id());
1434        let sprite_atlas = platform_window.sprite_atlas();
1435        let mouse_position = platform_window.mouse_position();
1436        let modifiers = platform_window.modifiers();
1437        let capslock = platform_window.capslock();
1438        let content_size = platform_window.content_size();
1439        let scale_factor = platform_window.scale_factor();
1440        let appearance = platform_window.appearance();
1441        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1442        let invalidator = WindowInvalidator::new();
1443        let active = Rc::new(Cell::new(platform_window.is_active()));
1444        let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1445        let needs_present = Rc::new(Cell::new(false));
1446        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1447        let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1448        let last_frame_time = Rc::new(Cell::new(None));
1449
1450        platform_window
1451            .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1452        platform_window.set_background_appearance(window_background);
1453
1454        match window_bounds {
1455            WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1456            WindowBounds::Maximized(_) => platform_window.zoom(),
1457            WindowBounds::Windowed(_) => {}
1458        }
1459
1460        let accessibility_force_disabled = cx.accessibility_force_disabled;
1461        let a11y_active_flag = Arc::new(AtomicBool::new(false));
1462
1463        #[cfg(not(target_family = "wasm"))]
1464        if !accessibility_force_disabled {
1465            let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1466            if let Some(title) = &initial_window_title {
1467                initial_root_node.set_label(title.to_string());
1468            }
1469            let initial_tree = accesskit::TreeUpdate {
1470                nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1471                tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1472                tree_id: accesskit::TreeId::ROOT,
1473                focus: ROOT_NODE_ID,
1474            };
1475            let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1476            let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1477            let (action_sender, action_receiver) =
1478                async_channel::unbounded::<accesskit::ActionRequest>();
1479
1480            platform_window.a11y_init(crate::A11yCallbacks {
1481                activation: {
1482                    let active_flag = a11y_active_flag.clone();
1483                    Box::new(move || {
1484                        log::info!("Accessibility activated");
1485                        active_flag.store(true, SeqCst);
1486                        activation_sender.send_blocking(()).log_err();
1487                        Some(initial_tree.clone())
1488                    })
1489                },
1490                action: Box::new(move |request| {
1491                    action_sender.send_blocking(request).log_err();
1492                }),
1493                deactivation: {
1494                    let active_flag = a11y_active_flag.clone();
1495                    Box::new(move || {
1496                        log::info!("Accessibility deactivated");
1497                        active_flag.store(false, SeqCst);
1498                        deactivation_sender.send_blocking(()).log_err();
1499                    })
1500                },
1501            });
1502
1503            // A11y can be activated at any time, and so we cannot compute a
1504            // correct `TreeUpdate` on-demand. When this happens, we return a
1505            // default empty `TreeUpdate`.
1506            //
1507            // So we force a new frame, which will then send a correct `TreeUpdate`.
1508            let mut async_cx = cx.to_async();
1509            cx.foreground_executor()
1510                .spawn(async move {
1511                    while activation_receiver.recv().await.is_ok() {
1512                        handle
1513                            .update(&mut async_cx, |_, window, _| window.refresh())
1514                            .log_err();
1515                    }
1516                })
1517                .detach();
1518
1519            let mut async_cx = cx.to_async();
1520            cx.foreground_executor()
1521                .spawn(async move {
1522                    while deactivation_receiver.recv().await.is_ok() {
1523                        handle
1524                            .update(&mut async_cx, |_, window, _| window.refresh())
1525                            .log_err();
1526                    }
1527                })
1528                .detach();
1529
1530            let mut async_cx = cx.to_async();
1531            cx.foreground_executor()
1532                .spawn(async move {
1533                    while let Ok(request) = action_receiver.recv().await {
1534                        handle
1535                            .update(&mut async_cx, |_, window, cx| {
1536                                window.handle_a11y_action(request, cx);
1537                            })
1538                            .log_err();
1539                    }
1540                })
1541                .detach();
1542        }
1543
1544        platform_window.on_close(Box::new({
1545            let window_id = handle.window_id();
1546            let mut cx = cx.to_async();
1547            move || {
1548                let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1549                let _ = cx.update(|cx| {
1550                    SystemWindowTabController::remove_tab(cx, window_id);
1551                });
1552            }
1553        }));
1554        platform_window.on_request_frame(Box::new({
1555            let mut cx = cx.to_async();
1556            let invalidator = invalidator.clone();
1557            let active = active.clone();
1558            let needs_present = needs_present.clone();
1559            let next_frame_callbacks = next_frame_callbacks.clone();
1560            let input_rate_tracker = input_rate_tracker.clone();
1561            let mut deferred_force_render = false;
1562            move |request_frame_options| {
1563                // This must be checked before anything else: if this request
1564                // arrived re-entrantly while a draw is on this thread's stack
1565                // (e.g. via a nested message pump in the Windows window
1566                // procedure), drawing would nest draws, and even touching the
1567                // App would panic on its already-mutable borrow. Skip instead;
1568                // the platform leaves the window invalidated (or re-invalidates
1569                // it), so a fresh request arrives once the in-progress draw
1570                // unwinds. Remember force_render so the deferred frame still
1571                // bypasses the view cache.
1572                //
1573                // Returning here skips `complete_frame`, which on Wayland would
1574                // stall the window's frame callbacks (no `surface.commit()`) —
1575                // but calling it would hit the App borrow panic above, and this
1576                // branch is unreachable there in practice: only Windows pumps
1577                // platform events (and thus requests frames) mid-draw.
1578                if draw_in_progress() {
1579                    log::debug!("deferring re-entrant window draw request");
1580                    deferred_force_render |= request_frame_options.force_render;
1581                    return;
1582                }
1583                // Take the deferred flag first: `||` short-circuits, and leaving
1584                // the flag set when this request already forces a render would
1585                // force a second, redundant render on the next frame.
1586                let force_render =
1587                    mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1588
1589                let thermal_state = handle
1590                    .update(&mut cx, |_, _, cx| cx.thermal_state())
1591                    .log_err();
1592
1593                // Throttle frame rate based on conditions:
1594                // - Thermal pressure (Serious/Critical): cap to ~60fps
1595                // - Inactive window (not focused): cap to ~30fps to save energy
1596                let min_frame_interval = if request_frame_options.require_presentation
1597                    || (!request_frame_options.force_render
1598                        && next_frame_callbacks.borrow().is_empty())
1599                {
1600                    None
1601                } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1602                    Some(Duration::from_micros(33333))
1603                } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1604                    Some(Duration::from_micros(16667))
1605                } else {
1606                    None
1607                };
1608
1609                let now = Instant::now();
1610                if let Some(min_interval) = min_frame_interval {
1611                    if let Some(last_frame) = last_frame_time.get()
1612                        && now.duration_since(last_frame) < min_interval
1613                    {
1614                        // Don't lose a pending forced render to throttling.
1615                        deferred_force_render |= force_render;
1616                        // Must still complete the frame on platforms that require it.
1617                        // On Wayland, `surface.frame()` was already called to request the
1618                        // next frame callback, so we must call `surface.commit()` (via
1619                        // `complete_frame`) or the compositor won't send another callback.
1620                        handle
1621                            .update(&mut cx, |_, window, _| window.complete_frame())
1622                            .log_err();
1623                        return;
1624                    }
1625                }
1626                last_frame_time.set(Some(now));
1627
1628                let next_frame_callbacks = next_frame_callbacks.take();
1629                if !next_frame_callbacks.is_empty() {
1630                    handle
1631                        .update(&mut cx, |_, window, cx| {
1632                            for callback in next_frame_callbacks {
1633                                callback(window, cx);
1634                            }
1635                        })
1636                        .log_err();
1637                }
1638
1639                // Keep presenting if input was recently arriving at a high rate (>= 60fps).
1640                // Once high-rate input is detected, we sustain presentation for 1 second
1641                // to prevent display underclocking during active input.
1642                let needs_present = request_frame_options.require_presentation
1643                    || needs_present.get()
1644                    || input_rate_tracker.borrow_mut().is_high_rate();
1645
1646                if invalidator.is_dirty() || force_render {
1647                    measure("frame duration", || {
1648                        handle
1649                            .update(&mut cx, |_, window, cx| {
1650                                if force_render {
1651                                    // Bypass cached view reuse so we don't replay stale
1652                                    // atlas tile references after a GPU device recovery.
1653                                    window.refresh();
1654                                }
1655                                let arena_clear_needed = window.draw(cx);
1656                                window.present();
1657                                arena_clear_needed.clear(cx);
1658                            })
1659                            .log_err();
1660                    })
1661                } else if needs_present {
1662                    handle
1663                        .update(&mut cx, |_, window, _| window.present())
1664                        .log_err();
1665                }
1666
1667                handle
1668                    .update(&mut cx, |_, window, _| {
1669                        window.complete_frame();
1670                    })
1671                    .log_err();
1672            }
1673        }));
1674        platform_window.on_resize(Box::new({
1675            let mut cx = cx.to_async();
1676            move |_, _| {
1677                handle
1678                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1679                    .log_err();
1680            }
1681        }));
1682        platform_window.on_moved(Box::new({
1683            let mut cx = cx.to_async();
1684            move || {
1685                handle
1686                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1687                    .log_err();
1688            }
1689        }));
1690        platform_window.on_appearance_changed(Box::new({
1691            let cx = cx.to_async();
1692            let foreground_executor = cx.foreground_executor().clone();
1693            move || {
1694                let mut cx = cx.clone();
1695                // Defer the update because changing the AppKit appearance may
1696                // synchronously invoke this callback while App is already borrowed.
1697                foreground_executor
1698                    .spawn(async move {
1699                        handle
1700                            .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1701                            .log_err();
1702                    })
1703                    .detach();
1704            }
1705        }));
1706        platform_window.on_button_layout_changed(Box::new({
1707            let mut cx = cx.to_async();
1708            move || {
1709                handle
1710                    .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1711                    .log_err();
1712            }
1713        }));
1714        platform_window.on_active_status_change(Box::new({
1715            let mut cx = cx.to_async();
1716            move |active| {
1717                handle
1718                    .update(&mut cx, |_, window, cx| {
1719                        window.active.set(active);
1720                        window.modifiers = window.platform_window.modifiers();
1721                        window.capslock = window.platform_window.capslock();
1722                        window
1723                            .activation_observers
1724                            .clone()
1725                            .retain(&(), |callback| callback(window, cx));
1726
1727                        window.bounds_changed(cx);
1728                        window.refresh();
1729
1730                        SystemWindowTabController::update_last_active(cx, window.handle.id);
1731                    })
1732                    .log_err();
1733            }
1734        }));
1735        platform_window.on_hover_status_change(Box::new({
1736            let mut cx = cx.to_async();
1737            move |active| {
1738                handle
1739                    .update(&mut cx, |_, window, _| {
1740                        window.hovered.set(active);
1741                        window.refresh();
1742                    })
1743                    .log_err();
1744            }
1745        }));
1746        platform_window.on_input({
1747            let mut cx = cx.to_async();
1748            Box::new(move |event| {
1749                handle
1750                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1751                    .log_err()
1752                    .unwrap_or(DispatchEventResult::default())
1753            })
1754        });
1755        platform_window.on_hit_test_window_control({
1756            let mut cx = cx.to_async();
1757            Box::new(move || {
1758                handle
1759                    .update(&mut cx, |_, window, _cx| {
1760                        for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1761                            if window.mouse_hit_test.ids.contains(&hitbox.id) {
1762                                return Some(*area);
1763                            }
1764                        }
1765                        None
1766                    })
1767                    .log_err()
1768                    .unwrap_or(None)
1769            })
1770        });
1771        platform_window.on_move_tab_to_new_window({
1772            let mut cx = cx.to_async();
1773            Box::new(move || {
1774                handle
1775                    .update(&mut cx, |_, _window, cx| {
1776                        SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1777                    })
1778                    .log_err();
1779            })
1780        });
1781        platform_window.on_merge_all_windows({
1782            let mut cx = cx.to_async();
1783            Box::new(move || {
1784                handle
1785                    .update(&mut cx, |_, _window, cx| {
1786                        SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1787                    })
1788                    .log_err();
1789            })
1790        });
1791        platform_window.on_select_next_tab({
1792            let mut cx = cx.to_async();
1793            Box::new(move || {
1794                handle
1795                    .update(&mut cx, |_, _window, cx| {
1796                        SystemWindowTabController::select_next_tab(cx, handle.window_id());
1797                    })
1798                    .log_err();
1799            })
1800        });
1801        platform_window.on_select_previous_tab({
1802            let mut cx = cx.to_async();
1803            Box::new(move || {
1804                handle
1805                    .update(&mut cx, |_, _window, cx| {
1806                        SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1807                    })
1808                    .log_err();
1809            })
1810        });
1811        platform_window.on_toggle_tab_bar({
1812            let mut cx = cx.to_async();
1813            Box::new(move || {
1814                handle
1815                    .update(&mut cx, |_, window, cx| {
1816                        let tab_bar_visible = window.platform_window.tab_bar_visible();
1817                        SystemWindowTabController::set_visible(cx, tab_bar_visible);
1818                    })
1819                    .log_err();
1820            })
1821        });
1822
1823        if let Some(app_id) = app_id {
1824            platform_window.set_app_id(&app_id);
1825        }
1826
1827        platform_window.map_window().unwrap();
1828
1829        Ok(Window {
1830            handle,
1831            invalidator,
1832            removed: false,
1833            platform_window,
1834            display_id,
1835            is_resizable,
1836            is_minimizable,
1837            sprite_atlas,
1838            text_system,
1839            text_rendering_mode: cx.text_rendering_mode.clone(),
1840            rem_size: px(16.),
1841            rem_size_override_stack: SmallVec::new(),
1842            viewport_size: content_size,
1843            layout_engine: Some(TaffyLayoutEngine::new()),
1844            root: None,
1845            element_id_stack: SmallVec::default(),
1846            text_style_stack: Vec::new(),
1847            rendered_entity_stack: Vec::new(),
1848            element_offset_stack: Vec::new(),
1849            content_mask_stack: Vec::new(),
1850            element_opacity: 1.0,
1851            requested_autoscroll: None,
1852            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1853            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1854            next_frame_callbacks,
1855            next_hitbox_id: HitboxId(0),
1856            next_tooltip_id: TooltipId::default(),
1857            tooltip_bounds: None,
1858            dirty_views: FxHashSet::default(),
1859            focus_listeners: SubscriberSet::new(),
1860            focus_lost_listeners: SubscriberSet::new(),
1861            default_prevented: true,
1862            mouse_position,
1863            mouse_hit_test: HitTest::default(),
1864            modifiers,
1865            capslock,
1866            scale_factor,
1867            bounds_observers: SubscriberSet::new(),
1868            appearance,
1869            appearance_observers: SubscriberSet::new(),
1870            button_layout_observers: SubscriberSet::new(),
1871            active,
1872            hovered,
1873            needs_present,
1874            input_rate_tracker,
1875            #[cfg(feature = "input-latency-histogram")]
1876            input_latency_tracker: InputLatencyTracker::new()?,
1877            last_input_modality: InputModality::Mouse,
1878            refreshing: false,
1879            activation_observers: SubscriberSet::new(),
1880            focus: None,
1881            focus_enabled: true,
1882            focus_generation: 0,
1883            pending_input: None,
1884            pending_modifier: ModifierState::default(),
1885            pending_input_observers: SubscriberSet::new(),
1886            prompt: None,
1887            client_inset: None,
1888            image_cache_stack: Vec::new(),
1889            captured_hitbox: None,
1890            #[cfg(any(feature = "inspector", debug_assertions))]
1891            inspector: None,
1892            a11y: A11y::new(
1893                a11y_active_flag,
1894                accessibility_force_disabled,
1895                initial_window_title,
1896            ),
1897        })
1898    }
1899
1900    pub(crate) fn new_focus_listener(
1901        &self,
1902        value: AnyWindowFocusListener,
1903    ) -> (Subscription, impl FnOnce() + use<>) {
1904        self.focus_listeners.insert((), value)
1905    }
1906}
1907
1908#[derive(Clone, Debug, Default, PartialEq, Eq)]
1909#[expect(missing_docs)]
1910pub struct DispatchEventResult {
1911    pub propagate: bool,
1912    pub default_prevented: bool,
1913}
1914
1915/// Indicates which region of the window is visible. Content falling outside of this mask will not be
1916/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
1917/// to leave room to support more complex shapes in the future.
1918#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1919#[repr(C)]
1920pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1921    /// The bounds
1922    pub bounds: Bounds<P>,
1923}
1924
1925impl ContentMask<Pixels> {
1926    /// Scale the content mask's pixel units by the given scaling factor.
1927    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1928        ContentMask {
1929            bounds: self.bounds.scale(factor),
1930        }
1931    }
1932
1933    /// Intersect the content mask with the given content mask.
1934    pub fn intersect(&self, other: &Self) -> Self {
1935        let bounds = self.bounds.intersect(&other.bounds);
1936        ContentMask { bounds }
1937    }
1938}
1939
1940impl Window {
1941    fn mark_view_dirty(&mut self, view_id: EntityId) {
1942        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
1943        // should already be dirty.
1944        for view_id in self
1945            .rendered_frame
1946            .dispatch_tree
1947            .view_path_reversed(view_id)
1948        {
1949            if !self.dirty_views.insert(view_id) {
1950                break;
1951            }
1952        }
1953    }
1954
1955    /// Registers a callback to be invoked when the window appearance changes.
1956    pub fn observe_window_appearance(
1957        &self,
1958        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1959    ) -> Subscription {
1960        let (subscription, activate) = self.appearance_observers.insert(
1961            (),
1962            Box::new(move |window, cx| {
1963                callback(window, cx);
1964                true
1965            }),
1966        );
1967        activate();
1968        subscription
1969    }
1970
1971    /// Registers a callback to be invoked when the window button layout changes.
1972    pub fn observe_button_layout_changed(
1973        &self,
1974        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1975    ) -> Subscription {
1976        let (subscription, activate) = self.button_layout_observers.insert(
1977            (),
1978            Box::new(move |window, cx| {
1979                callback(window, cx);
1980                true
1981            }),
1982        );
1983        activate();
1984        subscription
1985    }
1986
1987    /// Replaces the root entity of the window with a new one.
1988    pub fn replace_root<E>(
1989        &mut self,
1990        cx: &mut App,
1991        build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1992    ) -> Entity<E>
1993    where
1994        E: 'static + Render,
1995    {
1996        let view = cx.new(|cx| build_view(self, cx));
1997        self.root = Some(view.clone().into());
1998        self.refresh();
1999        view
2000    }
2001
2002    /// Returns the root entity of the window, if it has one.
2003    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2004    where
2005        E: 'static + Render,
2006    {
2007        self.root
2008            .as_ref()
2009            .map(|view| view.clone().downcast::<E>().ok())
2010    }
2011
2012    /// Obtain a handle to the window that belongs to this context.
2013    pub fn window_handle(&self) -> AnyWindowHandle {
2014        self.handle
2015    }
2016
2017    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
2018    pub fn refresh(&mut self) {
2019        if self.invalidator.not_drawing() {
2020            self.refreshing = true;
2021            self.invalidator.set_dirty(true);
2022        }
2023    }
2024
2025    /// Close this window.
2026    pub fn remove_window(&mut self) {
2027        self.clear_pending_keystrokes();
2028        self.removed = true;
2029    }
2030
2031    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
2032    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2033        self.focus
2034            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2035    }
2036
2037    /// Move focus to the element associated with the given [`FocusHandle`].
2038    pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2039        if !self.focus_enabled || self.focus == Some(handle.id) {
2040            return;
2041        }
2042
2043        self.focus = Some(handle.id);
2044        self.focus_generation = self.focus_generation.wrapping_add(1);
2045        self.clear_pending_keystrokes();
2046
2047        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
2048        // current effect cycle, and only for this window.
2049        let window_handle = self.handle;
2050        cx.defer(move |cx| {
2051            window_handle
2052                .update(cx, |_, window, cx| {
2053                    window.pending_input_changed(cx);
2054                })
2055                .ok();
2056        });
2057
2058        self.refresh();
2059    }
2060
2061    /// Remove focus from all elements within this context's window.
2062    pub fn blur(&mut self) {
2063        if !self.focus_enabled {
2064            return;
2065        }
2066
2067        if self.focus.is_some() {
2068            self.focus_generation = self.focus_generation.wrapping_add(1);
2069        }
2070        self.focus = None;
2071        self.refresh();
2072    }
2073
2074    /// Blur the window and don't allow anything in it to be focused again.
2075    pub fn disable_focus(&mut self) {
2076        self.blur();
2077        self.focus_enabled = false;
2078    }
2079
2080    /// Move focus to next tab stop.
2081    pub fn focus_next(&mut self, cx: &mut App) {
2082        if !self.focus_enabled {
2083            return;
2084        }
2085
2086        if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2087            self.focus(&handle, cx)
2088        }
2089    }
2090
2091    /// Move focus to previous tab stop.
2092    pub fn focus_prev(&mut self, cx: &mut App) {
2093        if !self.focus_enabled {
2094            return;
2095        }
2096
2097        if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2098            self.focus(&handle, cx)
2099        }
2100    }
2101
2102    /// Accessor for the text system.
2103    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2104        &self.text_system
2105    }
2106
2107    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
2108    pub fn text_style(&self) -> TextStyle {
2109        let mut style = TextStyle::default();
2110        for refinement in &self.text_style_stack {
2111            style.refine(refinement);
2112        }
2113        style
2114    }
2115
2116    /// Check if the platform window is maximized.
2117    ///
2118    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
2119    pub fn is_maximized(&self) -> bool {
2120        self.platform_window.is_maximized()
2121    }
2122
2123    /// request a certain window decoration (Wayland)
2124    pub fn request_decorations(&self, decorations: WindowDecorations) {
2125        self.platform_window.request_decorations(decorations);
2126    }
2127
2128    /// Set the exclusive zone for a layer-shell surface: how much screen space it
2129    /// reserves so other surfaces avoid occluding it (e.g. a panel reserving space).
2130    /// Positive values reserve that distance from the anchored edge, 0 lets the
2131    /// surface be moved out of others' exclusive zones, and -1 ignores reserved
2132    /// space and may extend under other surfaces. (Wayland layer-shell windows only)
2133    pub fn set_exclusive_zone(&self, zone: Pixels) {
2134        self.platform_window.set_exclusive_zone(zone);
2135    }
2136
2137    /// Set which anchored edge a layer-shell surface's exclusive zone applies to.
2138    /// This is only needed to disambiguate a corner-anchored surface; otherwise the
2139    /// edge is deduced from the anchor. The edge must be a single edge the surface
2140    /// is anchored to, or it is ignored. (Wayland layer-shell windows only)
2141    #[cfg(all(target_os = "linux", feature = "wayland"))]
2142    pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2143        self.platform_window.set_exclusive_edge(edge);
2144    }
2145
2146    /// Start an interactive window resize operation if this window is resizable.
2147    pub fn start_window_resize(&self, edge: ResizeEdge) {
2148        if self.is_resizable {
2149            self.platform_window.start_window_resize(edge);
2150        }
2151    }
2152
2153    /// Linux (wayland) only: Set the window's input region, the area that receives pointer
2154    /// and touch input. Events outside it pass through to whatever is below the window.
2155    ///
2156    /// - `Some(rects)` restricts input to the union of `rects`, in window coordinates.
2157    /// - `Some(&[])` is an empty region, so the window receives no pointer or touch input.
2158    /// - `None` resets the region to the default, so the whole window receives input again.
2159    pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2160        self.platform_window.set_input_region(region);
2161    }
2162
2163    /// Return the `WindowBounds` to indicate that how a window should be opened
2164    /// after it has been closed
2165    pub fn window_bounds(&self) -> WindowBounds {
2166        self.platform_window.window_bounds()
2167    }
2168
2169    /// Return the `WindowBounds` excluding insets (Wayland and X11)
2170    pub fn inner_window_bounds(&self) -> WindowBounds {
2171        self.platform_window.inner_window_bounds()
2172    }
2173
2174    /// Dispatch the given action on the currently focused element.
2175    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2176        let focus_id = self.focused(cx).map(|handle| handle.id);
2177
2178        let window = self.handle;
2179        cx.defer(move |cx| {
2180            window
2181                .update(cx, |_, window, cx| {
2182                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2183                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2184                })
2185                .log_err();
2186        })
2187    }
2188
2189    pub(crate) fn dispatch_keystroke_observers(
2190        &mut self,
2191        event: &dyn Any,
2192        action: Option<Box<dyn Action>>,
2193        context_stack: Vec<KeyContext>,
2194        cx: &mut App,
2195    ) {
2196        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2197            return;
2198        };
2199
2200        cx.keystroke_observers.clone().retain(&(), move |callback| {
2201            (callback)(
2202                &KeystrokeEvent {
2203                    keystroke: key_down_event.keystroke.clone(),
2204                    action: action.as_ref().map(|action| action.boxed_clone()),
2205                    context_stack: context_stack.clone(),
2206                },
2207                self,
2208                cx,
2209            )
2210        });
2211    }
2212
2213    pub(crate) fn dispatch_keystroke_interceptors(
2214        &mut self,
2215        event: &dyn Any,
2216        context_stack: Vec<KeyContext>,
2217        cx: &mut App,
2218    ) {
2219        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2220            return;
2221        };
2222
2223        cx.keystroke_interceptors
2224            .clone()
2225            .retain(&(), move |callback| {
2226                (callback)(
2227                    &KeystrokeEvent {
2228                        keystroke: key_down_event.keystroke.clone(),
2229                        action: None,
2230                        context_stack: context_stack.clone(),
2231                    },
2232                    self,
2233                    cx,
2234                )
2235            });
2236    }
2237
2238    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2239    /// that are currently on the stack to be returned to the app.
2240    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2241        let handle = self.handle;
2242        cx.defer(move |cx| {
2243            handle.update(cx, |_, window, cx| f(window, cx)).ok();
2244        });
2245    }
2246
2247    /// Subscribe to events emitted by a entity.
2248    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2249    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
2250    pub fn observe<T: 'static>(
2251        &mut self,
2252        observed: &Entity<T>,
2253        cx: &mut App,
2254        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2255    ) -> Subscription {
2256        let entity_id = observed.entity_id();
2257        let observed = observed.downgrade();
2258        let window_handle = self.handle;
2259        cx.new_observer(
2260            entity_id,
2261            Box::new(move |cx| {
2262                window_handle
2263                    .update(cx, |_, window, cx| {
2264                        if let Some(handle) = observed.upgrade() {
2265                            on_notify(handle, window, cx);
2266                            true
2267                        } else {
2268                            false
2269                        }
2270                    })
2271                    .unwrap_or(false)
2272            }),
2273        )
2274    }
2275
2276    /// Subscribe to events emitted by a entity.
2277    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2278    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
2279    pub fn subscribe<Emitter, Evt>(
2280        &mut self,
2281        entity: &Entity<Emitter>,
2282        cx: &mut App,
2283        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2284    ) -> Subscription
2285    where
2286        Emitter: EventEmitter<Evt>,
2287        Evt: 'static,
2288    {
2289        let entity_id = entity.entity_id();
2290        let handle = entity.downgrade();
2291        let window_handle = self.handle;
2292        cx.new_subscription(
2293            entity_id,
2294            (
2295                TypeId::of::<Evt>(),
2296                Box::new(move |event, cx| {
2297                    window_handle
2298                        .update(cx, |_, window, cx| {
2299                            if let Some(entity) = handle.upgrade() {
2300                                let event = event.downcast_ref().expect("invalid event type");
2301                                on_event(entity, event, window, cx);
2302                                true
2303                            } else {
2304                                false
2305                            }
2306                        })
2307                        .unwrap_or(false)
2308                }),
2309            ),
2310        )
2311    }
2312
2313    /// Register a callback to be invoked when the given `Entity` is released.
2314    pub fn observe_release<T>(
2315        &self,
2316        entity: &Entity<T>,
2317        cx: &mut App,
2318        mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2319    ) -> Subscription
2320    where
2321        T: 'static,
2322    {
2323        let entity_id = entity.entity_id();
2324        let window_handle = self.handle;
2325        let (subscription, activate) = cx.release_listeners.insert(
2326            entity_id,
2327            Box::new(move |entity, cx| {
2328                let entity = entity.downcast_mut().expect("invalid entity type");
2329                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2330            }),
2331        );
2332        activate();
2333        subscription
2334    }
2335
2336    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
2337    /// await points in async code.
2338    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2339        AsyncWindowContext::new_context(cx.to_async(), self.handle)
2340    }
2341
2342    /// Schedule the given closure to be run directly after the current frame is rendered.
2343    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2344        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2345    }
2346
2347    /// Schedule a frame to be drawn on the next animation frame.
2348    ///
2349    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
2350    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
2351    ///
2352    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
2353    ///
2354    /// Callers driving purely decorative animations (spinners, pulses, and the
2355    /// like) should prefer [`AnimationExt::with_animation`](crate::AnimationExt::with_animation),
2356    /// which automatically respects [`App::reduce_motion`]. When using this
2357    /// method directly for decorative motion, check [`App::reduce_motion`]
2358    /// and skip the frame request when it is set.
2359    pub fn request_animation_frame(&self) {
2360        let entity = self.current_view();
2361        self.on_next_frame(move |_, cx| cx.notify(entity));
2362    }
2363
2364    /// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran.
2365    ///
2366    /// Tests have no platform frame loop, so this simulates the delivery of the
2367    /// next frame.
2368    #[cfg(any(test, feature = "test-support"))]
2369    pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2370        let callbacks = self.next_frame_callbacks.take();
2371        let count = callbacks.len();
2372        for callback in callbacks {
2373            callback(self, cx);
2374        }
2375        count
2376    }
2377
2378    /// Spawn the future returned by the given closure on the application thread pool.
2379    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
2380    /// use within your future.
2381    #[track_caller]
2382    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2383    where
2384        R: 'static,
2385        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2386    {
2387        let handle = self.handle;
2388        cx.spawn(async move |app| {
2389            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2390            f(&mut async_window_cx).await
2391        })
2392    }
2393
2394    /// Spawn the future returned by the given closure on the application thread
2395    /// pool, with the given priority. The closure is provided a handle to the
2396    /// current window and an `AsyncWindowContext` for use within your future.
2397    #[track_caller]
2398    pub fn spawn_with_priority<AsyncFn, R>(
2399        &self,
2400        priority: Priority,
2401        cx: &App,
2402        f: AsyncFn,
2403    ) -> Task<R>
2404    where
2405        R: 'static,
2406        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2407    {
2408        let handle = self.handle;
2409        cx.spawn_with_priority(priority, async move |app| {
2410            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2411            f(&mut async_window_cx).await
2412        })
2413    }
2414
2415    /// Notify the window that its bounds have changed.
2416    ///
2417    /// This updates internal state like `viewport_size` and `scale_factor` from
2418    /// the platform window, then notifies observers. Normally called automatically
2419    /// by the platform's resize callback, but exposed publicly for test infrastructure.
2420    pub fn bounds_changed(&mut self, cx: &mut App) {
2421        self.scale_factor = self.platform_window.scale_factor();
2422        self.viewport_size = self.platform_window.content_size();
2423        self.display_id = self.platform_window.display().map(|display| display.id());
2424        self.mouse_position = self.platform_window.mouse_position();
2425
2426        self.refresh();
2427
2428        self.bounds_observers
2429            .clone()
2430            .retain(&(), |callback| callback(self, cx));
2431    }
2432
2433    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
2434    pub fn bounds(&self) -> Bounds<Pixels> {
2435        self.platform_window.bounds()
2436    }
2437
2438    /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
2439    /// This does not present the frame to screen - useful for visual testing where we want
2440    /// to capture what would be rendered without displaying it or requiring the window to be visible.
2441    #[cfg(any(test, feature = "test-support"))]
2442    pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2443        self.platform_window
2444            .render_to_image(&self.rendered_frame.scene)
2445    }
2446
2447    /// Set the content size of the window.
2448    pub fn resize(&mut self, size: Size<Pixels>) {
2449        self.platform_window.resize(size);
2450    }
2451
2452    /// Returns whether or not the window is currently fullscreen
2453    pub fn is_fullscreen(&self) -> bool {
2454        self.platform_window.is_fullscreen()
2455    }
2456
2457    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2458        self.appearance = self.platform_window.appearance();
2459
2460        self.appearance_observers
2461            .clone()
2462            .retain(&(), |callback| callback(self, cx));
2463    }
2464
2465    pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2466        self.button_layout_observers
2467            .clone()
2468            .retain(&(), |callback| callback(self, cx));
2469    }
2470
2471    /// Returns the appearance of the current window.
2472    pub fn appearance(&self) -> WindowAppearance {
2473        self.appearance
2474    }
2475
2476    /// Returns the size of the drawable area within the window.
2477    pub fn viewport_size(&self) -> Size<Pixels> {
2478        self.viewport_size
2479    }
2480
2481    /// Returns whether this window is focused by the operating system (receiving key events).
2482    pub fn is_window_active(&self) -> bool {
2483        self.active.get()
2484    }
2485
2486    /// Returns whether this window is considered to be the window
2487    /// that currently owns the mouse cursor.
2488    /// On mac, this is equivalent to `is_window_active`.
2489    pub fn is_window_hovered(&self) -> bool {
2490        if cfg!(any(
2491            target_os = "windows",
2492            target_os = "linux",
2493            target_os = "freebsd"
2494        )) {
2495            self.hovered.get()
2496        } else {
2497            self.is_window_active()
2498        }
2499    }
2500
2501    /// Toggle zoom on the window.
2502    pub fn zoom_window(&self) {
2503        self.platform_window.zoom();
2504    }
2505
2506    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
2507    pub fn show_window_menu(&self, position: Point<Pixels>) {
2508        self.platform_window.show_window_menu(position)
2509    }
2510
2511    /// Handle window movement for Linux and macOS.
2512    /// Tells the compositor to take control of window movement (Wayland and X11)
2513    ///
2514    /// Events may not be received during a move operation.
2515    pub fn start_window_move(&self) {
2516        self.platform_window.start_window_move()
2517    }
2518
2519    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
2520    pub fn set_client_inset(&mut self, inset: Pixels) {
2521        self.client_inset = Some(inset);
2522        self.platform_window.set_client_inset(inset);
2523    }
2524
2525    /// Returns the client_inset value by [`Self::set_client_inset`].
2526    pub fn client_inset(&self) -> Option<Pixels> {
2527        self.client_inset
2528    }
2529
2530    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
2531    pub fn window_decorations(&self) -> Decorations {
2532        self.platform_window.window_decorations()
2533    }
2534
2535    /// Returns whether this window is resizable.
2536    pub fn is_resizable(&self) -> bool {
2537        self.is_resizable
2538    }
2539
2540    /// Returns whether this window is minimizable.
2541    pub fn is_minimizable(&self) -> bool {
2542        self.is_minimizable
2543    }
2544
2545    /// Returns the controls supported by the platform.
2546    pub fn window_controls(&self) -> WindowControls {
2547        self.platform_window.window_controls()
2548    }
2549
2550    /// Updates the window's title at the platform level.
2551    pub fn set_window_title(&mut self, title: &str) {
2552        self.platform_window.set_title(title);
2553        self.a11y.set_window_title(title.to_string());
2554    }
2555
2556    /// Sets the position of the macOS traffic light buttons.
2557    #[cfg(target_os = "macos")]
2558    pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2559        self.platform_window.set_traffic_light_position(position);
2560    }
2561
2562    /// Sets the application identifier.
2563    pub fn set_app_id(&mut self, app_id: &str) {
2564        self.platform_window.set_app_id(app_id);
2565    }
2566
2567    /// Sets the window background appearance.
2568    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2569        self.platform_window
2570            .set_background_appearance(background_appearance);
2571    }
2572
2573    /// Mark the window as dirty at the platform level.
2574    pub fn set_window_edited(&mut self, edited: bool) {
2575        self.platform_window.set_edited(edited);
2576    }
2577
2578    /// Set the path of the file this window represents.
2579    /// On macOS, this sets the window's accessibility document property (AXDocument).
2580    pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2581        self.platform_window.set_document_path(path);
2582    }
2583
2584    /// Determine the display on which the window is visible.
2585    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2586        cx.platform
2587            .displays()
2588            .into_iter()
2589            .find(|display| Some(display.id()) == self.display_id)
2590    }
2591
2592    /// Show the platform character palette.
2593    pub fn show_character_palette(&self) {
2594        self.platform_window.show_character_palette();
2595    }
2596
2597    /// The scale factor of the display associated with the window. For example, it could
2598    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
2599    /// be rendered as two pixels on screen.
2600    pub fn scale_factor(&self) -> f32 {
2601        self.scale_factor
2602    }
2603
2604    /// Overrides the display scale factor for tests.
2605    #[cfg(any(test, feature = "test-support"))]
2606    pub fn set_scale_factor(&mut self, scale_factor: f32) {
2607        self.scale_factor = scale_factor;
2608        self.refresh();
2609    }
2610
2611    /// The size of an em for the base font of the application. Adjusting this value allows the
2612    /// UI to scale, just like zooming a web page.
2613    pub fn rem_size(&self) -> Pixels {
2614        self.rem_size_override_stack
2615            .last()
2616            .copied()
2617            .unwrap_or(self.rem_size)
2618    }
2619
2620    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
2621    /// UI to scale, just like zooming a web page.
2622    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2623        self.rem_size = rem_size.into();
2624    }
2625
2626    /// Acquire a globally unique identifier for the given ElementId.
2627    /// Only valid for the duration of the provided closure.
2628    pub fn with_global_id<R>(
2629        &mut self,
2630        element_id: ElementId,
2631        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2632    ) -> R {
2633        self.with_id(element_id, |this| {
2634            let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2635
2636            f(&global_id, this)
2637        })
2638    }
2639
2640    /// Calls the provided closure with the element ID pushed on the stack.
2641    #[inline]
2642    pub fn with_id<R>(
2643        &mut self,
2644        element_id: impl Into<ElementId>,
2645        f: impl FnOnce(&mut Self) -> R,
2646    ) -> R {
2647        self.element_id_stack.push(element_id.into());
2648        let result = f(self);
2649        self.element_id_stack.pop();
2650        result
2651    }
2652
2653    /// Executes the provided function with the specified rem size.
2654    ///
2655    /// This method must only be called as part of element drawing.
2656    // This function is called in a highly recursive manner in editor
2657    // prepainting, make sure its inlined to reduce the stack burden
2658    #[inline]
2659    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2660    where
2661        F: FnOnce(&mut Self) -> R,
2662    {
2663        self.invalidator.debug_assert_paint_or_prepaint();
2664
2665        if let Some(rem_size) = rem_size {
2666            self.rem_size_override_stack.push(rem_size.into());
2667            let result = f(self);
2668            self.rem_size_override_stack.pop();
2669            result
2670        } else {
2671            f(self)
2672        }
2673    }
2674
2675    /// The line height associated with the current text style.
2676    pub fn line_height(&self) -> Pixels {
2677        self.text_style().line_height_in_pixels(self.rem_size())
2678    }
2679
2680    /// Rounds a logical value to the nearest device pixel.
2681    #[inline]
2682    pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2683        px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2684    }
2685
2686    /// f64 variant of [`Self::pixel_snap`].
2687    #[inline]
2688    pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2689        let scale_factor = f64::from(self.scale_factor());
2690        round_half_toward_zero_f64(value * scale_factor) / scale_factor
2691    }
2692
2693    /// Snaps a bounds' origin and size to the nearest device pixel.
2694    #[inline]
2695    pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2696        bounds.map(|c| self.pixel_snap(c))
2697    }
2698
2699    /// Snaps a point's coordinates to the nearest device pixel.
2700    #[inline]
2701    pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2702        position.map(|c| self.pixel_snap(c))
2703    }
2704
2705    #[inline]
2706    fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2707        let scale_factor = self.scale_factor();
2708        let left = round_to_device_pixel(bounds.left().0, scale_factor);
2709        let top = round_to_device_pixel(bounds.top().0, scale_factor);
2710        let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2711        let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2712        Bounds::from_corners(
2713            point(ScaledPixels(left), ScaledPixels(top)),
2714            point(ScaledPixels(right), ScaledPixels(bottom)),
2715        )
2716    }
2717
2718    /// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear.
2719    #[inline]
2720    fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2721        ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2722    }
2723
2724    #[inline]
2725    fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2726        edges.map(|e| self.snap_stroke(*e))
2727    }
2728
2729    /// Floors the near edge and ceils the far edge, producing a strict superset of the raw region.
2730    #[inline]
2731    fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2732        let scale_factor = self.scale_factor();
2733        let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2734        let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2735        let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2736        let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2737        Bounds::from_corners(
2738            point(ScaledPixels(left), ScaledPixels(top)),
2739            point(ScaledPixels(right), ScaledPixels(bottom)),
2740        )
2741    }
2742
2743    #[inline]
2744    fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2745        ContentMask {
2746            bounds: self.cover_bounds(self.content_mask().bounds),
2747        }
2748    }
2749
2750    /// Call to prevent the default action of an event. Currently only used to prevent
2751    /// parent elements from becoming focused on mouse down.
2752    pub fn prevent_default(&mut self) {
2753        self.default_prevented = true;
2754    }
2755
2756    /// Obtain whether default has been prevented for the event currently being dispatched.
2757    pub fn default_prevented(&self) -> bool {
2758        self.default_prevented
2759    }
2760
2761    /// Determine whether the given action is available along the dispatch path to the currently focused element.
2762    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2763        let node_id =
2764            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2765        self.rendered_frame
2766            .dispatch_tree
2767            .is_action_available(action, node_id)
2768    }
2769
2770    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
2771    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2772        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2773        self.rendered_frame
2774            .dispatch_tree
2775            .is_action_available(action, node_id)
2776    }
2777
2778    /// The position of the mouse relative to the window.
2779    pub fn mouse_position(&self) -> Point<Pixels> {
2780        self.mouse_position
2781    }
2782
2783    /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
2784    /// events will be routed to listeners that check this hitbox's `is_hovered` status,
2785    /// regardless of actual hit testing. This enables drag operations that continue
2786    /// even when the pointer moves outside the element's bounds.
2787    ///
2788    /// The capture is automatically released on mouse up.
2789    pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2790        self.captured_hitbox = Some(hitbox_id);
2791    }
2792
2793    /// Releases any active pointer capture.
2794    pub fn release_pointer(&mut self) {
2795        self.captured_hitbox = None;
2796    }
2797
2798    /// Returns the hitbox that has captured the pointer, if any.
2799    pub fn captured_hitbox(&self) -> Option<HitboxId> {
2800        self.captured_hitbox
2801    }
2802
2803    /// The current state of the keyboard's modifiers
2804    pub fn modifiers(&self) -> Modifiers {
2805        self.modifiers
2806    }
2807
2808    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
2809    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
2810    pub fn last_input_was_keyboard(&self) -> bool {
2811        self.last_input_modality == InputModality::Keyboard
2812    }
2813
2814    /// The current state of the keyboard's capslock
2815    pub fn capslock(&self) -> Capslock {
2816        self.capslock
2817    }
2818
2819    fn complete_frame(&self) {
2820        self.platform_window.completed_frame();
2821    }
2822
2823    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
2824    /// the contents of the new [`Scene`], use [`Self::present`].
2825    #[profiling::function]
2826    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2827        // Drain unconditionally so a stale first-invalidation timestamp can't
2828        // leak into a later frame across enable/disable of frame tracing.
2829        let frame_dirty = self.invalidator.take_frame_dirty();
2830        let draw_started_at = profiler::frame_trace_enabled().then(Instant::now);
2831
2832        // Set up the per-App arena for element allocation during this draw.
2833        // This ensures that multiple test Apps have isolated arenas.
2834        let arena_scope = ElementArenaScope::enter(&cx.element_arena);
2835
2836        self.invalidate_entities();
2837        cx.entities.clear_accessed();
2838        debug_assert!(self.rendered_entity_stack.is_empty());
2839        self.invalidator.set_dirty(false);
2840        self.requested_autoscroll = None;
2841
2842        // Restore the previously-used input handler.
2843        // Place it back into a None slot (left by a previous .take()) so that
2844        // cached paint_range indices in reuse_paint find the handler at the
2845        // expected position.
2846        if let Some(input_handler) = self.platform_window.take_input_handler() {
2847            if let Some(slot) = self
2848                .rendered_frame
2849                .input_handlers
2850                .iter_mut()
2851                .rev()
2852                .find(|h| h.is_none())
2853            {
2854                *slot = Some(input_handler);
2855            } else {
2856                self.rendered_frame.input_handlers.push(Some(input_handler));
2857            }
2858        }
2859        if !cx.mode.skip_drawing() {
2860            self.draw_roots(cx);
2861        }
2862        self.dirty_views.clear();
2863        self.next_frame.window_active = self.active.get();
2864
2865        // Register requested input handler with the platform window.
2866        // Use .take() instead of .pop() to preserve Vec length, so that cached
2867        // paint_range indices remain valid for reuse_paint on the next frame.
2868        // Search backwards to find the last Some entry, since reuse_paint may
2869        // have copied None slots from the previous frame. (Fixes #50456)
2870        if let Some(input_handler) = self
2871            .next_frame
2872            .input_handlers
2873            .iter_mut()
2874            .rev()
2875            .find_map(|h| h.take())
2876        {
2877            self.platform_window.set_input_handler(input_handler);
2878        }
2879
2880        self.layout_engine.as_mut().unwrap().clear();
2881        self.text_system().finish_frame();
2882        self.next_frame.finish(&mut self.rendered_frame);
2883
2884        self.invalidator.set_phase(DrawPhase::Focus);
2885        let previous_focus_path = self.rendered_frame.focus_path();
2886        let previous_window_active = self.rendered_frame.window_active;
2887        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2888        self.next_frame.clear();
2889        let current_focus_path = self.rendered_frame.focus_path();
2890        let current_window_active = self.rendered_frame.window_active;
2891        let mut focus_before_listeners = self.focus;
2892
2893        if previous_focus_path != current_focus_path
2894            || previous_window_active != current_window_active
2895        {
2896            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2897                self.focus_lost_listeners
2898                    .clone()
2899                    .retain(&(), |listener| listener(self, cx));
2900                // The focus-lost fallback (e.g. a workspace refocusing itself) may target
2901                // an element that isn't part of the element tree, in which case scheduling
2902                // a redraw below would dispatch focus-lost again, looping forever. Only
2903                // track focus movement caused by the focus listeners.
2904                focus_before_listeners = self.focus;
2905            }
2906
2907            let event = WindowFocusEvent {
2908                previous_focus_path: if previous_window_active {
2909                    previous_focus_path
2910                } else {
2911                    Default::default()
2912                },
2913                current_focus_path: if current_window_active {
2914                    current_focus_path
2915                } else {
2916                    Default::default()
2917                },
2918            };
2919            self.focus_listeners
2920                .clone()
2921                .retain(&(), |listener| listener(&event, self, cx));
2922        }
2923
2924        debug_assert!(self.rendered_entity_stack.is_empty());
2925        self.record_entities_accessed(cx);
2926        self.reset_cursor_style(cx);
2927        self.refreshing = false;
2928        self.invalidator.set_phase(DrawPhase::None);
2929        // Focus listeners may move focus (e.g. a dock forwarding focus to its active
2930        // panel). `Window::focus` suppresses `refresh` while a draw is in progress, so
2931        // schedule another frame here to render the new focus state and dispatch the
2932        // resulting focus events.
2933        if self.focus != focus_before_listeners {
2934            self.refresh();
2935        }
2936        self.needs_present.set(true);
2937
2938        if let Some(draw_start) = draw_started_at {
2939            profiler::record_frame_timing(profiler::FrameTiming {
2940                window_id: self.handle.window_id(),
2941                dirty_at: frame_dirty.dirty_at,
2942                invalidations: frame_dirty.invalidations,
2943                draw_start,
2944                draw_end: Instant::now(),
2945            });
2946        }
2947
2948        // Exit the scope to obtain the arena-clear token this draw owes; the
2949        // scope's teardown itself happens in `ElementArenaScope::drop`.
2950        arena_scope.exit(&cx.element_arena)
2951    }
2952
2953    fn record_entities_accessed(&mut self, cx: &mut App) {
2954        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2955        let mut entities = mem::take(entities_ref.deref_mut());
2956        let handle = self.handle;
2957        cx.record_entities_accessed(
2958            handle,
2959            // Try moving window invalidator into the Window
2960            self.invalidator.clone(),
2961            &entities,
2962        );
2963        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2964        mem::swap(&mut entities, entities_ref.deref_mut());
2965    }
2966
2967    fn invalidate_entities(&mut self) {
2968        let mut views = self.invalidator.take_views();
2969        for entity in views.drain() {
2970            self.mark_view_dirty(entity);
2971        }
2972        self.invalidator.replace_views(views);
2973    }
2974
2975    #[profiling::function]
2976    fn present(&mut self) {
2977        self.platform_window.draw(&self.rendered_frame.scene);
2978        #[cfg(feature = "input-latency-histogram")]
2979        self.input_latency_tracker.record_frame_presented();
2980        self.needs_present.set(false);
2981        profiling::finish_frame!();
2982    }
2983
2984    /// Presents the most recently drawn frame if it hasn't been presented yet.
2985    ///
2986    /// Benchmarks drive drawing synchronously rather than through a platform
2987    /// frame-request loop, so they call this after each measured update to
2988    /// submit the frame like production presentation would.
2989    #[cfg(feature = "bench")]
2990    pub fn present_if_needed(&mut self) {
2991        if self.needs_present.get() {
2992            self.present();
2993        }
2994    }
2995
2996    /// Returns a snapshot of the current input-latency histograms.
2997    #[cfg(feature = "input-latency-histogram")]
2998    pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
2999        self.input_latency_tracker.snapshot()
3000    }
3001
3002    fn draw_roots(&mut self, cx: &mut App) {
3003        self.invalidator.set_phase(DrawPhase::Prepaint);
3004        self.tooltip_bounds.take();
3005
3006        self.a11y.sync_active_flag();
3007        if self.a11y.is_active() {
3008            self.a11y.begin_frame();
3009        }
3010
3011        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3012        let root_size = {
3013            #[cfg(any(feature = "inspector", debug_assertions))]
3014            {
3015                if self.inspector.is_some() {
3016                    let mut size = self.viewport_size;
3017                    size.width = (size.width - _inspector_width).max(px(0.0));
3018                    size
3019                } else {
3020                    self.viewport_size
3021                }
3022            }
3023            #[cfg(not(any(feature = "inspector", debug_assertions)))]
3024            {
3025                self.viewport_size
3026            }
3027        };
3028
3029        // Layout all root elements. Like the root element on the web, which
3030        // stretches to fill the viewport unless explicitly sized, window roots
3031        // fill the window when their size is `auto`.
3032        let scale_factor = self.scale_factor();
3033        let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3034        let root_layout_id = root_element.request_layout(self, cx);
3035        self.layout_engine
3036            .as_mut()
3037            .unwrap()
3038            .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3039        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3040
3041        #[cfg(any(feature = "inspector", debug_assertions))]
3042        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3043
3044        self.prepaint_deferred_draws(cx);
3045
3046        let mut prompt_element = None;
3047        let mut active_drag_element = None;
3048        let mut tooltip_element = None;
3049        if let Some(prompt) = self.prompt.take() {
3050            let mut element = prompt.view.any_view().into_any_element();
3051            let prompt_layout_id = element.request_layout(self, cx);
3052            self.layout_engine
3053                .as_mut()
3054                .unwrap()
3055                .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3056            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3057            prompt_element = Some(element);
3058            self.prompt = Some(prompt);
3059        } else if let Some(active_drag) = cx.active_drag.take() {
3060            let mut element = active_drag.view.clone().into_any_element();
3061            let offset = self.mouse_position() - active_drag.cursor_offset;
3062            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3063            active_drag_element = Some(element);
3064            cx.active_drag = Some(active_drag);
3065        } else {
3066            tooltip_element = self.prepaint_tooltip(cx);
3067        }
3068
3069        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3070
3071        // Now actually paint the elements.
3072        self.invalidator.set_phase(DrawPhase::Paint);
3073        root_element.paint(self, cx);
3074
3075        #[cfg(any(feature = "inspector", debug_assertions))]
3076        self.paint_inspector(inspector_element, cx);
3077
3078        self.paint_deferred_draws(cx);
3079
3080        if let Some(mut prompt_element) = prompt_element {
3081            prompt_element.paint(self, cx);
3082        } else if let Some(mut drag_element) = active_drag_element {
3083            drag_element.paint(self, cx);
3084        } else if let Some(mut tooltip_element) = tooltip_element {
3085            tooltip_element.paint(self, cx);
3086        }
3087
3088        #[cfg(any(feature = "inspector", debug_assertions))]
3089        self.paint_inspector_hitbox(cx);
3090
3091        // a11y may have been activated/deactivated halfway through the frame
3092        let a11y_active_start_of_frame = self.a11y.is_active();
3093        self.a11y.sync_active_flag();
3094        let a11y_active_end_of_frame = self.a11y.is_active();
3095
3096        let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3097
3098        if a11y_active_start_of_frame {
3099            // Harvest frame metadata for the debug dump while the live window
3100            // and frame are still in scope.
3101            let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3102                viewport_size: self.viewport_size,
3103                scale_factor: self.scale_factor,
3104                tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3105            };
3106            // clear the builder state regardless
3107            let tree_update = self.a11y.end_frame(frame_info);
3108
3109            if should_send_a11y_update {
3110                log::debug!(
3111                    "Sending a11y tree update: {} nodes",
3112                    tree_update.nodes.len()
3113                );
3114                self.platform_window.a11y_tree_update(tree_update);
3115            }
3116        }
3117    }
3118
3119    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3120        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
3121        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3122            let Some(Some(tooltip_request)) = self
3123                .next_frame
3124                .tooltip_requests
3125                .get(tooltip_request_index)
3126                .cloned()
3127            else {
3128                log::error!("Unexpectedly absent TooltipRequest");
3129                continue;
3130            };
3131            let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3132            let mouse_position = tooltip_request.tooltip.mouse_position;
3133            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3134
3135            let mut tooltip_bounds =
3136                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3137            let window_bounds = Bounds {
3138                origin: Point::default(),
3139                size: self.viewport_size(),
3140            };
3141
3142            if tooltip_bounds.right() > window_bounds.right() {
3143                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3144                if new_x >= Pixels::ZERO {
3145                    tooltip_bounds.origin.x = new_x;
3146                } else {
3147                    tooltip_bounds.origin.x = cmp::max(
3148                        Pixels::ZERO,
3149                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3150                    );
3151                }
3152            }
3153
3154            if tooltip_bounds.bottom() > window_bounds.bottom() {
3155                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3156                if new_y >= Pixels::ZERO {
3157                    tooltip_bounds.origin.y = new_y;
3158                } else {
3159                    tooltip_bounds.origin.y = cmp::max(
3160                        Pixels::ZERO,
3161                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3162                    );
3163                }
3164            }
3165
3166            // It's possible for an element to have an active tooltip while not being painted (e.g.
3167            // via the `visible_on_hover` method). Since mouse listeners are not active in this
3168            // case, instead update the tooltip's visibility here.
3169            let is_visible =
3170                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3171            if !is_visible {
3172                continue;
3173            }
3174
3175            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3176                element.prepaint(window, cx)
3177            });
3178
3179            self.tooltip_bounds = Some(TooltipBounds {
3180                id: tooltip_request.id,
3181                bounds: tooltip_bounds,
3182            });
3183            return Some(element);
3184        }
3185        None
3186    }
3187
3188    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3189        assert_eq!(self.element_id_stack.len(), 0);
3190
3191        // Process deferred draws in multiple rounds to support nesting.
3192        // Each round processes all current deferred draws, which may push new ones.
3193        //
3194        // The draws are processed in place rather than being moved out of
3195        // `next_frame.deferred_draws`: `prepaint_index` snapshots that vector's
3196        // length, so any prepaint range recorded during a round (view caches,
3197        // nested deferred draws) must index the same vector `reuse_prepaint`
3198        // slices on the next frame. Moving the draws out and re-appending them
3199        // shifts the indices of nested draws, causing reused subtrees to graft
3200        // the wrong deferred draws and panic in the dispatch tree.
3201        let mut round_start = 0;
3202        let mut depth = 0;
3203        loop {
3204            let round_end = self.next_frame.deferred_draws.len();
3205            if round_start == round_end {
3206                break;
3207            }
3208            // Limit maximum nesting depth to prevent infinite loops.
3209            assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3210            depth += 1;
3211
3212            // Sort this round by priority.
3213            let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3214            traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3215
3216            for deferred_draw_ix in traversal_order {
3217                let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3218                    let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3219                    self.element_id_stack
3220                        .clone_from(&deferred_draw.element_id_stack);
3221                    self.text_style_stack
3222                        .clone_from(&deferred_draw.text_style_stack);
3223                    (
3224                        deferred_draw.element.take(),
3225                        deferred_draw.parent_node,
3226                        deferred_draw.current_view,
3227                        deferred_draw.rem_size,
3228                        deferred_draw.absolute_offset,
3229                        deferred_draw.prepaint_range.clone(),
3230                    )
3231                };
3232                self.next_frame.dispatch_tree.set_active_node(parent_node);
3233
3234                let prepaint_start = self.prepaint_index();
3235                if let Some(mut element) = element {
3236                    self.with_rendered_view(current_view, |window| {
3237                        window.with_rem_size(Some(rem_size), |window| {
3238                            window.with_absolute_element_offset(absolute_offset, |window| {
3239                                element.prepaint(window, cx);
3240                            });
3241                        });
3242                    });
3243                    self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3244                } else {
3245                    self.reuse_prepaint(prepaint_range);
3246                }
3247                let prepaint_end = self.prepaint_index();
3248                self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3249                    prepaint_start..prepaint_end;
3250            }
3251
3252            self.element_id_stack.clear();
3253            self.text_style_stack.clear();
3254            round_start = round_end;
3255        }
3256    }
3257
3258    fn paint_deferred_draws(&mut self, cx: &mut App) {
3259        assert_eq!(self.element_id_stack.len(), 0);
3260
3261        // Paint all deferred draws in priority order.
3262        // Since prepaint has already processed nested deferreds, we just paint them all.
3263        if self.next_frame.deferred_draws.len() == 0 {
3264            return;
3265        }
3266
3267        let traversal_order = self.deferred_draw_traversal_order();
3268        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3269        for deferred_draw_ix in traversal_order {
3270            let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3271            self.element_id_stack
3272                .clone_from(&deferred_draw.element_id_stack);
3273            self.next_frame
3274                .dispatch_tree
3275                .set_active_node(deferred_draw.parent_node);
3276
3277            let paint_start = self.paint_index();
3278            let content_mask = deferred_draw.content_mask;
3279            if let Some(element) = deferred_draw.element.as_mut() {
3280                self.with_rendered_view(deferred_draw.current_view, |window| {
3281                    window.with_content_mask(content_mask, |window| {
3282                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3283                            element.paint(window, cx);
3284                        });
3285                    })
3286                })
3287            } else {
3288                self.reuse_paint(deferred_draw.paint_range.clone());
3289            }
3290            let paint_end = self.paint_index();
3291            deferred_draw.paint_range = paint_start..paint_end;
3292        }
3293        self.next_frame.deferred_draws = deferred_draws;
3294        self.element_id_stack.clear();
3295    }
3296
3297    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3298        let deferred_count = self.next_frame.deferred_draws.len();
3299        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3300        sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3301        sorted_indices
3302    }
3303
3304    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3305        PrepaintStateIndex {
3306            hitboxes_index: self.next_frame.hitboxes.len(),
3307            tooltips_index: self.next_frame.tooltip_requests.len(),
3308            deferred_draws_index: self.next_frame.deferred_draws.len(),
3309            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3310            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3311            line_layout_index: self.text_system.layout_index(),
3312        }
3313    }
3314
3315    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3316        self.next_frame.hitboxes.extend(
3317            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3318                .iter()
3319                .cloned(),
3320        );
3321        self.next_frame.tooltip_requests.extend(
3322            self.rendered_frame.tooltip_requests
3323                [range.start.tooltips_index..range.end.tooltips_index]
3324                .iter_mut()
3325                .map(|request| request.take()),
3326        );
3327        self.next_frame.accessed_element_states.extend(
3328            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3329                ..range.end.accessed_element_states_index]
3330                .iter()
3331                .map(|(id, type_id)| (id.clone(), *type_id)),
3332        );
3333        self.text_system
3334            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3335
3336        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3337            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3338            &mut self.rendered_frame.dispatch_tree,
3339            self.focus,
3340        );
3341
3342        if reused_subtree.contains_focus() {
3343            self.next_frame.focus = self.focus;
3344        }
3345
3346        self.next_frame.deferred_draws.extend(
3347            self.rendered_frame.deferred_draws
3348                [range.start.deferred_draws_index..range.end.deferred_draws_index]
3349                .iter()
3350                .map(|deferred_draw| DeferredDraw {
3351                    current_view: deferred_draw.current_view,
3352                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3353                    element_id_stack: deferred_draw.element_id_stack.clone(),
3354                    text_style_stack: deferred_draw.text_style_stack.clone(),
3355                    content_mask: deferred_draw.content_mask,
3356                    rem_size: deferred_draw.rem_size,
3357                    priority: deferred_draw.priority,
3358                    element: None,
3359                    absolute_offset: deferred_draw.absolute_offset,
3360                    prepaint_range: deferred_draw.prepaint_range.clone(),
3361                    paint_range: deferred_draw.paint_range.clone(),
3362                }),
3363        );
3364    }
3365
3366    pub(crate) fn paint_index(&self) -> PaintIndex {
3367        PaintIndex {
3368            scene_index: self.next_frame.scene.len(),
3369            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3370            input_handlers_index: self.next_frame.input_handlers.len(),
3371            cursor_styles_index: self.next_frame.cursor_styles.len(),
3372            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3373            tab_handle_index: self.next_frame.tab_stops.paint_index(),
3374            line_layout_index: self.text_system.layout_index(),
3375        }
3376    }
3377
3378    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3379        self.next_frame.cursor_styles.extend(
3380            self.rendered_frame.cursor_styles
3381                [range.start.cursor_styles_index..range.end.cursor_styles_index]
3382                .iter()
3383                .cloned(),
3384        );
3385        self.next_frame.input_handlers.extend(
3386            self.rendered_frame.input_handlers
3387                [range.start.input_handlers_index..range.end.input_handlers_index]
3388                .iter_mut()
3389                .map(|handler| handler.take()),
3390        );
3391        self.next_frame.mouse_listeners.extend(
3392            self.rendered_frame.mouse_listeners
3393                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3394                .iter_mut()
3395                .map(|listener| listener.take()),
3396        );
3397        self.next_frame.accessed_element_states.extend(
3398            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3399                ..range.end.accessed_element_states_index]
3400                .iter()
3401                .map(|(id, type_id)| (id.clone(), *type_id)),
3402        );
3403        self.next_frame.tab_stops.replay(
3404            &self.rendered_frame.tab_stops.insertion_history
3405                [range.start.tab_handle_index..range.end.tab_handle_index],
3406        );
3407
3408        self.text_system
3409            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3410        self.next_frame.scene.replay(
3411            range.start.scene_index..range.end.scene_index,
3412            &self.rendered_frame.scene,
3413        );
3414    }
3415
3416    /// Push a text style onto the stack, and call a function with that style active.
3417    /// Use [`Window::text_style`] to get the current, combined text style. This method
3418    /// should only be called as part of element drawing.
3419    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3420    where
3421        F: FnOnce(&mut Self) -> R,
3422    {
3423        self.invalidator.debug_assert_paint_or_prepaint();
3424        if let Some(style) = style {
3425            self.text_style_stack.push(style);
3426            let result = f(self);
3427            self.text_style_stack.pop();
3428            result
3429        } else {
3430            f(self)
3431        }
3432    }
3433
3434    /// Updates the cursor style at the platform level. This method should only be called
3435    /// during the paint phase of element drawing.
3436    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3437        self.invalidator.debug_assert_paint();
3438        self.next_frame.cursor_styles.push(CursorStyleRequest {
3439            hitbox_id: Some(hitbox.id),
3440            style,
3441        });
3442    }
3443
3444    /// Updates the cursor style for the entire window at the platform level. A cursor
3445    /// style using this method will have precedence over any cursor style set using
3446    /// `set_cursor_style`. This method should only be called during the paint
3447    /// phase of element drawing.
3448    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3449        self.invalidator.debug_assert_paint();
3450        self.next_frame.cursor_styles.push(CursorStyleRequest {
3451            hitbox_id: None,
3452            style,
3453        })
3454    }
3455
3456    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
3457    /// during the paint phase of element drawing.
3458    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3459        self.invalidator.debug_assert_prepaint();
3460        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3461        self.next_frame
3462            .tooltip_requests
3463            .push(Some(TooltipRequest { id, tooltip }));
3464        id
3465    }
3466
3467    /// Invoke the given function with the given content mask after intersecting it
3468    /// with the current mask. This method should only be called during element drawing.
3469    // This function is called in a highly recursive manner in editor
3470    // prepainting, make sure its inlined to reduce the stack burden
3471    #[inline]
3472    pub fn with_content_mask<R>(
3473        &mut self,
3474        mask: Option<ContentMask<Pixels>>,
3475        f: impl FnOnce(&mut Self) -> R,
3476    ) -> R {
3477        self.invalidator.debug_assert_paint_or_prepaint();
3478        if let Some(mask) = mask {
3479            let mask = mask.intersect(&self.content_mask());
3480            self.content_mask_stack.push(mask);
3481            let result = f(self);
3482            self.content_mask_stack.pop();
3483            result
3484        } else {
3485            f(self)
3486        }
3487    }
3488
3489    /// Updates the global element offset relative to the current offset. This is used to implement
3490    /// scrolling. This method should only be called during the prepaint phase of element drawing.
3491    pub fn with_element_offset<R>(
3492        &mut self,
3493        offset: Point<Pixels>,
3494        f: impl FnOnce(&mut Self) -> R,
3495    ) -> R {
3496        self.invalidator.debug_assert_prepaint();
3497
3498        if offset.is_zero() {
3499            return f(self);
3500        };
3501
3502        let abs_offset = self.element_offset() + offset;
3503        self.with_absolute_element_offset(abs_offset, f)
3504    }
3505
3506    /// Updates the global element offset based on the given offset. This is used to implement
3507    /// drag handles and other manual painting of elements. This method should only be called during
3508    /// the prepaint phase of element drawing.
3509    pub fn with_absolute_element_offset<R>(
3510        &mut self,
3511        offset: Point<Pixels>,
3512        f: impl FnOnce(&mut Self) -> R,
3513    ) -> R {
3514        self.invalidator.debug_assert_prepaint();
3515        self.element_offset_stack.push(offset);
3516        let result = f(self);
3517        self.element_offset_stack.pop();
3518        result
3519    }
3520
3521    pub(crate) fn with_element_opacity<R>(
3522        &mut self,
3523        opacity: Option<f32>,
3524        f: impl FnOnce(&mut Self) -> R,
3525    ) -> R {
3526        self.invalidator.debug_assert_paint_or_prepaint();
3527
3528        let Some(opacity) = opacity else {
3529            return f(self);
3530        };
3531
3532        let previous_opacity = self.element_opacity;
3533        self.element_opacity = previous_opacity * opacity;
3534        let result = f(self);
3535        self.element_opacity = previous_opacity;
3536        result
3537    }
3538
3539    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
3540    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
3541    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
3542    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
3543    /// called during the prepaint phase of element drawing.
3544    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3545        self.invalidator.debug_assert_prepaint();
3546        let index = self.prepaint_index();
3547        let result = f(self);
3548        if result.is_err() {
3549            self.next_frame.hitboxes.truncate(index.hitboxes_index);
3550            self.next_frame
3551                .tooltip_requests
3552                .truncate(index.tooltips_index);
3553            self.next_frame
3554                .deferred_draws
3555                .truncate(index.deferred_draws_index);
3556            self.next_frame
3557                .dispatch_tree
3558                .truncate(index.dispatch_tree_index);
3559            self.next_frame
3560                .accessed_element_states
3561                .truncate(index.accessed_element_states_index);
3562            self.text_system.truncate_layouts(index.line_layout_index);
3563        }
3564        result
3565    }
3566
3567    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
3568    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
3569    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
3570    /// that supports this method being called on the elements it contains. This method should only be
3571    /// called during the prepaint phase of element drawing.
3572    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3573        self.invalidator.debug_assert_prepaint();
3574        self.requested_autoscroll = Some(bounds);
3575    }
3576
3577    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
3578    /// described in [`Self::request_autoscroll`].
3579    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3580        self.invalidator.debug_assert_prepaint();
3581        self.requested_autoscroll.take()
3582    }
3583
3584    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
3585    /// Your view will be re-drawn once the asset has finished loading.
3586    ///
3587    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3588    /// time.
3589    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3590        let (task, is_first) = cx.fetch_asset::<A>(source);
3591        task.clone().now_or_never().or_else(|| {
3592            if is_first {
3593                let entity_id = self.current_view();
3594                self.spawn(cx, {
3595                    let task = task.clone();
3596                    async move |cx| {
3597                        task.await;
3598
3599                        cx.on_next_frame(move |_, cx| {
3600                            cx.notify(entity_id);
3601                        });
3602                    }
3603                })
3604                .detach();
3605            }
3606
3607            None
3608        })
3609    }
3610
3611    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
3612    /// Your view will not be re-drawn once the asset has finished loading.
3613    ///
3614    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3615    /// time.
3616    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3617        let (task, _) = cx.fetch_asset::<A>(source);
3618        task.now_or_never()
3619    }
3620    /// Obtain the current element offset. This method should only be called during the
3621    /// prepaint phase of element drawing.
3622    pub fn element_offset(&self) -> Point<Pixels> {
3623        self.invalidator.debug_assert_prepaint();
3624        self.element_offset_stack
3625            .last()
3626            .copied()
3627            .unwrap_or_default()
3628    }
3629
3630    /// Obtain the current element opacity. This method should only be called during the
3631    /// prepaint phase of element drawing.
3632    #[inline]
3633    pub(crate) fn element_opacity(&self) -> f32 {
3634        self.invalidator.debug_assert_paint_or_prepaint();
3635        self.element_opacity
3636    }
3637
3638    /// Obtain the current content mask. This method should only be called during element drawing.
3639    pub fn content_mask(&self) -> ContentMask<Pixels> {
3640        self.invalidator.debug_assert_paint_or_prepaint();
3641        self.content_mask_stack
3642            .last()
3643            .cloned()
3644            .unwrap_or_else(|| ContentMask {
3645                bounds: Bounds {
3646                    origin: Point::default(),
3647                    size: self.viewport_size,
3648                },
3649            })
3650    }
3651
3652    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
3653    /// This can be used within a custom element to distinguish multiple sets of child elements.
3654    pub fn with_element_namespace<R>(
3655        &mut self,
3656        element_id: impl Into<ElementId>,
3657        f: impl FnOnce(&mut Self) -> R,
3658    ) -> R {
3659        self.element_id_stack.push(element_id.into());
3660        let result = f(self);
3661        self.element_id_stack.pop();
3662        result
3663    }
3664
3665    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
3666    pub fn use_keyed_state<S: 'static>(
3667        &mut self,
3668        key: impl Into<ElementId>,
3669        cx: &mut App,
3670        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3671    ) -> Entity<S> {
3672        let current_view = self.current_view();
3673        self.with_global_id(key.into(), |global_id, window| {
3674            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3675                if let Some(state) = state {
3676                    (state.clone(), state)
3677                } else {
3678                    let new_state = cx.new(|cx| init(window, cx));
3679                    cx.observe(&new_state, move |_, cx| {
3680                        cx.notify(current_view);
3681                    })
3682                    .detach();
3683                    (new_state.clone(), new_state)
3684                }
3685            })
3686        })
3687    }
3688
3689    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
3690    ///
3691    /// NOTE: This method uses the location of the caller to generate an ID for this state.
3692    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
3693    ///       you can provide a custom ElementID using the `use_keyed_state` method.
3694    #[track_caller]
3695    pub fn use_state<S: 'static>(
3696        &mut self,
3697        cx: &mut App,
3698        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3699    ) -> Entity<S> {
3700        self.use_keyed_state(
3701            ElementId::CodeLocation(*core::panic::Location::caller()),
3702            cx,
3703            init,
3704        )
3705    }
3706
3707    /// Updates or initializes state for an element with the given id that lives across multiple
3708    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
3709    /// to the given closure. The state returned by the closure will be stored so it can be referenced
3710    /// when drawing the next frame. This method should only be called as part of element drawing.
3711    pub fn with_element_state<S, R>(
3712        &mut self,
3713        global_id: &GlobalElementId,
3714        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3715    ) -> R
3716    where
3717        S: 'static,
3718    {
3719        self.invalidator.debug_assert_paint_or_prepaint();
3720
3721        let key = (global_id.clone(), TypeId::of::<S>());
3722        self.next_frame.accessed_element_states.push(key.clone());
3723
3724        if let Some(any) = self
3725            .next_frame
3726            .element_states
3727            .remove(&key)
3728            .or_else(|| self.rendered_frame.element_states.remove(&key))
3729        {
3730            let ElementStateBox {
3731                inner,
3732                #[cfg(debug_assertions)]
3733                type_name,
3734            } = any;
3735            // Using the extra inner option to avoid needing to reallocate a new box.
3736            let mut state_box = inner
3737                .downcast::<Option<S>>()
3738                .map_err(|_| {
3739                    #[cfg(debug_assertions)]
3740                    {
3741                        anyhow::anyhow!(
3742                            "invalid element state type for id, requested {:?}, actual: {:?}",
3743                            std::any::type_name::<S>(),
3744                            type_name
3745                        )
3746                    }
3747
3748                    #[cfg(not(debug_assertions))]
3749                    {
3750                        anyhow::anyhow!(
3751                            "invalid element state type for id, requested {:?}",
3752                            std::any::type_name::<S>(),
3753                        )
3754                    }
3755                })
3756                .unwrap();
3757
3758            let state = state_box.take().expect(
3759                "reentrant call to with_element_state for the same state type and element id",
3760            );
3761            let (result, state) = f(Some(state), self);
3762            state_box.replace(state);
3763            self.next_frame.element_states.insert(
3764                key,
3765                ElementStateBox {
3766                    inner: state_box,
3767                    #[cfg(debug_assertions)]
3768                    type_name,
3769                },
3770            );
3771            result
3772        } else {
3773            let (result, state) = f(None, self);
3774            self.next_frame.element_states.insert(
3775                key,
3776                ElementStateBox {
3777                    inner: Box::new(Some(state)),
3778                    #[cfg(debug_assertions)]
3779                    type_name: std::any::type_name::<S>(),
3780                },
3781            );
3782            result
3783        }
3784    }
3785
3786    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
3787    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
3788    /// when the element is guaranteed to have an id.
3789    ///
3790    /// The first option means 'no ID provided'
3791    /// The second option means 'not yet initialized'
3792    pub fn with_optional_element_state<S, R>(
3793        &mut self,
3794        global_id: Option<&GlobalElementId>,
3795        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3796    ) -> R
3797    where
3798        S: 'static,
3799    {
3800        self.invalidator.debug_assert_paint_or_prepaint();
3801
3802        if let Some(global_id) = global_id {
3803            self.with_element_state(global_id, |state, cx| {
3804                let (result, state) = f(Some(state), cx);
3805                let state =
3806                    state.expect("you must return some state when you pass some element id");
3807                (result, state)
3808            })
3809        } else {
3810            let (result, state) = f(None, self);
3811            debug_assert!(
3812                state.is_none(),
3813                "you must not return an element state when passing None for the global id"
3814            );
3815            result
3816        }
3817    }
3818
3819    /// Executes the given closure within the context of a tab group.
3820    #[inline]
3821    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3822        if let Some(index) = index {
3823            self.next_frame.tab_stops.begin_group(index);
3824            let result = f(self);
3825            self.next_frame.tab_stops.end_group();
3826            result
3827        } else {
3828            f(self)
3829        }
3830    }
3831
3832    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
3833    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3834    /// with higher values being drawn on top.
3835    ///
3836    /// When `content_mask` is provided, the deferred element will be clipped to that region during
3837    /// both prepaint and paint. When `None`, no additional clipping is applied.
3838    ///
3839    /// This method should only be called as part of the prepaint phase of element drawing.
3840    pub fn defer_draw(
3841        &mut self,
3842        element: AnyElement,
3843        absolute_offset: Point<Pixels>,
3844        priority: usize,
3845        content_mask: Option<ContentMask<Pixels>>,
3846    ) {
3847        self.invalidator.debug_assert_prepaint();
3848        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3849        self.next_frame.deferred_draws.push(DeferredDraw {
3850            current_view: self.current_view(),
3851            parent_node,
3852            element_id_stack: self.element_id_stack.clone(),
3853            text_style_stack: self.text_style_stack.clone(),
3854            content_mask,
3855            rem_size: self.rem_size(),
3856            priority,
3857            element: Some(element),
3858            absolute_offset,
3859            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3860            paint_range: PaintIndex::default()..PaintIndex::default(),
3861        });
3862    }
3863
3864    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3865    /// of geometry that are non-overlapping and have the same draw order. This is typically used
3866    /// for performance reasons.
3867    ///
3868    /// This method should only be called as part of the paint phase of element drawing.
3869    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3870        self.invalidator.debug_assert_paint();
3871
3872        let content_mask = self.content_mask();
3873        let clipped_bounds = bounds.intersect(&content_mask.bounds);
3874        if !clipped_bounds.is_empty() {
3875            self.next_frame
3876                .scene
3877                .push_layer(self.cover_bounds(clipped_bounds));
3878        }
3879
3880        let result = f(self);
3881
3882        if !clipped_bounds.is_empty() {
3883            self.next_frame.scene.pop_layer();
3884        }
3885
3886        result
3887    }
3888
3889    /// Paint the drop (non-inset) shadows from `shadows` into the scene at the current
3890    /// z-index. Inset shadows are skipped; paint those with [`Self::paint_inset_shadows`]
3891    /// after the element's background so they layer on top of the fill.
3892    ///
3893    /// This method should only be called as part of the paint phase of element drawing.
3894    pub fn paint_drop_shadows(
3895        &mut self,
3896        bounds: Bounds<Pixels>,
3897        corner_radii: Corners<Pixels>,
3898        shadows: &[BoxShadow],
3899    ) {
3900        self.invalidator.debug_assert_paint();
3901
3902        let scale_factor = self.scale_factor();
3903        let content_mask = self.snapped_content_mask();
3904        let opacity = self.element_opacity();
3905        let element_bounds = self.cover_bounds(bounds);
3906        let element_corner_radii = corner_radii.scale(scale_factor);
3907        for shadow in shadows {
3908            if shadow.inset {
3909                continue;
3910            }
3911            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3912            self.next_frame.scene.insert_primitive(Shadow {
3913                order: 0,
3914                blur_radius: shadow.blur_radius.scale(scale_factor),
3915                bounds: self.cover_bounds(shadow_bounds),
3916                content_mask,
3917                corner_radii: corner_radii.scale(scale_factor),
3918                color: shadow.color.opacity(opacity),
3919                element_bounds,
3920                element_corner_radii,
3921                inset: 0,
3922                pad: 0,
3923            });
3924        }
3925    }
3926
3927    /// Paint the inset shadows from `shadows` into the scene at the current z-index. Should
3928    /// be called after the element's background so the shadow layers on top of the fill.
3929    /// Drop shadows are skipped; paint those with [`Self::paint_drop_shadows`] before the background.
3930    pub fn paint_inset_shadows(
3931        &mut self,
3932        bounds: Bounds<Pixels>,
3933        corner_radii: Corners<Pixels>,
3934        shadows: &[BoxShadow],
3935    ) {
3936        self.invalidator.debug_assert_paint();
3937
3938        let scale_factor = self.scale_factor();
3939        let content_mask = self.snapped_content_mask();
3940        let opacity = self.element_opacity();
3941        let element_bounds = self.cover_bounds(bounds);
3942        let element_corner_radii = corner_radii.scale(scale_factor);
3943        for shadow in shadows {
3944            if !shadow.inset {
3945                continue;
3946            }
3947            let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
3948            // Clamp at zero so a large spread can't produce negative radii, which would
3949            // break the SDF in the shader.
3950            let zero = Pixels::ZERO;
3951            let hole_corner_radii = Corners {
3952                top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
3953                top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
3954                bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
3955                bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
3956            };
3957            self.next_frame.scene.insert_primitive(Shadow {
3958                order: 0,
3959                blur_radius: shadow.blur_radius.scale(scale_factor),
3960                bounds: self.cover_bounds(hole),
3961                content_mask,
3962                corner_radii: hole_corner_radii.scale(scale_factor),
3963                color: shadow.color.opacity(opacity),
3964                element_bounds,
3965                element_corner_radii,
3966                inset: 1,
3967                pad: 0,
3968            });
3969        }
3970    }
3971
3972    /// Paint one or more quads into the scene for the next frame at the current stacking context.
3973    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3974    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3975    ///
3976    /// This method should only be called as part of the paint phase of element drawing.
3977    ///
3978    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3979    /// where the circular arcs meet. This will not display well when combined with dashed borders.
3980    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3981    pub fn paint_quad(&mut self, quad: PaintQuad) {
3982        self.invalidator.debug_assert_paint();
3983
3984        let opacity = self.element_opacity();
3985        let snapped_bounds = self.snap_bounds(quad.bounds);
3986        let snapped_border_widths = self.snap_border_widths(quad.border_widths);
3987        let quad = Quad {
3988            order: 0,
3989            bounds: snapped_bounds,
3990            content_mask: self.snapped_content_mask(),
3991            background: quad.background.opacity(opacity),
3992            border_color: quad.border_color.opacity(opacity),
3993            corner_radii: quad.corner_radii.scale(self.scale_factor()),
3994            border_widths: snapped_border_widths,
3995            border_style: quad.border_style,
3996        };
3997
3998        if !quad.background.is_transparent() {
3999            self.next_frame.scene.insert_primitive(quad);
4000            return;
4001        }
4002
4003        // We're drawing a quad with a border but no fill color. Painting this quad would run the quad shader for every
4004        // transparent interior pixel, which is especially costly when the quad is large.
4005        // Instead, split it into four non-overlapping strips that cover the regions where borders are painted:
4006        // the side strips own the straight left and right edges, while the top and bottom strips own the horizontal
4007        // edges and the rounded corners.
4008        let radii = &quad.corner_radii;
4009        let widths = &quad.border_widths;
4010
4011        let antialias_slack = point(ScaledPixels(1.0), ScaledPixels(1.0));
4012        let top_left_inset = point(
4013            widths.left,
4014            widths.top.max(radii.top_left).max(radii.top_right),
4015        ) + antialias_slack;
4016        let bottom_right_inset = point(
4017            widths.right,
4018            widths.bottom.max(radii.bottom_left).max(radii.bottom_right),
4019        ) + antialias_slack;
4020
4021        let outer_bounds = quad.bounds;
4022        let inner_bounds = Bounds::from_corners(
4023            outer_bounds.origin + top_left_inset,
4024            outer_bounds.bottom_right() - bottom_right_inset,
4025        );
4026
4027        if inner_bounds.is_empty() {
4028            self.next_frame.scene.insert_primitive(quad);
4029            return;
4030        }
4031
4032        let strips = [
4033            // Top
4034            Bounds::from_corners(
4035                outer_bounds.origin,
4036                point(outer_bounds.right(), inner_bounds.top()),
4037            ),
4038            // Bottom
4039            Bounds::from_corners(
4040                point(outer_bounds.left(), inner_bounds.bottom()),
4041                outer_bounds.bottom_right(),
4042            ),
4043            // Left
4044            Bounds::from_corners(
4045                point(outer_bounds.left(), inner_bounds.top()),
4046                inner_bounds.bottom_left(),
4047            ),
4048            // Right
4049            Bounds::from_corners(
4050                inner_bounds.top_right(),
4051                point(outer_bounds.right(), inner_bounds.bottom()),
4052            ),
4053        ];
4054
4055        for strip in strips {
4056            let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4057            if !content_mask_bounds.is_empty() {
4058                self.next_frame.scene.insert_primitive(Quad {
4059                    content_mask: ContentMask {
4060                        bounds: content_mask_bounds,
4061                    },
4062                    ..quad
4063                });
4064            }
4065        }
4066    }
4067
4068    /// Paint the given `Path` into the scene for the next frame at the current z-index.
4069    ///
4070    /// This method should only be called as part of the paint phase of element drawing.
4071    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4072        self.invalidator.debug_assert_paint();
4073
4074        let scale_factor = self.scale_factor();
4075        let content_mask = self.content_mask();
4076        let opacity = self.element_opacity();
4077        path.content_mask = content_mask;
4078        let color: Background = color.into();
4079        path.color = color.opacity(opacity);
4080        self.next_frame
4081            .scene
4082            .insert_primitive(path.scale(scale_factor));
4083    }
4084
4085    /// Paint an underline into the scene for the next frame at the current z-index.
4086    ///
4087    /// This method should only be called as part of the paint phase of element drawing.
4088    pub fn paint_underline(
4089        &mut self,
4090        origin: Point<Pixels>,
4091        width: Pixels,
4092        style: &UnderlineStyle,
4093    ) {
4094        self.invalidator.debug_assert_paint();
4095
4096        let scale_factor = self.scale_factor();
4097        let thickness = self.snap_stroke(style.thickness);
4098        let height = if style.wavy {
4099            ScaledPixels(thickness.0 * 3.)
4100        } else {
4101            thickness
4102        };
4103        let bounds = Bounds {
4104            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4105            size: size(self.snap_stroke(width), height),
4106        };
4107        let element_opacity = self.element_opacity();
4108
4109        self.next_frame.scene.insert_primitive(Underline {
4110            order: 0,
4111            pad: 0,
4112            bounds,
4113            content_mask: self.snapped_content_mask(),
4114            color: style.color.unwrap_or_default().opacity(element_opacity),
4115            thickness,
4116            wavy: style.wavy.into(),
4117        });
4118    }
4119
4120    /// Paint a strikethrough into the scene for the next frame at the current z-index.
4121    ///
4122    /// This method should only be called as part of the paint phase of element drawing.
4123    pub fn paint_strikethrough(
4124        &mut self,
4125        origin: Point<Pixels>,
4126        width: Pixels,
4127        style: &StrikethroughStyle,
4128    ) {
4129        self.invalidator.debug_assert_paint();
4130
4131        let scale_factor = self.scale_factor();
4132        let height = style.thickness;
4133        let bounds = Bounds {
4134            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4135            size: size(self.snap_stroke(width), self.snap_stroke(height)),
4136        };
4137        let opacity = self.element_opacity();
4138
4139        self.next_frame.scene.insert_primitive(Underline {
4140            order: 0,
4141            pad: 0,
4142            bounds,
4143            content_mask: self.snapped_content_mask(),
4144            thickness: self.snap_stroke(style.thickness),
4145            color: style.color.unwrap_or_default().opacity(opacity),
4146            wavy: false.into(),
4147        });
4148    }
4149
4150    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
4151    ///
4152    /// The y component of the origin is the baseline of the glyph.
4153    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
4154    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
4155    /// This method is only useful if you need to paint a single glyph that has already been shaped.
4156    ///
4157    /// This method should only be called as part of the paint phase of element drawing.
4158    pub fn paint_glyph(
4159        &mut self,
4160        origin: Point<Pixels>,
4161        font_id: FontId,
4162        glyph_id: GlyphId,
4163        font_size: Pixels,
4164        color: Hsla,
4165    ) -> Result<()> {
4166        self.invalidator.debug_assert_paint();
4167
4168        let element_opacity = self.element_opacity();
4169        let scale_factor = self.scale_factor();
4170        let glyph_origin = origin.scale(scale_factor);
4171
4172        let quantized_origin = Point::new(
4173            round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
4174                / SUBPIXEL_VARIANTS_X as f32,
4175            round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
4176                / SUBPIXEL_VARIANTS_Y as f32,
4177        );
4178        let subpixel_variant = Point::new(
4179            (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
4180            (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
4181        );
4182        let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
4183        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4184        let dilation = self.text_system().glyph_dilation_for_color(color);
4185        let params = RenderGlyphParams {
4186            font_id,
4187            glyph_id,
4188            font_size,
4189            subpixel_variant,
4190            scale_factor,
4191            is_emoji: false,
4192            subpixel_rendering,
4193            dilation,
4194        };
4195
4196        let raster_bounds = self.text_system().raster_bounds(&params)?;
4197        if !raster_bounds.is_zero() {
4198            let tile = self
4199                .sprite_atlas
4200                .get_or_insert_with(&params.clone().into(), &mut || {
4201                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
4202                    Ok(Some((size, Cow::Owned(bytes))))
4203                })?
4204                .expect("Callback above only errors or returns Some");
4205            let bounds = Bounds {
4206                origin: integer_origin + raster_bounds.origin.map(Into::into),
4207                size: tile.bounds.size.map(Into::into),
4208            };
4209            let content_mask = self.snapped_content_mask();
4210
4211            if subpixel_rendering {
4212                self.next_frame.scene.insert_primitive(SubpixelSprite {
4213                    order: 0,
4214                    pad: 0,
4215                    bounds,
4216                    content_mask,
4217                    color: color.opacity(element_opacity),
4218                    tile,
4219                    transformation: TransformationMatrix::unit(),
4220                });
4221            } else {
4222                self.next_frame.scene.insert_primitive(MonochromeSprite {
4223                    order: 0,
4224                    pad: 0,
4225                    bounds,
4226                    content_mask,
4227                    color: color.opacity(element_opacity),
4228                    tile,
4229                    transformation: TransformationMatrix::unit(),
4230                });
4231            }
4232        }
4233        Ok(())
4234    }
4235
4236    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4237        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4238            return false;
4239        }
4240
4241        if !self.platform_window.is_subpixel_rendering_supported() {
4242            return false;
4243        }
4244
4245        let mode = match self.text_rendering_mode.get() {
4246            TextRenderingMode::PlatformDefault => self
4247                .text_system()
4248                .recommended_rendering_mode(font_id, font_size),
4249            mode => mode,
4250        };
4251
4252        mode == TextRenderingMode::Subpixel
4253    }
4254
4255    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
4256    ///
4257    /// The y component of the origin is the baseline of the glyph.
4258    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
4259    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
4260    /// This method is only useful if you need to paint a single emoji that has already been shaped.
4261    ///
4262    /// This method should only be called as part of the paint phase of element drawing.
4263    pub fn paint_emoji(
4264        &mut self,
4265        origin: Point<Pixels>,
4266        font_id: FontId,
4267        glyph_id: GlyphId,
4268        font_size: Pixels,
4269    ) -> Result<()> {
4270        self.invalidator.debug_assert_paint();
4271
4272        let scale_factor = self.scale_factor();
4273        let glyph_origin = origin.scale(scale_factor);
4274        let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
4275        let params = RenderGlyphParams {
4276            font_id,
4277            glyph_id,
4278            font_size,
4279            subpixel_variant: Default::default(),
4280            scale_factor,
4281            is_emoji: true,
4282            subpixel_rendering: false,
4283            dilation: 0,
4284        };
4285
4286        let raster_bounds = self.text_system().raster_bounds(&params)?;
4287        if !raster_bounds.is_zero() {
4288            let tile = self
4289                .sprite_atlas
4290                .get_or_insert_with(&params.clone().into(), &mut || {
4291                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
4292                    Ok(Some((size, Cow::Owned(bytes))))
4293                })?
4294                .expect("Callback above only errors or returns Some");
4295
4296            let bounds = Bounds {
4297                origin: integer_origin + raster_bounds.origin.map(Into::into),
4298                size: tile.bounds.size.map(Into::into),
4299            };
4300            let content_mask = self.snapped_content_mask();
4301            let opacity = self.element_opacity();
4302
4303            self.next_frame.scene.insert_primitive(PolychromeSprite {
4304                order: 0,
4305                pad: 0,
4306                grayscale: false.into(),
4307                bounds,
4308                corner_radii: Default::default(),
4309                content_mask,
4310                tile,
4311                opacity,
4312            });
4313        }
4314        Ok(())
4315    }
4316
4317    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
4318    ///
4319    /// This method should only be called as part of the paint phase of element drawing.
4320    pub fn paint_svg(
4321        &mut self,
4322        bounds: Bounds<Pixels>,
4323        path: SharedString,
4324        mut data: Option<&[u8]>,
4325        transformation: TransformationMatrix,
4326        color: Hsla,
4327        cx: &App,
4328    ) -> Result<()> {
4329        self.invalidator.debug_assert_paint();
4330
4331        let element_opacity = self.element_opacity();
4332        let bounds = self.snap_bounds(bounds);
4333
4334        let params = RenderSvgParams {
4335            path,
4336            size: bounds.size.map(|pixels| {
4337                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
4338            }),
4339        };
4340
4341        let Some(tile) =
4342            self.sprite_atlas
4343                .get_or_insert_with(&params.clone().into(), &mut || {
4344                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
4345                    else {
4346                        return Ok(None);
4347                    };
4348                    Ok(Some((size, Cow::Owned(bytes))))
4349                })?
4350        else {
4351            return Ok(());
4352        };
4353        let content_mask = self.snapped_content_mask();
4354        let svg_bounds = Bounds {
4355            origin: bounds.center()
4356                - Point::new(
4357                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4358                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4359                ),
4360            size: tile
4361                .bounds
4362                .size
4363                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4364        };
4365        let final_bounds = svg_bounds
4366            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4367            .map_size(|size| size.ceil());
4368
4369        self.next_frame.scene.insert_primitive(MonochromeSprite {
4370            order: 0,
4371            pad: 0,
4372            bounds: final_bounds,
4373            content_mask,
4374            color: color.opacity(element_opacity),
4375            tile,
4376            transformation,
4377        });
4378
4379        Ok(())
4380    }
4381
4382    /// Paint an image into the scene for the next frame at the current z-index.
4383    /// This method will panic if the frame_index is not valid
4384    ///
4385    /// This method should only be called as part of the paint phase of element drawing.
4386    /// Paint an image into `bounds`, positioning and scaling it according to `image_bounds`.
4387    ///
4388    /// The visible region rendered is `bounds.intersect(&image_bounds)`, with `corner_radii`
4389    /// applied to `bounds`.
4390    pub fn paint_image(
4391        &mut self,
4392        bounds: Bounds<Pixels>,
4393        image_bounds: Bounds<Pixels>,
4394        corner_radii: Corners<Pixels>,
4395        data: Arc<RenderImage>,
4396        frame_index: usize,
4397        grayscale: bool,
4398    ) -> Result<()> {
4399        self.invalidator.debug_assert_paint();
4400
4401        let visible_bounds = bounds.intersect(&image_bounds);
4402        if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
4403            return Ok(());
4404        }
4405        if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
4406            return Ok(());
4407        }
4408
4409        let params = RenderImageParams {
4410            image_id: data.id,
4411            frame_index,
4412        };
4413
4414        let tile = self
4415            .sprite_atlas
4416            .get_or_insert_with(&params.into(), &mut || {
4417                Ok(Some((
4418                    data.size(frame_index),
4419                    Cow::Borrowed(
4420                        data.as_bytes(frame_index)
4421                            .expect("It's the caller's job to pass a valid frame index"),
4422                    ),
4423                )))
4424            })?
4425            .expect("Callback above only returns Some");
4426
4427        let visible_bounds_snapped = self.snap_bounds(visible_bounds);
4428
4429        let sub_tile = if visible_bounds == image_bounds {
4430            tile
4431        } else {
4432            let x_offset_ratio =
4433                (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
4434            let y_offset_ratio =
4435                (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
4436            let width_ratio = visible_bounds.size.width / image_bounds.size.width;
4437            let height_ratio = visible_bounds.size.height / image_bounds.size.height;
4438
4439            let tile_origin_x = tile.bounds.origin.x.0;
4440            let tile_origin_y = tile.bounds.origin.y.0;
4441            let tile_width = tile.bounds.size.width.0;
4442            let tile_height = tile.bounds.size.height.0;
4443
4444            let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
4445            let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
4446            let sub_width = (width_ratio * tile_width as f32).round() as i32;
4447            let sub_height = (height_ratio * tile_height as f32).round() as i32;
4448
4449            let max_x = tile_origin_x + tile_width;
4450            let max_y = tile_origin_y + tile_height;
4451
4452            let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
4453            let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
4454            let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
4455            let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
4456
4457            AtlasTile {
4458                bounds: Bounds {
4459                    origin: point(
4460                        DevicePixels(clamped_origin_x),
4461                        DevicePixels(clamped_origin_y),
4462                    ),
4463                    size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
4464                },
4465                ..tile
4466            }
4467        };
4468
4469        let content_mask = self.snapped_content_mask();
4470        let corner_radii = corner_radii
4471            .clamp_radii_for_quad_size(visible_bounds.size)
4472            .scale(self.scale_factor());
4473        let opacity = self.element_opacity();
4474
4475        self.next_frame.scene.insert_primitive(PolychromeSprite {
4476            order: 0,
4477            pad: 0,
4478            grayscale: grayscale.into(),
4479            bounds: visible_bounds_snapped,
4480            content_mask,
4481            corner_radii,
4482            tile: sub_tile,
4483            opacity,
4484        });
4485        Ok(())
4486    }
4487
4488    /// Paint a surface into the scene for the next frame at the current z-index.
4489    ///
4490    /// This method should only be called as part of the paint phase of element drawing.
4491    #[cfg(target_os = "macos")]
4492    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
4493        use crate::PaintSurface;
4494
4495        self.invalidator.debug_assert_paint();
4496
4497        let bounds = self.snap_bounds(bounds);
4498        let content_mask = self.snapped_content_mask();
4499        self.next_frame.scene.insert_primitive(PaintSurface {
4500            order: 0,
4501            bounds,
4502            content_mask,
4503            image_buffer,
4504        });
4505    }
4506
4507    /// Removes an image from the sprite atlas.
4508    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
4509        for frame_index in 0..data.frame_count() {
4510            let params = RenderImageParams {
4511                image_id: data.id,
4512                frame_index,
4513            };
4514
4515            self.sprite_atlas.remove(&params.clone().into());
4516        }
4517
4518        Ok(())
4519    }
4520
4521    /// Returns whether every frame of an image is present in the sprite atlas.
4522    #[cfg(any(test, feature = "test-support"))]
4523    pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
4524        data.frame_count() > 0
4525            && (0..data.frame_count()).all(|frame_index| {
4526                self.sprite_atlas.contains(
4527                    &RenderImageParams {
4528                        image_id: data.id,
4529                        frame_index,
4530                    }
4531                    .into(),
4532                )
4533            })
4534    }
4535
4536    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
4537    /// layout is being requested, along with the layout ids of any children. This method is called during
4538    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
4539    ///
4540    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
4541    #[must_use]
4542    pub fn request_layout(
4543        &mut self,
4544        style: Style,
4545        children: impl IntoIterator<Item = LayoutId>,
4546        cx: &mut App,
4547    ) -> LayoutId {
4548        self.invalidator.debug_assert_prepaint();
4549
4550        cx.layout_id_buffer.clear();
4551        cx.layout_id_buffer.extend(children);
4552        let rem_size = self.rem_size();
4553        let scale_factor = self.scale_factor();
4554
4555        self.layout_engine.as_mut().unwrap().request_layout(
4556            style,
4557            rem_size,
4558            scale_factor,
4559            &cx.layout_id_buffer,
4560        )
4561    }
4562
4563    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
4564    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
4565    /// determine the element's size. One place this is used internally is when measuring text.
4566    ///
4567    /// The given closure is invoked at layout time with the known dimensions and available space and
4568    /// returns a `Size`.
4569    ///
4570    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
4571    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
4572    where
4573        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
4574            + 'static,
4575    {
4576        self.invalidator.debug_assert_prepaint();
4577
4578        let rem_size = self.rem_size();
4579        let scale_factor = self.scale_factor();
4580        self.layout_engine
4581            .as_mut()
4582            .unwrap()
4583            .request_measured_layout(style, rem_size, scale_factor, measure)
4584    }
4585
4586    /// Compute the layout for the given id within the given available space.
4587    /// This method is called for its side effect, typically by the framework prior to painting.
4588    /// After calling it, you can request the bounds of the given layout node id or any descendant.
4589    ///
4590    /// This method should only be called as part of the prepaint phase of element drawing.
4591    pub fn compute_layout(
4592        &mut self,
4593        layout_id: LayoutId,
4594        available_space: Size<AvailableSpace>,
4595        cx: &mut App,
4596    ) {
4597        self.invalidator.debug_assert_prepaint();
4598
4599        let mut layout_engine = self.layout_engine.take().unwrap();
4600        layout_engine.compute_layout(layout_id, available_space, self, cx);
4601        self.layout_engine = Some(layout_engine);
4602    }
4603
4604    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
4605    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
4606    ///
4607    /// This method should only be called as part of element drawing.
4608    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
4609        self.invalidator.debug_assert_prepaint();
4610
4611        let scale_factor = self.scale_factor();
4612        let mut bounds = self
4613            .layout_engine
4614            .as_mut()
4615            .unwrap()
4616            .layout_bounds(layout_id, scale_factor)
4617            .map(Into::into);
4618        let snapped_offset = self.pixel_snap_point(self.element_offset());
4619        bounds.origin += snapped_offset;
4620        bounds
4621    }
4622
4623    /// This method should be called during `prepaint`. You can use
4624    /// the returned [Hitbox] during `paint` or in an event handler
4625    /// to determine whether the inserted hitbox was the topmost.
4626    ///
4627    /// This method should only be called as part of the prepaint phase of element drawing.
4628    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
4629        self.invalidator.debug_assert_prepaint();
4630
4631        let content_mask = self.content_mask();
4632        let mut id = self.next_hitbox_id;
4633        self.next_hitbox_id = self.next_hitbox_id.next();
4634        let hitbox = Hitbox {
4635            id,
4636            bounds,
4637            content_mask,
4638            behavior,
4639        };
4640        self.next_frame.hitboxes.push(hitbox.clone());
4641        hitbox
4642    }
4643
4644    /// Set a hitbox which will act as a control area of the platform window.
4645    ///
4646    /// This method should only be called as part of the paint phase of element drawing.
4647    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
4648        self.invalidator.debug_assert_paint();
4649        self.next_frame.window_control_hitboxes.push((area, hitbox));
4650    }
4651
4652    /// Sets the key context for the current element. This context will be used to translate
4653    /// keybindings into actions.
4654    ///
4655    /// This method should only be called as part of the paint phase of element drawing.
4656    pub fn set_key_context(&mut self, context: KeyContext) {
4657        self.invalidator.debug_assert_paint();
4658        self.next_frame.dispatch_tree.set_key_context(context);
4659    }
4660
4661    /// Sets the focus handle for the current element. This handle will be used to manage focus state
4662    /// and keyboard event dispatch for the element.
4663    ///
4664    /// This method should only be called as part of the prepaint phase of element drawing.
4665    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4666        self.invalidator.debug_assert_prepaint();
4667        if focus_handle.is_focused(self) {
4668            self.next_frame.focus = Some(focus_handle.id);
4669        }
4670        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4671    }
4672
4673    /// Sets the view id for the current element, which will be used to manage view caching.
4674    ///
4675    /// This method should only be called as part of element prepaint. We plan on removing this
4676    /// method eventually when we solve some issues that require us to construct editor elements
4677    /// directly instead of always using editors via views.
4678    pub fn set_view_id(&mut self, view_id: EntityId) {
4679        self.invalidator.debug_assert_prepaint();
4680        self.next_frame.dispatch_tree.set_view_id(view_id);
4681    }
4682
4683    /// Get the entity ID for the currently rendering view
4684    pub fn current_view(&self) -> EntityId {
4685        self.invalidator.debug_assert_paint_or_prepaint();
4686        self.rendered_entity_stack.last().copied().unwrap()
4687    }
4688
4689    #[inline]
4690    pub(crate) fn with_rendered_view<R>(
4691        &mut self,
4692        id: EntityId,
4693        f: impl FnOnce(&mut Self) -> R,
4694    ) -> R {
4695        self.rendered_entity_stack.push(id);
4696        let result = f(self);
4697        self.rendered_entity_stack.pop();
4698        result
4699    }
4700
4701    /// Executes the provided function with the specified image cache.
4702    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4703    where
4704        F: FnOnce(&mut Self) -> R,
4705    {
4706        if let Some(image_cache) = image_cache {
4707            self.image_cache_stack.push(image_cache);
4708            let result = f(self);
4709            self.image_cache_stack.pop();
4710            result
4711        } else {
4712            f(self)
4713        }
4714    }
4715
4716    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
4717    /// platform to receive textual input with proper integration with concerns such
4718    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
4719    /// rendered.
4720    ///
4721    /// This method should only be called as part of the paint phase of element drawing.
4722    ///
4723    /// [element_input_handler]: crate::ElementInputHandler
4724    pub fn handle_input(
4725        &mut self,
4726        focus_handle: &FocusHandle,
4727        input_handler: impl InputHandler,
4728        cx: &App,
4729    ) {
4730        self.invalidator.debug_assert_paint();
4731
4732        if focus_handle.is_focused(self) {
4733            let cx = self.to_async(cx);
4734            self.next_frame
4735                .input_handlers
4736                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
4737        }
4738    }
4739
4740    /// Register a mouse event listener on the window for the next frame. The type of event
4741    /// is determined by the first parameter of the given listener. When the next frame is rendered
4742    /// the listener will be cleared.
4743    ///
4744    /// This method should only be called as part of the paint phase of element drawing.
4745    pub fn on_mouse_event<Event: MouseEvent>(
4746        &mut self,
4747        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4748    ) {
4749        self.invalidator.debug_assert_paint();
4750
4751        self.next_frame.mouse_listeners.push(Some(Box::new(
4752            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
4753                if let Some(event) = event.downcast_ref() {
4754                    listener(event, phase, window, cx)
4755                }
4756            },
4757        )));
4758    }
4759
4760    /// Register a key event listener on this node for the next frame. The type of event
4761    /// is determined by the first parameter of the given listener. When the next frame is rendered
4762    /// the listener will be cleared.
4763    ///
4764    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4765    /// a specific need to register a listener yourself.
4766    ///
4767    /// This method should only be called as part of the paint phase of element drawing.
4768    pub fn on_key_event<Event: KeyEvent>(
4769        &mut self,
4770        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4771    ) {
4772        self.invalidator.debug_assert_paint();
4773
4774        self.next_frame.dispatch_tree.on_key_event(Rc::new(
4775            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4776                if let Some(event) = event.downcast_ref::<Event>() {
4777                    listener(event, phase, window, cx)
4778                }
4779            },
4780        ));
4781    }
4782
4783    /// Register a modifiers changed event listener on the window for the next frame.
4784    ///
4785    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4786    /// a specific need to register a global listener.
4787    ///
4788    /// This method should only be called as part of the paint phase of element drawing.
4789    pub fn on_modifiers_changed(
4790        &mut self,
4791        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4792    ) {
4793        self.invalidator.debug_assert_paint();
4794
4795        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4796            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4797                listener(event, window, cx)
4798            },
4799        ));
4800    }
4801
4802    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4803    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4804    /// Returns a subscription and persists until the subscription is dropped.
4805    pub fn on_focus_in(
4806        &mut self,
4807        handle: &FocusHandle,
4808        cx: &mut App,
4809        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4810    ) -> Subscription {
4811        let focus_id = handle.id;
4812        let (subscription, activate) =
4813            self.new_focus_listener(Box::new(move |event, window, cx| {
4814                if event.is_focus_in(focus_id) {
4815                    listener(window, cx);
4816                }
4817                true
4818            }));
4819        cx.defer(move |_| activate());
4820        subscription
4821    }
4822
4823    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4824    /// Returns a subscription and persists until the subscription is dropped.
4825    pub fn on_focus_out(
4826        &mut self,
4827        handle: &FocusHandle,
4828        cx: &mut App,
4829        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4830    ) -> Subscription {
4831        let focus_id = handle.id;
4832        let (subscription, activate) =
4833            self.new_focus_listener(Box::new(move |event, window, cx| {
4834                if let Some(blurred_id) = event.previous_focus_path.last().copied()
4835                    && event.is_focus_out(focus_id)
4836                {
4837                    let event = FocusOutEvent {
4838                        blurred: WeakFocusHandle {
4839                            id: blurred_id,
4840                            handles: Arc::downgrade(&cx.focus_handles),
4841                        },
4842                    };
4843                    listener(event, window, cx)
4844                }
4845                true
4846            }));
4847        cx.defer(move |_| activate());
4848        subscription
4849    }
4850
4851    fn reset_cursor_style(&self, cx: &mut App) {
4852        // Set the cursor only if we're the active window.
4853        if self.is_window_hovered() {
4854            let style = self
4855                .rendered_frame
4856                .cursor_style(self)
4857                .unwrap_or(CursorStyle::Arrow);
4858            cx.platform.set_cursor_style(style);
4859        }
4860    }
4861
4862    /// Dispatch a given keystroke as though the user had typed it.
4863    /// You can create a keystroke with Keystroke::parse("").
4864    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4865        let keystroke = keystroke.with_simulated_ime();
4866        let result = self.dispatch_event(
4867            PlatformInput::KeyDown(KeyDownEvent {
4868                keystroke: keystroke.clone(),
4869                is_held: false,
4870                prefer_character_input: false,
4871            }),
4872            cx,
4873        );
4874        if !result.propagate {
4875            return true;
4876        }
4877
4878        if let Some(input) = keystroke.key_char
4879            && let Some(mut input_handler) = self.platform_window.take_input_handler()
4880        {
4881            input_handler.dispatch_input(&input, self, cx);
4882            self.platform_window.set_input_handler(input_handler);
4883            return true;
4884        }
4885
4886        false
4887    }
4888
4889    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
4890    /// binding for the action (last binding added to the keymap).
4891    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4892        self.highest_precedence_binding_for_action(action)
4893            .map(|binding| {
4894                binding
4895                    .keystrokes()
4896                    .iter()
4897                    .map(ToString::to_string)
4898                    .collect::<Vec<_>>()
4899                    .join(" ")
4900            })
4901            .unwrap_or_else(|| action.name().to_string())
4902    }
4903
4904    /// Dispatch a mouse or keyboard event on the window.
4905    #[profiling::function]
4906    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4907        #[cfg(feature = "input-latency-histogram")]
4908        let dispatch_time = Instant::now();
4909        let update_count_before = self.invalidator.update_count();
4910        // Track input modality for focus-visible styling and hover suppression.
4911        // Hover is suppressed during keyboard modality so that keyboard navigation
4912        // doesn't show hover highlights on the item under the mouse cursor.
4913        let old_modality = self.last_input_modality;
4914        self.last_input_modality = match &event {
4915            PlatformInput::KeyDown(_) => InputModality::Keyboard,
4916            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4917            PlatformInput::Touch(_) => InputModality::Touch,
4918            _ => self.last_input_modality,
4919        };
4920        if self.last_input_modality != old_modality {
4921            self.refresh();
4922        }
4923
4924        // Handlers may set this to false by calling `stop_propagation`.
4925        cx.propagate_event = true;
4926        // Handlers may set this to true by calling `prevent_default`.
4927        self.default_prevented = false;
4928
4929        let event = match event {
4930            // Track the mouse position with our own state, since accessing the platform
4931            // API for the mouse position can only occur on the main thread.
4932            PlatformInput::MouseMove(mouse_move) => {
4933                self.mouse_position = mouse_move.position;
4934                self.modifiers = mouse_move.modifiers;
4935                PlatformInput::MouseMove(mouse_move)
4936            }
4937            PlatformInput::MouseDown(mouse_down) => {
4938                self.mouse_position = mouse_down.position;
4939                self.modifiers = mouse_down.modifiers;
4940                PlatformInput::MouseDown(mouse_down)
4941            }
4942            PlatformInput::MouseUp(mouse_up) => {
4943                self.mouse_position = mouse_up.position;
4944                self.modifiers = mouse_up.modifiers;
4945                PlatformInput::MouseUp(mouse_up)
4946            }
4947            PlatformInput::MousePressure(mouse_pressure) => {
4948                PlatformInput::MousePressure(mouse_pressure)
4949            }
4950            PlatformInput::MouseExited(mouse_exited) => {
4951                self.modifiers = mouse_exited.modifiers;
4952                PlatformInput::MouseExited(mouse_exited)
4953            }
4954            PlatformInput::ModifiersChanged(modifiers_changed) => {
4955                self.modifiers = modifiers_changed.modifiers;
4956                self.capslock = modifiers_changed.capslock;
4957                PlatformInput::ModifiersChanged(modifiers_changed)
4958            }
4959            PlatformInput::ScrollWheel(scroll_wheel) => {
4960                self.mouse_position = scroll_wheel.position;
4961                self.modifiers = scroll_wheel.modifiers;
4962                PlatformInput::ScrollWheel(scroll_wheel)
4963            }
4964            PlatformInput::Pinch(pinch) => {
4965                self.mouse_position = pinch.position;
4966                self.modifiers = pinch.modifiers;
4967                PlatformInput::Pinch(pinch)
4968            }
4969            // Translate dragging and dropping of external files from the operating system
4970            // to internal drag and drop events.
4971            PlatformInput::FileDrop(file_drop) => match file_drop {
4972                FileDropEvent::Entered { position, paths } => {
4973                    self.mouse_position = position;
4974                    let source_window = self.handle.window_id();
4975                    if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
4976                        cx.active_drag = Some(AnyDrag {
4977                            value: Arc::new(paths.clone()),
4978                            view: cx.new(|_| paths).into(),
4979                            cursor_offset: position,
4980                            cursor_style: None,
4981                            external_payload_source: None,
4982                        });
4983                    }
4984                    PlatformInput::MouseMove(MouseMoveEvent {
4985                        position,
4986                        pressed_button: Some(MouseButton::Left),
4987                        modifiers: Modifiers::default(),
4988                    })
4989                }
4990                FileDropEvent::Pending { position } => {
4991                    self.mouse_position = position;
4992                    PlatformInput::MouseMove(MouseMoveEvent {
4993                        position,
4994                        pressed_button: Some(MouseButton::Left),
4995                        modifiers: Modifiers::default(),
4996                    })
4997                }
4998                FileDropEvent::Submit { position } => {
4999                    cx.activate(true);
5000                    self.mouse_position = position;
5001                    PlatformInput::MouseUp(MouseUpEvent {
5002                        button: MouseButton::Left,
5003                        position,
5004                        modifiers: Modifiers::default(),
5005                        click_count: 1,
5006                    })
5007                }
5008                FileDropEvent::Exited => {
5009                    if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5010                        cx.active_drag.take();
5011                    }
5012                    self.refresh();
5013                    PlatformInput::FileDrop(FileDropEvent::Exited)
5014                }
5015                FileDropEvent::Ended => {
5016                    cx.end_platform_drag(self.handle.window_id());
5017                    self.refresh();
5018                    PlatformInput::FileDrop(FileDropEvent::Ended)
5019                }
5020            },
5021            PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5022            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5023        };
5024
5025        if let Some(any_mouse_event) = event.mouse_event() {
5026            self.dispatch_mouse_event(any_mouse_event, cx);
5027        } else if let Some(any_key_event) = event.keyboard_event() {
5028            self.dispatch_key_event(any_key_event, cx);
5029        }
5030
5031        // Must run after the move is dispatched: the platform owns the gesture afterwards, so this
5032        // is the last chance for drag listeners to see the pointer leave and reset their state.
5033        self.promote_external_drag_to_platform(&event, cx);
5034
5035        if self.invalidator.update_count() > update_count_before {
5036            self.input_rate_tracker.borrow_mut().record_input();
5037            #[cfg(feature = "input-latency-histogram")]
5038            if self.invalidator.not_drawing() {
5039                self.input_latency_tracker.record_input(dispatch_time);
5040            } else {
5041                self.input_latency_tracker.record_mid_draw_input();
5042            }
5043        }
5044
5045        DispatchEventResult {
5046            propagate: cx.propagate_event,
5047            default_prevented: self.default_prevented,
5048        }
5049    }
5050
5051    fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5052        let PlatformInput::MouseMove(mouse_move) = event else {
5053            return;
5054        };
5055        if mouse_move.pressed_button != Some(MouseButton::Left) {
5056            return;
5057        }
5058        if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5059            return;
5060        }
5061        if !self.platform_window.can_start_external_drag() {
5062            return;
5063        }
5064        let Some(payload_source) = cx
5065            .active_drag
5066            .as_mut()
5067            .and_then(|drag| drag.external_payload_source.take())
5068        else {
5069            return;
5070        };
5071        let Some(payload) = payload_source(self, cx) else {
5072            return;
5073        };
5074        if self.platform_window.start_external_drag(&payload)
5075            && cx.hand_active_drag_to_platform(self.handle.window_id())
5076        {
5077            self.refresh();
5078        }
5079    }
5080
5081    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5082        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
5083        if hit_test != self.mouse_hit_test {
5084            self.mouse_hit_test = hit_test;
5085            self.reset_cursor_style(cx);
5086        }
5087
5088        #[cfg(any(feature = "inspector", debug_assertions))]
5089        if self.is_inspector_picking(cx) {
5090            self.handle_inspector_mouse_event(event, cx);
5091            // When inspector is picking, all other mouse handling is skipped.
5092            return;
5093        }
5094
5095        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
5096
5097        // Capture phase, events bubble from back to front. Handlers for this phase are used for
5098        // special purposes, such as detecting events outside of a given Bounds.
5099        for listener in &mut mouse_listeners {
5100            let listener = listener.as_mut().unwrap();
5101            listener(event, DispatchPhase::Capture, self, cx);
5102            if !cx.propagate_event {
5103                break;
5104            }
5105        }
5106
5107        // Bubble phase, where most normal handlers do their work.
5108        if cx.propagate_event {
5109            for listener in mouse_listeners.iter_mut().rev() {
5110                let listener = listener.as_mut().unwrap();
5111                listener(event, DispatchPhase::Bubble, self, cx);
5112                if !cx.propagate_event {
5113                    break;
5114                }
5115            }
5116        }
5117
5118        self.rendered_frame.mouse_listeners = mouse_listeners;
5119
5120        if cx.has_active_drag() {
5121            if event.is::<MouseMoveEvent>() {
5122                // If this was a mouse move event, redraw the window so that the
5123                // active drag can follow the mouse cursor.
5124                self.refresh();
5125            } else if event.is::<MouseUpEvent>() {
5126                // If this was a mouse up event, cancel the active drag and redraw
5127                // the window.
5128                cx.active_drag = None;
5129                self.refresh();
5130            }
5131        }
5132
5133        // Auto-release pointer capture on mouse up
5134        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
5135            self.captured_hitbox = None;
5136        }
5137    }
5138
5139    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
5140        if self.invalidator.is_dirty() {
5141            self.draw(cx).clear(cx);
5142        }
5143
5144        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5145        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5146
5147        let mut keystroke: Option<Keystroke> = None;
5148
5149        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
5150            if event.modifiers.number_of_modifiers() == 0
5151                && self.pending_modifier.modifiers.number_of_modifiers() == 1
5152                && !self.pending_modifier.saw_other_input
5153            {
5154                let key = match self.pending_modifier.modifiers {
5155                    modifiers if modifiers.shift => Some("shift"),
5156                    modifiers if modifiers.control => Some("control"),
5157                    modifiers if modifiers.alt => Some("alt"),
5158                    modifiers if modifiers.platform => Some("platform"),
5159                    modifiers if modifiers.function => Some("function"),
5160                    _ => None,
5161                };
5162                if let Some(key) = key {
5163                    keystroke = Some(Keystroke {
5164                        key: key.to_string(),
5165                        key_char: None,
5166                        modifiers: Modifiers::default(),
5167                    });
5168                }
5169            }
5170
5171            if self.pending_modifier.modifiers.number_of_modifiers() == 0
5172                && event.modifiers.number_of_modifiers() == 1
5173            {
5174                self.pending_modifier.saw_other_input = false
5175            } else if event.modifiers.number_of_modifiers() > 1 {
5176                self.pending_modifier.saw_other_input = true
5177            }
5178            self.pending_modifier.modifiers = event.modifiers
5179        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
5180            self.pending_modifier.saw_other_input = true;
5181            keystroke = Some(key_down_event.keystroke.clone());
5182            if key_down_event.keystroke.key_char.is_some()
5183                && matches!(
5184                    cx.cursor_hide_mode,
5185                    CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
5186                )
5187            {
5188                cx.platform.hide_cursor_until_mouse_moves();
5189            }
5190        }
5191
5192        let Some(keystroke) = keystroke else {
5193            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5194            return;
5195        };
5196
5197        cx.propagate_event = true;
5198        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
5199        if !cx.propagate_event {
5200            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5201            return;
5202        }
5203
5204        let mut currently_pending = self.pending_input.take().unwrap_or_default();
5205        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
5206            currently_pending = PendingInput::default();
5207        }
5208
5209        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
5210            currently_pending.keystrokes,
5211            keystroke,
5212            &dispatch_path,
5213        );
5214
5215        if !match_result.to_replay.is_empty() {
5216            self.replay_pending_input(match_result.to_replay, cx);
5217            cx.propagate_event = true;
5218        }
5219
5220        if !match_result.pending.is_empty() {
5221            currently_pending.timer.take();
5222            currently_pending.keystrokes = match_result.pending;
5223            currently_pending.focus = self.focus;
5224
5225            let text_input_requires_timeout = event
5226                .downcast_ref::<KeyDownEvent>()
5227                .filter(|key_down| key_down.keystroke.key_char.is_some())
5228                .and_then(|_| self.platform_window.take_input_handler())
5229                .map_or(false, |mut input_handler| {
5230                    let accepts = input_handler.accepts_text_input(self, cx);
5231                    self.platform_window.set_input_handler(input_handler);
5232                    accepts
5233                });
5234
5235            currently_pending.needs_timeout |=
5236                match_result.pending_has_binding || text_input_requires_timeout;
5237
5238            if currently_pending.needs_timeout {
5239                let generation = Rc::new(());
5240                currently_pending.generation = generation.clone();
5241                currently_pending.timer = Some(self.spawn(cx, async move |cx| {
5242                    cx.background_executor.timer(Duration::from_secs(1)).await;
5243                    cx.update_if_present(move |window, cx| {
5244                        if !window
5245                            .pending_input
5246                            .as_ref()
5247                            .is_some_and(|pending| Rc::ptr_eq(&pending.generation, &generation))
5248                        {
5249                            return;
5250                        }
5251                        let Some(currently_pending) = window
5252                            .pending_input
5253                            .take()
5254                            .filter(|pending| pending.focus == window.focus)
5255                        else {
5256                            return;
5257                        };
5258
5259                        let node_id = window.focus_node_id_in_rendered_frame(window.focus);
5260                        let dispatch_path =
5261                            window.rendered_frame.dispatch_tree.dispatch_path(node_id);
5262
5263                        let to_replay = window
5264                            .rendered_frame
5265                            .dispatch_tree
5266                            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
5267
5268                        window.pending_input_changed(cx);
5269                        window.replay_pending_input(to_replay, cx)
5270                    })
5271                    .log_err();
5272                }));
5273            } else {
5274                currently_pending.timer = None;
5275            }
5276            self.pending_input = Some(currently_pending);
5277            self.pending_input_changed(cx);
5278            cx.propagate_event = false;
5279            return;
5280        }
5281
5282        let skip_bindings = event
5283            .downcast_ref::<KeyDownEvent>()
5284            .filter(|key_down_event| key_down_event.prefer_character_input)
5285            .map(|_| {
5286                self.platform_window
5287                    .take_input_handler()
5288                    .map_or(false, |mut input_handler| {
5289                        let accepts = input_handler.accepts_text_input(self, cx);
5290                        self.platform_window.set_input_handler(input_handler);
5291                        // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
5292                        // we prefer the text input over bindings.
5293                        accepts
5294                    })
5295            })
5296            .unwrap_or(false);
5297
5298        if !skip_bindings {
5299            for binding in match_result.bindings {
5300                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5301                if !cx.propagate_event {
5302                    self.dispatch_keystroke_observers(
5303                        event,
5304                        Some(binding.action),
5305                        match_result.context_stack,
5306                        cx,
5307                    );
5308                    self.pending_input_changed(cx);
5309                    return;
5310                }
5311            }
5312        }
5313
5314        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
5315        self.pending_input_changed(cx);
5316    }
5317
5318    fn finish_dispatch_key_event(
5319        &mut self,
5320        event: &dyn Any,
5321        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
5322        context_stack: Vec<KeyContext>,
5323        cx: &mut App,
5324    ) {
5325        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
5326        if !cx.propagate_event {
5327            return;
5328        }
5329
5330        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
5331        if !cx.propagate_event {
5332            return;
5333        }
5334
5335        self.dispatch_keystroke_observers(event, None, context_stack, cx);
5336    }
5337
5338    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
5339        self.pending_input_observers
5340            .clone()
5341            .retain(&(), |callback| callback(self, cx));
5342    }
5343
5344    fn dispatch_key_down_up_event(
5345        &mut self,
5346        event: &dyn Any,
5347        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5348        cx: &mut App,
5349    ) {
5350        // Capture phase
5351        for node_id in dispatch_path {
5352            let node = self.rendered_frame.dispatch_tree.node(*node_id);
5353
5354            for key_listener in node.key_listeners.clone() {
5355                key_listener(event, DispatchPhase::Capture, self, cx);
5356                if !cx.propagate_event {
5357                    return;
5358                }
5359            }
5360        }
5361
5362        // Bubble phase
5363        for node_id in dispatch_path.iter().rev() {
5364            // Handle low level key events
5365            let node = self.rendered_frame.dispatch_tree.node(*node_id);
5366            for key_listener in node.key_listeners.clone() {
5367                key_listener(event, DispatchPhase::Bubble, self, cx);
5368                if !cx.propagate_event {
5369                    return;
5370                }
5371            }
5372        }
5373    }
5374
5375    fn dispatch_modifiers_changed_event(
5376        &mut self,
5377        event: &dyn Any,
5378        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5379        cx: &mut App,
5380    ) {
5381        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
5382            return;
5383        };
5384        for node_id in dispatch_path.iter().rev() {
5385            let node = self.rendered_frame.dispatch_tree.node(*node_id);
5386            for listener in node.modifiers_changed_listeners.clone() {
5387                listener(event, self, cx);
5388                if !cx.propagate_event {
5389                    return;
5390                }
5391            }
5392        }
5393    }
5394
5395    /// Pending input that can still complete a binding. Input left over from a previous focus can
5396    /// never complete one.
5397    fn active_pending_input(&self) -> Option<&PendingInput> {
5398        self.pending_input
5399            .as_ref()
5400            .filter(|pending_input| pending_input.focus == self.focus)
5401    }
5402
5403    /// Determine whether a potential multi-stroke key binding is in progress on this window.
5404    pub fn has_pending_keystrokes(&self) -> bool {
5405        self.active_pending_input().is_some()
5406    }
5407
5408    pub(crate) fn clear_pending_keystrokes(&mut self) {
5409        self.pending_input.take();
5410    }
5411
5412    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
5413    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
5414        self.active_pending_input()
5415            .map(|pending_input| pending_input.keystrokes.as_slice())
5416    }
5417
5418    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
5419        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5420        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5421
5422        'replay: for replay in replays {
5423            let event = KeyDownEvent {
5424                keystroke: replay.keystroke.clone(),
5425                is_held: false,
5426                prefer_character_input: true,
5427            };
5428
5429            cx.propagate_event = true;
5430            for binding in replay.bindings {
5431                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5432                if !cx.propagate_event {
5433                    self.dispatch_keystroke_observers(
5434                        &event,
5435                        Some(binding.action),
5436                        Vec::default(),
5437                        cx,
5438                    );
5439                    continue 'replay;
5440                }
5441            }
5442
5443            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
5444            if !cx.propagate_event {
5445                continue 'replay;
5446            }
5447            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
5448                && let Some(mut input_handler) = self.platform_window.take_input_handler()
5449            {
5450                input_handler.dispatch_input(&input, self, cx);
5451                self.platform_window.set_input_handler(input_handler)
5452            }
5453        }
5454    }
5455
5456    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
5457        focus_id
5458            .and_then(|focus_id| {
5459                self.rendered_frame
5460                    .dispatch_tree
5461                    .focusable_node_id(focus_id)
5462            })
5463            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
5464    }
5465
5466    fn dispatch_action_on_node(
5467        &mut self,
5468        node_id: DispatchNodeId,
5469        action: &dyn Action,
5470        cx: &mut App,
5471    ) {
5472        self.dispatch_action_on_node_inner(node_id, action, cx);
5473
5474        if !cx.propagate_event
5475            && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
5476            && self.last_input_was_keyboard()
5477        {
5478            cx.platform.hide_cursor_until_mouse_moves();
5479        }
5480    }
5481
5482    fn dispatch_action_on_node_inner(
5483        &mut self,
5484        node_id: DispatchNodeId,
5485        action: &dyn Action,
5486        cx: &mut App,
5487    ) {
5488        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5489
5490        // Capture phase for global actions.
5491        cx.propagate_event = true;
5492        if let Some(mut global_listeners) = cx
5493            .global_action_listeners
5494            .remove(&action.as_any().type_id())
5495        {
5496            for listener in &global_listeners {
5497                profiler::update_running_action(action, cx);
5498                listener(action.as_any(), DispatchPhase::Capture, cx);
5499                profiler::save_action_timing();
5500                if !cx.propagate_event {
5501                    break;
5502                }
5503            }
5504
5505            global_listeners.extend(
5506                cx.global_action_listeners
5507                    .remove(&action.as_any().type_id())
5508                    .unwrap_or_default(),
5509            );
5510
5511            cx.global_action_listeners
5512                .insert(action.as_any().type_id(), global_listeners);
5513        }
5514
5515        if !cx.propagate_event {
5516            return;
5517        }
5518
5519        // Capture phase for window actions.
5520        for node_id in &dispatch_path {
5521            let node = self.rendered_frame.dispatch_tree.node(*node_id);
5522            for DispatchActionListener {
5523                action_type,
5524                listener,
5525            } in node.action_listeners.clone()
5526            {
5527                let any_action = action.as_any();
5528                if action_type == any_action.type_id() {
5529                    profiler::update_running_action(action, cx);
5530                    listener(any_action, DispatchPhase::Capture, self, cx);
5531                    profiler::save_action_timing();
5532
5533                    if !cx.propagate_event {
5534                        return;
5535                    }
5536                }
5537            }
5538        }
5539
5540        // Bubble phase for window actions.
5541        for node_id in dispatch_path.iter().rev() {
5542            let node = self.rendered_frame.dispatch_tree.node(*node_id);
5543            for DispatchActionListener {
5544                action_type,
5545                listener,
5546            } in node.action_listeners.clone()
5547            {
5548                let any_action = action.as_any();
5549                if action_type == any_action.type_id() {
5550                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
5551                    profiler::update_running_action(action, cx);
5552                    listener(any_action, DispatchPhase::Bubble, self, cx);
5553                    profiler::save_action_timing();
5554
5555                    if !cx.propagate_event {
5556                        return;
5557                    }
5558                }
5559            }
5560        }
5561
5562        // Bubble phase for global actions.
5563        if let Some(mut global_listeners) = cx
5564            .global_action_listeners
5565            .remove(&action.as_any().type_id())
5566        {
5567            for listener in global_listeners.iter().rev() {
5568                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
5569
5570                profiler::update_running_action(action, cx);
5571                listener(action.as_any(), DispatchPhase::Bubble, cx);
5572                profiler::save_action_timing();
5573                if !cx.propagate_event {
5574                    break;
5575                }
5576            }
5577
5578            global_listeners.extend(
5579                cx.global_action_listeners
5580                    .remove(&action.as_any().type_id())
5581                    .unwrap_or_default(),
5582            );
5583
5584            cx.global_action_listeners
5585                .insert(action.as_any().type_id(), global_listeners);
5586        }
5587    }
5588
5589    /// Register the given handler to be invoked whenever the global of the given type
5590    /// is updated.
5591    pub fn observe_global<G: Global>(
5592        &mut self,
5593        cx: &mut App,
5594        f: impl Fn(&mut Window, &mut App) + 'static,
5595    ) -> Subscription {
5596        let window_handle = self.handle;
5597        let (subscription, activate) = cx.global_observers.insert(
5598            TypeId::of::<G>(),
5599            Box::new(move |cx| {
5600                window_handle
5601                    .update(cx, |_, window, cx| f(window, cx))
5602                    .is_ok()
5603            }),
5604        );
5605        cx.defer(move |_| activate());
5606        subscription
5607    }
5608
5609    /// Focus the current window and bring it to the foreground at the platform level.
5610    pub fn activate_window(&self) {
5611        self.platform_window.activate();
5612    }
5613
5614    /// Requests that the operating system draw attention to this window.
5615    pub fn request_attention(&self) {
5616        self.platform_window.request_attention();
5617    }
5618
5619    /// Minimize the current window at the platform level.
5620    pub fn minimize_window(&self) {
5621        self.platform_window.minimize();
5622    }
5623
5624    /// Toggle full screen status on the current window at the platform level.
5625    pub fn toggle_fullscreen(&self) {
5626        self.platform_window.toggle_fullscreen();
5627    }
5628
5629    /// Updates the IME panel position suggestions for languages like japanese, chinese.
5630    pub fn invalidate_character_coordinates(&self) {
5631        self.on_next_frame(|window, cx| {
5632            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
5633                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
5634                    window.platform_window.update_ime_position(bounds);
5635                }
5636                window.platform_window.set_input_handler(input_handler);
5637            }
5638        });
5639    }
5640
5641    /// Present a platform dialog.
5642    /// The provided message will be presented, along with buttons for each answer.
5643    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
5644    pub fn prompt<T>(
5645        &mut self,
5646        level: PromptLevel,
5647        message: &str,
5648        detail: Option<&str>,
5649        answers: &[T],
5650        cx: &mut App,
5651    ) -> oneshot::Receiver<usize>
5652    where
5653        T: Clone + Into<PromptButton>,
5654    {
5655        let prompt_builder = cx.prompt_builder.take();
5656        let Some(prompt_builder) = prompt_builder else {
5657            unreachable!("Re-entrant window prompting is not supported by GPUI");
5658        };
5659
5660        let answers = answers
5661            .iter()
5662            .map(|answer| answer.clone().into())
5663            .collect::<Vec<_>>();
5664
5665        let receiver = match &prompt_builder {
5666            PromptBuilder::Default => self
5667                .platform_window
5668                .prompt(level, message, detail, &answers)
5669                .unwrap_or_else(|| {
5670                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5671                }),
5672            PromptBuilder::Custom(_) => {
5673                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5674            }
5675        };
5676
5677        cx.prompt_builder = Some(prompt_builder);
5678
5679        receiver
5680    }
5681
5682    fn build_custom_prompt(
5683        &mut self,
5684        prompt_builder: &PromptBuilder,
5685        level: PromptLevel,
5686        message: &str,
5687        detail: Option<&str>,
5688        answers: &[PromptButton],
5689        cx: &mut App,
5690    ) -> oneshot::Receiver<usize> {
5691        let (sender, receiver) = oneshot::channel();
5692        let handle = PromptHandle::new(sender);
5693        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
5694        self.prompt = Some(handle);
5695        receiver
5696    }
5697
5698    /// Returns whether a prompt rendered by GPUI is currently active in this window.
5699    ///
5700    /// This is only true for prompts rendered in the window (see
5701    /// [`App::set_prompt_builder`]), not for platform-native prompt dialogs.
5702    pub fn has_active_prompt(&self) -> bool {
5703        self.prompt.is_some()
5704    }
5705
5706    /// Returns the current context stack.
5707    pub fn context_stack(&self) -> Vec<KeyContext> {
5708        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5709        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5710        dispatch_tree
5711            .dispatch_path(node_id)
5712            .iter()
5713            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
5714            .collect()
5715    }
5716
5717    /// Returns all available actions for the focused element.
5718    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
5719        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5720        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
5721        for action_type in cx.global_action_listeners.keys() {
5722            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
5723                let action = cx.actions.build_action_type(action_type).ok();
5724                if let Some(action) = action {
5725                    actions.insert(ix, action);
5726                }
5727            }
5728        }
5729        actions
5730    }
5731
5732    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
5733    /// returned in the order they were added. For display, the last binding should take precedence.
5734    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
5735        self.rendered_frame
5736            .dispatch_tree
5737            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
5738    }
5739
5740    /// Returns the highest precedence key binding that invokes an action on the currently focused
5741    /// element. This is more efficient than getting the last result of `bindings_for_action`.
5742    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
5743        self.rendered_frame
5744            .dispatch_tree
5745            .highest_precedence_binding_for_action(
5746                action,
5747                &self.rendered_frame.dispatch_tree.context_stack,
5748            )
5749    }
5750
5751    /// Returns the key bindings for an action in a context.
5752    pub fn bindings_for_action_in_context(
5753        &self,
5754        action: &dyn Action,
5755        context: KeyContext,
5756    ) -> Vec<KeyBinding> {
5757        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5758        dispatch_tree.bindings_for_action(action, &[context])
5759    }
5760
5761    /// Returns the highest precedence key binding for an action in a context. This is more
5762    /// efficient than getting the last result of `bindings_for_action_in_context`.
5763    pub fn highest_precedence_binding_for_action_in_context(
5764        &self,
5765        action: &dyn Action,
5766        context: KeyContext,
5767    ) -> Option<KeyBinding> {
5768        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5769        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
5770    }
5771
5772    /// Returns any bindings that would invoke an action on the given focus handle if it were
5773    /// focused. Bindings are returned in the order they were added. For display, the last binding
5774    /// should take precedence.
5775    pub fn bindings_for_action_in(
5776        &self,
5777        action: &dyn Action,
5778        focus_handle: &FocusHandle,
5779    ) -> Vec<KeyBinding> {
5780        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5781        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
5782            return vec![];
5783        };
5784        dispatch_tree.bindings_for_action(action, &context_stack)
5785    }
5786
5787    /// Returns the highest precedence key binding that would invoke an action on the given focus
5788    /// handle if it were focused. This is more efficient than getting the last result of
5789    /// `bindings_for_action_in`.
5790    pub fn highest_precedence_binding_for_action_in(
5791        &self,
5792        action: &dyn Action,
5793        focus_handle: &FocusHandle,
5794    ) -> Option<KeyBinding> {
5795        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5796        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
5797        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
5798    }
5799
5800    /// Find the bindings that can follow the current input sequence for the current context stack.
5801    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
5802        self.rendered_frame
5803            .dispatch_tree
5804            .possible_next_bindings_for_input(input, &self.context_stack())
5805    }
5806
5807    fn context_stack_for_focus_handle(
5808        &self,
5809        focus_handle: &FocusHandle,
5810    ) -> Option<Vec<KeyContext>> {
5811        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5812        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
5813        let context_stack: Vec<_> = dispatch_tree
5814            .dispatch_path(node_id)
5815            .into_iter()
5816            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
5817            .collect();
5818        Some(context_stack)
5819    }
5820
5821    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
5822    pub fn listener_for<T: 'static, E>(
5823        &self,
5824        view: &Entity<T>,
5825        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
5826    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
5827        let view = view.downgrade();
5828        move |e: &E, window: &mut Window, cx: &mut App| {
5829            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
5830        }
5831    }
5832
5833    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
5834    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
5835        &self,
5836        entity: &Entity<E>,
5837        f: Callback,
5838    ) -> impl Fn(&mut Window, &mut App) + 'static {
5839        let entity = entity.downgrade();
5840        move |window: &mut Window, cx: &mut App| {
5841            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
5842        }
5843    }
5844
5845    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
5846    /// If the callback returns false, the window won't be closed.
5847    pub fn on_window_should_close(
5848        &self,
5849        cx: &App,
5850        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
5851    ) {
5852        let mut cx = self.to_async(cx);
5853        self.platform_window.on_should_close(Box::new(move || {
5854            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
5855        }))
5856    }
5857
5858    /// Register an action listener on this node for the next frame. The type of action
5859    /// is determined by the first parameter of the given listener. When the next frame is rendered
5860    /// the listener will be cleared.
5861    ///
5862    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5863    /// a specific need to register a listener yourself.
5864    ///
5865    /// This method should only be called as part of the paint phase of element drawing.
5866    pub fn on_action(
5867        &mut self,
5868        action_type: TypeId,
5869        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5870    ) {
5871        self.invalidator.debug_assert_paint();
5872
5873        self.next_frame
5874            .dispatch_tree
5875            .on_action(action_type, Rc::new(listener));
5876    }
5877
5878    /// Register a capturing action listener on this node for the next frame if the condition is true.
5879    /// The type of action is determined by the first parameter of the given listener. When the next
5880    /// frame is rendered the listener will be cleared.
5881    ///
5882    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5883    /// a specific need to register a listener yourself.
5884    ///
5885    /// This method should only be called as part of the paint phase of element drawing.
5886    pub fn on_action_when(
5887        &mut self,
5888        condition: bool,
5889        action_type: TypeId,
5890        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5891    ) {
5892        self.invalidator.debug_assert_paint();
5893
5894        if condition {
5895            self.next_frame
5896                .dispatch_tree
5897                .on_action(action_type, Rc::new(listener));
5898        }
5899    }
5900
5901    /// Read information about the GPU backing this window.
5902    /// Currently returns None on Mac and Windows.
5903    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5904        self.platform_window.gpu_specs()
5905    }
5906
5907    /// Perform titlebar double-click action.
5908    /// This is macOS specific.
5909    pub fn titlebar_double_click(&self) {
5910        self.platform_window
5911            .titlebar_double_click(self.is_resizable, self.is_minimizable);
5912    }
5913
5914    /// Gets the window's title at the platform level.
5915    /// This is macOS specific.
5916    pub fn window_title(&self) -> String {
5917        self.platform_window.get_title()
5918    }
5919
5920    /// Returns a list of all tabbed windows and their titles.
5921    /// This is macOS specific.
5922    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5923        self.platform_window.tabbed_windows()
5924    }
5925
5926    /// Returns the tab bar visibility.
5927    /// This is macOS specific.
5928    pub fn tab_bar_visible(&self) -> bool {
5929        self.platform_window.tab_bar_visible()
5930    }
5931
5932    /// Merges all open windows into a single tabbed window.
5933    /// This is macOS specific.
5934    pub fn merge_all_windows(&self) {
5935        self.platform_window.merge_all_windows()
5936    }
5937
5938    /// Moves the tab to a new containing window.
5939    /// This is macOS specific.
5940    pub fn move_tab_to_new_window(&self) {
5941        self.platform_window.move_tab_to_new_window()
5942    }
5943
5944    /// Shows or hides the window tab overview.
5945    /// This is macOS specific.
5946    pub fn toggle_window_tab_overview(&self) {
5947        self.platform_window.toggle_window_tab_overview()
5948    }
5949
5950    /// Sets the tabbing identifier for the window.
5951    /// This is macOS specific.
5952    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5953        self.platform_window
5954            .set_tabbing_identifier(tabbing_identifier)
5955    }
5956
5957    /// Request the OS to play an alert sound. On some platforms this is associated
5958    /// with the window, for others it's just a simple global function call.
5959    pub fn play_system_bell(&self) {
5960        self.platform_window.play_system_bell()
5961    }
5962
5963    /// Returns whether accessibility features are active for this frame,
5964    /// i.e. whether assistive technology (such as a screen reader) is
5965    /// connected and an accessibility tree is being built.
5966    ///
5967    /// Use this to skip computing data during rendering that is only
5968    /// observable through the accessibility tree. When accessibility is
5969    /// activated, a redraw is forced, so gated work is recomputed before the
5970    /// next tree update is sent to the platform.
5971    ///
5972    /// See the [accessibility guide](crate::_accessibility) for an overview.
5973    pub fn is_a11y_active(&self) -> bool {
5974        self.a11y.is_active()
5975    }
5976
5977    /// Debug representation of the last frame's accessibility information.
5978    pub fn debug_a11y_tree_json(&self) -> Option<String> {
5979        self.a11y.debug_tree_json()
5980    }
5981
5982    /// Register a listener for an accessibility action on a specific node.
5983    /// The listener will be called when a screen reader requests the given
5984    /// action on the node identified by `node_id`.
5985    ///
5986    /// See the [accessibility guide](crate::_accessibility) for an overview.
5987    pub fn on_a11y_action(
5988        &mut self,
5989        node_id: accesskit::NodeId,
5990        action: accesskit::Action,
5991        listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
5992    ) {
5993        self.a11y
5994            .action_listeners
5995            .entry(node_id)
5996            .or_default()
5997            .push((action, Box::new(listener)));
5998    }
5999
6000    #[cfg(not(target_family = "wasm"))]
6001    pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
6002        // Take listeners out temporarily so the closures can borrow Window
6003        // mutably, then restore them afterward.
6004        if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
6005            let extra_data = request.data.as_ref();
6006            let mut matched = false;
6007            for (action, listener) in &mut listeners {
6008                if *action == request.action {
6009                    listener(extra_data, self, cx);
6010                    matched = true;
6011                }
6012            }
6013            self.a11y
6014                .action_listeners
6015                .insert(request.target_node, listeners);
6016            if matched {
6017                return;
6018            }
6019        }
6020
6021        // Fall back to built-in action handling.
6022        match request.action {
6023            accesskit::Action::Click => {
6024                if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
6025                    let center = bounds.center();
6026                    let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
6027                        button: MouseButton::Left,
6028                        position: center,
6029                        modifiers: Modifiers::default(),
6030                        click_count: 1,
6031                        first_mouse: false,
6032                    });
6033                    let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
6034                        button: MouseButton::Left,
6035                        position: center,
6036                        modifiers: Modifiers::default(),
6037                        click_count: 1,
6038                    });
6039                    self.dispatch_event(mouse_down, cx);
6040                    self.dispatch_event(mouse_up, cx);
6041                }
6042            }
6043            accesskit::Action::Focus => {
6044                if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
6045                    && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
6046                {
6047                    self.focus(&handle, cx);
6048                }
6049            }
6050            accesskit::Action::Blur => {
6051                self.blur();
6052            }
6053            _ => {
6054                log::debug!(
6055                    "Unhandled a11y action: {:?} on {:?}",
6056                    request.action,
6057                    request.target_node
6058                );
6059            }
6060        }
6061    }
6062
6063    /// Toggles the inspector mode on this window.
6064    #[cfg(any(feature = "inspector", debug_assertions))]
6065    pub fn toggle_inspector(&mut self, cx: &mut App) {
6066        self.inspector = match self.inspector {
6067            None => Some(cx.new(|_| Inspector::new())),
6068            Some(_) => None,
6069        };
6070        self.refresh();
6071    }
6072
6073    /// Returns true if the window is in inspector mode.
6074    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
6075        #[cfg(any(feature = "inspector", debug_assertions))]
6076        {
6077            if let Some(inspector) = &self.inspector {
6078                return inspector.read(_cx).is_picking();
6079            }
6080        }
6081        false
6082    }
6083
6084    /// Executes the provided function with mutable access to an inspector state.
6085    #[cfg(any(feature = "inspector", debug_assertions))]
6086    pub fn with_inspector_state<T: 'static, R>(
6087        &mut self,
6088        _inspector_id: Option<&crate::InspectorElementId>,
6089        cx: &mut App,
6090        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
6091    ) -> R {
6092        if let Some(inspector_id) = _inspector_id
6093            && let Some(inspector) = &self.inspector
6094        {
6095            let inspector = inspector.clone();
6096            let active_element_id = inspector.read(cx).active_element_id();
6097            if Some(inspector_id) == active_element_id {
6098                return inspector.update(cx, |inspector, _cx| {
6099                    inspector.with_active_element_state(self, f)
6100                });
6101            }
6102        }
6103        f(&mut None, self)
6104    }
6105
6106    #[cfg(any(feature = "inspector", debug_assertions))]
6107    pub(crate) fn build_inspector_element_id(
6108        &mut self,
6109        path: crate::InspectorElementPath,
6110    ) -> crate::InspectorElementId {
6111        self.invalidator.debug_assert_paint_or_prepaint();
6112        let path = Rc::new(path);
6113        let next_instance_id = self
6114            .next_frame
6115            .next_inspector_instance_ids
6116            .entry(path.clone())
6117            .or_insert(0);
6118        let instance_id = *next_instance_id;
6119        *next_instance_id += 1;
6120        crate::InspectorElementId { path, instance_id }
6121    }
6122
6123    #[cfg(any(feature = "inspector", debug_assertions))]
6124    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
6125        if let Some(inspector) = self.inspector.take() {
6126            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
6127            inspector_element.prepaint_as_root(
6128                point(self.viewport_size.width - inspector_width, px(0.0)),
6129                size(inspector_width, self.viewport_size.height).into(),
6130                self,
6131                cx,
6132            );
6133            self.inspector = Some(inspector);
6134            Some(inspector_element)
6135        } else {
6136            None
6137        }
6138    }
6139
6140    #[cfg(any(feature = "inspector", debug_assertions))]
6141    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
6142        if let Some(mut inspector_element) = inspector_element {
6143            inspector_element.paint(self, cx);
6144        };
6145    }
6146
6147    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
6148    /// inspect UI elements by clicking on them.
6149    #[cfg(any(feature = "inspector", debug_assertions))]
6150    pub fn insert_inspector_hitbox(
6151        &mut self,
6152        hitbox_id: HitboxId,
6153        inspector_id: Option<&crate::InspectorElementId>,
6154        cx: &App,
6155    ) {
6156        self.invalidator.debug_assert_paint_or_prepaint();
6157        if !self.is_inspector_picking(cx) {
6158            return;
6159        }
6160        if let Some(inspector_id) = inspector_id {
6161            self.next_frame
6162                .inspector_hitboxes
6163                .insert(hitbox_id, inspector_id.clone());
6164        }
6165    }
6166
6167    #[cfg(any(feature = "inspector", debug_assertions))]
6168    fn paint_inspector_hitbox(&mut self, cx: &App) {
6169        if let Some(inspector) = self.inspector.as_ref() {
6170            let inspector = inspector.read(cx);
6171            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
6172                && let Some(hitbox) = self
6173                    .next_frame
6174                    .hitboxes
6175                    .iter()
6176                    .find(|hitbox| hitbox.id == hitbox_id)
6177            {
6178                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
6179            }
6180        }
6181    }
6182
6183    #[cfg(any(feature = "inspector", debug_assertions))]
6184    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6185        let Some(inspector) = self.inspector.clone() else {
6186            return;
6187        };
6188        if event.downcast_ref::<MouseMoveEvent>().is_some() {
6189            inspector.update(cx, |inspector, _cx| {
6190                if let Some((_, inspector_id)) =
6191                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6192                {
6193                    inspector.hover(inspector_id, self);
6194                }
6195            });
6196        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
6197            inspector.update(cx, |inspector, _cx| {
6198                if let Some((_, inspector_id)) =
6199                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6200                {
6201                    inspector.select(inspector_id, self);
6202                }
6203            });
6204        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
6205            // This should be kept in sync with SCROLL_LINES in x11 platform.
6206            const SCROLL_LINES: f32 = 3.0;
6207            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
6208            let delta_y = event
6209                .delta
6210                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
6211                .y;
6212            if let Some(inspector) = self.inspector.clone() {
6213                inspector.update(cx, |inspector, _cx| {
6214                    if let Some(depth) = inspector.pick_depth.as_mut() {
6215                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
6216                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
6217                        if *depth < 0.0 {
6218                            *depth = 0.0;
6219                        } else if *depth > max_depth {
6220                            *depth = max_depth;
6221                        }
6222                        if let Some((_, inspector_id)) =
6223                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6224                        {
6225                            inspector.set_active_element_id(inspector_id, self);
6226                        }
6227                    }
6228                });
6229            }
6230        }
6231    }
6232
6233    #[cfg(any(feature = "inspector", debug_assertions))]
6234    fn hovered_inspector_hitbox(
6235        &self,
6236        inspector: &Inspector,
6237        frame: &Frame,
6238    ) -> Option<(HitboxId, crate::InspectorElementId)> {
6239        if let Some(pick_depth) = inspector.pick_depth {
6240            let depth = (pick_depth as i64).try_into().unwrap_or(0);
6241            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
6242            let skip_count = (depth as usize).min(max_skipped);
6243            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
6244                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
6245                    return Some((*hitbox_id, inspector_id.clone()));
6246                }
6247            }
6248        }
6249        None
6250    }
6251
6252    /// For testing: set the current modifier keys state.
6253    /// This does not generate any events.
6254    #[cfg(any(test, feature = "test-support"))]
6255    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
6256        self.modifiers = modifiers;
6257    }
6258
6259    /// For testing: simulate a mouse move event to the given position.
6260    /// This dispatches the event through the normal event handling path,
6261    /// which will trigger hover states and tooltips.
6262    #[cfg(any(test, feature = "test-support"))]
6263    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
6264        let event = PlatformInput::MouseMove(MouseMoveEvent {
6265            position,
6266            modifiers: self.modifiers,
6267            pressed_button: None,
6268        });
6269        let _ = self.dispatch_event(event, cx);
6270    }
6271}
6272
6273// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
6274slotmap::new_key_type! {
6275    /// A unique identifier for a window.
6276    pub struct WindowId;
6277}
6278
6279impl WindowId {
6280    /// Converts this window ID to a `u64`.
6281    pub fn as_u64(&self) -> u64 {
6282        self.0.as_ffi()
6283    }
6284}
6285
6286impl From<u64> for WindowId {
6287    fn from(value: u64) -> Self {
6288        WindowId(slotmap::KeyData::from_ffi(value))
6289    }
6290}
6291
6292/// A handle to a window with a specific root view type.
6293/// Note that this does not keep the window alive on its own.
6294#[derive(Deref, DerefMut)]
6295pub struct WindowHandle<V> {
6296    #[deref]
6297    #[deref_mut]
6298    pub(crate) any_handle: AnyWindowHandle,
6299    state_type: PhantomData<fn(V) -> V>,
6300}
6301
6302impl<V> Debug for WindowHandle<V> {
6303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6304        f.debug_struct("WindowHandle")
6305            .field("any_handle", &self.any_handle.id.as_u64())
6306            .finish()
6307    }
6308}
6309
6310impl<V: 'static + Render> WindowHandle<V> {
6311    /// Creates a new handle from a window ID.
6312    /// This does not check if the root type of the window is `V`.
6313    pub fn new(id: WindowId) -> Self {
6314        WindowHandle {
6315            any_handle: AnyWindowHandle {
6316                id,
6317                state_type: TypeId::of::<V>(),
6318            },
6319            state_type: PhantomData,
6320        }
6321    }
6322
6323    /// Get the root view out of this window.
6324    ///
6325    /// This will fail if the window is closed or if the root view's type does not match `V`.
6326    #[cfg(any(test, feature = "test-support"))]
6327    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
6328    where
6329        C: AppContext,
6330    {
6331        cx.update_window(self.any_handle, |root_view, _, _| {
6332            root_view
6333                .downcast::<V>()
6334                .map_err(|_| anyhow!("the type of the window's root view has changed"))
6335        })?
6336    }
6337
6338    /// Updates the root view of this window.
6339    ///
6340    /// This will fail if the window has been closed or if the root view's type does not match
6341    pub fn update<C, R>(
6342        &self,
6343        cx: &mut C,
6344        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
6345    ) -> Result<R>
6346    where
6347        C: AppContext,
6348    {
6349        cx.update_window(self.any_handle, |root_view, window, cx| {
6350            let view = root_view
6351                .downcast::<V>()
6352                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6353
6354            Ok(view.update(cx, |view, cx| update(view, window, cx)))
6355        })?
6356    }
6357
6358    /// Read the root view out of this window.
6359    ///
6360    /// This will fail if the window is closed or if the root view's type does not match `V`.
6361    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
6362        let x = cx
6363            .windows
6364            .get(self.id)
6365            .and_then(|window| {
6366                window
6367                    .as_deref()
6368                    .and_then(|window| window.root.clone())
6369                    .map(|root_view| root_view.downcast::<V>())
6370            })
6371            .context("window not found")?
6372            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6373
6374        Ok(x.read(cx))
6375    }
6376
6377    /// Read the root view out of this window, with a callback
6378    ///
6379    /// This will fail if the window is closed or if the root view's type does not match `V`.
6380    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
6381    where
6382        C: AppContext,
6383    {
6384        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
6385    }
6386
6387    /// Read the root view pointer off of this window.
6388    ///
6389    /// This will fail if the window is closed or if the root view's type does not match `V`.
6390    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
6391    where
6392        C: AppContext,
6393    {
6394        cx.read_window(self, |root_view, _cx| root_view)
6395    }
6396
6397    /// Check if this window is 'active'.
6398    ///
6399    /// Will return `None` if the window is closed or currently
6400    /// borrowed.
6401    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
6402        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
6403            .ok()
6404    }
6405}
6406
6407impl<V> Copy for WindowHandle<V> {}
6408
6409impl<V> Clone for WindowHandle<V> {
6410    fn clone(&self) -> Self {
6411        *self
6412    }
6413}
6414
6415impl<V> PartialEq for WindowHandle<V> {
6416    fn eq(&self, other: &Self) -> bool {
6417        self.any_handle == other.any_handle
6418    }
6419}
6420
6421impl<V> Eq for WindowHandle<V> {}
6422
6423impl<V> Hash for WindowHandle<V> {
6424    fn hash<H: Hasher>(&self, state: &mut H) {
6425        self.any_handle.hash(state);
6426    }
6427}
6428
6429impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
6430    fn from(val: WindowHandle<V>) -> Self {
6431        val.any_handle
6432    }
6433}
6434
6435/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
6436#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
6437pub struct AnyWindowHandle {
6438    pub(crate) id: WindowId,
6439    state_type: TypeId,
6440}
6441
6442impl AnyWindowHandle {
6443    /// Get the ID of this window.
6444    pub fn window_id(&self) -> WindowId {
6445        self.id
6446    }
6447
6448    /// Attempt to convert this handle to a window handle with a specific root view type.
6449    /// If the types do not match, this will return `None`.
6450    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
6451        if TypeId::of::<T>() == self.state_type {
6452            Some(WindowHandle {
6453                any_handle: *self,
6454                state_type: PhantomData,
6455            })
6456        } else {
6457            None
6458        }
6459    }
6460
6461    /// Updates the state of the root view of this window.
6462    ///
6463    /// This will fail if the window has been closed.
6464    pub fn update<C, R>(
6465        self,
6466        cx: &mut C,
6467        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
6468    ) -> Result<R>
6469    where
6470        C: AppContext,
6471    {
6472        cx.update_window(self, update)
6473    }
6474
6475    /// Read the state of the root view of this window.
6476    ///
6477    /// This will fail if the window has been closed.
6478    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
6479    where
6480        C: AppContext,
6481        T: 'static,
6482    {
6483        let view = self
6484            .downcast::<T>()
6485            .context("the type of the window's root view has changed")?;
6486
6487        cx.read_window(&view, read)
6488    }
6489}
6490
6491impl HasWindowHandle for Window {
6492    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
6493        self.platform_window.window_handle()
6494    }
6495}
6496
6497impl HasDisplayHandle for Window {
6498    fn display_handle(
6499        &self,
6500    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
6501        self.platform_window.display_handle()
6502    }
6503}
6504
6505/// An identifier for an [`Element`].
6506///
6507/// Can be constructed with a string, a number, or both, as well
6508/// as other internal representations.
6509#[derive(Clone, Debug, Eq, PartialEq, Hash)]
6510pub enum ElementId {
6511    /// The ID of a View element
6512    View(EntityId),
6513    /// An integer ID.
6514    Integer(u64),
6515    /// A string based ID.
6516    Name(SharedString),
6517    /// A UUID.
6518    Uuid(Uuid),
6519    /// An ID that's equated with a focus handle.
6520    FocusHandle(FocusId),
6521    /// A combination of a name and an integer.
6522    NamedInteger(SharedString, u64),
6523    /// A path.
6524    Path(Arc<std::path::Path>),
6525    /// A code location.
6526    CodeLocation(core::panic::Location<'static>),
6527    /// A labeled child of an element.
6528    NamedChild(Arc<ElementId>, SharedString),
6529    /// A byte array ID (used for text-anchors)
6530    OpaqueId([u8; 20]),
6531}
6532
6533impl ElementId {
6534    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
6535    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
6536        Self::NamedInteger(name.into(), integer as u64)
6537    }
6538}
6539
6540impl Display for ElementId {
6541    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6542        match self {
6543            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
6544            ElementId::Integer(ix) => write!(f, "{}", ix)?,
6545            ElementId::Name(name) => write!(f, "{}", name)?,
6546            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
6547            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
6548            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
6549            ElementId::Path(path) => write!(f, "{}", path.display())?,
6550            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
6551            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
6552            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
6553        }
6554
6555        Ok(())
6556    }
6557}
6558
6559impl TryInto<SharedString> for ElementId {
6560    type Error = anyhow::Error;
6561
6562    fn try_into(self) -> anyhow::Result<SharedString> {
6563        if let ElementId::Name(name) = self {
6564            Ok(name)
6565        } else {
6566            anyhow::bail!("element id is not string")
6567        }
6568    }
6569}
6570
6571impl From<usize> for ElementId {
6572    fn from(id: usize) -> Self {
6573        ElementId::Integer(id as u64)
6574    }
6575}
6576
6577impl From<i32> for ElementId {
6578    fn from(id: i32) -> Self {
6579        Self::Integer(id as u64)
6580    }
6581}
6582
6583impl From<SharedString> for ElementId {
6584    fn from(name: SharedString) -> Self {
6585        ElementId::Name(name)
6586    }
6587}
6588
6589impl From<String> for ElementId {
6590    fn from(name: String) -> Self {
6591        ElementId::Name(name.into())
6592    }
6593}
6594
6595impl From<Arc<str>> for ElementId {
6596    fn from(name: Arc<str>) -> Self {
6597        ElementId::Name(name.into())
6598    }
6599}
6600
6601impl From<Arc<std::path::Path>> for ElementId {
6602    fn from(path: Arc<std::path::Path>) -> Self {
6603        ElementId::Path(path)
6604    }
6605}
6606
6607impl From<&'static str> for ElementId {
6608    fn from(name: &'static str) -> Self {
6609        ElementId::Name(SharedString::new_static(name))
6610    }
6611}
6612
6613impl<'a> From<&'a FocusHandle> for ElementId {
6614    fn from(handle: &'a FocusHandle) -> Self {
6615        ElementId::FocusHandle(handle.id)
6616    }
6617}
6618
6619impl From<(&'static str, EntityId)> for ElementId {
6620    fn from((name, id): (&'static str, EntityId)) -> Self {
6621        ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
6622    }
6623}
6624
6625impl From<(&'static str, usize)> for ElementId {
6626    fn from((name, id): (&'static str, usize)) -> Self {
6627        ElementId::NamedInteger(SharedString::new_static(name), id as u64)
6628    }
6629}
6630
6631impl From<(SharedString, usize)> for ElementId {
6632    fn from((name, id): (SharedString, usize)) -> Self {
6633        ElementId::NamedInteger(name, id as u64)
6634    }
6635}
6636
6637impl From<(&'static str, u64)> for ElementId {
6638    fn from((name, id): (&'static str, u64)) -> Self {
6639        ElementId::NamedInteger(SharedString::new_static(name), id)
6640    }
6641}
6642
6643impl From<Uuid> for ElementId {
6644    fn from(value: Uuid) -> Self {
6645        Self::Uuid(value)
6646    }
6647}
6648
6649impl From<(&'static str, u32)> for ElementId {
6650    fn from((name, id): (&'static str, u32)) -> Self {
6651        ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
6652    }
6653}
6654
6655impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
6656    fn from((id, name): (ElementId, T)) -> Self {
6657        ElementId::NamedChild(Arc::new(id), name.into())
6658    }
6659}
6660
6661impl From<&'static core::panic::Location<'static>> for ElementId {
6662    fn from(location: &'static core::panic::Location<'static>) -> Self {
6663        ElementId::CodeLocation(*location)
6664    }
6665}
6666
6667impl From<[u8; 20]> for ElementId {
6668    fn from(opaque_id: [u8; 20]) -> Self {
6669        ElementId::OpaqueId(opaque_id)
6670    }
6671}
6672
6673/// A rectangle to be rendered in the window at the given position and size.
6674/// Passed as an argument [`Window::paint_quad`].
6675#[derive(Clone)]
6676pub struct PaintQuad {
6677    /// The bounds of the quad within the window.
6678    pub bounds: Bounds<Pixels>,
6679    /// The radii of the quad's corners.
6680    pub corner_radii: Corners<Pixels>,
6681    /// The background color of the quad.
6682    pub background: Background,
6683    /// The widths of the quad's borders.
6684    pub border_widths: Edges<Pixels>,
6685    /// The color of the quad's borders.
6686    pub border_color: Hsla,
6687    /// The style of the quad's borders.
6688    pub border_style: BorderStyle,
6689}
6690
6691impl PaintQuad {
6692    /// Sets the corner radii of the quad.
6693    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
6694        PaintQuad {
6695            corner_radii: corner_radii.into(),
6696            ..self
6697        }
6698    }
6699
6700    /// Sets the border widths of the quad.
6701    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
6702        PaintQuad {
6703            border_widths: border_widths.into(),
6704            ..self
6705        }
6706    }
6707
6708    /// Sets the border color of the quad.
6709    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
6710        PaintQuad {
6711            border_color: border_color.into(),
6712            ..self
6713        }
6714    }
6715
6716    /// Sets the background color of the quad.
6717    pub fn background(self, background: impl Into<Background>) -> Self {
6718        PaintQuad {
6719            background: background.into(),
6720            ..self
6721        }
6722    }
6723}
6724
6725/// Creates a quad with the given parameters.
6726pub fn quad(
6727    bounds: Bounds<Pixels>,
6728    corner_radii: impl Into<Corners<Pixels>>,
6729    background: impl Into<Background>,
6730    border_widths: impl Into<Edges<Pixels>>,
6731    border_color: impl Into<Hsla>,
6732    border_style: BorderStyle,
6733) -> PaintQuad {
6734    PaintQuad {
6735        bounds,
6736        corner_radii: corner_radii.into(),
6737        background: background.into(),
6738        border_widths: border_widths.into(),
6739        border_color: border_color.into(),
6740        border_style,
6741    }
6742}
6743
6744/// Creates a filled quad with the given bounds and background color.
6745pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
6746    PaintQuad {
6747        bounds: bounds.into(),
6748        corner_radii: (0.).into(),
6749        background: background.into(),
6750        border_widths: (0.).into(),
6751        border_color: transparent_black(),
6752        border_style: BorderStyle::default(),
6753    }
6754}
6755
6756/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
6757pub fn outline(
6758    bounds: impl Into<Bounds<Pixels>>,
6759    border_color: impl Into<Hsla>,
6760    border_style: BorderStyle,
6761) -> PaintQuad {
6762    PaintQuad {
6763        bounds: bounds.into(),
6764        corner_radii: (0.).into(),
6765        background: transparent_black().into(),
6766        border_widths: (1.).into(),
6767        border_color: border_color.into(),
6768        border_style,
6769    }
6770}
6771
6772#[cfg(test)]
6773mod tests {
6774    use std::{
6775        cell::{Cell, RefCell},
6776        path::PathBuf,
6777        rc::Rc,
6778    };
6779
6780    use crate::{
6781        AnyWindowHandle, AppContext as _, Bounds, Context, DragMoveEvent, Empty,
6782        ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
6783        InputEvent as _, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
6784        MouseMoveEvent, ParentElement, Pixels, Point, Render, StatefulInteractiveElement as _,
6785        Styled, TestAppContext, Window, WindowAppearance, WindowOptions, canvas, div, point, px,
6786        size,
6787    };
6788
6789    struct EmptyView;
6790
6791    impl Render for EmptyView {
6792        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6793            div()
6794        }
6795    }
6796
6797    crate::actions!(pending_timeout_regression, [TimeoutAction]);
6798
6799    struct PendingView {
6800        focus: FocusHandle,
6801        dispatched: Rc<Cell<usize>>,
6802    }
6803
6804    impl Render for PendingView {
6805        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6806            let dispatched = self.dispatched.clone();
6807            div()
6808                .track_focus(&self.focus)
6809                .on_action(move |_: &TimeoutAction, _, _| {
6810                    dispatched.set(dispatched.get() + 1);
6811                })
6812        }
6813    }
6814
6815    #[gpui::test]
6816    fn stale_pending_timeout_does_not_consume_replacement(cx: &mut TestAppContext) {
6817        use crate::{KeyBinding, KeyDownEvent, Keystroke, PlatformInput};
6818        use std::time::Duration;
6819        let dispatched = Rc::new(Cell::new(0));
6820        cx.update(|cx| {
6821            cx.bind_keys([
6822                KeyBinding::new("ctrl-k", TimeoutAction, None),
6823                KeyBinding::new("ctrl-k ctrl-c", TimeoutAction, None),
6824            ])
6825        });
6826        let window = cx.add_window(|window, cx| {
6827            let focus = cx.focus_handle();
6828            window.focus(&focus, cx);
6829            PendingView {
6830                focus,
6831                dispatched: dispatched.clone(),
6832            }
6833        });
6834        let send_prefix = |window: &mut Window, cx: &mut crate::App| {
6835            window.dispatch_event(
6836                PlatformInput::KeyDown(KeyDownEvent {
6837                    keystroke: Keystroke::parse("ctrl-k").unwrap(),
6838                    is_held: false,
6839                    prefer_character_input: false,
6840                }),
6841                cx,
6842            );
6843        };
6844        let _stale = cx
6845            .update_window(window.into(), |_, window, cx| {
6846                send_prefix(window, cx);
6847                // Retain the actual production task beyond sequence replacement to
6848                // exercise the generation guard independently of task cancellation.
6849                window.pending_input.as_mut().unwrap().timer.take().unwrap()
6850            })
6851            .unwrap();
6852        cx.executor().advance_clock(Duration::from_millis(500));
6853        cx.update_window(window.into(), |_, window, cx| send_prefix(window, cx))
6854            .unwrap();
6855        assert_eq!(dispatched.get(), 1);
6856        cx.executor().advance_clock(Duration::from_millis(500));
6857        cx.run_until_parked();
6858        window
6859            .update(cx, |_, window, _| assert!(window.has_pending_keystrokes()))
6860            .unwrap();
6861        assert_eq!(dispatched.get(), 1);
6862        cx.executor().advance_clock(Duration::from_millis(500));
6863        cx.run_until_parked();
6864        assert_eq!(dispatched.get(), 2);
6865    }
6866
6867    #[gpui::test]
6868    fn resumed_timeout_cannot_update_replacement_window(cx: &mut TestAppContext) {
6869        use futures::channel::oneshot;
6870        use std::time::Duration;
6871
6872        let old = cx.add_window(|_, _| EmptyView);
6873        let (resume, resumed) = oneshot::channel();
6874        let timer_ready = Rc::new(Cell::new(false));
6875        let completed = Rc::new(Cell::new(false));
6876        let _task = old
6877            .update(cx, |_, window, app| {
6878                let timer_ready = timer_ready.clone();
6879                let completed = completed.clone();
6880                window.spawn(app, async move |cx| {
6881                    cx.background_executor.timer(Duration::from_secs(1)).await;
6882                    timer_ready.set(true);
6883                    // Hold a resumed task at the lifecycle boundary. Production has
6884                    // no await here, but cancellation must also tolerate late work.
6885                    resumed.await.unwrap();
6886                    assert_eq!(
6887                        cx.update_if_present(|_, _| panic!("stale work ran"))
6888                            .unwrap(),
6889                        None
6890                    );
6891                    completed.set(true);
6892                })
6893            })
6894            .unwrap();
6895        cx.executor().advance_clock(Duration::from_secs(1));
6896        cx.run_until_parked();
6897        assert!(timer_ready.get());
6898        old.update(cx, |_, window, _| window.remove_window())
6899            .unwrap();
6900        let replacement = cx.add_window(|_, _| EmptyView);
6901        assert_ne!(old.window_id(), replacement.window_id());
6902        resume.send(()).unwrap();
6903        cx.run_until_parked();
6904        assert!(completed.get());
6905        replacement
6906            .update(cx, |_, window, _| assert!(!window.has_pending_keystrokes()))
6907            .unwrap();
6908    }
6909
6910    #[gpui::test]
6911    fn optional_window_update_preserves_unrelated_errors(cx: &mut TestAppContext) {
6912        let window = cx.add_window(|_, _| EmptyView);
6913        let mut context = window
6914            .update(cx, |_, window, app| window.to_async(app))
6915            .unwrap();
6916        assert_eq!(context.update_if_present(|_, _| 42).unwrap(), Some(42));
6917        // Callback errors stay nested values, just as with the original update API.
6918        assert!(
6919            context
6920                .update_if_present(|_, _| Err::<(), _>(anyhow::anyhow!("callback failure")))
6921                .unwrap()
6922                .unwrap()
6923                .is_err()
6924        );
6925        cx.update(|_| {
6926            assert!(context.update_if_present(|_, _| ()).is_err());
6927        });
6928        window
6929            .update(cx, |_, window, _| window.remove_window())
6930            .unwrap();
6931        assert_eq!(context.update_if_present(|_, _| ()).unwrap(), None);
6932    }
6933
6934    struct OpensWindowOnPaint {
6935        opened: Rc<Cell<bool>>,
6936    }
6937
6938    impl Render for OpensWindowOnPaint {
6939        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6940            let opened = self.opened.clone();
6941            div()
6942                .size_full()
6943                .child(canvas(
6944                    |_, _, _| {},
6945                    move |_, _, _window, cx| {
6946                        if !opened.replace(true) {
6947                            cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
6948                                .unwrap();
6949                        }
6950                    },
6951                ))
6952                // Siblings painted after the canvas: their elements were
6953                // allocated in the arena before the nested draw, so they detect
6954                // a mid-draw arena clear when painted afterwards.
6955                .child(div().child("after"))
6956        }
6957    }
6958
6959    /// Opening a window synchronously draws it and requests an element arena
6960    /// clear. When that happens from within another window's draw (here: from
6961    /// an element's paint), the clear must be deferred until the outer draw
6962    /// finishes, or the outer draw's arena-allocated elements would be freed
6963    /// out from under it.
6964    #[test]
6965    fn test_window_opened_during_draw_defers_arena_clear() {
6966        let mut cx = TestAppContext::single();
6967
6968        let opened = Rc::new(Cell::new(false));
6969        // add_window draws once, which runs the nested open_window mid-draw.
6970        let window = cx.add_window({
6971            let opened = opened.clone();
6972            move |_, _| OpensWindowOnPaint { opened }
6973        });
6974
6975        assert!(opened.get());
6976        assert_eq!(cx.windows().len(), 2);
6977
6978        // The deferred clear must actually run once the outer draw unwinds:
6979        // subsequent draws of both windows work against a fresh arena.
6980        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
6981            .unwrap();
6982    }
6983
6984    #[gpui::test]
6985    fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
6986        let window = cx.add_window(|_, _| EmptyView);
6987        let observed_appearance = Rc::new(Cell::new(None));
6988        let _subscription = window
6989            .update(cx, {
6990                let observed_appearance = observed_appearance.clone();
6991                move |_, window, _| {
6992                    window.observe_window_appearance(move |window, _| {
6993                        observed_appearance.set(Some(window.appearance()));
6994                    })
6995                }
6996            })
6997            .unwrap();
6998        let test_window = cx.test_window(window.into());
6999
7000        cx.update(|_| {
7001            test_window.simulate_appearance_change(WindowAppearance::Dark);
7002            assert_eq!(observed_appearance.get(), None);
7003        });
7004        cx.run_until_parked();
7005
7006        assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
7007    }
7008
7009    struct RootView {
7010        explicit_size: bool,
7011        child_bounds: Rc<Cell<Bounds<Pixels>>>,
7012    }
7013
7014    impl Render for RootView {
7015        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7016            let child_bounds = self.child_bounds.clone();
7017            let root = div().flex().flex_col().child(
7018                canvas(
7019                    move |bounds, _, _| child_bounds.set(bounds),
7020                    |_, _, _, _| {},
7021                )
7022                .size_full(),
7023            );
7024            if self.explicit_size {
7025                root.w(px(300.)).h(px(200.))
7026            } else {
7027                root
7028            }
7029        }
7030    }
7031
7032    #[test]
7033    fn auto_sized_window_root_fills_the_window() {
7034        let mut cx = TestAppContext::single();
7035        let child_bounds = Rc::new(Cell::new(Bounds::default()));
7036        let window = cx.add_window({
7037            let child_bounds = child_bounds.clone();
7038            move |_, _| RootView {
7039                explicit_size: false,
7040                child_bounds,
7041            }
7042        });
7043
7044        let viewport_size = cx
7045            .update_window(window.into(), |_, window, cx| {
7046                window.draw(cx).clear(cx);
7047                window.viewport_size()
7048            })
7049            .unwrap();
7050
7051        assert_eq!(child_bounds.get().size, viewport_size);
7052    }
7053
7054    #[test]
7055    fn explicitly_sized_window_root_keeps_its_size() {
7056        let mut cx = TestAppContext::single();
7057        let child_bounds = Rc::new(Cell::new(Bounds::default()));
7058        let window = cx.add_window({
7059            let child_bounds = child_bounds.clone();
7060            move |_, _| RootView {
7061                explicit_size: true,
7062                child_bounds,
7063            }
7064        });
7065
7066        cx.update_window(window.into(), |_, window, cx| {
7067            window.draw(cx).clear(cx);
7068        })
7069        .unwrap();
7070
7071        assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
7072    }
7073
7074    struct FileDragView {
7075        path: PathBuf,
7076        observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7077        observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7078    }
7079
7080    impl Render for FileDragView {
7081        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7082            div()
7083                .id("file-drag")
7084                .size_full()
7085                .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
7086                .external_drag_payload(|path: &PathBuf, _, _| {
7087                    Some(ExternalDragPayload::Files(FileDragPaths::new([(
7088                        path.clone(),
7089                        true,
7090                    )])))
7091                })
7092                .on_drag_move({
7093                    let observed_drag_moves = self.observed_drag_moves.clone();
7094                    move |event: &DragMoveEvent<PathBuf>, _, _| {
7095                        observed_drag_moves.borrow_mut().push(event.event.position);
7096                    }
7097                })
7098                .on_drop({
7099                    let observed_drops = self.observed_drops.clone();
7100                    move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
7101                })
7102        }
7103    }
7104
7105    #[gpui::test]
7106    fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
7107        struct Drag {
7108            window: AnyWindowHandle,
7109            observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7110            observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7111        }
7112
7113        fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
7114            let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
7115            let observed_drops = Rc::new(RefCell::new(Vec::new()));
7116            let window: AnyWindowHandle = cx
7117                .add_window({
7118                    let observed_drag_moves = observed_drag_moves.clone();
7119                    let observed_drops = observed_drops.clone();
7120                    move |_, _| FileDragView {
7121                        path,
7122                        observed_drag_moves,
7123                        observed_drops,
7124                    }
7125                })
7126                .into();
7127            cx.test_window(window)
7128                .set_start_external_drag_result(platform_result);
7129
7130            let update_result = cx.update_window(window, |_, window, cx| {
7131                window.draw(cx).clear(cx);
7132                window.dispatch_event(
7133                    MouseDownEvent {
7134                        position: point(px(10.), px(10.)),
7135                        button: MouseButton::Left,
7136                        modifiers: Default::default(),
7137                        click_count: 1,
7138                        first_mouse: false,
7139                    }
7140                    .to_platform_input(),
7141                    cx,
7142                );
7143                window.dispatch_event(
7144                    MouseMoveEvent {
7145                        position: point(px(20.), px(20.)),
7146                        pressed_button: Some(MouseButton::Left),
7147                        modifiers: Default::default(),
7148                    }
7149                    .to_platform_input(),
7150                    cx,
7151                );
7152                assert!(cx.active_drag.is_some());
7153            });
7154            assert!(
7155                update_result.is_ok(),
7156                "failed to start drag: {update_result:?}"
7157            );
7158
7159            assert!(cx.test_window(window).external_drag_files().is_empty());
7160            Drag {
7161                window,
7162                observed_drag_moves,
7163                observed_drops,
7164            }
7165        }
7166
7167        let successful_path = PathBuf::from("/tmp/successful-drag");
7168        let successful = start_drag(cx, successful_path.clone(), true);
7169        let outside_position = point(px(-1.), px(20.));
7170        let update_result = cx.update_window(successful.window, |_, window, cx| {
7171            window.dispatch_event(
7172                MouseMoveEvent {
7173                    position: outside_position,
7174                    pressed_button: Some(MouseButton::Left),
7175                    modifiers: Default::default(),
7176                }
7177                .to_platform_input(),
7178                cx,
7179            );
7180            assert!(cx.active_drag.is_none());
7181        });
7182        assert!(
7183            update_result.is_ok(),
7184            "failed to promote drag: {update_result:?}"
7185        );
7186        assert_eq!(
7187            cx.test_window(successful.window).external_drag_files(),
7188            [(successful_path.clone(), true)]
7189        );
7190        // Views must still see the move that leaves the window, otherwise they never learn to tear
7191        // down the drag state they built up while the pointer was inside.
7192        assert_eq!(
7193            successful.observed_drag_moves.borrow().last(),
7194            Some(&outside_position)
7195        );
7196
7197        let destination: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
7198        let reentry_position = point(px(30.), px(30.));
7199        let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
7200        let update_result = cx.update_window(destination, |_, window, cx| {
7201            window.dispatch_event(
7202                FileDropEvent::Entered {
7203                    position: reentry_position,
7204                    paths: external_paths(),
7205                }
7206                .to_platform_input(),
7207                cx,
7208            );
7209            assert!(
7210                cx.active_drag
7211                    .as_ref()
7212                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7213            );
7214            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7215            assert!(cx.active_drag.is_none());
7216        });
7217        assert!(
7218            update_result.is_ok(),
7219            "failed to handle drag in destination window: {update_result:?}"
7220        );
7221
7222        let update_result = cx.update_window(successful.window, |_, window, cx| {
7223            window.dispatch_event(
7224                FileDropEvent::Entered {
7225                    position: reentry_position,
7226                    paths: external_paths(),
7227                }
7228                .to_platform_input(),
7229                cx,
7230            );
7231            assert!(
7232                cx.active_drag
7233                    .as_ref()
7234                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7235            );
7236            assert_eq!(
7237                successful.observed_drag_moves.borrow().last(),
7238                Some(&reentry_position)
7239            );
7240
7241            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7242            assert!(cx.active_drag.is_none());
7243
7244            window.dispatch_event(
7245                FileDropEvent::Entered {
7246                    position: reentry_position,
7247                    paths: external_paths(),
7248                }
7249                .to_platform_input(),
7250                cx,
7251            );
7252            assert!(
7253                cx.active_drag
7254                    .as_ref()
7255                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7256            );
7257
7258            window.dispatch_event(
7259                FileDropEvent::Submit {
7260                    position: reentry_position,
7261                }
7262                .to_platform_input(),
7263                cx,
7264            );
7265            assert_eq!(
7266                successful.observed_drops.borrow().as_slice(),
7267                std::slice::from_ref(&successful_path)
7268            );
7269            assert!(cx.active_drag.is_none());
7270
7271            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7272            assert!(cx.active_drag.is_none());
7273            window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
7274            assert!(cx.active_drag.is_none());
7275
7276            window.dispatch_event(
7277                FileDropEvent::Entered {
7278                    position: reentry_position,
7279                    paths: external_paths(),
7280                }
7281                .to_platform_input(),
7282                cx,
7283            );
7284            assert!(
7285                cx.active_drag
7286                    .as_ref()
7287                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7288            );
7289            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7290        });
7291        assert!(
7292            update_result.is_ok(),
7293            "failed to restore drag in source window: {update_result:?}"
7294        );
7295
7296        let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
7297        let cancelled = start_drag(cx, cancelled_path.clone(), true);
7298        let update_result = cx.update_window(cancelled.window, |_, window, cx| {
7299            window.dispatch_event(
7300                MouseMoveEvent {
7301                    position: outside_position,
7302                    pressed_button: Some(MouseButton::Left),
7303                    modifiers: Default::default(),
7304                }
7305                .to_platform_input(),
7306                cx,
7307            );
7308            assert!(cx.active_drag.is_none());
7309
7310            window.dispatch_event(
7311                FileDropEvent::Entered {
7312                    position: reentry_position,
7313                    paths: ExternalPaths([cancelled_path].into_iter().collect()),
7314                }
7315                .to_platform_input(),
7316                cx,
7317            );
7318            assert!(
7319                cx.active_drag
7320                    .as_ref()
7321                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7322            );
7323            assert!(cx.stop_active_drag(window));
7324            assert!(cx.active_drag.is_none());
7325        });
7326        assert!(
7327            update_result.is_ok(),
7328            "failed to cancel restored drag: {update_result:?}"
7329        );
7330        assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
7331
7332        let removed_path = PathBuf::from("/tmp/removed-window-drag");
7333        let removed = start_drag(cx, removed_path, true);
7334        let removed_window_id = removed.window.window_id();
7335        let update_result = cx.update_window(removed.window, |_, window, cx| {
7336            window.dispatch_event(
7337                MouseMoveEvent {
7338                    position: outside_position,
7339                    pressed_button: Some(MouseButton::Left),
7340                    modifiers: Default::default(),
7341                }
7342                .to_platform_input(),
7343                cx,
7344            );
7345            assert!(cx.active_drag.is_none());
7346            window.remove_window();
7347        });
7348        assert!(
7349            update_result.is_ok(),
7350            "failed to remove drag source window: {update_result:?}"
7351        );
7352        assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
7353
7354        let failed_path = PathBuf::from("/tmp/failed-drag");
7355        let failed = start_drag(cx, failed_path.clone(), false);
7356        let update_result = cx.update_window(failed.window, |_, window, cx| {
7357            for x_position in [-1., -2.] {
7358                window.dispatch_event(
7359                    MouseMoveEvent {
7360                        position: point(px(x_position), px(20.)),
7361                        pressed_button: Some(MouseButton::Left),
7362                        modifiers: Default::default(),
7363                    }
7364                    .to_platform_input(),
7365                    cx,
7366                );
7367            }
7368            assert!(cx.active_drag.is_some());
7369        });
7370        assert!(
7371            update_result.is_ok(),
7372            "failed to retain drag after platform failure: {update_result:?}"
7373        );
7374        assert_eq!(
7375            cx.test_window(failed.window).external_drag_files(),
7376            [(failed_path, true)]
7377        );
7378    }
7379
7380    struct FocusForwarder {
7381        a: FocusHandle,
7382        b: FocusHandle,
7383    }
7384
7385    impl Render for FocusForwarder {
7386        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7387            div()
7388                .size_full()
7389                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
7390                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
7391        }
7392    }
7393
7394    /// When a focus listener moves focus again (e.g. a dock forwarding focus to its
7395    /// active panel), the resulting focus events must be dispatched without waiting
7396    /// for an unrelated redraw of the window.
7397    #[gpui::test]
7398    fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
7399        let b_focus_count = Rc::new(Cell::new(0));
7400        let window = cx.add_window({
7401            let b_focus_count = b_focus_count.clone();
7402            move |window, cx| {
7403                let a = cx.focus_handle();
7404                let b = cx.focus_handle();
7405                cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
7406                    let b = this.b.clone();
7407                    window.focus(&b, cx);
7408                })
7409                .detach();
7410                cx.on_focus(&b, window, move |_, _, _| {
7411                    b_focus_count.set(b_focus_count.get() + 1);
7412                })
7413                .detach();
7414                FocusForwarder { a, b }
7415            }
7416        });
7417
7418        window
7419            .update(cx, |_, window, _| window.activate_window())
7420            .unwrap();
7421        cx.executor().run_until_parked();
7422
7423        window
7424            .update(cx, |this, window, cx| {
7425                let a = this.a.clone();
7426                window.focus(&a, cx);
7427            })
7428            .unwrap();
7429        cx.executor().run_until_parked();
7430
7431        window
7432            .update(cx, |this, window, _| {
7433                assert!(this.b.is_focused(window));
7434            })
7435            .unwrap();
7436        assert_eq!(b_focus_count.get(), 1);
7437    }
7438
7439    #[gpui::test]
7440    fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
7441        use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
7442
7443        let window = cx.add_window(|_, _| EmptyView);
7444        window
7445            .update(cx, |_, window, _| {
7446                assert!(matches!(
7447                    window.window_handle(),
7448                    Err(HandleError::NotSupported)
7449                ));
7450                assert!(matches!(
7451                    window.display_handle(),
7452                    Err(HandleError::NotSupported)
7453                ));
7454            })
7455            .unwrap();
7456    }
7457}