Skip to main content

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