Skip to main content

gpui/
window.rs

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