Skip to main content

gpui/
window.rs

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