Skip to main content

gpui_authoring/
window.rs

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