Skip to main content

gpui/
window.rs

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