Skip to main content

gpui/
window.rs

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