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