Skip to main content

gpui/
window.rs

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