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