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(any(test, feature = "test-support", 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.paint_glyph_transformed(
5300            origin,
5301            font_id,
5302            glyph_id,
5303            font_size,
5304            color,
5305            TransformationMatrix::unit(),
5306        )
5307    }
5308
5309    /// Arc-rs extension: native glyph with a caller supplied sprite transform.
5310    pub fn paint_glyph_transformed(
5311        &mut self,
5312        origin: Point<Pixels>,
5313        font_id: FontId,
5314        glyph_id: GlyphId,
5315        font_size: Pixels,
5316        color: Hsla,
5317        transformation: TransformationMatrix,
5318    ) -> Result<()> {
5319        self.invalidator.debug_assert_paint();
5320
5321        let element_opacity = self.element_opacity();
5322        let scale_factor = self.scale_factor();
5323        let glyph_origin = origin.scale(scale_factor);
5324
5325        let quantized_origin = Point::new(
5326            round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
5327                / SUBPIXEL_VARIANTS_X as f32,
5328            round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
5329                / SUBPIXEL_VARIANTS_Y as f32,
5330        );
5331        let subpixel_variant = Point::new(
5332            (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
5333            (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
5334        );
5335        let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
5336        let subpixel_rendering = transformation == TransformationMatrix::unit()
5337            && self.should_use_subpixel_rendering(font_id, font_size);
5338        let dilation = self.text_system().glyph_dilation_for_color(color);
5339        let params = RenderGlyphParams {
5340            font_id,
5341            glyph_id,
5342            font_size,
5343            subpixel_variant,
5344            scale_factor,
5345            is_emoji: false,
5346            subpixel_rendering,
5347            dilation,
5348        };
5349
5350        let raster_bounds = self.text_system().raster_bounds(&params)?;
5351        if !raster_bounds.is_zero() {
5352            let tile = self
5353                .sprite_atlas
5354                .get_or_insert_with(params.clone().into(), &mut || {
5355                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
5356                    Ok(Some((size, Cow::Owned(bytes))))
5357                })?
5358                .expect("Callback above only errors or returns Some");
5359            let bounds = Bounds {
5360                origin: integer_origin + raster_bounds.origin.map(Into::into),
5361                size: tile.bounds.size.map(Into::into),
5362            };
5363            let content_mask = self.snapped_content_mask();
5364
5365            if subpixel_rendering {
5366                self.next_frame.scene.insert_primitive(SubpixelSprite {
5367                    order: 0,
5368                    pad: 0,
5369                    bounds,
5370                    content_mask,
5371                    color: color.opacity(element_opacity),
5372                    tile,
5373                    transformation: TransformationMatrix::unit(),
5374                });
5375            } else {
5376                self.next_frame.scene.insert_primitive(MonochromeSprite {
5377                    order: 0,
5378                    animation: SpriteAnimationId::NONE,
5379                    bounds,
5380                    content_mask,
5381                    color: color.opacity(element_opacity),
5382                    tile,
5383                    transformation,
5384                });
5385            }
5386        }
5387        Ok(())
5388    }
5389
5390    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
5391        // Checked first because it's cheap, while some platforms lock the window to read its
5392        // background appearance, and this runs for every glyph.
5393        if !self.platform_window.is_subpixel_rendering_supported() {
5394            return false;
5395        }
5396
5397        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
5398            return false;
5399        }
5400
5401        let mode = match self.text_rendering_mode.get() {
5402            TextRenderingMode::PlatformDefault => self
5403                .text_system()
5404                .recommended_rendering_mode(font_id, font_size),
5405            mode => mode,
5406        };
5407
5408        mode == TextRenderingMode::Subpixel
5409    }
5410
5411    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
5412    ///
5413    /// The y component of the origin is the baseline of the glyph.
5414    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
5415    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
5416    /// This method is only useful if you need to paint a single emoji that has already been shaped.
5417    ///
5418    /// This method should only be called as part of the paint phase of element drawing.
5419    pub fn paint_emoji(
5420        &mut self,
5421        origin: Point<Pixels>,
5422        font_id: FontId,
5423        glyph_id: GlyphId,
5424        font_size: Pixels,
5425    ) -> Result<()> {
5426        self.invalidator.debug_assert_paint();
5427
5428        let scale_factor = self.scale_factor();
5429        let glyph_origin = origin.scale(scale_factor);
5430        let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
5431        let params = RenderGlyphParams {
5432            font_id,
5433            glyph_id,
5434            font_size,
5435            subpixel_variant: Default::default(),
5436            scale_factor,
5437            is_emoji: true,
5438            subpixel_rendering: false,
5439            dilation: 0,
5440        };
5441
5442        let raster_bounds = self.text_system().raster_bounds(&params)?;
5443        if !raster_bounds.is_zero() {
5444            let tile = self
5445                .sprite_atlas
5446                .get_or_insert_with(params.clone().into(), &mut || {
5447                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
5448                    Ok(Some((size, Cow::Owned(bytes))))
5449                })?
5450                .expect("Callback above only errors or returns Some");
5451
5452            let bounds = Bounds {
5453                origin: integer_origin + raster_bounds.origin.map(Into::into),
5454                size: tile.bounds.size.map(Into::into),
5455            };
5456            let content_mask = self.snapped_content_mask();
5457            let opacity = self.element_opacity();
5458
5459            self.next_frame.scene.insert_primitive(PolychromeSprite {
5460                order: 0,
5461                pad: 0,
5462                grayscale: false.into(),
5463                bounds,
5464                corner_radii: Default::default(),
5465                content_mask,
5466                tile,
5467                opacity,
5468            });
5469        }
5470        Ok(())
5471    }
5472
5473    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
5474    ///
5475    /// This method should only be called as part of the paint phase of element drawing.
5476    /// Arc-rs extension: uploads raw coverage once, with fractional positioning and tint.
5477    pub fn paint_alpha_mask(
5478        &mut self,
5479        bounds: Bounds<Pixels>,
5480        mask: &crate::AlphaMask,
5481        transformation: TransformationMatrix,
5482        color: Hsla,
5483    ) -> Result<()> {
5484        self.invalidator.debug_assert_paint();
5485        let Some(tile) = self
5486            .sprite_atlas
5487            .get_or_insert_with(crate::AtlasKey::AlphaMask(mask.id), &mut || {
5488                Ok(Some((mask.size, Cow::Borrowed(mask.bytes.as_ref()))))
5489            })?
5490        else {
5491            return Ok(());
5492        };
5493        self.next_frame.scene.insert_primitive(MonochromeSprite {
5494            order: 0,
5495            animation: SpriteAnimationId::NONE,
5496            bounds: bounds.scale(self.scale_factor()),
5497            content_mask: self.snapped_content_mask(),
5498            color: color.opacity(self.element_opacity()),
5499            tile,
5500            transformation,
5501        });
5502        Ok(())
5503    }
5504
5505    /// Releases this window's atlas allocation for a raw coverage mask.
5506    pub fn drop_alpha_mask(&mut self, mask: &crate::AlphaMask) {
5507        self.sprite_atlas
5508            .remove(&crate::AtlasKey::AlphaMask(mask.id));
5509    }
5510
5511    /// Paints an SVG through the renderer's monochrome sprite atlas.
5512    pub fn paint_svg(
5513        &mut self,
5514        bounds: Bounds<Pixels>,
5515        path: SharedString,
5516        data: Option<&[u8]>,
5517        transformation: TransformationMatrix,
5518        color: Hsla,
5519        cx: &App,
5520    ) -> Result<()> {
5521        self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
5522    }
5523
5524    /// Like [`Self::paint_svg`], with an `animation` the window applies before every
5525    /// present, so the view isn't re-rendered to advance it.
5526    pub(crate) fn paint_animated_svg(
5527        &mut self,
5528        bounds: Bounds<Pixels>,
5529        path: SharedString,
5530        data: Option<&[u8]>,
5531        transformation: TransformationMatrix,
5532        animation: Option<SpriteAnimation>,
5533        color: Hsla,
5534        cx: &App,
5535    ) -> Result<()> {
5536        self.invalidator.debug_assert_paint();
5537
5538        let element_opacity = self.element_opacity();
5539        let bounds = self.snap_bounds(bounds);
5540
5541        let params = RenderSvgParams {
5542            path,
5543            size: bounds.size.map(|pixels| {
5544                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
5545            }),
5546        };
5547
5548        let Some(tile) =
5549            self.sprite_atlas
5550                .get_or_insert_with(params.clone().into(), &mut || {
5551                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
5552                    else {
5553                        return Ok(None);
5554                    };
5555                    Ok(Some((size, Cow::Owned(bytes))))
5556                })?
5557        else {
5558            return Ok(());
5559        };
5560        let content_mask = self.snapped_content_mask();
5561        let svg_bounds = Bounds {
5562            origin: bounds.center()
5563                - Point::new(
5564                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5565                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5566                ),
5567            size: tile
5568                .bounds
5569                .size
5570                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
5571        };
5572        let final_bounds = svg_bounds
5573            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
5574            .map_size(|size| size.ceil());
5575
5576        let sprite = MonochromeSprite {
5577            order: 0,
5578            animation: SpriteAnimationId::NONE,
5579            bounds: final_bounds,
5580            content_mask,
5581            color: color.opacity(element_opacity),
5582            tile,
5583            transformation,
5584        };
5585        match animation {
5586            Some(animation) => self
5587                .next_frame
5588                .scene
5589                .insert_animated_sprite(sprite, animation),
5590            None => self.next_frame.scene.insert_primitive(sprite),
5591        }
5592
5593        Ok(())
5594    }
5595
5596    /// Paint an image into the scene for the next frame at the current z-index.
5597    /// This method will panic if the frame_index is not valid
5598    ///
5599    /// This method should only be called as part of the paint phase of element drawing.
5600    /// Paint an image into `bounds`, positioning and scaling it according to `image_bounds`.
5601    ///
5602    /// The visible region rendered is `bounds.intersect(&image_bounds)`, with `corner_radii`
5603    /// applied to `bounds`.
5604    pub fn paint_image(
5605        &mut self,
5606        bounds: Bounds<Pixels>,
5607        image_bounds: Bounds<Pixels>,
5608        corner_radii: Corners<Pixels>,
5609        data: Arc<RenderImage>,
5610        frame_index: usize,
5611        grayscale: bool,
5612    ) -> Result<()> {
5613        self.invalidator.debug_assert_paint();
5614
5615        let visible_bounds = bounds.intersect(&image_bounds);
5616        if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
5617            return Ok(());
5618        }
5619        if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
5620            return Ok(());
5621        }
5622
5623        let params = RenderImageParams {
5624            image_id: data.id,
5625            frame_index,
5626        };
5627
5628        let tile = self
5629            .sprite_atlas
5630            .get_or_insert_with(params.into(), &mut || {
5631                Ok(Some((
5632                    data.size(frame_index),
5633                    Cow::Borrowed(
5634                        data.as_bytes(frame_index)
5635                            .expect("It's the caller's job to pass a valid frame index"),
5636                    ),
5637                )))
5638            })?
5639            .expect("Callback above only returns Some");
5640
5641        let visible_bounds_snapped = self.snap_bounds(visible_bounds);
5642
5643        let sub_tile = if visible_bounds == image_bounds {
5644            tile
5645        } else {
5646            let x_offset_ratio =
5647                (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
5648            let y_offset_ratio =
5649                (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
5650            let width_ratio = visible_bounds.size.width / image_bounds.size.width;
5651            let height_ratio = visible_bounds.size.height / image_bounds.size.height;
5652
5653            let tile_origin_x = tile.bounds.origin.x.0;
5654            let tile_origin_y = tile.bounds.origin.y.0;
5655            let tile_width = tile.bounds.size.width.0;
5656            let tile_height = tile.bounds.size.height.0;
5657
5658            let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
5659            let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
5660            let sub_width = (width_ratio * tile_width as f32).round() as i32;
5661            let sub_height = (height_ratio * tile_height as f32).round() as i32;
5662
5663            let max_x = tile_origin_x + tile_width;
5664            let max_y = tile_origin_y + tile_height;
5665
5666            let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
5667            let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
5668            let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
5669            let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
5670
5671            AtlasTile {
5672                bounds: Bounds {
5673                    origin: point(
5674                        DevicePixels(clamped_origin_x),
5675                        DevicePixels(clamped_origin_y),
5676                    ),
5677                    size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
5678                },
5679                ..tile
5680            }
5681        };
5682
5683        let content_mask = self.snapped_content_mask();
5684        let corner_radii = corner_radii
5685            .clamp_radii_for_quad_size(visible_bounds.size)
5686            .scale(self.scale_factor());
5687        let opacity = self.element_opacity();
5688
5689        self.next_frame.scene.insert_primitive(PolychromeSprite {
5690            order: 0,
5691            pad: 0,
5692            grayscale: grayscale.into(),
5693            bounds: visible_bounds_snapped,
5694            content_mask,
5695            corner_radii,
5696            tile: sub_tile,
5697            opacity,
5698        });
5699        Ok(())
5700    }
5701
5702    /// Paint a surface into the scene for the next frame at the current z-index.
5703    ///
5704    /// This method should only be called as part of the paint phase of element drawing.
5705    #[cfg(any(target_os = "macos", target_os = "ios"))]
5706    pub fn paint_surface(
5707        &mut self,
5708        bounds: Bounds<Pixels>,
5709        image_buffer: CFRetained<CVPixelBuffer>,
5710    ) {
5711        use crate::PaintSurface;
5712
5713        self.invalidator.debug_assert_paint();
5714
5715        let bounds = self.snap_bounds(bounds);
5716        let content_mask = self.snapped_content_mask();
5717        self.next_frame.scene.insert_primitive(PaintSurface {
5718            order: 0,
5719            bounds,
5720            content_mask,
5721            image_buffer,
5722        });
5723    }
5724
5725    /// Removes an image from the sprite atlas.
5726    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
5727        for frame_index in 0..data.frame_count() {
5728            let params = RenderImageParams {
5729                image_id: data.id,
5730                frame_index,
5731            };
5732
5733            self.sprite_atlas.remove(&params.into());
5734        }
5735
5736        Ok(())
5737    }
5738
5739    /// Returns whether every frame of an image is present in the sprite atlas.
5740    #[cfg(any(test, feature = "test-support"))]
5741    pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
5742        data.frame_count() > 0
5743            && (0..data.frame_count()).all(|frame_index| {
5744                self.sprite_atlas.contains(
5745                    &RenderImageParams {
5746                        image_id: data.id,
5747                        frame_index,
5748                    }
5749                    .into(),
5750                )
5751            })
5752    }
5753
5754    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
5755    /// layout is being requested, along with the layout ids of any children. This method is called during
5756    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
5757    ///
5758    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
5759    #[must_use]
5760    pub fn request_layout(
5761        &mut self,
5762        style: Style,
5763        children: impl IntoIterator<Item = LayoutId>,
5764        cx: &mut App,
5765    ) -> LayoutId {
5766        self.invalidator.debug_assert_prepaint();
5767
5768        cx.layout_id_buffer.clear();
5769        cx.layout_id_buffer.extend(children);
5770        let rem_size = self.rem_size();
5771        let scale_factor = self.scale_factor();
5772
5773        self.layout_engine.as_mut().unwrap().request_layout(
5774            style,
5775            rem_size,
5776            scale_factor,
5777            &cx.layout_id_buffer,
5778        )
5779    }
5780
5781    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
5782    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
5783    /// determine the element's size. One place this is used internally is when measuring text.
5784    ///
5785    /// The given closure is invoked at layout time with the known dimensions and available space and
5786    /// returns a `Size`.
5787    ///
5788    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
5789    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5790    where
5791        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5792            + 'static,
5793    {
5794        self.invalidator.debug_assert_prepaint();
5795
5796        let rem_size = self.rem_size();
5797        let scale_factor = self.scale_factor();
5798        self.layout_engine
5799            .as_mut()
5800            .unwrap()
5801            .request_measured_layout(style, rem_size, scale_factor, measure)
5802    }
5803
5804    /// Compute the layout for the given id within the given available space.
5805    /// This method is called for its side effect, typically by the framework prior to painting.
5806    /// After calling it, you can request the bounds of the given layout node id or any descendant.
5807    ///
5808    /// This method should only be called as part of the prepaint phase of element drawing.
5809    pub fn compute_layout(
5810        &mut self,
5811        layout_id: LayoutId,
5812        available_space: Size<AvailableSpace>,
5813        cx: &mut App,
5814    ) {
5815        self.invalidator.debug_assert_prepaint();
5816
5817        let mut layout_engine = self.layout_engine.take().unwrap();
5818        layout_engine.compute_layout(layout_id, available_space, self, cx);
5819        self.layout_engine = Some(layout_engine);
5820    }
5821
5822    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
5823    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
5824    ///
5825    /// This method should only be called as part of element drawing.
5826    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5827        self.invalidator.debug_assert_prepaint();
5828
5829        let scale_factor = self.scale_factor();
5830        let mut bounds = self
5831            .layout_engine
5832            .as_mut()
5833            .unwrap()
5834            .layout_bounds(layout_id, scale_factor)
5835            .map(Into::into);
5836        let snapped_offset = self.pixel_snap_point(self.element_offset());
5837        bounds.origin += snapped_offset;
5838        bounds
5839    }
5840
5841    /// This method should be called during `prepaint`. You can use
5842    /// the returned [Hitbox] during `paint` or in an event handler
5843    /// to determine whether the inserted hitbox was the topmost.
5844    ///
5845    /// This method should only be called as part of the prepaint phase of element drawing.
5846    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5847        self.invalidator.debug_assert_prepaint();
5848
5849        let content_mask = self.content_mask();
5850        let id = self.next_hitbox_id;
5851        self.next_hitbox_id = self.next_hitbox_id.next();
5852        let hitbox = Hitbox {
5853            id,
5854            bounds,
5855            content_mask,
5856            behavior,
5857        };
5858        self.next_frame.hitboxes.push(hitbox.clone());
5859        hitbox
5860    }
5861
5862    /// Set a hitbox which will act as a control area of the platform window.
5863    ///
5864    /// This method should only be called as part of the paint phase of element drawing.
5865    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5866        self.invalidator.debug_assert_paint();
5867        self.next_frame.window_control_hitboxes.push((area, hitbox));
5868    }
5869
5870    /// Sets the key context for the current element. This context will be used to translate
5871    /// keybindings into actions.
5872    ///
5873    /// This method should only be called as part of the paint phase of element drawing.
5874    pub fn set_key_context(&mut self, context: KeyContext) {
5875        self.invalidator.debug_assert_paint();
5876        self.next_frame.dispatch_tree.set_key_context(context);
5877    }
5878
5879    /// Sets the focus handle for the current element. This handle will be used to manage focus state
5880    /// and keyboard event dispatch for the element.
5881    ///
5882    /// This method should only be called as part of the prepaint phase of element drawing.
5883    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5884        self.invalidator.debug_assert_prepaint();
5885        if focus_handle.is_focused(self) {
5886            self.next_frame.focus = Some(focus_handle.id);
5887        }
5888        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5889    }
5890
5891    /// Sets the view id for the current element, which will be used to manage view caching.
5892    ///
5893    /// This method should only be called as part of element prepaint. We plan on removing this
5894    /// method eventually when we solve some issues that require us to construct editor elements
5895    /// directly instead of always using editors via views.
5896    pub fn set_view_id(&mut self, view_id: EntityId) {
5897        self.invalidator.debug_assert_prepaint();
5898        self.next_frame.dispatch_tree.set_view_id(view_id);
5899    }
5900
5901    /// Get the entity ID for the currently rendering view
5902    pub fn current_view(&self) -> EntityId {
5903        self.invalidator.debug_assert_paint_or_prepaint();
5904        self.rendered_entity_stack.last().copied().unwrap()
5905    }
5906
5907    #[inline]
5908    pub(crate) fn with_rendered_view<R>(
5909        &mut self,
5910        id: EntityId,
5911        f: impl FnOnce(&mut Self) -> R,
5912    ) -> R {
5913        self.rendered_entity_stack.push(id);
5914        let result = f(self);
5915        self.rendered_entity_stack.pop();
5916        result
5917    }
5918
5919    /// Executes the provided function with the specified image cache.
5920    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5921    where
5922        F: FnOnce(&mut Self) -> R,
5923    {
5924        if let Some(image_cache) = image_cache {
5925            self.image_cache_stack.push(image_cache);
5926            let result = f(self);
5927            self.image_cache_stack.pop();
5928            result
5929        } else {
5930            f(self)
5931        }
5932    }
5933
5934    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
5935    /// platform to receive textual input with proper integration with concerns such
5936    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
5937    /// rendered.
5938    ///
5939    /// This method should only be called as part of the paint phase of element drawing.
5940    ///
5941    /// [element_input_handler]: crate::ElementInputHandler
5942    pub fn handle_input(
5943        &mut self,
5944        focus_handle: &FocusHandle,
5945        input_handler: impl InputHandler,
5946        cx: &App,
5947    ) {
5948        self.invalidator.debug_assert_paint();
5949
5950        if focus_handle.is_focused(self) {
5951            let cx = self.to_async(cx);
5952            self.next_frame.input_handlers.push(Some(
5953                PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
5954            ));
5955        }
5956    }
5957
5958    /// Notifies native text services that the focused component's text changed.
5959    ///
5960    /// Text components should call this after application-driven edits, in addition
5961    /// to notifying GPUI to redraw. Unfocused or unregistered components are ignored.
5962    pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
5963        if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
5964            self.platform_window
5965                .text_input_state_changed(TextInputStateChange::ContentChanged);
5966        }
5967    }
5968
5969    /// Notifies native text services that the focused component's selection changed.
5970    ///
5971    /// Text components should call this after application-driven selection changes,
5972    /// in addition to notifying GPUI to redraw.
5973    pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
5974        if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
5975            self.platform_window
5976                .text_input_state_changed(TextInputStateChange::SelectionChanged);
5977        }
5978    }
5979
5980    /// Forwards the focused input handler's [`TextInputConfiguration`] to the
5981    /// platform window when it differs from the last forwarded value. With no
5982    /// input handler the default configuration applies, so a field's
5983    /// preferences don't outlive its focus.
5984    fn apply_text_input_configuration(&mut self, cx: &mut App) {
5985        let configuration = match self.platform_window.take_input_handler() {
5986            Some(mut input_handler) => {
5987                let configuration = input_handler.text_input_configuration(self, cx);
5988                self.platform_window.set_input_handler(input_handler);
5989                configuration
5990            }
5991            None => TextInputConfiguration::default(),
5992        };
5993        if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5994            self.platform_window
5995                .set_text_input_configuration(configuration.clone());
5996            self.last_text_input_configuration = Some(configuration);
5997        }
5998    }
5999
6000    /// Register a mouse event listener on the window for the next frame. The type of event
6001    /// is determined by the first parameter of the given listener. When the next frame is rendered
6002    /// the listener will be cleared.
6003    ///
6004    /// This method should only be called as part of the paint phase of element drawing.
6005    pub fn on_mouse_event<Event: MouseEvent>(
6006        &mut self,
6007        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
6008    ) {
6009        self.invalidator.debug_assert_paint();
6010
6011        self.next_frame.mouse_listeners.push(Some(Box::new(
6012            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
6013                if let Some(event) = event.downcast_ref() {
6014                    listener(event, phase, window, cx)
6015                }
6016            },
6017        )));
6018    }
6019
6020    /// Register a key event listener on this node for the next frame. The type of event
6021    /// is determined by the first parameter of the given listener. When the next frame is rendered
6022    /// the listener will be cleared.
6023    ///
6024    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
6025    /// a specific need to register a listener yourself.
6026    ///
6027    /// This method should only be called as part of the paint phase of element drawing.
6028    pub fn on_key_event<Event: KeyEvent>(
6029        &mut self,
6030        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
6031    ) {
6032        self.invalidator.debug_assert_paint();
6033
6034        self.next_frame.dispatch_tree.on_key_event(Rc::new(
6035            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
6036                if let Some(event) = event.downcast_ref::<Event>() {
6037                    listener(event, phase, window, cx)
6038                }
6039            },
6040        ));
6041    }
6042
6043    /// Register a modifiers changed event listener on the window for the next frame.
6044    ///
6045    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
6046    /// a specific need to register a global listener.
6047    ///
6048    /// This method should only be called as part of the paint phase of element drawing.
6049    pub fn on_modifiers_changed(
6050        &mut self,
6051        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
6052    ) {
6053        self.invalidator.debug_assert_paint();
6054
6055        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
6056            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
6057                listener(event, window, cx)
6058            },
6059        ));
6060    }
6061
6062    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
6063    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
6064    /// Returns a subscription and persists until the subscription is dropped.
6065    pub fn on_focus_in(
6066        &mut self,
6067        handle: &FocusHandle,
6068        cx: &mut App,
6069        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
6070    ) -> Subscription {
6071        let focus_id = handle.id;
6072        let (subscription, activate) =
6073            self.new_focus_listener(Box::new(move |event, window, cx| {
6074                if event.is_focus_in(focus_id) {
6075                    listener(window, cx);
6076                }
6077                true
6078            }));
6079        cx.defer(move |_| activate());
6080        subscription
6081    }
6082
6083    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
6084    /// Returns a subscription and persists until the subscription is dropped.
6085    pub fn on_focus_out(
6086        &mut self,
6087        handle: &FocusHandle,
6088        cx: &mut App,
6089        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
6090    ) -> Subscription {
6091        let focus_id = handle.id;
6092        let (subscription, activate) =
6093            self.new_focus_listener(Box::new(move |event, window, cx| {
6094                if let Some(blurred_id) = event.previous_focus_path.last().copied()
6095                    && event.is_focus_out(focus_id)
6096                {
6097                    let event = FocusOutEvent {
6098                        blurred: WeakFocusHandle {
6099                            id: blurred_id,
6100                            handles: Arc::downgrade(&cx.focus_handles),
6101                        },
6102                    };
6103                    listener(event, window, cx)
6104                }
6105                true
6106            }));
6107        cx.defer(move |_| activate());
6108        subscription
6109    }
6110
6111    fn reset_cursor_style(&self, cx: &mut App) {
6112        // Set the cursor only if we're the active window.
6113        if self.is_window_hovered() {
6114            // A drag can start before the next paint records its cursor in the frame.
6115            let style = cx
6116                .active_drag_cursor_style()
6117                .or_else(|| self.rendered_frame.cursor_style(self))
6118                .unwrap_or(CursorStyle::Arrow);
6119            cx.platform.set_cursor_style(style);
6120        }
6121    }
6122
6123    /// Dispatch a given keystroke as though the user had typed it.
6124    /// You can create a keystroke with Keystroke::parse("").
6125    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
6126        let keystroke = keystroke.with_simulated_ime();
6127        let result = self.dispatch_event(
6128            PlatformInput::KeyDown(KeyDownEvent {
6129                keystroke: keystroke.clone(),
6130                is_held: false,
6131                prefer_character_input: false,
6132            }),
6133            cx,
6134        );
6135        if !result.propagate {
6136            return true;
6137        }
6138
6139        if let Some(input) = keystroke.key_char
6140            && let Some(mut input_handler) = self.platform_window.take_input_handler()
6141        {
6142            input_handler.dispatch_input(&input, self, cx);
6143            self.platform_window.set_input_handler(input_handler);
6144            return true;
6145        }
6146
6147        false
6148    }
6149
6150    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
6151    /// binding for the action (last binding added to the keymap).
6152    pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
6153        self.highest_precedence_binding_for_action(action)
6154            .map(|binding| {
6155                binding
6156                    .keystrokes()
6157                    .iter()
6158                    .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
6159                    .collect::<Vec<_>>()
6160                    .join(" ")
6161            })
6162            .unwrap_or_else(|| action.name().to_string())
6163    }
6164
6165    /// Dispatch a mouse, keyboard, or touch event on the window.
6166    #[profiling::function]
6167    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
6168        #[cfg(feature = "profiler")]
6169        self.window_profiler.begin_input(event.kind_name());
6170        let update_count_before = self.invalidator.update_count();
6171        // Track input modality for focus-visible styling and hover suppression.
6172        // Hover is suppressed during keyboard modality so that keyboard navigation
6173        // doesn't show hover highlights on the item under the mouse cursor.
6174        let old_modality = self.last_input_modality;
6175        self.last_input_modality = match &event {
6176            PlatformInput::KeyDown(_) => InputModality::Keyboard,
6177            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
6178            PlatformInput::Touch(_) => InputModality::Touch,
6179            _ => self.last_input_modality,
6180        };
6181        if self.last_input_modality != old_modality {
6182            self.refresh();
6183        }
6184
6185        // Handlers may set this to false by calling `stop_propagation`.
6186        cx.propagate_event = true;
6187        // Handlers may set this to true by calling `prevent_default`.
6188        self.default_prevented = false;
6189
6190        let event = match event {
6191            // Track the mouse position with our own state, since accessing the platform
6192            // API for the mouse position can only occur on the main thread.
6193            PlatformInput::MouseMove(mouse_move) => {
6194                self.mouse_position = mouse_move.position;
6195                self.modifiers = mouse_move.modifiers;
6196                PlatformInput::MouseMove(mouse_move)
6197            }
6198            PlatformInput::MouseDown(mouse_down) => {
6199                self.mouse_position = mouse_down.position;
6200                self.modifiers = mouse_down.modifiers;
6201                PlatformInput::MouseDown(mouse_down)
6202            }
6203            PlatformInput::MouseUp(mouse_up) => {
6204                self.mouse_position = mouse_up.position;
6205                self.modifiers = mouse_up.modifiers;
6206                PlatformInput::MouseUp(mouse_up)
6207            }
6208            PlatformInput::MousePressure(mouse_pressure) => {
6209                PlatformInput::MousePressure(mouse_pressure)
6210            }
6211            PlatformInput::MouseExited(mouse_exited) => {
6212                self.modifiers = mouse_exited.modifiers;
6213                PlatformInput::MouseExited(mouse_exited)
6214            }
6215            PlatformInput::ModifiersChanged(modifiers_changed) => {
6216                self.modifiers = modifiers_changed.modifiers;
6217                self.capslock = modifiers_changed.capslock;
6218                PlatformInput::ModifiersChanged(modifiers_changed)
6219            }
6220            PlatformInput::Scroll(scroll_wheel) => {
6221                self.mouse_position = scroll_wheel.position;
6222                self.modifiers = scroll_wheel.modifiers;
6223                PlatformInput::Scroll(scroll_wheel)
6224            }
6225            PlatformInput::Pinch(pinch) => {
6226                self.mouse_position = pinch.position;
6227                self.modifiers = pinch.modifiers;
6228                PlatformInput::Pinch(pinch)
6229            }
6230            // Translate dragging and dropping of external files from the operating system
6231            // to internal drag and drop events.
6232            PlatformInput::FileDrop(file_drop) => match file_drop {
6233                FileDropEvent::Entered { position, paths } => {
6234                    self.mouse_position = position;
6235                    let source_window = self.handle.window_id();
6236                    if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
6237                        cx.active_drag = Some(AnyDrag {
6238                            value: Arc::new(paths.clone()),
6239                            view: cx.new(|_| paths).into(),
6240                            cursor_offset: position,
6241                            cursor_style: None,
6242                            external_payload_source: None,
6243                        });
6244                    }
6245                    PlatformInput::MouseMove(MouseMoveEvent {
6246                        position,
6247                        pressed_button: Some(MouseButton::Left),
6248                        modifiers: Modifiers::default(),
6249                    })
6250                }
6251                FileDropEvent::Pending { position } => {
6252                    self.mouse_position = position;
6253                    PlatformInput::MouseMove(MouseMoveEvent {
6254                        position,
6255                        pressed_button: Some(MouseButton::Left),
6256                        modifiers: Modifiers::default(),
6257                    })
6258                }
6259                FileDropEvent::Submit { position } => {
6260                    cx.activate(true);
6261                    self.mouse_position = position;
6262                    PlatformInput::MouseUp(MouseUpEvent {
6263                        button: MouseButton::Left,
6264                        position,
6265                        modifiers: Modifiers::default(),
6266                        click_count: 1,
6267                    })
6268                }
6269                FileDropEvent::Exited => {
6270                    if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
6271                        cx.active_drag.take();
6272                    }
6273                    self.refresh();
6274                    PlatformInput::FileDrop(FileDropEvent::Exited)
6275                }
6276                FileDropEvent::Ended => {
6277                    cx.end_platform_drag(self.handle.window_id());
6278                    self.refresh();
6279                    PlatformInput::FileDrop(FileDropEvent::Ended)
6280                }
6281            },
6282            PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
6283            PlatformInput::LongPress(long_press) => {
6284                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
6285                    long_press.start_position
6286                } else {
6287                    long_press.position
6288                };
6289                if long_press.phase == crate::TouchPhase::Started {
6290                    self.long_press_capture = None;
6291                }
6292                PlatformInput::LongPress(long_press)
6293            }
6294            PlatformInput::TouchDrag(touch_drag) => {
6295                self.mouse_position = touch_drag.start_position;
6296                PlatformInput::TouchDrag(touch_drag)
6297            }
6298            PlatformInput::BackGesture(back) => {
6299                self.mouse_position = back.start_position;
6300                PlatformInput::BackGesture(back)
6301            }
6302            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
6303        };
6304
6305        if let Some(any_mouse_event) = event.mouse_event() {
6306            self.dispatch_mouse_event(any_mouse_event, cx);
6307        } else if let Some(any_key_event) = event.keyboard_event() {
6308            self.dispatch_key_event(any_key_event, cx);
6309        } else if let Some(touch_event) = event.touch_event() {
6310            self.dispatch_touch_event(touch_event, cx);
6311        }
6312        if let PlatformInput::LongPress(long_press) = &event {
6313            match long_press.phase {
6314                crate::TouchPhase::Started if !self.default_prevented => {
6315                    self.long_press_capture = None;
6316                }
6317                crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
6318                    self.long_press_capture = None;
6319                }
6320                crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
6321            }
6322        }
6323
6324        // Must run after the move is dispatched: the platform owns the gesture afterwards, so this
6325        // is the last chance for drag listeners to see the pointer leave and reset their state.
6326        self.promote_external_drag_to_platform(&event, cx);
6327
6328        let caused_invalidation = self.invalidator.update_count() > update_count_before;
6329        if caused_invalidation {
6330            self.input_rate_tracker.borrow_mut().record_input();
6331        }
6332        #[cfg(feature = "profiler")]
6333        self.window_profiler.end_input(caused_invalidation);
6334
6335        DispatchEventResult {
6336            propagate: cx.propagate_event,
6337            default_prevented: self.default_prevented,
6338        }
6339    }
6340
6341    fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
6342        let PlatformInput::MouseMove(mouse_move) = event else {
6343            return;
6344        };
6345        if mouse_move.pressed_button != Some(MouseButton::Left) {
6346            return;
6347        }
6348        if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
6349            return;
6350        }
6351        if !self.platform_window.can_start_external_drag() {
6352            return;
6353        }
6354        let Some(payload_source) = cx
6355            .active_drag
6356            .as_mut()
6357            .and_then(|drag| drag.external_payload_source.take())
6358        else {
6359            return;
6360        };
6361        let Some(payload) = payload_source(self, cx) else {
6362            return;
6363        };
6364        if self.platform_window.start_external_drag(&payload)
6365            && cx.hand_active_drag_to_platform(self.handle.window_id())
6366        {
6367            self.refresh();
6368        }
6369    }
6370
6371    /// Whether recognized touch pans may use the platform's predicted touch
6372    /// positions ([`TouchEvent::predicted_position`]) to compensate for input
6373    /// latency. Defaults to true.
6374    pub fn touch_prediction_enabled(&self) -> bool {
6375        self.touch_prediction_enabled
6376    }
6377
6378    /// Sets whether recognized touch pans may use the platform's predicted
6379    /// touch positions. Disabling drops [`TouchEvent::predicted_position`]
6380    /// before gesture recognition, so pans track only raw touch positions.
6381    pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
6382        self.touch_prediction_enabled = enabled;
6383    }
6384
6385    /// Runs the portable gesture recognizer over a raw touch event and
6386    /// dispatches whatever it resolves (scroll steps, synthesized taps)
6387    /// through the ordinary mouse-event path.
6388    fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
6389        let mut event = event.clone();
6390        if !self.touch_prediction_enabled {
6391            event.predicted_position = None;
6392        }
6393        let recognized_gestures = self.touch_gestures.handle_event(&event);
6394        if event.phase == crate::TouchPhase::Started
6395            && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
6396        {
6397            self.dispatch_recognized_touch_gesture(touch_drag, cx);
6398        }
6399        if event.phase == crate::TouchPhase::Started
6400            && self.touch_gestures.pending_long_press().is_some()
6401        {
6402            self.long_press_capture = None;
6403        }
6404        let mut tapped = false;
6405        for gesture in recognized_gestures {
6406            tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
6407            self.dispatch_recognized_touch_gesture(gesture, cx);
6408        }
6409        if event.phase == crate::TouchPhase::Started {
6410            self.schedule_long_press_timer(cx);
6411        } else if self.touch_gestures.pending_long_press().is_none() {
6412            self.long_press_timer.take();
6413        }
6414        // The platform's touch-release handler may inspect the input handler
6415        // as soon as this dispatch returns (the web platform decides virtual
6416        // keyboard visibility there, inside the user gesture). Input handlers
6417        // are registered during draw, so draw now to make them reflect any
6418        // focus change the tap just caused.
6419        if tapped && self.invalidator.is_dirty() {
6420            self.draw(cx).clear(cx);
6421        }
6422        if self.touch_gestures.has_momentum() {
6423            self.schedule_touch_momentum_tick();
6424        }
6425    }
6426
6427    fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
6428        match gesture {
6429            RecognizedTouchGesture::Scroll(scroll_wheel) => {
6430                self.mouse_position = scroll_wheel.position;
6431                cx.propagate_event = true;
6432                self.dispatch_mouse_event(&scroll_wheel, cx);
6433            }
6434            RecognizedTouchGesture::Tap { down, up } => {
6435                self.mouse_position = up.position;
6436                cx.propagate_event = true;
6437                self.dispatch_mouse_event(&down, cx);
6438                cx.propagate_event = true;
6439                self.dispatch_mouse_event(&up, cx);
6440            }
6441            RecognizedTouchGesture::TouchDrag(touch_drag) => {
6442                self.mouse_position = touch_drag.start_position;
6443                cx.propagate_event = true;
6444                self.default_prevented = false;
6445                let started = touch_drag.phase == crate::TouchPhase::Started;
6446                self.dispatch_mouse_event(&touch_drag, cx);
6447                if started {
6448                    self.touch_gestures
6449                        .resolve_touch_drag(self.default_prevented);
6450                }
6451            }
6452            RecognizedTouchGesture::LongPress(long_press) => {
6453                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
6454                    long_press.start_position
6455                } else {
6456                    long_press.position
6457                };
6458                cx.propagate_event = true;
6459                self.default_prevented = false;
6460                let started = long_press.phase == crate::TouchPhase::Started;
6461                let ended = matches!(
6462                    long_press.phase,
6463                    crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
6464                );
6465                self.dispatch_mouse_event(&long_press, cx);
6466                if started {
6467                    let claimed = self.default_prevented;
6468                    self.touch_gestures.resolve_long_press(claimed);
6469                    if !claimed {
6470                        self.long_press_capture = None;
6471                    }
6472                }
6473                if ended {
6474                    self.long_press_capture = None;
6475                }
6476            }
6477        }
6478    }
6479
6480    fn schedule_long_press_timer(&mut self, cx: &mut App) {
6481        self.long_press_timer.take();
6482        let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
6483            return;
6484        };
6485        self.long_press_timer = Some(self.spawn(cx, async move |cx| {
6486            cx.background_executor.timer(duration).await;
6487            cx.update(move |window, cx| {
6488                window.long_press_timer.take();
6489                if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
6490                    window.dispatch_recognized_touch_gesture(gesture, cx);
6491                }
6492            })
6493            .with_context(|| {
6494                format!(
6495                    "handling long-press timer for window {:?}",
6496                    cx.window_handle().window_id()
6497                )
6498            })
6499            .log_err();
6500        }));
6501    }
6502
6503    fn schedule_touch_momentum_tick(&mut self) {
6504        self.on_next_frame(|window, cx| {
6505            if let Some(gesture) = window.touch_gestures.tick_momentum() {
6506                window.dispatch_recognized_touch_gesture(gesture, cx);
6507            }
6508            if window.touch_gestures.has_momentum() {
6509                window.schedule_touch_momentum_tick();
6510            }
6511        });
6512    }
6513
6514    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6515        self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position());
6516
6517        #[cfg(any(feature = "inspector", debug_assertions))]
6518        if self.is_inspector_picking(cx) {
6519            self.reset_cursor_style(cx);
6520            self.handle_inspector_mouse_event(event, cx);
6521            // When inspector is picking, all other mouse handling is skipped.
6522            return;
6523        }
6524
6525        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
6526
6527        // Capture phase, events bubble from back to front. Handlers for this phase are used for
6528        // special purposes, such as detecting events outside of a given Bounds.
6529        for listener in &mut mouse_listeners {
6530            let listener = listener.as_mut().unwrap();
6531            listener(event, DispatchPhase::Capture, self, cx);
6532            if !cx.propagate_event {
6533                break;
6534            }
6535        }
6536
6537        // Bubble phase, where most normal handlers do their work.
6538        if cx.propagate_event {
6539            for listener in mouse_listeners.iter_mut().rev() {
6540                let listener = listener.as_mut().unwrap();
6541                listener(event, DispatchPhase::Bubble, self, cx);
6542                if !cx.propagate_event {
6543                    break;
6544                }
6545            }
6546        }
6547
6548        self.rendered_frame.mouse_listeners = mouse_listeners;
6549
6550        if cx.has_active_drag() {
6551            if event.is::<MouseMoveEvent>() {
6552                // If this was a mouse move event, redraw the window so that the
6553                // active drag can follow the mouse cursor.
6554                self.refresh();
6555            } else if event.is::<MouseUpEvent>() {
6556                // If this was a mouse up event, cancel the active drag and redraw
6557                // the window.
6558                cx.active_drag = None;
6559                self.refresh();
6560            }
6561        }
6562
6563        // Auto-release pointer capture on mouse up
6564        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
6565            self.captured_hitbox = None;
6566        }
6567
6568        // Runs after the listeners so that a drag they start takes effect in this event. Resolving
6569        // the cursor any earlier would briefly select whatever is under the pointer instead.
6570        self.reset_cursor_style(cx);
6571    }
6572
6573    // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
6574    // we prefer the text input over bindings.
6575    fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
6576        let prefer_character_input = event
6577            .downcast_ref::<KeyDownEvent>()
6578            .is_some_and(|key_down_event| key_down_event.prefer_character_input);
6579        if !prefer_character_input {
6580            return InputPreference::KeyBindings;
6581        }
6582        let Some(mut input_handler) = self.platform_window.take_input_handler() else {
6583            return InputPreference::KeyBindings;
6584        };
6585        let accepts_text_input = input_handler.accepts_text_input(self, cx);
6586        self.platform_window.set_input_handler(input_handler);
6587        if accepts_text_input {
6588            InputPreference::CharacterInput
6589        } else {
6590            InputPreference::KeyBindings
6591        }
6592    }
6593
6594    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
6595        if self.invalidator.is_dirty() {
6596            self.draw(cx).clear(cx);
6597        }
6598
6599        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6600        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6601
6602        let mut keystroke: Option<Keystroke> = None;
6603
6604        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
6605            if event.modifiers.number_of_modifiers() == 0
6606                && self.pending_modifier.modifiers.number_of_modifiers() == 1
6607                && !self.pending_modifier.saw_other_input
6608            {
6609                let key = match self.pending_modifier.modifiers {
6610                    modifiers if modifiers.shift => Some("shift"),
6611                    modifiers if modifiers.control => Some("control"),
6612                    modifiers if modifiers.alt => Some("alt"),
6613                    modifiers if modifiers.platform => Some("platform"),
6614                    modifiers if modifiers.function => Some("function"),
6615                    _ => None,
6616                };
6617                if let Some(key) = key {
6618                    keystroke = Some(Keystroke {
6619                        key: key.to_string(),
6620                        key_char: None,
6621                        modifiers: Modifiers::default(),
6622                    });
6623                }
6624            }
6625
6626            if self.pending_modifier.modifiers.number_of_modifiers() == 0
6627                && event.modifiers.number_of_modifiers() == 1
6628            {
6629                self.pending_modifier.saw_other_input = false
6630            } else if event.modifiers.number_of_modifiers() > 1 {
6631                self.pending_modifier.saw_other_input = true
6632            }
6633            self.pending_modifier.modifiers = event.modifiers
6634        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
6635            self.pending_modifier.saw_other_input = true;
6636            keystroke = Some(key_down_event.keystroke.clone());
6637            if key_down_event.keystroke.key_char.is_some()
6638                && matches!(
6639                    cx.cursor_hide_mode,
6640                    CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
6641                )
6642            {
6643                cx.platform.hide_cursor_until_mouse_moves();
6644            }
6645        }
6646
6647        let Some(keystroke) = keystroke else {
6648            self.finish_dispatch_key_event(
6649                event,
6650                None,
6651                InputPreference::KeyBindings,
6652                dispatch_path,
6653                self.context_stack(),
6654                cx,
6655            );
6656            return;
6657        };
6658
6659        let input_preference = self.input_preference(event, cx);
6660
6661        cx.propagate_event = true;
6662        self.dispatch_keystroke_interceptors(
6663            &keystroke,
6664            input_preference,
6665            self.context_stack(),
6666            cx,
6667        );
6668        if !cx.propagate_event {
6669            self.finish_dispatch_key_event(
6670                event,
6671                Some(&keystroke),
6672                input_preference,
6673                dispatch_path,
6674                self.context_stack(),
6675                cx,
6676            );
6677            return;
6678        }
6679
6680        let mut currently_pending = self.pending_input.take().unwrap_or_default();
6681        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
6682            currently_pending = PendingInput::default();
6683        }
6684
6685        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
6686            currently_pending.keystrokes,
6687            keystroke.clone(),
6688            &dispatch_path,
6689        );
6690
6691        if !match_result.to_replay.is_empty() {
6692            self.replay_pending_input(match_result.to_replay, cx);
6693            cx.propagate_event = true;
6694        }
6695
6696        if !match_result.pending.is_empty() {
6697            let previous_timeout = currently_pending.timeout.take();
6698            currently_pending.keystrokes = match_result.pending;
6699            currently_pending.focus = self.focus;
6700
6701            let text_input_requires_timeout = event
6702                .downcast_ref::<KeyDownEvent>()
6703                .filter(|key_down| key_down.keystroke.key_char.is_some())
6704                .and_then(|_| self.platform_window.take_input_handler())
6705                .map_or(false, |mut input_handler| {
6706                    let accepts = input_handler.accepts_text_input(self, cx);
6707                    self.platform_window.set_input_handler(input_handler);
6708                    accepts
6709                });
6710
6711            let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
6712            let needs_timeout = previous_timeout.is_some()
6713                || match_result.pending_has_binding
6714                || text_input_requires_timeout
6715                || standalone_modifier;
6716            currently_pending.timeout = if needs_timeout {
6717                match previous_timeout {
6718                    Some(mut timeout) if timeout.is_paused() => {
6719                        timeout.reset_duration(PENDING_INPUT_TIMEOUT);
6720                        Some(timeout)
6721                    }
6722                    previous_timeout => {
6723                        drop(previous_timeout);
6724                        Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
6725                    }
6726                }
6727            } else {
6728                None
6729            };
6730            self.pending_input = Some(currently_pending);
6731            self.pending_input_changed(cx);
6732            cx.propagate_event = false;
6733            return;
6734        }
6735
6736        // Interceptors or replayed actions may have changed whether the input handler accepts text.
6737        let input_preference = self.input_preference(event, cx);
6738        if input_preference == InputPreference::KeyBindings {
6739            for binding in match_result.bindings {
6740                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6741                if !cx.propagate_event {
6742                    self.dispatch_keystroke_observers(
6743                        &keystroke,
6744                        input_preference,
6745                        Some(binding.action.as_ref()),
6746                        match_result.context_stack,
6747                        cx,
6748                    );
6749                    self.pending_input_changed(cx);
6750                    return;
6751                }
6752            }
6753        }
6754
6755        self.finish_dispatch_key_event(
6756            event,
6757            Some(&keystroke),
6758            input_preference,
6759            dispatch_path,
6760            match_result.context_stack,
6761            cx,
6762        );
6763        self.pending_input_changed(cx);
6764    }
6765
6766    fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6767        let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6768        PendingInputTimeout {
6769            duration,
6770            remaining: duration,
6771            state: PendingInputTimeoutState::Running { started_at, task },
6772        }
6773    }
6774
6775    fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6776        let started_at = cx.background_executor().now();
6777        let task = self.spawn(cx, async move |cx| {
6778            cx.background_executor.timer(remaining).await;
6779            cx.update(move |window, cx| window.flush_pending_input(cx))
6780                .with_context(|| {
6781                    format!(
6782                        "handling pending input timeout for window {:?}",
6783                        cx.window_handle().window_id()
6784                    )
6785                })
6786                .log_err();
6787        });
6788        (started_at, task)
6789    }
6790
6791    /// Ends a pending multi-key binding as its timeout does, dispatching what
6792    /// the keys pressed so far are bound to on their own.
6793    fn flush_pending_input(&mut self, cx: &mut App) {
6794        let Some(currently_pending) = self
6795            .pending_input
6796            .take()
6797            .filter(|pending| pending.focus == self.focus)
6798        else {
6799            return;
6800        };
6801
6802        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6803        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6804
6805        let to_replay = self
6806            .rendered_frame
6807            .dispatch_tree
6808            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6809
6810        self.pending_input_changed(cx);
6811        self.replay_pending_input(to_replay, cx)
6812    }
6813
6814    fn finish_dispatch_key_event(
6815        &mut self,
6816        event: &dyn Any,
6817        recognized_keystroke: Option<&Keystroke>,
6818        input_preference: InputPreference,
6819        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6820        context_stack: Vec<KeyContext>,
6821        cx: &mut App,
6822    ) {
6823        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6824        if !cx.propagate_event {
6825            return;
6826        }
6827
6828        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6829        if !cx.propagate_event {
6830            return;
6831        }
6832
6833        if let Some(keystroke) = recognized_keystroke {
6834            self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
6835        }
6836    }
6837
6838    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6839        self.pending_input_observers
6840            .clone()
6841            .retain(|callback| callback(self, cx));
6842    }
6843
6844    fn defer_pending_input_changed(&self, cx: &mut App) {
6845        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
6846        // current effect cycle, and only for this window.
6847        let window_handle = self.handle;
6848        cx.defer(move |cx| {
6849            window_handle
6850                .update(cx, |_, window, cx| {
6851                    window.pending_input_changed(cx);
6852                })
6853                .ok();
6854        });
6855    }
6856
6857    fn dispatch_key_down_up_event(
6858        &mut self,
6859        event: &dyn Any,
6860        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6861        cx: &mut App,
6862    ) {
6863        // Capture phase
6864        for node_id in dispatch_path {
6865            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6866
6867            for key_listener in node.key_listeners.clone() {
6868                key_listener(event, DispatchPhase::Capture, self, cx);
6869                if !cx.propagate_event {
6870                    return;
6871                }
6872            }
6873        }
6874
6875        // Bubble phase
6876        for node_id in dispatch_path.iter().rev() {
6877            // Handle low level key events
6878            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6879            for key_listener in node.key_listeners.clone() {
6880                key_listener(event, DispatchPhase::Bubble, self, cx);
6881                if !cx.propagate_event {
6882                    return;
6883                }
6884            }
6885        }
6886    }
6887
6888    fn dispatch_modifiers_changed_event(
6889        &mut self,
6890        event: &dyn Any,
6891        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6892        cx: &mut App,
6893    ) {
6894        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6895            return;
6896        };
6897        for node_id in dispatch_path.iter().rev() {
6898            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6899            for listener in node.modifiers_changed_listeners.clone() {
6900                listener(event, self, cx);
6901                if !cx.propagate_event {
6902                    return;
6903                }
6904            }
6905        }
6906    }
6907
6908    /// Determine whether a potential multi-stroke key binding is in progress on this window.
6909    pub fn has_pending_keystrokes(&self) -> bool {
6910        self.pending_input().is_some()
6911    }
6912
6913    #[cfg(test)]
6914    pub(crate) fn pending_input_is_none(&self) -> bool {
6915        self.pending_input.is_none()
6916    }
6917
6918    pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6919        if self.pending_input.take().is_some() {
6920            self.defer_pending_input_changed(cx);
6921        }
6922    }
6923
6924    /// Returns pending input that can still complete a multi-stroke key binding. Input left over
6925    /// from a previous focus can never complete one.
6926    pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6927        self.pending_input
6928            .as_ref()
6929            .filter(|pending_input| pending_input.focus == self.focus)
6930            .map(|pending_input| PendingInputStatus {
6931                keystrokes: pending_input.keystrokes.as_slice(),
6932                timeout: pending_input
6933                    .timeout
6934                    .as_ref()
6935                    .map(PendingInputTimeout::status),
6936            })
6937    }
6938
6939    /// Pauses or resumes the current pending input timeout on behalf of `owner`.
6940    ///
6941    /// A paused timeout resumes automatically if `owner` is released. Returns whether the timeout
6942    /// state changed. A timeout paused by one owner cannot be resumed by another.
6943    pub fn set_pending_input_timeout_paused<T: 'static>(
6944        &mut self,
6945        owner: &Entity<T>,
6946        paused: bool,
6947        cx: &mut App,
6948    ) -> bool {
6949        let owner_id = owner.entity_id();
6950        if !paused {
6951            return self.resume_pending_input_timeout(owner_id, cx);
6952        }
6953
6954        let timeout = self
6955            .pending_input
6956            .as_ref()
6957            .filter(|pending_input| pending_input.focus == self.focus)
6958            .and_then(|pending_input| pending_input.timeout.as_ref());
6959        let Some(timeout) = timeout else {
6960            return false;
6961        };
6962        if timeout.is_paused() {
6963            return false;
6964        }
6965
6966        let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
6967            window.resume_pending_input_timeout(owner_id, cx);
6968        });
6969        let now = cx.background_executor().now();
6970        let changed = self
6971            .pending_input
6972            .as_mut()
6973            .filter(|pending_input| pending_input.focus == self.focus)
6974            .and_then(|pending_input| pending_input.timeout.as_mut())
6975            .is_some_and(|timeout| {
6976                timeout.pause(
6977                    PendingInputTimeoutPause {
6978                        owner_id,
6979                        _release_subscription: release_subscription,
6980                    },
6981                    now,
6982                )
6983            });
6984
6985        if changed {
6986            self.defer_pending_input_changed(cx);
6987        }
6988        changed
6989    }
6990
6991    fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
6992        let Some(remaining) = self
6993            .pending_input
6994            .as_ref()
6995            .and_then(|pending_input| pending_input.timeout.as_ref())
6996            .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
6997            .map(|timeout| timeout.remaining)
6998        else {
6999            return false;
7000        };
7001
7002        let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
7003        let changed = self
7004            .pending_input
7005            .as_mut()
7006            .and_then(|pending_input| pending_input.timeout.as_mut())
7007            .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
7008
7009        if changed {
7010            self.defer_pending_input_changed(cx);
7011        }
7012        changed
7013    }
7014
7015    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
7016    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
7017        self.pending_input()
7018            .map(|pending_input| pending_input.keystrokes())
7019    }
7020
7021    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
7022        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7023        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
7024
7025        'replay: for replay in replays {
7026            let event = KeyDownEvent {
7027                keystroke: replay.keystroke.clone(),
7028                is_held: false,
7029                prefer_character_input: true,
7030            };
7031
7032            cx.propagate_event = true;
7033            for binding in replay.bindings {
7034                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
7035                if !cx.propagate_event {
7036                    self.dispatch_keystroke_observers(
7037                        &replay.keystroke,
7038                        InputPreference::KeyBindings,
7039                        Some(binding.action.as_ref()),
7040                        Vec::default(),
7041                        cx,
7042                    );
7043                    continue 'replay;
7044                }
7045            }
7046
7047            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
7048            if !cx.propagate_event {
7049                continue 'replay;
7050            }
7051            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
7052                && let Some(mut input_handler) = self.platform_window.take_input_handler()
7053            {
7054                input_handler.dispatch_input(&input, self, cx);
7055                self.platform_window.set_input_handler(input_handler)
7056            }
7057        }
7058    }
7059
7060    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
7061        focus_id
7062            .and_then(|focus_id| {
7063                self.rendered_frame
7064                    .dispatch_tree
7065                    .focusable_node_id(focus_id)
7066            })
7067            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
7068    }
7069
7070    fn dispatch_action_on_node(
7071        &mut self,
7072        node_id: DispatchNodeId,
7073        action: &dyn Action,
7074        cx: &mut App,
7075    ) {
7076        self.dispatch_action_on_node_inner(node_id, action, cx);
7077
7078        if !cx.propagate_event
7079            && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
7080            && self.last_input_was_keyboard()
7081        {
7082            cx.platform.hide_cursor_until_mouse_moves();
7083        }
7084    }
7085
7086    fn dispatch_action_on_node_inner(
7087        &mut self,
7088        node_id: DispatchNodeId,
7089        action: &dyn Action,
7090        cx: &mut App,
7091    ) {
7092        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
7093
7094        // Capture phase for global actions.
7095        cx.propagate_event = true;
7096        if let Some(mut global_listeners) = cx
7097            .global_action_listeners
7098            .remove(&action.as_any().type_id())
7099        {
7100            for listener in &global_listeners {
7101                #[cfg(feature = "profiler")]
7102                self.window_profiler.begin_action_handler(action, cx);
7103                listener(action.as_any(), DispatchPhase::Capture, cx);
7104                #[cfg(feature = "profiler")]
7105                self.window_profiler.end_action_handler();
7106                if !cx.propagate_event {
7107                    break;
7108                }
7109            }
7110
7111            global_listeners.extend(
7112                cx.global_action_listeners
7113                    .remove(&action.as_any().type_id())
7114                    .unwrap_or_default(),
7115            );
7116
7117            cx.global_action_listeners
7118                .insert(action.as_any().type_id(), global_listeners);
7119        }
7120
7121        if !cx.propagate_event {
7122            return;
7123        }
7124
7125        // Capture phase for window actions.
7126        for node_id in &dispatch_path {
7127            let node = self.rendered_frame.dispatch_tree.node(*node_id);
7128            for DispatchActionListener {
7129                action_type,
7130                listener,
7131            } in node.action_listeners.clone()
7132            {
7133                let any_action = action.as_any();
7134                if action_type == any_action.type_id() {
7135                    #[cfg(feature = "profiler")]
7136                    self.window_profiler.begin_action_handler(action, cx);
7137                    listener(any_action, DispatchPhase::Capture, self, cx);
7138                    #[cfg(feature = "profiler")]
7139                    self.window_profiler.end_action_handler();
7140
7141                    if !cx.propagate_event {
7142                        return;
7143                    }
7144                }
7145            }
7146        }
7147
7148        // Bubble phase for window actions.
7149        for node_id in dispatch_path.iter().rev() {
7150            let node = self.rendered_frame.dispatch_tree.node(*node_id);
7151            for DispatchActionListener {
7152                action_type,
7153                listener,
7154            } in node.action_listeners.clone()
7155            {
7156                let any_action = action.as_any();
7157                if action_type == any_action.type_id() {
7158                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
7159                    #[cfg(feature = "profiler")]
7160                    self.window_profiler.begin_action_handler(action, cx);
7161                    listener(any_action, DispatchPhase::Bubble, self, cx);
7162                    #[cfg(feature = "profiler")]
7163                    self.window_profiler.end_action_handler();
7164
7165                    if !cx.propagate_event {
7166                        return;
7167                    }
7168                }
7169            }
7170        }
7171
7172        // Bubble phase for global actions.
7173        if let Some(mut global_listeners) = cx
7174            .global_action_listeners
7175            .remove(&action.as_any().type_id())
7176        {
7177            for listener in global_listeners.iter().rev() {
7178                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
7179
7180                #[cfg(feature = "profiler")]
7181                self.window_profiler.begin_action_handler(action, cx);
7182                listener(action.as_any(), DispatchPhase::Bubble, cx);
7183                #[cfg(feature = "profiler")]
7184                self.window_profiler.end_action_handler();
7185                if !cx.propagate_event {
7186                    break;
7187                }
7188            }
7189
7190            global_listeners.extend(
7191                cx.global_action_listeners
7192                    .remove(&action.as_any().type_id())
7193                    .unwrap_or_default(),
7194            );
7195
7196            cx.global_action_listeners
7197                .insert(action.as_any().type_id(), global_listeners);
7198        }
7199    }
7200
7201    /// Register the given handler to be invoked whenever the global of the given type
7202    /// is updated.
7203    pub fn observe_global<G: Global>(
7204        &mut self,
7205        cx: &mut App,
7206        f: impl Fn(&mut Window, &mut App) + 'static,
7207    ) -> Subscription {
7208        let window_handle = self.handle;
7209        let (subscription, activate) = cx.global_observers.insert_pending(
7210            TypeId::of::<G>(),
7211            Box::new(move |cx| {
7212                window_handle
7213                    .update(cx, |_, window, cx| f(window, cx))
7214                    .is_ok()
7215            }),
7216        );
7217        cx.defer(move |_| activate());
7218        subscription
7219    }
7220
7221    /// Focus the current window and bring it to the foreground at the platform level.
7222    pub fn activate_window(&self) {
7223        self.platform_window.activate();
7224    }
7225
7226    /// Requests that the operating system draw attention to this window.
7227    pub fn request_attention(&self) {
7228        self.platform_window.request_attention();
7229    }
7230
7231    /// Minimize the current window at the platform level.
7232    pub fn minimize_window(&self) {
7233        self.platform_window.minimize();
7234    }
7235
7236    /// Toggle full screen status on the current window at the platform level.
7237    pub fn toggle_fullscreen(&self) {
7238        self.platform_window.toggle_fullscreen();
7239    }
7240
7241    /// Toggle simple (borderless) fullscreen, where the window covers the entire
7242    /// screen including the menu bar and, on notched displays, the area around the
7243    /// notch. Unlike [`Window::toggle_fullscreen`], this does not move the window
7244    /// into its own Mission Control space. Only has an effect on macOS.
7245    pub fn toggle_simple_fullscreen(&self) {
7246        self.platform_window.toggle_simple_fullscreen();
7247    }
7248
7249    /// Updates the IME panel position suggestions for languages like japanese, chinese.
7250    pub fn invalidate_character_coordinates(&self) {
7251        self.on_next_frame(|window, cx| {
7252            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
7253                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
7254                    window.platform_window.update_ime_position(bounds);
7255                }
7256                window.platform_window.set_input_handler(input_handler);
7257            }
7258        });
7259    }
7260
7261    /// Present a platform dialog.
7262    /// The provided message will be presented, along with buttons for each answer.
7263    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
7264    pub fn prompt<T>(
7265        &mut self,
7266        level: PromptLevel,
7267        message: &str,
7268        detail: Option<&str>,
7269        answers: &[T],
7270        cx: &mut App,
7271    ) -> oneshot::Receiver<usize>
7272    where
7273        T: Clone + Into<PromptButton>,
7274    {
7275        let prompt_builder = cx.prompt_builder.take();
7276        let Some(prompt_builder) = prompt_builder else {
7277            unreachable!("Re-entrant window prompting is not supported by GPUI");
7278        };
7279
7280        let answers = answers
7281            .iter()
7282            .map(|answer| answer.clone().into())
7283            .collect::<Vec<_>>();
7284
7285        let receiver = match &prompt_builder {
7286            PromptBuilder::Default => self
7287                .platform_window
7288                .prompt(level, message, detail, &answers)
7289                .unwrap_or_else(|| {
7290                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
7291                }),
7292            PromptBuilder::Custom(_) => {
7293                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
7294            }
7295        };
7296
7297        cx.prompt_builder = Some(prompt_builder);
7298
7299        receiver
7300    }
7301
7302    fn build_custom_prompt(
7303        &mut self,
7304        prompt_builder: &PromptBuilder,
7305        level: PromptLevel,
7306        message: &str,
7307        detail: Option<&str>,
7308        answers: &[PromptButton],
7309        cx: &mut App,
7310    ) -> oneshot::Receiver<usize> {
7311        let (sender, receiver) = oneshot::channel();
7312        let handle = PromptHandle::new(sender);
7313        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
7314        self.prompt = Some(handle);
7315        receiver
7316    }
7317
7318    /// Returns whether a prompt rendered by GPUI is currently active in this window.
7319    ///
7320    /// This is only true for prompts rendered in the window (see
7321    /// [`App::set_prompt_builder`]), not for platform-native prompt dialogs.
7322    pub fn has_active_prompt(&self) -> bool {
7323        self.prompt.is_some()
7324    }
7325
7326    /// Returns the current context stack.
7327    pub fn context_stack(&self) -> Vec<KeyContext> {
7328        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7329        let dispatch_tree = &self.rendered_frame.dispatch_tree;
7330        dispatch_tree
7331            .dispatch_path(node_id)
7332            .iter()
7333            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
7334            .collect()
7335    }
7336
7337    /// Returns all available actions for the focused element.
7338    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
7339        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7340        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
7341        for action_type in cx.global_action_listeners.keys() {
7342            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
7343                let action = cx.actions.build_action_type(action_type).ok();
7344                if let Some(action) = action {
7345                    actions.insert(ix, action);
7346                }
7347            }
7348        }
7349        actions
7350    }
7351
7352    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
7353    /// returned in the order they were added. For display, the last binding should take precedence.
7354    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
7355        self.rendered_frame
7356            .dispatch_tree
7357            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
7358    }
7359
7360    /// Returns the highest precedence key binding that invokes an action on the currently focused
7361    /// element. This is more efficient than getting the last result of `bindings_for_action`.
7362    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
7363        self.rendered_frame
7364            .dispatch_tree
7365            .highest_precedence_binding_for_action(
7366                action,
7367                &self.rendered_frame.dispatch_tree.context_stack,
7368            )
7369    }
7370
7371    /// Returns the key bindings for an action in a context.
7372    pub fn bindings_for_action_in_context(
7373        &self,
7374        action: &dyn Action,
7375        context: KeyContext,
7376    ) -> Vec<KeyBinding> {
7377        let dispatch_tree = &self.rendered_frame.dispatch_tree;
7378        dispatch_tree.bindings_for_action(action, &[context])
7379    }
7380
7381    /// Returns the highest precedence key binding for an action in a context. This is more
7382    /// efficient than getting the last result of `bindings_for_action_in_context`.
7383    pub fn highest_precedence_binding_for_action_in_context(
7384        &self,
7385        action: &dyn Action,
7386        context: KeyContext,
7387    ) -> Option<KeyBinding> {
7388        let dispatch_tree = &self.rendered_frame.dispatch_tree;
7389        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
7390    }
7391
7392    /// Returns any bindings that would invoke an action on the given focus handle if it were
7393    /// focused. Bindings are returned in the order they were added. For display, the last binding
7394    /// should take precedence.
7395    pub fn bindings_for_action_in(
7396        &self,
7397        action: &dyn Action,
7398        focus_handle: &FocusHandle,
7399    ) -> Vec<KeyBinding> {
7400        let dispatch_tree = &self.rendered_frame.dispatch_tree;
7401        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
7402            return vec![];
7403        };
7404        dispatch_tree.bindings_for_action(action, &context_stack)
7405    }
7406
7407    /// Returns the highest precedence key binding that would invoke an action on the given focus
7408    /// handle if it were focused. This is more efficient than getting the last result of
7409    /// `bindings_for_action_in`.
7410    pub fn highest_precedence_binding_for_action_in(
7411        &self,
7412        action: &dyn Action,
7413        focus_handle: &FocusHandle,
7414    ) -> Option<KeyBinding> {
7415        let dispatch_tree = &self.rendered_frame.dispatch_tree;
7416        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
7417        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
7418    }
7419
7420    /// Find the bindings that can follow the current input sequence for the current context stack.
7421    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
7422        self.rendered_frame
7423            .dispatch_tree
7424            .possible_next_bindings_for_input(input, &self.context_stack())
7425    }
7426
7427    fn context_stack_for_focus_handle(
7428        &self,
7429        focus_handle: &FocusHandle,
7430    ) -> Option<Vec<KeyContext>> {
7431        let dispatch_tree = &self.rendered_frame.dispatch_tree;
7432        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
7433        let context_stack: Vec<_> = dispatch_tree
7434            .dispatch_path(node_id)
7435            .into_iter()
7436            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
7437            .collect();
7438        Some(context_stack)
7439    }
7440
7441    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
7442    pub fn listener_for<T: 'static, E>(
7443        &self,
7444        view: &Entity<T>,
7445        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
7446    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
7447        let view = view.downgrade();
7448        move |e: &E, window: &mut Window, cx: &mut App| {
7449            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
7450        }
7451    }
7452
7453    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
7454    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
7455        &self,
7456        entity: &Entity<E>,
7457        f: Callback,
7458    ) -> impl Fn(&mut Window, &mut App) + 'static {
7459        let entity = entity.downgrade();
7460        move |window: &mut Window, cx: &mut App| {
7461            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
7462        }
7463    }
7464
7465    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
7466    /// If the callback returns false, the window won't be closed.
7467    pub fn on_window_should_close(
7468        &self,
7469        cx: &App,
7470        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
7471    ) {
7472        let mut cx = self.to_async(cx);
7473        self.platform_window.on_should_close(Box::new(move || {
7474            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
7475        }))
7476    }
7477
7478    /// Register an action listener on this node for the next frame. The type of action
7479    /// is determined by the first parameter of the given listener. When the next frame is rendered
7480    /// the listener will be cleared.
7481    ///
7482    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
7483    /// a specific need to register a listener yourself.
7484    ///
7485    /// This method should only be called as part of the paint phase of element drawing.
7486    pub fn on_action(
7487        &mut self,
7488        action_type: TypeId,
7489        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7490    ) {
7491        self.invalidator.debug_assert_paint();
7492
7493        self.next_frame
7494            .dispatch_tree
7495            .on_action(action_type, Rc::new(listener));
7496    }
7497
7498    /// Register a capturing action listener on this node for the next frame if the condition is true.
7499    /// The type of action is determined by the first parameter of the given listener. When the next
7500    /// frame is rendered the listener will be cleared.
7501    ///
7502    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
7503    /// a specific need to register a listener yourself.
7504    ///
7505    /// This method should only be called as part of the paint phase of element drawing.
7506    pub fn on_action_when(
7507        &mut self,
7508        condition: bool,
7509        action_type: TypeId,
7510        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7511    ) {
7512        self.invalidator.debug_assert_paint();
7513
7514        if condition {
7515            self.next_frame
7516                .dispatch_tree
7517                .on_action(action_type, Rc::new(listener));
7518        }
7519    }
7520
7521    /// Read information about the GPU backing this window.
7522    /// Currently returns None on Mac and Windows.
7523    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
7524        self.platform_window.gpu_specs()
7525    }
7526
7527    /// Perform titlebar double-click action.
7528    /// This is macOS specific.
7529    pub fn titlebar_double_click(&self) {
7530        self.platform_window
7531            .titlebar_double_click(self.is_resizable, self.is_minimizable);
7532    }
7533
7534    /// Gets the window's title at the platform level.
7535    /// This is macOS specific.
7536    pub fn window_title(&self) -> String {
7537        self.platform_window.get_title()
7538    }
7539
7540    /// Returns a list of all tabbed windows and their titles.
7541    /// This is macOS specific.
7542    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
7543        self.platform_window.tabbed_windows()
7544    }
7545
7546    /// Returns the tab bar visibility.
7547    /// This is macOS specific.
7548    pub fn tab_bar_visible(&self) -> bool {
7549        self.platform_window.tab_bar_visible()
7550    }
7551
7552    /// Merges all open windows into a single tabbed window.
7553    /// This is macOS specific.
7554    pub fn merge_all_windows(&self) {
7555        self.platform_window.merge_all_windows()
7556    }
7557
7558    /// Moves the tab to a new containing window.
7559    /// This is macOS specific.
7560    pub fn move_tab_to_new_window(&self) {
7561        self.platform_window.move_tab_to_new_window()
7562    }
7563
7564    /// Shows or hides the window tab overview.
7565    /// This is macOS specific.
7566    pub fn toggle_window_tab_overview(&self) {
7567        self.platform_window.toggle_window_tab_overview()
7568    }
7569
7570    /// Sets the tabbing identifier for the window.
7571    /// This is macOS specific.
7572    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
7573        self.platform_window
7574            .set_tabbing_identifier(tabbing_identifier)
7575    }
7576
7577    /// Request the OS to play an alert sound. On some platforms this is associated
7578    /// with the window, for others it's just a simple global function call.
7579    pub fn play_system_bell(&self) {
7580        self.platform_window.play_system_bell()
7581    }
7582
7583    /// Returns whether accessibility support is enabled for this window.
7584    ///
7585    /// This is false when the app was created with [`crate::Application::new_inaccessible`].
7586    /// Unlike [`Self::is_a11y_active`], this does not depend on whether assistive
7587    /// technology is currently connected, so it can be used to gate subscriptions
7588    /// that are only needed for accessibility.
7589    pub fn is_a11y_enabled(&self) -> bool {
7590        self.a11y.is_enabled()
7591    }
7592
7593    /// Returns whether accessibility features are active for this frame,
7594    /// i.e. whether assistive technology (such as a screen reader) is
7595    /// connected and an accessibility tree is being built.
7596    ///
7597    /// Use this to skip computing data during rendering that is only
7598    /// observable through the accessibility tree. When accessibility is
7599    /// activated, a redraw is forced, so gated work is recomputed before the
7600    /// next tree update is sent to the platform.
7601    ///
7602    /// See the [accessibility guide](crate::_accessibility) for an overview.
7603    pub fn is_a11y_active(&self) -> bool {
7604        self.a11y.is_active()
7605    }
7606
7607    /// Debug representation of the last frame's accessibility information.
7608    pub fn debug_a11y_tree_json(&self) -> Option<String> {
7609        self.a11y.debug_tree_json()
7610    }
7611
7612    /// Register a listener for an accessibility action on a specific node.
7613    /// The listener will be called when a screen reader requests the given
7614    /// action on the node identified by `node_id`.
7615    ///
7616    /// See the [accessibility guide](crate::_accessibility) for an overview.
7617    pub fn on_a11y_action(
7618        &mut self,
7619        node_id: accesskit::NodeId,
7620        action: accesskit::Action,
7621        listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
7622    ) {
7623        self.a11y
7624            .action_listeners
7625            .entry(node_id)
7626            .or_default()
7627            .push((action, Box::new(listener)));
7628    }
7629
7630    #[cfg(not(target_family = "wasm"))]
7631    pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
7632        // Take listeners out temporarily so the closures can borrow Window
7633        // mutably, then restore them afterward.
7634        if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
7635            let extra_data = request.data.as_ref();
7636            let mut matched = false;
7637            for (action, listener) in &mut listeners {
7638                if *action == request.action {
7639                    listener(extra_data, self, cx);
7640                    matched = true;
7641                }
7642            }
7643            self.a11y
7644                .action_listeners
7645                .insert(request.target_node, listeners);
7646            if matched {
7647                return;
7648            }
7649        }
7650
7651        // Fall back to built-in action handling.
7652        match request.action {
7653            accesskit::Action::Click => {
7654                if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
7655                    let center = bounds.center();
7656                    let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
7657                        button: MouseButton::Left,
7658                        position: center,
7659                        modifiers: Modifiers::default(),
7660                        click_count: 1,
7661                        first_mouse: false,
7662                    });
7663                    let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
7664                        button: MouseButton::Left,
7665                        position: center,
7666                        modifiers: Modifiers::default(),
7667                        click_count: 1,
7668                    });
7669                    self.dispatch_event(mouse_down, cx);
7670                    self.dispatch_event(mouse_up, cx);
7671                }
7672            }
7673            accesskit::Action::Focus => {
7674                if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
7675                    && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
7676                {
7677                    self.focus(&handle, cx);
7678                }
7679            }
7680            accesskit::Action::Blur => {
7681                self.blur(cx);
7682            }
7683            _ => {
7684                log::debug!(
7685                    "Unhandled a11y action: {:?} on {:?}",
7686                    request.action,
7687                    request.target_node
7688                );
7689            }
7690        }
7691    }
7692
7693    /// Toggles the inspector mode on this window.
7694    #[cfg(any(feature = "inspector", debug_assertions))]
7695    pub fn toggle_inspector(&mut self, cx: &mut App) {
7696        self.inspector = match self.inspector {
7697            None => Some(cx.new(|_| Inspector::new())),
7698            Some(_) => {
7699                self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
7700                self.rendered_frame.inspector_hitboxes = FxHashMap::default();
7701                self.next_frame.next_inspector_instance_ids = FxHashMap::default();
7702                self.next_frame.inspector_hitboxes = FxHashMap::default();
7703                None
7704            }
7705        };
7706        self.refresh();
7707    }
7708
7709    /// Returns true if the window is in inspector mode.
7710    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
7711        #[cfg(any(feature = "inspector", debug_assertions))]
7712        {
7713            if let Some(inspector) = &self.inspector {
7714                return inspector.read(_cx).is_picking();
7715            }
7716        }
7717        false
7718    }
7719
7720    /// Executes the provided function with mutable access to an inspector state.
7721    #[cfg(any(feature = "inspector", debug_assertions))]
7722    pub fn with_inspector_state<T: 'static, R>(
7723        &mut self,
7724        inspector_id: Option<&crate::InspectorElementId>,
7725        cx: &mut App,
7726        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7727    ) -> Option<R> {
7728        let inspector_id = inspector_id?;
7729        let inspector = self.inspector.as_ref()?;
7730        if inspector.read(cx).active_element_id() != Some(inspector_id) {
7731            return None;
7732        }
7733        let inspector = inspector.clone();
7734        Some(inspector.update(cx, |inspector, _cx| {
7735            inspector.with_active_element_state(self, f)
7736        }))
7737    }
7738
7739    #[cfg(any(feature = "inspector", debug_assertions))]
7740    pub(crate) fn inspector_enabled(&self) -> bool {
7741        self.inspector.is_some()
7742    }
7743
7744    #[cfg(any(feature = "inspector", debug_assertions))]
7745    pub(crate) fn build_inspector_element_id(
7746        &mut self,
7747        path: crate::InspectorElementPath,
7748    ) -> crate::InspectorElementId {
7749        self.invalidator.debug_assert_paint_or_prepaint();
7750        let path = Rc::new(path);
7751        let next_instance_id = self
7752            .next_frame
7753            .next_inspector_instance_ids
7754            .entry(path.clone())
7755            .or_insert(0);
7756        let instance_id = *next_instance_id;
7757        *next_instance_id += 1;
7758        crate::InspectorElementId { path, instance_id }
7759    }
7760
7761    #[cfg(any(feature = "inspector", debug_assertions))]
7762    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
7763        if let Some(inspector) = self.inspector.take() {
7764            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
7765            inspector_element.prepaint_as_root(
7766                point(self.viewport_size.width - inspector_width, px(0.0)),
7767                size(inspector_width, self.viewport_size.height).into(),
7768                self,
7769                cx,
7770            );
7771            self.inspector = Some(inspector);
7772            Some(inspector_element)
7773        } else {
7774            None
7775        }
7776    }
7777
7778    #[cfg(any(feature = "inspector", debug_assertions))]
7779    fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
7780        if let Some(mut inspector_element) = inspector_element {
7781            inspector_element.paint(self, cx);
7782        };
7783    }
7784
7785    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
7786    /// inspect UI elements by clicking on them.
7787    #[cfg(any(feature = "inspector", debug_assertions))]
7788    pub fn insert_inspector_hitbox(
7789        &mut self,
7790        hitbox_id: HitboxId,
7791        inspector_id: Option<&crate::InspectorElementId>,
7792        cx: &App,
7793    ) {
7794        self.invalidator.debug_assert_paint_or_prepaint();
7795        if !self.is_inspector_picking(cx) {
7796            return;
7797        }
7798        if let Some(inspector_id) = inspector_id {
7799            self.next_frame
7800                .inspector_hitboxes
7801                .insert(hitbox_id, inspector_id.clone());
7802        }
7803    }
7804
7805    #[cfg(any(feature = "inspector", debug_assertions))]
7806    fn paint_inspector_hitbox(&mut self, cx: &App) {
7807        if let Some(inspector) = self.inspector.as_ref() {
7808            let inspector = inspector.read(cx);
7809            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
7810                && let Some(hitbox) = self
7811                    .next_frame
7812                    .hitboxes
7813                    .iter()
7814                    .find(|hitbox| hitbox.id == hitbox_id)
7815            {
7816                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7817            }
7818        }
7819    }
7820
7821    #[cfg(any(feature = "inspector", debug_assertions))]
7822    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7823        let Some(inspector) = self.inspector.clone() else {
7824            return;
7825        };
7826        if event.downcast_ref::<MouseMoveEvent>().is_some() {
7827            inspector.update(cx, |inspector, _cx| {
7828                if let Some((_, inspector_id)) =
7829                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7830                {
7831                    inspector.hover(inspector_id, self);
7832                }
7833            });
7834        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7835            inspector.update(cx, |inspector, _cx| {
7836                if let Some((_, inspector_id)) =
7837                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7838                {
7839                    inspector.select(inspector_id, self);
7840                }
7841            });
7842        } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
7843            // This should be kept in sync with SCROLL_LINES in x11 platform.
7844            const SCROLL_LINES: f32 = 3.0;
7845            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7846            let delta_y = event
7847                .delta
7848                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7849                .y;
7850            inspector.update(cx, |inspector, _cx| {
7851                if let Some(depth) = inspector.pick_depth.as_mut() {
7852                    *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7853                    let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
7854                    if *depth < 0.0 {
7855                        *depth = 0.0;
7856                    } else if *depth > max_depth {
7857                        *depth = max_depth;
7858                    }
7859                    if let Some((_, inspector_id)) =
7860                        self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7861                    {
7862                        inspector.set_active_element_id(inspector_id, self);
7863                    }
7864                }
7865            });
7866        }
7867    }
7868
7869    #[cfg(any(feature = "inspector", debug_assertions))]
7870    fn hovered_inspector_hitbox(
7871        &self,
7872        inspector: &Inspector,
7873        frame: &Frame,
7874    ) -> Option<(HitboxId, crate::InspectorElementId)> {
7875        if let Some(pick_depth) = inspector.pick_depth {
7876            let depth = (pick_depth as i64).try_into().unwrap_or(0);
7877            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
7878            let skip_count = (depth as usize).min(max_skipped);
7879            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
7880                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7881                    return Some((*hitbox_id, inspector_id.clone()));
7882                }
7883            }
7884        }
7885        None
7886    }
7887
7888    /// For testing: set the current modifier keys state.
7889    /// This does not generate any events.
7890    #[cfg(any(test, feature = "test-support"))]
7891    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7892        self.modifiers = modifiers;
7893    }
7894
7895    /// For testing: simulate a mouse move event to the given position.
7896    /// This dispatches the event through the normal event handling path,
7897    /// which will trigger hover states and tooltips.
7898    #[cfg(any(test, feature = "test-support"))]
7899    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7900        let event = PlatformInput::MouseMove(MouseMoveEvent {
7901            position,
7902            modifiers: self.modifiers,
7903            pressed_button: None,
7904        });
7905        let _ = self.dispatch_event(event, cx);
7906    }
7907
7908    #[inline(never)]
7909    fn take_element_state(
7910        &mut self,
7911        global_id: &GlobalElementId,
7912        state_type: TypeId,
7913    ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
7914        let key = (global_id.clone(), state_type);
7915        self.next_frame.accessed_element_states.push(key.clone());
7916        let state = self
7917            .next_frame
7918            .element_states
7919            .remove(&key)
7920            .or_else(|| self.rendered_frame.element_states.remove(&key));
7921        (key, state)
7922    }
7923
7924    #[inline(never)]
7925    fn insert_element_state(
7926        &mut self,
7927        key: (GlobalElementId, TypeId),
7928        state: ElementStateBox,
7929    ) -> Option<ElementStateBox> {
7930        self.next_frame.element_states.insert(key, state)
7931    }
7932
7933    #[inline(never)]
7934    fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
7935        cx.observe(state, move |_, cx| {
7936            cx.notify(current_view);
7937        })
7938        .detach();
7939    }
7940}
7941
7942// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
7943slotmap::new_key_type! {
7944    /// A unique identifier for a window.
7945    pub struct WindowId;
7946}
7947
7948impl WindowId {
7949    /// Converts this window ID to a `u64`.
7950    pub fn as_u64(&self) -> u64 {
7951        self.0.as_ffi()
7952    }
7953}
7954
7955impl From<u64> for WindowId {
7956    fn from(value: u64) -> Self {
7957        WindowId(slotmap::KeyData::from_ffi(value))
7958    }
7959}
7960
7961/// A handle to a window with a specific root view type.
7962/// Note that this does not keep the window alive on its own.
7963#[derive(Deref, DerefMut)]
7964pub struct WindowHandle<V> {
7965    #[deref]
7966    #[deref_mut]
7967    pub(crate) any_handle: AnyWindowHandle,
7968    state_type: PhantomData<fn(V) -> V>,
7969}
7970
7971impl<V> Debug for WindowHandle<V> {
7972    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7973        f.debug_struct("WindowHandle")
7974            .field("any_handle", &self.any_handle.id.as_u64())
7975            .finish()
7976    }
7977}
7978
7979impl<V: 'static + Render> WindowHandle<V> {
7980    /// Creates a new handle from a window ID.
7981    /// This does not check if the root type of the window is `V`.
7982    pub fn new(id: WindowId) -> Self {
7983        WindowHandle {
7984            any_handle: AnyWindowHandle {
7985                id,
7986                state_type: TypeId::of::<V>(),
7987                root_entity_type_name: std::any::type_name::<V>(),
7988            },
7989            state_type: PhantomData,
7990        }
7991    }
7992
7993    /// Get the root view out of this window.
7994    ///
7995    /// This will fail if the window is closed or if the root view's type does not match `V`.
7996    #[cfg(any(test, feature = "test-support"))]
7997    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
7998    where
7999        C: AppContext,
8000    {
8001        cx.update_window(self.any_handle, |root_view, _, _| {
8002            root_view
8003                .downcast::<V>()
8004                .map_err(|_| anyhow!("the type of the window's root view has changed"))
8005        })?
8006    }
8007
8008    /// Updates the root view of this window.
8009    ///
8010    /// This will fail if the window has been closed or if the root view's type does not match
8011    #[track_caller]
8012    pub fn update<C, R>(
8013        &self,
8014        cx: &mut C,
8015        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
8016    ) -> Result<R>
8017    where
8018        C: AppContext,
8019    {
8020        cx.update_window(self.any_handle, |root_view, window, cx| {
8021            let view = root_view
8022                .downcast::<V>()
8023                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
8024
8025            Ok(view.update(cx, |view, cx| update(view, window, cx)))
8026        })?
8027    }
8028
8029    /// Read the root view out of this window.
8030    ///
8031    /// This will fail if the window is closed or if the root view's type does not match `V`.
8032    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
8033        let x = cx
8034            .windows
8035            .get(self.id)
8036            .and_then(|window| {
8037                window
8038                    .as_deref()
8039                    .and_then(|window| window.root.clone())
8040                    .map(|root_view| root_view.downcast::<V>())
8041            })
8042            .context("window not found")?
8043            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
8044
8045        Ok(x.read(cx))
8046    }
8047
8048    /// Read the root view out of this window, with a callback
8049    ///
8050    /// This will fail if the window is closed or if the root view's type does not match `V`.
8051    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
8052    where
8053        C: AppContext,
8054    {
8055        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
8056    }
8057
8058    /// Read the root view pointer off of this window.
8059    ///
8060    /// This will fail if the window is closed or if the root view's type does not match `V`.
8061    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
8062    where
8063        C: AppContext,
8064    {
8065        cx.read_window(self, |root_view, _cx| root_view)
8066    }
8067
8068    /// Check if this window is 'active'.
8069    ///
8070    /// Will return `None` if the window is closed or currently
8071    /// borrowed.
8072    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
8073        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
8074            .ok()
8075    }
8076}
8077
8078impl<V> Copy for WindowHandle<V> {}
8079
8080impl<V> Clone for WindowHandle<V> {
8081    fn clone(&self) -> Self {
8082        *self
8083    }
8084}
8085
8086impl<V> PartialEq for WindowHandle<V> {
8087    fn eq(&self, other: &Self) -> bool {
8088        self.any_handle == other.any_handle
8089    }
8090}
8091
8092impl<V> Eq for WindowHandle<V> {}
8093
8094impl<V> Hash for WindowHandle<V> {
8095    fn hash<H: Hasher>(&self, state: &mut H) {
8096        self.any_handle.hash(state);
8097    }
8098}
8099
8100impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
8101    fn from(val: WindowHandle<V>) -> Self {
8102        val.any_handle
8103    }
8104}
8105
8106/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
8107#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
8108pub struct AnyWindowHandle {
8109    pub(crate) id: WindowId,
8110    state_type: TypeId,
8111    root_entity_type_name: &'static str,
8112}
8113
8114impl AnyWindowHandle {
8115    /// Get the ID of this window.
8116    pub fn window_id(&self) -> WindowId {
8117        self.id
8118    }
8119
8120    /// Returns the name of the window's declared root entity type.
8121    pub fn root_entity_type_name(&self) -> &'static str {
8122        self.root_entity_type_name
8123    }
8124
8125    /// Attempt to convert this handle to a window handle with a specific root view type.
8126    /// If the types do not match, this will return `None`.
8127    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
8128        if TypeId::of::<T>() == self.state_type {
8129            Some(WindowHandle {
8130                any_handle: *self,
8131                state_type: PhantomData,
8132            })
8133        } else {
8134            None
8135        }
8136    }
8137
8138    /// Updates the state of the root view of this window.
8139    ///
8140    /// This will fail if the window has been closed.
8141    #[track_caller]
8142    pub fn update<C, R>(
8143        self,
8144        cx: &mut C,
8145        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
8146    ) -> Result<R>
8147    where
8148        C: AppContext,
8149    {
8150        cx.update_window(self, update)
8151    }
8152
8153    /// Read the state of the root view of this window.
8154    ///
8155    /// This will fail if the window has been closed.
8156    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
8157    where
8158        C: AppContext,
8159        T: 'static,
8160    {
8161        let view = self
8162            .downcast::<T>()
8163            .context("the type of the window's root view has changed")?;
8164
8165        cx.read_window(&view, read)
8166    }
8167}
8168
8169impl HasWindowHandle for Window {
8170    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
8171        self.platform_window.window_handle()
8172    }
8173}
8174
8175impl HasDisplayHandle for Window {
8176    fn display_handle(
8177        &self,
8178    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
8179        self.platform_window.display_handle()
8180    }
8181}
8182
8183/// An identifier for an [`Element`].
8184///
8185/// Can be constructed with a string, a number, or both, as well
8186/// as other internal representations.
8187#[derive(Clone, Debug, Eq, PartialEq, Hash)]
8188pub enum ElementId {
8189    /// The ID of a View element
8190    View(EntityId),
8191    /// An integer ID.
8192    Integer(u64),
8193    /// A string based ID.
8194    Name(SharedString),
8195    /// A UUID.
8196    Uuid(Uuid),
8197    /// An ID that's equated with a focus handle.
8198    FocusHandle(FocusId),
8199    /// A combination of a name and an integer.
8200    NamedInteger(SharedString, u64),
8201    /// A path.
8202    Path(Arc<std::path::Path>),
8203    /// A code location.
8204    CodeLocation(core::panic::Location<'static>),
8205    /// A labeled child of an element.
8206    NamedChild(Arc<ElementId>, SharedString),
8207    /// A byte array ID (used for text-anchors)
8208    OpaqueId([u8; 20]),
8209}
8210
8211impl ElementId {
8212    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
8213    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
8214        Self::NamedInteger(name.into(), integer as u64)
8215    }
8216}
8217
8218impl Display for ElementId {
8219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8220        match self {
8221            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
8222            ElementId::Integer(ix) => write!(f, "{}", ix)?,
8223            ElementId::Name(name) => write!(f, "{}", name)?,
8224            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
8225            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
8226            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
8227            ElementId::Path(path) => write!(f, "{}", path.display())?,
8228            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
8229            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
8230            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
8231        }
8232
8233        Ok(())
8234    }
8235}
8236
8237impl TryInto<SharedString> for ElementId {
8238    type Error = anyhow::Error;
8239
8240    fn try_into(self) -> anyhow::Result<SharedString> {
8241        if let ElementId::Name(name) = self {
8242            Ok(name)
8243        } else {
8244            anyhow::bail!("element id is not string")
8245        }
8246    }
8247}
8248
8249impl From<u64> for ElementId {
8250    fn from(id: u64) -> Self {
8251        ElementId::Integer(id)
8252    }
8253}
8254
8255impl From<usize> for ElementId {
8256    fn from(id: usize) -> Self {
8257        ElementId::Integer(id as u64)
8258    }
8259}
8260
8261impl From<i32> for ElementId {
8262    fn from(id: i32) -> Self {
8263        Self::Integer(id as u64)
8264    }
8265}
8266
8267impl From<SharedString> for ElementId {
8268    fn from(name: SharedString) -> Self {
8269        ElementId::Name(name)
8270    }
8271}
8272
8273impl From<String> for ElementId {
8274    fn from(name: String) -> Self {
8275        ElementId::Name(name.into())
8276    }
8277}
8278
8279impl From<Arc<str>> for ElementId {
8280    fn from(name: Arc<str>) -> Self {
8281        ElementId::Name(name.into())
8282    }
8283}
8284
8285impl From<Arc<std::path::Path>> for ElementId {
8286    fn from(path: Arc<std::path::Path>) -> Self {
8287        ElementId::Path(path)
8288    }
8289}
8290
8291impl From<&'static str> for ElementId {
8292    fn from(name: &'static str) -> Self {
8293        ElementId::Name(SharedString::new_static(name))
8294    }
8295}
8296
8297impl<'a> From<&'a FocusHandle> for ElementId {
8298    fn from(handle: &'a FocusHandle) -> Self {
8299        ElementId::FocusHandle(handle.id)
8300    }
8301}
8302
8303impl From<(&'static str, EntityId)> for ElementId {
8304    fn from((name, id): (&'static str, EntityId)) -> Self {
8305        ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
8306    }
8307}
8308
8309impl From<(&'static str, usize)> for ElementId {
8310    fn from((name, id): (&'static str, usize)) -> Self {
8311        ElementId::NamedInteger(SharedString::new_static(name), id as u64)
8312    }
8313}
8314
8315impl From<(SharedString, usize)> for ElementId {
8316    fn from((name, id): (SharedString, usize)) -> Self {
8317        ElementId::NamedInteger(name, id as u64)
8318    }
8319}
8320
8321impl From<(&'static str, u64)> for ElementId {
8322    fn from((name, id): (&'static str, u64)) -> Self {
8323        ElementId::NamedInteger(SharedString::new_static(name), id)
8324    }
8325}
8326
8327impl From<Uuid> for ElementId {
8328    fn from(value: Uuid) -> Self {
8329        Self::Uuid(value)
8330    }
8331}
8332
8333impl From<(&'static str, u32)> for ElementId {
8334    fn from((name, id): (&'static str, u32)) -> Self {
8335        ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
8336    }
8337}
8338
8339impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
8340    fn from((id, name): (ElementId, T)) -> Self {
8341        ElementId::NamedChild(Arc::new(id), name.into())
8342    }
8343}
8344
8345impl From<&'static core::panic::Location<'static>> for ElementId {
8346    fn from(location: &'static core::panic::Location<'static>) -> Self {
8347        ElementId::CodeLocation(*location)
8348    }
8349}
8350
8351impl From<[u8; 20]> for ElementId {
8352    fn from(opaque_id: [u8; 20]) -> Self {
8353        ElementId::OpaqueId(opaque_id)
8354    }
8355}
8356
8357/// A rectangle to be rendered in the window at the given position and size.
8358/// Passed as an argument [`Window::paint_quad`].
8359#[derive(Clone)]
8360pub struct PaintQuad {
8361    /// The bounds of the quad within the window.
8362    pub bounds: Bounds<Pixels>,
8363    /// The radii of the quad's corners.
8364    pub corner_radii: Corners<Pixels>,
8365    /// The background color of the quad.
8366    pub background: Background,
8367    /// The widths of the quad's borders.
8368    pub border_widths: Edges<Pixels>,
8369    /// The color of the quad's borders.
8370    pub border_color: Hsla,
8371    /// The style of the quad's borders.
8372    pub border_style: BorderStyle,
8373}
8374
8375impl PaintQuad {
8376    /// Sets the corner radii of the quad.
8377    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
8378        PaintQuad {
8379            corner_radii: corner_radii.into(),
8380            ..self
8381        }
8382    }
8383
8384    /// Sets the border widths of the quad.
8385    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
8386        PaintQuad {
8387            border_widths: border_widths.into(),
8388            ..self
8389        }
8390    }
8391
8392    /// Sets the border color of the quad.
8393    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
8394        PaintQuad {
8395            border_color: border_color.into(),
8396            ..self
8397        }
8398    }
8399
8400    /// Sets the background color of the quad.
8401    pub fn background(self, background: impl Into<Background>) -> Self {
8402        PaintQuad {
8403            background: background.into(),
8404            ..self
8405        }
8406    }
8407}
8408
8409/// Creates a quad with the given parameters.
8410pub fn quad(
8411    bounds: Bounds<Pixels>,
8412    corner_radii: impl Into<Corners<Pixels>>,
8413    background: impl Into<Background>,
8414    border_widths: impl Into<Edges<Pixels>>,
8415    border_color: impl Into<Hsla>,
8416    border_style: BorderStyle,
8417) -> PaintQuad {
8418    PaintQuad {
8419        bounds,
8420        corner_radii: corner_radii.into(),
8421        background: background.into(),
8422        border_widths: border_widths.into(),
8423        border_color: border_color.into(),
8424        border_style,
8425    }
8426}
8427
8428/// Creates a filled quad with the given bounds and background color.
8429pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
8430    PaintQuad {
8431        bounds: bounds.into(),
8432        corner_radii: (0.).into(),
8433        background: background.into(),
8434        border_widths: (0.).into(),
8435        border_color: transparent_black(),
8436        border_style: BorderStyle::default(),
8437    }
8438}
8439
8440/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
8441pub fn outline(
8442    bounds: impl Into<Bounds<Pixels>>,
8443    border_color: impl Into<Hsla>,
8444    border_style: BorderStyle,
8445) -> PaintQuad {
8446    PaintQuad {
8447        bounds: bounds.into(),
8448        corner_radii: (0.).into(),
8449        background: transparent_black().into(),
8450        border_widths: (1.).into(),
8451        border_color: border_color.into(),
8452        border_style,
8453    }
8454}
8455
8456#[inline(never)]
8457fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
8458    if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
8459        // SAFETY: The pointer is valid for the duration of the draw operation
8460        // that set it, and we're being called during that same draw.
8461        let arena_cell = unsafe { &*arena_pointer };
8462        callback(&mut arena_cell.borrow_mut());
8463        Ok(())
8464    } else {
8465        ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
8466    }
8467}
8468
8469#[cfg(test)]
8470mod tests {
8471    use std::{
8472        cell::{Cell, RefCell},
8473        path::PathBuf,
8474        rc::Rc,
8475        time::Duration,
8476    };
8477
8478    use crate::{
8479        AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
8480        Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
8481        ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
8482        InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
8483        MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
8484        Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
8485        TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
8486        UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
8487        size,
8488    };
8489
8490    #[gpui::test]
8491    async fn test_focus_handle_release(cx: &mut TestAppContext) {
8492        let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
8493        let handle_id = handle.id;
8494        let weak_handle = handle.downgrade();
8495        let retained = handle.clone();
8496        drop(handle);
8497
8498        cx.update(|_| {});
8499        cx.read(|cx| {
8500            let handles = cx.focus_handles.read();
8501            assert_eq!(handles.handles.len(), 2);
8502            assert!(handles.dropped_handles.is_empty());
8503        });
8504        assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
8505
8506        cx.background_spawn(async move { drop(retained) }).await;
8507        assert_eq!(weak_handle.upgrade(), None);
8508        cx.read(|cx| {
8509            assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
8510        });
8511        cx.update(|_| {});
8512        cx.read(|cx| {
8513            let handles = cx.focus_handles.read();
8514            assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
8515            assert!(handles.dropped_handles.is_empty());
8516        });
8517
8518        let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
8519        assert_eq!(weak_handle.upgrade(), None);
8520        cx.update(|cx| {
8521            drop(replacements);
8522            cx.defer(move |_| drop(survivor));
8523        });
8524        cx.read(|cx| {
8525            let handles = cx.focus_handles.read();
8526            assert_eq!(handles.handles.len(), 0);
8527            assert!(handles.dropped_handles.is_empty());
8528        });
8529    }
8530
8531    #[gpui::test]
8532    fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
8533        let windows = [
8534            cx.add_window(|_, _| EmptyView),
8535            cx.add_window(|_, _| EmptyView),
8536            cx.add_window(|_, _| EmptyView),
8537            cx.add_window(|_, _| EmptyView),
8538            cx.add_window(|_, _| EmptyView),
8539        ];
8540        let (handle, other_handle, survivor) =
8541            cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
8542        for window in &windows[..2] {
8543            window
8544                .update(cx, |_, window, cx| window.focus(&handle, cx))
8545                .expect("window exists");
8546        }
8547        windows[2]
8548            .update(cx, |_, window, cx| window.focus(&other_handle, cx))
8549            .expect("window exists");
8550        windows[3]
8551            .update(cx, |_, window, cx| window.focus(&survivor, cx))
8552            .expect("window exists");
8553
8554        cx.update(|cx| {
8555            for _ in 0..1_000 {
8556                drop(cx.focus_handle());
8557            }
8558            drop((handle, other_handle));
8559        });
8560        for window in &windows[..3] {
8561            window
8562                .update(cx, |_, window, _| assert_eq!(window.focus, None))
8563                .expect("window exists");
8564        }
8565        windows[3]
8566            .update(cx, |_, window, cx| {
8567                assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
8568                assert_eq!(window.focus_generation, 1);
8569            })
8570            .expect("window exists");
8571        windows[4]
8572            .update(cx, |_, window, _| {
8573                assert_eq!(window.focus, None);
8574                assert_eq!(window.focus_generation, 0);
8575            })
8576            .expect("window exists");
8577    }
8578
8579    #[gpui::test]
8580    fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
8581        let window = cx.add_window(|_, _| EmptyView);
8582        let platform_window = cx.test_window(window.into());
8583        {
8584            let app = cx.app.borrow_mut();
8585            platform_window.simulate_close();
8586            assert!(app.windows.contains_key(window.window_id()));
8587        }
8588        cx.run_until_parked();
8589        assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
8590    }
8591
8592    #[cfg(feature = "profiler")]
8593    #[gpui::test]
8594    fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
8595        use crate::FrameRequestSource;
8596        use crate::profiler::journal::{
8597            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8598        };
8599        use scheduler::Instant;
8600
8601        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8602        let window = cx.add_window(|_, _| EmptyView);
8603        let platform_window = cx.test_window(window.into());
8604        platform_window.simulate_frame_request(RequestFrameOptions::default());
8605        let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
8606        let mut collector = journal.collector();
8607
8608        for (signal_at, source) in [
8609            (Some(Instant::now()), FrameRequestSource::NativeCallback),
8610            (Some(Instant::now()), FrameRequestSource::LocalSchedule),
8611            (None, FrameRequestSource::NativeCallback),
8612        ] {
8613            platform_window.simulate_frame_request(RequestFrameOptions {
8614                signal_at,
8615                signal_source: source,
8616                require_presentation: true,
8617                ..Default::default()
8618            });
8619            let entries = collector.collect_unseen().entries;
8620            let signal_index = entries
8621                .iter()
8622                .position(|entry| {
8623                    matches!(
8624                        entry,
8625                        ForegroundJournalEntry::PlatformSignal(signal)
8626                            if signal.window_id == window.window_id()
8627                                && signal.signal_at == signal_at
8628                                && signal.source == source
8629                                && signal_at.is_none_or(|at| signal.handled_at >= at)
8630                    )
8631                })
8632                .expect("frame request metadata");
8633            let skip_index = entries
8634                .iter()
8635                .position(|entry| {
8636                    matches!(
8637                        entry,
8638                        ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8639                            if skipped.window_id == window.window_id()
8640                                && skipped.reason == FrameSkipReason::NoRenderNeeded
8641                    )
8642                })
8643                .expect("completed no-render boundary");
8644            assert!(signal_index < skip_index);
8645        }
8646    }
8647
8648    #[cfg(feature = "profiler")]
8649    #[gpui::test]
8650    fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
8651        use crate::profiler::journal::{
8652            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8653        };
8654        use scheduler::Instant;
8655
8656        // Test mode draws during effect flushing, bypassing platform frame throttling.
8657        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8658        let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
8659        let mut collector = journal.collector();
8660        for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
8661            // Keep the throttle closed without depending on short wall-clock deadlines.
8662            let window = cx
8663                .app
8664                .borrow_mut()
8665                .open_window(
8666                    WindowOptions {
8667                        inactive_frame_interval: Some(Duration::from_secs(3600)),
8668                        ..Default::default()
8669                    },
8670                    |_, cx| cx.new(|_| EmptyView),
8671                )
8672                .expect("open inactive test window");
8673            let platform_window = cx.test_window(window.into());
8674            platform_window.simulate_active_status_change(false);
8675            platform_window.simulate_frame_request(RequestFrameOptions::default());
8676            let callback_ran = Rc::new(Cell::new(false));
8677            let draws_before = window
8678                .update(cx, |_, window, _| {
8679                    let draws_before = window
8680                        .frame_duration_snapshot()
8681                        .draw_duration_histogram
8682                        .len();
8683                    if initially_dirty {
8684                        window.refresh();
8685                    }
8686                    if schedule_callback {
8687                        window.on_next_frame({
8688                            let callback_ran = callback_ran.clone();
8689                            move |window, _| {
8690                                callback_ran.set(true);
8691                                window.refresh();
8692                            }
8693                        });
8694                    }
8695                    draws_before
8696                })
8697                .expect("schedule throttled frame");
8698            // Skips only seal retained work, so give the throttled skip some.
8699            let input_at = Instant::now();
8700            journal::record_input(journal::InputTiming {
8701                kind: "test",
8702                start: input_at,
8703                end: input_at,
8704                caused_invalidation: false,
8705            });
8706            collector.collect_unseen();
8707            let wakes_before = platform_window.frame_wake_count();
8708            platform_window.simulate_frame_request(RequestFrameOptions {
8709                signal_at: Some(Instant::now()),
8710                ..Default::default()
8711            });
8712            window
8713                .update(cx, |_, window, _| {
8714                    assert_eq!(
8715                        window
8716                            .frame_duration_snapshot()
8717                            .draw_duration_histogram
8718                            .len(),
8719                        draws_before,
8720                    );
8721                })
8722                .expect("inspect deferred frame");
8723            assert!(!callback_ran.get());
8724            assert!(platform_window.frame_scheduled());
8725            assert!(platform_window.frame_wake_count() > wakes_before);
8726            assert!(collector.collect_unseen().entries.iter().any(|entry| {
8727                matches!(
8728                    entry,
8729                    ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8730                        if skipped.window_id == window.window_id()
8731                            && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
8732                )
8733            }));
8734            platform_window.simulate_frame_request(RequestFrameOptions {
8735                signal_at: Some(Instant::now()),
8736                require_presentation: true,
8737                ..Default::default()
8738            });
8739            window
8740                .update(cx, |_, window, _| {
8741                    assert_eq!(
8742                        window
8743                            .frame_duration_snapshot()
8744                            .draw_duration_histogram
8745                            .len(),
8746                        draws_before + 1,
8747                    );
8748                })
8749                .expect("inspect presented frame");
8750            assert_eq!(callback_ran.get(), schedule_callback);
8751        }
8752    }
8753
8754    /// A stale cache is only visible if the snapshot reports GPUI's cached
8755    /// value separately from what the platform reports now.
8756    #[gpui::test]
8757    fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
8758        use crate::WindowVisibility;
8759
8760        let window = cx.add_window(|_, _| EmptyView);
8761        let window_id = window.window_id().as_u64();
8762        let window_state = |cx: &mut TestAppContext| {
8763            let state = cx.update(|cx| cx.debug_state());
8764            state["windows"]
8765                .as_array()
8766                .and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
8767                .cloned()
8768                .expect("the open window is listed")
8769        };
8770
8771        let state = window_state(cx);
8772        assert_eq!(state["visibility"]["cached"], "Visible");
8773        assert_eq!(state["visibility"]["platform"], "Visible");
8774
8775        cx.test_window(window.into())
8776            .simulate_visibility_change(WindowVisibility::Hidden);
8777        let state = window_state(cx);
8778        assert_eq!(state["visibility"]["cached"], "Hidden");
8779        assert_eq!(state["visibility"]["platform"], "Hidden");
8780    }
8781
8782    /// Visibility transitions reach observers exactly once each, with the new
8783    /// state already stored on the window, and never wake the platform for a
8784    /// frame: the platform requests one itself when it resumes presenting.
8785    #[gpui::test]
8786    fn test_window_visibility(cx: &mut TestAppContext) {
8787        use crate::WindowVisibility;
8788
8789        let window = cx.add_window(|_, _| EmptyView);
8790        let observed = Rc::new(RefCell::new(Vec::new()));
8791        let _subscription = window
8792            .update(cx, {
8793                let observed = observed.clone();
8794                move |_, window, _| {
8795                    assert_eq!(window.visibility(), WindowVisibility::Visible);
8796                    assert!(window.is_visible());
8797                    window.observe_window_visibility(move |visibility, window, _| {
8798                        assert_eq!(window.visibility(), visibility);
8799                        observed.borrow_mut().push(visibility);
8800                    })
8801                }
8802            })
8803            .unwrap();
8804        let test_window = cx.test_window(window.into());
8805        let frame_wake_count = test_window.frame_wake_count();
8806
8807        test_window.simulate_visibility_change(WindowVisibility::Hidden);
8808        assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
8809        window
8810            .update(cx, |_, window, _| assert!(!window.is_visible()))
8811            .unwrap();
8812
8813        // Platforms may report the same state again; observers only see changes.
8814        test_window.simulate_visibility_change(WindowVisibility::Hidden);
8815        assert_eq!(observed.borrow().len(), 1);
8816
8817        test_window.simulate_visibility_change(WindowVisibility::Visible);
8818        assert_eq!(
8819            *observed.borrow(),
8820            [WindowVisibility::Hidden, WindowVisibility::Visible]
8821        );
8822        window
8823            .update(cx, |_, window, _| assert!(window.is_visible()))
8824            .unwrap();
8825        assert_eq!(test_window.frame_wake_count(), frame_wake_count);
8826    }
8827
8828    /// App learns display state from the platform's display notifications,
8829    /// and a window from the platform's report of which display it is on.
8830    #[gpui::test]
8831    fn test_display_tracking(cx: &mut TestAppContext) {
8832        use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
8833
8834        let sixty_hertz = Duration::from_secs(1) / 60;
8835        let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
8836        let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
8837
8838        let display_events = Rc::new(RefCell::new(Vec::new()));
8839        let _display_subscription = cx.update({
8840            let display_events = display_events.clone();
8841            move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
8842        });
8843
8844        let window = cx.add_window(|window, cx| DisplayTracker {
8845            refresh_intervals: Vec::new(),
8846            _subscription: cx.observe_window_display(
8847                window,
8848                |tracker: &mut DisplayTracker, window, cx| {
8849                    tracker.refresh_intervals.push(window.refresh_interval(cx));
8850                },
8851            ),
8852        });
8853        let window_notifications = Rc::new(RefCell::new(Vec::new()));
8854        let _window_subscription = window
8855            .update(cx, {
8856                let window_notifications = window_notifications.clone();
8857                move |_, window, cx| {
8858                    assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
8859                    window.observe_window_display(move |window, cx| {
8860                        window_notifications
8861                            .borrow_mut()
8862                            .push((window.display_id, window.refresh_interval(cx)));
8863                    })
8864                }
8865            })
8866            .unwrap();
8867        let test_window = cx.test_window(window.into());
8868
8869        // The window may hear that it moved before App hears the display was
8870        // connected. App learns about the display before the window's
8871        // observers run, and the platform's later notification changes
8872        // nothing.
8873        cx.test_platform()
8874            .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
8875        test_window.simulate_move_to_display(DisplayId(2));
8876        assert_eq!(
8877            window_notifications.take(),
8878            [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
8879        );
8880        assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
8881        cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
8882        assert!(window_notifications.borrow().is_empty());
8883
8884        // Platforms may report a move that isn't one.
8885        test_window.simulate_move_to_display(DisplayId(2));
8886        assert!(window_notifications.borrow().is_empty());
8887
8888        cx.simulate_display_refresh_interval_change(
8889            DisplayId(2),
8890            Some(one_hundred_forty_four_hertz),
8891        );
8892        assert_eq!(
8893            window_notifications.take(),
8894            [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
8895        );
8896
8897        // Changes to a display the window isn't on don't notify it.
8898        cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
8899        cx.simulate_display_removed(DisplayId(1));
8900        assert!(window_notifications.borrow().is_empty());
8901
8902        assert_eq!(
8903            display_events.take(),
8904            [
8905                DisplayEvent::Changed {
8906                    id: DisplayId(2),
8907                    changes: DisplayChanges::REFRESH_INTERVAL,
8908                },
8909                DisplayEvent::Changed {
8910                    id: DisplayId(1),
8911                    changes: DisplayChanges::REFRESH_INTERVAL,
8912                },
8913                DisplayEvent::Removed(DisplayId(1)),
8914            ]
8915        );
8916        window
8917            .update(cx, |tracker, _, _| {
8918                assert_eq!(
8919                    tracker.refresh_intervals,
8920                    [
8921                        Some(one_hundred_twenty_hertz),
8922                        Some(one_hundred_forty_four_hertz)
8923                    ]
8924                );
8925            })
8926            .unwrap();
8927
8928        struct DisplayTracker {
8929            refresh_intervals: Vec<Option<Duration>>,
8930            _subscription: Subscription,
8931        }
8932
8933        impl Render for DisplayTracker {
8934            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8935                Empty
8936            }
8937        }
8938    }
8939
8940    #[gpui::test]
8941    fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
8942        use crate::Subscription;
8943
8944        struct BoundsObserver {
8945            _subscription: Subscription,
8946        }
8947
8948        impl Render for BoundsObserver {
8949            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8950                Empty
8951            }
8952        }
8953
8954        let opened_window = Rc::new(Cell::new(None));
8955        let window = cx.add_window({
8956            let opened_window = opened_window.clone();
8957            move |window, cx| BoundsObserver {
8958                _subscription: cx.observe_window_bounds(window, move |_, _, cx| {
8959                    let handle = cx
8960                        .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
8961                        .unwrap();
8962                    opened_window.set(Some(AnyWindowHandle::from(handle)));
8963                }),
8964            }
8965        });
8966        window
8967            .update(cx, |_, window, _| window.activate_window())
8968            .unwrap();
8969
8970        let new_size = size(px(400.), px(300.));
8971        cx.simulate_window_resize(window.into(), new_size);
8972
8973        let opened_window = opened_window
8974            .take()
8975            .expect("bounds observer should have opened a window");
8976        let opened_size = opened_window
8977            .update(cx, |_, window, _| window.bounds().size)
8978            .unwrap();
8979        assert_eq!(opened_size, new_size);
8980    }
8981
8982    #[gpui::test]
8983    fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
8984        let window = cx.add_window(|_, _| EmptyView);
8985        let mut platform_window = cx.test_window(window.into());
8986        platform_window.simulate_resize(size(px(400.), px(800.)));
8987        window
8988            .update(cx, |_, window, _| {
8989                assert_eq!(
8990                    window.visual_viewport_bounds(),
8991                    Bounds::new(Point::default(), size(px(400.), px(800.)))
8992                );
8993                assert_eq!(
8994                    window.fully_visible_bounds(),
8995                    window.visual_viewport_bounds()
8996                );
8997            })
8998            .unwrap();
8999
9000        platform_window.simulate_frame_request(RequestFrameOptions::default());
9001        let wakes = platform_window.frame_wake_count();
9002        let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
9003        platform_window.simulate_visual_viewport_change(visual_bounds);
9004        assert!(platform_window.frame_wake_count() > wakes);
9005        platform_window.simulate_frame_request(RequestFrameOptions::default());
9006        let wakes = platform_window.frame_wake_count();
9007        let insets = crate::WindowInsets {
9008            safe_area: crate::Edges {
9009                top: px(60.),
9010                right: px(20.),
9011                bottom: px(30.),
9012                left: px(-10.),
9013            },
9014            ime: crate::Edges {
9015                bottom: px(350.),
9016                ..Default::default()
9017            },
9018            ..Default::default()
9019        };
9020        platform_window.simulate_insets_change(insets.clone());
9021        assert!(platform_window.frame_wake_count() > wakes);
9022        window
9023            .update(cx, |_, window, cx| {
9024                let focus = cx.focus_handle();
9025                window.focus(&focus, cx);
9026                assert_eq!(window.insets(), insets);
9027                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
9028                assert_eq!(window.visual_viewport_bounds(), visual_bounds);
9029                assert_eq!(
9030                    window.fully_visible_bounds(),
9031                    Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
9032                );
9033                window.request_virtual_keyboard();
9034                window.dismiss_virtual_keyboard();
9035                assert!(focus.is_focused(window));
9036                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
9037            })
9038            .unwrap();
9039        assert_eq!(platform_window.virtual_keyboard_requests(), 1);
9040        assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
9041
9042        platform_window.simulate_insets_change(crate::WindowInsets {
9043            safe_area: crate::Edges {
9044                top: px(900.),
9045                left: px(500.),
9046                ..Default::default()
9047            },
9048            ..Default::default()
9049        });
9050        window
9051            .update(cx, |_, window, _| {
9052                assert_eq!(
9053                    window.fully_visible_bounds().size,
9054                    size(Pixels::ZERO, Pixels::ZERO)
9055                );
9056            })
9057            .unwrap();
9058
9059        // Some backends update geometry snapshots without delivering inset callbacks.
9060        use crate::PlatformWindow as _;
9061        platform_window.on_insets_changed(Box::new(|_| {}));
9062        platform_window.simulate_insets_change(crate::WindowInsets::default());
9063        window
9064            .update(cx, |_, window, _| {
9065                assert_eq!(window.insets(), crate::WindowInsets::default());
9066            })
9067            .unwrap();
9068    }
9069
9070    #[test]
9071    fn frame_throttle_tracks_display_refreshes() {
9072        let start = super::Instant::now();
9073        for (elapsed, interval) in [
9074            (Duration::from_micros(16_666), Duration::from_micros(16_667)),
9075            (Duration::from_micros(33_332), Duration::from_micros(33_333)),
9076        ] {
9077            let mut pacer = super::FramePacer::default();
9078            assert!(!pacer.should_defer(start, Some(interval)));
9079            assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
9080            assert!(!pacer.should_defer(start + elapsed, Some(interval)));
9081        }
9082    }
9083
9084    #[test]
9085    fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
9086        let start = super::Instant::now();
9087        let interval = Duration::from_micros(33_333);
9088        let mut pacer = super::FramePacer::default();
9089        assert!(!pacer.should_defer(start, Some(interval)));
9090        let delayed_frame = start + interval + Duration::from_millis(5);
9091        assert!(!pacer.should_defer(delayed_frame, Some(interval)));
9092        assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
9093        assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
9094
9095        // Even a stall just short of another full interval must not cause a burst.
9096        let after_stall = start + interval * 4 - Duration::from_millis(1);
9097        assert!(!pacer.should_defer(after_stall, Some(interval)));
9098        assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
9099        assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
9100        // Mandatory presentation bypasses the limit and establishes a fresh cadence.
9101        let mandatory_frame = after_stall + interval + Duration::from_millis(2);
9102        assert!(!pacer.should_defer(mandatory_frame, None));
9103        assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
9104    }
9105
9106    #[test]
9107    fn power_modes_preserve_frame_limits() {
9108        let options = WindowOptions::default();
9109        for (power_mode, active_interval, thermal_interval) in [
9110            (
9111                crate::PowerMode::LowPower,
9112                Some(Duration::from_micros(33_333)),
9113                Duration::from_micros(33_333),
9114            ),
9115            (
9116                crate::PowerMode::Unknown,
9117                None,
9118                Duration::from_micros(16_667),
9119            ),
9120            (
9121                crate::PowerMode::Balanced,
9122                None,
9123                Duration::from_micros(16_667),
9124            ),
9125            (
9126                crate::PowerMode::HighPower,
9127                None,
9128                Duration::from_micros(16_667),
9129            ),
9130        ] {
9131            assert_eq!(
9132                super::minimum_frame_interval(
9133                    true,
9134                    false,
9135                    options.inactive_frame_interval,
9136                    options.low_power_frame_interval,
9137                    options.thermal_frame_interval,
9138                    ThermalState::Nominal,
9139                    power_mode,
9140                ),
9141                active_interval,
9142            );
9143            assert_eq!(
9144                super::minimum_frame_interval(
9145                    true,
9146                    false,
9147                    options.inactive_frame_interval,
9148                    options.low_power_frame_interval,
9149                    options.thermal_frame_interval,
9150                    ThermalState::Serious,
9151                    power_mode,
9152                ),
9153                Some(thermal_interval),
9154            );
9155        }
9156    }
9157
9158    #[test]
9159    fn frame_limits_combine_enabled_intervals() {
9160        let short = Some(Duration::from_millis(10));
9161        let long = Some(Duration::from_millis(100));
9162        for (inactive, low_power, thermal, expected) in [
9163            (long, short, short, long),
9164            (short, long, short, long),
9165            (short, short, long, long),
9166            (long, None, None, long),
9167            (None, long, None, long),
9168            (None, None, long, long),
9169            (None, None, None, None),
9170        ] {
9171            assert_eq!(
9172                super::minimum_frame_interval(
9173                    true,
9174                    true,
9175                    inactive,
9176                    low_power,
9177                    thermal,
9178                    ThermalState::Critical,
9179                    crate::PowerMode::LowPower,
9180                ),
9181                expected,
9182            );
9183        }
9184        assert_eq!(
9185            super::minimum_frame_interval(
9186                false,
9187                true,
9188                long,
9189                long,
9190                long,
9191                ThermalState::Critical,
9192                crate::PowerMode::LowPower,
9193            ),
9194            None,
9195        );
9196    }
9197
9198    struct EmptyView;
9199
9200    impl Render for EmptyView {
9201        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9202            div()
9203        }
9204    }
9205
9206    struct OpensWindowOnPaint {
9207        opened: Rc<Cell<bool>>,
9208    }
9209
9210    impl Render for OpensWindowOnPaint {
9211        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9212            let opened = self.opened.clone();
9213            div()
9214                .size_full()
9215                .child(canvas(
9216                    |_, _, _| {},
9217                    move |_, _, _window, cx| {
9218                        if !opened.replace(true) {
9219                            cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
9220                                .unwrap();
9221                        }
9222                    },
9223                ))
9224                // Siblings painted after the canvas: their elements were
9225                // allocated in the arena before the nested draw, so they detect
9226                // a mid-draw arena clear when painted afterwards.
9227                .child(div().child("after"))
9228        }
9229    }
9230
9231    /// Opening a window synchronously draws it and requests an element arena
9232    /// clear. When that happens from within another window's draw (here: from
9233    /// an element's paint), the clear must be deferred until the outer draw
9234    /// finishes, or the outer draw's arena-allocated elements would be freed
9235    /// out from under it.
9236    #[test]
9237    fn test_window_opened_during_draw_defers_arena_clear() {
9238        let mut cx = TestAppContext::single();
9239
9240        let opened = Rc::new(Cell::new(false));
9241        // add_window draws once, which runs the nested open_window mid-draw.
9242        let window = cx.add_window({
9243            let opened = opened.clone();
9244            move |_, _| OpensWindowOnPaint { opened }
9245        });
9246
9247        assert!(opened.get());
9248        assert_eq!(cx.windows().len(), 2);
9249
9250        // The deferred clear must actually run once the outer draw unwinds:
9251        // subsequent draws of both windows work against a fresh arena.
9252        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9253            .unwrap();
9254    }
9255
9256    #[test]
9257    fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
9258        let mut cx = TestAppContext::single();
9259        let window = cx.add_window(|_, _| EmptyView);
9260        let handle: AnyWindowHandle = window.into();
9261        let window_state = |cx: &mut TestAppContext| {
9262            cx.update_window(handle, |_, window, _| {
9263                (
9264                    window.scale_factor(),
9265                    window.bounds(),
9266                    window.viewport_size(),
9267                )
9268            })
9269            .unwrap()
9270        };
9271
9272        let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
9273        assert_eq!(scale_factor, 2.0);
9274
9275        for (scale_factor, resized_size) in [
9276            (1.0, size(px(800.), px(600.))),
9277            (1.25, size(px(640.), px(480.))),
9278            (2.0, size(px(1024.), px(768.))),
9279        ] {
9280            cx.simulate_window_scale_factor_change(handle, scale_factor);
9281            assert_eq!(
9282                window_state(&mut cx),
9283                (scale_factor, expected_bounds, expected_bounds.size)
9284            );
9285
9286            cx.simulate_window_resize(handle, resized_size);
9287            expected_bounds.size = resized_size;
9288            assert_eq!(
9289                window_state(&mut cx),
9290                (scale_factor, expected_bounds, resized_size)
9291            );
9292        }
9293    }
9294
9295    #[gpui::test]
9296    fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
9297        let window = cx.add_window(|_, _| EmptyView);
9298        let handle = AnyWindowHandle::from(window);
9299        let notifications = Rc::new(Cell::new(0));
9300        window
9301            .update(cx, {
9302                let notifications = notifications.clone();
9303                |_, window, cx| {
9304                    cx.observe_window_bounds(window, move |_, _, _| {
9305                        notifications.set(notifications.get() + 1)
9306                    })
9307                    .detach();
9308                }
9309            })
9310            .unwrap();
9311        let window_state = |cx: &mut TestAppContext| {
9312            cx.update_window(handle, |_, window, _| {
9313                (
9314                    window.is_fullscreen(),
9315                    window.bounds().size,
9316                    window.viewport_size(),
9317                )
9318            })
9319            .unwrap()
9320        };
9321        let initial_size = window_state(cx).1;
9322
9323        window
9324            .update(cx, |_, window, _| window.toggle_fullscreen())
9325            .unwrap();
9326        cx.run_until_parked();
9327        assert_eq!(window_state(cx), (true, initial_size, initial_size));
9328        assert_eq!(notifications.get(), 1);
9329
9330        let resized_size = size(px(800.), px(600.));
9331        window
9332            .update(cx, |_, window, _| window.toggle_fullscreen())
9333            .unwrap();
9334        cx.simulate_window_resize(handle, resized_size);
9335        cx.run_until_parked();
9336        assert_eq!(window_state(cx), (false, resized_size, resized_size));
9337    }
9338
9339    /// Platforms that stop requesting frames for idle windows (currently web)
9340    /// rely on the frame waker firing whenever frame demand arises; a demand
9341    /// source that skips the waker shows up there as a window that silently
9342    /// stops repainting until unrelated activity wakes it.
9343    #[gpui::test]
9344    fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
9345        let window = cx.add_window(|_, _| EmptyView);
9346        let test_window = cx.test_window(window.into());
9347        // This test exercises idle wakeups, not the inactive-window frame limit.
9348        test_window.simulate_active_status_change(true);
9349
9350        // Windows start dirty, and that can predate waker installation;
9351        // installing the waker must deliver the pending wake or the first
9352        // frame would never be requested.
9353        assert!(
9354            test_window.frame_wake_count() >= 1,
9355            "opening a window must wake the frame source for the initial frame"
9356        );
9357
9358        // Serve outstanding demand (present the frame drawn by `add_window`).
9359        test_window.simulate_frame_request(RequestFrameOptions::default());
9360
9361        // An idle window must not wake on clean frames or plain updates, or
9362        // the frame source could never stop.
9363        let baseline = test_window.frame_wake_count();
9364        test_window.simulate_frame_request(RequestFrameOptions::default());
9365        window.update(cx, |_, _, _| {}).unwrap();
9366        assert_eq!(
9367            test_window.frame_wake_count(),
9368            baseline,
9369            "clean frames and non-notifying updates must not wake the frame source"
9370        );
9371
9372        // Notifying a view in an idle window is the core demand signal.
9373        window.update(cx, |_, _, cx| cx.notify()).unwrap();
9374        assert!(
9375            test_window.frame_wake_count() > baseline,
9376            "notifying a view in an idle window must wake the frame source"
9377        );
9378
9379        // Serving that demand returns to idle without further wakes.
9380        test_window.simulate_frame_request(RequestFrameOptions::default());
9381        let baseline = test_window.frame_wake_count();
9382        test_window.simulate_frame_request(RequestFrameOptions::default());
9383        assert_eq!(
9384            test_window.frame_wake_count(),
9385            baseline,
9386            "serving demand must return the window to idle"
9387        );
9388
9389        // Next-frame callbacks create demand without dirtying the window.
9390        window
9391            .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
9392            .unwrap();
9393        assert!(
9394            test_window.frame_wake_count() > baseline,
9395            "scheduling a next-frame callback in an idle window must wake the frame source"
9396        );
9397    }
9398
9399    /// A frame request that arrives while next-frame callbacks are pending
9400    /// must never strand them: either the frame runs them, or (when the
9401    /// inactive-window frame-rate throttle defers the frame) the waker fires
9402    /// so another request is delivered.
9403    #[gpui::test]
9404    fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
9405        let window = cx.add_window(|_, _| EmptyView);
9406        let test_window = cx.test_window(window.into());
9407        // Establish a recent last-frame time so the inactive-window throttle
9408        // can engage on the next request.
9409        test_window.simulate_frame_request(RequestFrameOptions::default());
9410
9411        let callback_ran = Rc::new(Cell::new(false));
9412        window
9413            .update(cx, {
9414                let callback_ran = callback_ran.clone();
9415                move |_, window, _| {
9416                    window.on_next_frame(move |_, _| callback_ran.set(true));
9417                }
9418            })
9419            .unwrap();
9420
9421        let baseline = test_window.frame_wake_count();
9422        test_window.simulate_frame_request(RequestFrameOptions::default());
9423        // The test window is inactive, so this request throttles to ~30fps
9424        // when it lands within the throttle interval of the previous frame
9425        // (the common case here, but timing-dependent): the callback is
9426        // deferred and the waker must re-arm the frame source. On a slow run
9427        // the request instead lands outside the interval and runs the
9428        // callback directly.
9429        assert!(
9430            test_window.frame_wake_count() > baseline || callback_ran.get(),
9431            "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
9432        );
9433    }
9434
9435    #[gpui::test]
9436    fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
9437        use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
9438
9439        let window = cx.add_window(|_, _| EmptyView);
9440        window
9441            .update(cx, |_, window, _| {
9442                assert!(matches!(
9443                    window.window_handle(),
9444                    Err(HandleError::NotSupported)
9445                ));
9446                assert!(matches!(
9447                    window.display_handle(),
9448                    Err(HandleError::NotSupported)
9449                ));
9450            })
9451            .unwrap();
9452    }
9453
9454    #[gpui::test]
9455    fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
9456        let window = cx.add_window(|_, _| EmptyView);
9457        let observed_appearance = Rc::new(Cell::new(None));
9458        let _subscription = window
9459            .update(cx, {
9460                let observed_appearance = observed_appearance.clone();
9461                move |_, window, _| {
9462                    window.observe_window_appearance(move |window, _| {
9463                        observed_appearance.set(Some(window.appearance()));
9464                    })
9465                }
9466            })
9467            .unwrap();
9468        let test_window = cx.test_window(window.into());
9469
9470        cx.update(|_| {
9471            test_window.simulate_appearance_change(WindowAppearance::Dark);
9472            assert_eq!(observed_appearance.get(), None);
9473        });
9474        cx.run_until_parked();
9475
9476        assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
9477    }
9478
9479    #[gpui::test]
9480    fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
9481        let window = cx.add_window(|_, _| Empty);
9482        let test_window = cx.test_window(window.into());
9483
9484        assert!(test_window.simulate_scheduled_frame());
9485        assert!(test_window.simulate_scheduled_frame());
9486        assert!(!test_window.frame_scheduled());
9487
9488        cx.update_window(window.into(), |_, window, _| {
9489            window.active.set(true);
9490            window.on_next_frame(|_, _| {});
9491        })
9492        .unwrap();
9493        assert!(
9494            test_window.frame_scheduled(),
9495            "queuing work on a parked window must wake the render loop"
9496        );
9497
9498        assert!(test_window.simulate_scheduled_frame());
9499        assert!(
9500            test_window.frame_scheduled(),
9501            "presenting the frame must await one compositor callback"
9502        );
9503        assert!(test_window.simulate_scheduled_frame());
9504        assert!(!test_window.frame_scheduled());
9505    }
9506
9507    #[gpui::test]
9508    fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
9509        let window = cx.add_window(|_, _| Empty);
9510        let test_window = cx.test_window(window.into());
9511
9512        assert!(test_window.simulate_scheduled_frame());
9513        assert!(test_window.simulate_scheduled_frame());
9514        assert!(!test_window.frame_scheduled());
9515
9516        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9517            .unwrap();
9518
9519        assert!(
9520            test_window.frame_scheduled(),
9521            "a rendered scene awaiting presentation must wake the render loop"
9522        );
9523    }
9524
9525    #[gpui::test]
9526    fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
9527        let window = cx.add_window(|_, _| Empty);
9528        let test_window = cx.test_window(window.into());
9529
9530        let callback_ran = Rc::new(Cell::new(false));
9531        cx.update_window(window.into(), |_, window, _| {
9532            // Inactive windows are frame-rate throttled, which would defer the
9533            // ticks this test drives manually.
9534            window.active.set(true);
9535            let callback_ran = callback_ran.clone();
9536            window.on_next_frame(move |window, _| {
9537                window.on_next_frame(move |_, _| callback_ran.set(true));
9538            });
9539        })
9540        .unwrap();
9541
9542        assert!(test_window.simulate_scheduled_frame());
9543        assert!(!callback_ran.get());
9544        assert!(
9545            test_window.frame_scheduled(),
9546            "a callback queued mid-frame must schedule a follow-up before the loop parks"
9547        );
9548
9549        assert!(test_window.simulate_scheduled_frame());
9550        assert!(callback_ran.get());
9551    }
9552
9553    struct RootView {
9554        explicit_size: bool,
9555        child_bounds: Rc<Cell<Bounds<Pixels>>>,
9556    }
9557
9558    impl Render for RootView {
9559        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9560            let child_bounds = self.child_bounds.clone();
9561            let root = div().flex().flex_col().child(
9562                canvas(
9563                    move |bounds, _, _| child_bounds.set(bounds),
9564                    |_, _, _, _| {},
9565                )
9566                .size_full(),
9567            );
9568            if self.explicit_size {
9569                root.w(px(300.)).h(px(200.))
9570            } else {
9571                root
9572            }
9573        }
9574    }
9575
9576    #[test]
9577    fn auto_sized_window_root_fills_the_window() {
9578        let mut cx = TestAppContext::single();
9579        let child_bounds = Rc::new(Cell::new(Bounds::default()));
9580        let window = cx.add_window({
9581            let child_bounds = child_bounds.clone();
9582            move |_, _| RootView {
9583                explicit_size: false,
9584                child_bounds,
9585            }
9586        });
9587
9588        let viewport_size = cx
9589            .update_window(window.into(), |_, window, cx| {
9590                window.draw(cx).clear(cx);
9591                window.viewport_size()
9592            })
9593            .unwrap();
9594
9595        assert_eq!(child_bounds.get().size, viewport_size);
9596    }
9597
9598    #[test]
9599    fn explicitly_sized_window_root_keeps_its_size() {
9600        let mut cx = TestAppContext::single();
9601        let child_bounds = Rc::new(Cell::new(Bounds::default()));
9602        let window = cx.add_window({
9603            let child_bounds = child_bounds.clone();
9604            move |_, _| RootView {
9605                explicit_size: true,
9606                child_bounds,
9607            }
9608        });
9609
9610        cx.update_window(window.into(), |_, window, cx| {
9611            window.draw(cx).clear(cx);
9612        })
9613        .unwrap();
9614
9615        assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
9616    }
9617
9618    struct FileDragView {
9619        path: PathBuf,
9620        observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
9621        observed_drops: Rc<RefCell<Vec<PathBuf>>>,
9622    }
9623
9624    struct FileDropExitView(Rc<Cell<usize>>);
9625
9626    impl Render for FileDropExitView {
9627        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9628            div().size_full().on_file_drop_exit({
9629                let observed_file_drop_exit = self.0.clone();
9630                move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
9631            })
9632        }
9633    }
9634
9635    impl Render for FileDragView {
9636        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9637            div()
9638                .id("file-drag")
9639                .size_full()
9640                .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
9641                .external_drag_payload(|path: &PathBuf, _, _| {
9642                    Some(ExternalDragPayload::Files(FileDragPaths::new([(
9643                        path.clone(),
9644                        true,
9645                    )])))
9646                })
9647                .on_drag_move({
9648                    let observed_drag_moves = self.observed_drag_moves.clone();
9649                    move |event: &DragMoveEvent<PathBuf>, _, _| {
9650                        observed_drag_moves.borrow_mut().push(event.event.position);
9651                    }
9652                })
9653                .on_drop({
9654                    let observed_drops = self.observed_drops.clone();
9655                    move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
9656                })
9657        }
9658    }
9659
9660    #[gpui::test]
9661    fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
9662        struct Drag {
9663            window: AnyWindowHandle,
9664            observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
9665            observed_drops: Rc<RefCell<Vec<PathBuf>>>,
9666        }
9667
9668        fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
9669            let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
9670            let observed_drops = Rc::new(RefCell::new(Vec::new()));
9671            let window: AnyWindowHandle = cx
9672                .add_window({
9673                    let observed_drag_moves = observed_drag_moves.clone();
9674                    let observed_drops = observed_drops.clone();
9675                    move |_, _| FileDragView {
9676                        path,
9677                        observed_drag_moves,
9678                        observed_drops,
9679                    }
9680                })
9681                .into();
9682            cx.test_window(window)
9683                .set_start_external_drag_result(platform_result);
9684
9685            let update_result = cx.update_window(window, |_, window, cx| {
9686                window.draw(cx).clear(cx);
9687                window.dispatch_event(
9688                    MouseDownEvent {
9689                        position: point(px(10.), px(10.)),
9690                        button: MouseButton::Left,
9691                        modifiers: Default::default(),
9692                        click_count: 1,
9693                        first_mouse: false,
9694                    }
9695                    .to_platform_input(),
9696                    cx,
9697                );
9698                window.dispatch_event(
9699                    MouseMoveEvent {
9700                        position: point(px(20.), px(20.)),
9701                        pressed_button: Some(MouseButton::Left),
9702                        modifiers: Default::default(),
9703                    }
9704                    .to_platform_input(),
9705                    cx,
9706                );
9707                assert!(cx.active_drag.is_some());
9708            });
9709            assert!(
9710                update_result.is_ok(),
9711                "failed to start drag: {update_result:?}"
9712            );
9713
9714            assert!(cx.test_window(window).external_drag_files().is_empty());
9715            Drag {
9716                window,
9717                observed_drag_moves,
9718                observed_drops,
9719            }
9720        }
9721
9722        let successful_path = PathBuf::from("/tmp/successful-drag");
9723        let successful = start_drag(cx, successful_path.clone(), true);
9724        let outside_position = point(px(-1.), px(20.));
9725        let update_result = cx.update_window(successful.window, |_, window, cx| {
9726            window.dispatch_event(
9727                MouseMoveEvent {
9728                    position: outside_position,
9729                    pressed_button: Some(MouseButton::Left),
9730                    modifiers: Default::default(),
9731                }
9732                .to_platform_input(),
9733                cx,
9734            );
9735            assert!(cx.active_drag.is_none());
9736        });
9737        assert!(
9738            update_result.is_ok(),
9739            "failed to promote drag: {update_result:?}"
9740        );
9741        assert_eq!(
9742            cx.test_window(successful.window).external_drag_files(),
9743            [(successful_path.clone(), true)]
9744        );
9745        // Views must still see the move that leaves the window, otherwise they never learn to tear
9746        // down the drag state they built up while the pointer was inside.
9747        assert_eq!(
9748            successful.observed_drag_moves.borrow().last(),
9749            Some(&outside_position)
9750        );
9751
9752        let first_destination_exit_count = Rc::new(Cell::new(0));
9753        let first_destination: AnyWindowHandle = cx
9754            .add_window({
9755                let first_destination_exit_count = first_destination_exit_count.clone();
9756                move |_, _| FileDropExitView(first_destination_exit_count)
9757            })
9758            .into();
9759        let second_destination_exit_count = Rc::new(Cell::new(0));
9760        let second_destination: AnyWindowHandle = cx
9761            .add_window({
9762                let second_destination_exit_count = second_destination_exit_count.clone();
9763                move |_, _| FileDropExitView(second_destination_exit_count)
9764            })
9765            .into();
9766        let reentry_position = point(px(30.), px(30.));
9767        let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
9768        let update_result = cx.update_window(first_destination, |_, window, cx| {
9769            window.draw(cx).clear(cx);
9770            window.dispatch_event(
9771                FileDropEvent::Entered {
9772                    position: reentry_position,
9773                    paths: external_paths(),
9774                }
9775                .to_platform_input(),
9776                cx,
9777            );
9778            assert!(
9779                cx.active_drag
9780                    .as_ref()
9781                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9782            );
9783            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9784            assert!(cx.active_drag.is_none());
9785            assert_eq!(first_destination_exit_count.get(), 1);
9786            assert_eq!(second_destination_exit_count.get(), 0);
9787        });
9788        assert!(
9789            update_result.is_ok(),
9790            "failed to handle drag in first destination window: {update_result:?}"
9791        );
9792
9793        let update_result = cx.update_window(second_destination, |_, window, cx| {
9794            window.draw(cx).clear(cx);
9795            window.dispatch_event(
9796                PlatformInput::KeyDown(KeyDownEvent {
9797                    keystroke: Keystroke::parse("down").expect("valid keystroke"),
9798                    is_held: false,
9799                    prefer_character_input: false,
9800                }),
9801                cx,
9802            );
9803            window.dispatch_event(
9804                FileDropEvent::Entered {
9805                    position: reentry_position,
9806                    paths: external_paths(),
9807                }
9808                .to_platform_input(),
9809                cx,
9810            );
9811            assert!(
9812                cx.active_drag
9813                    .as_ref()
9814                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9815            );
9816            assert_eq!(first_destination_exit_count.get(), 1);
9817            assert_eq!(second_destination_exit_count.get(), 0);
9818
9819            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9820            assert!(cx.active_drag.is_none());
9821            assert_eq!(first_destination_exit_count.get(), 1);
9822            assert_eq!(second_destination_exit_count.get(), 1);
9823        });
9824        assert!(
9825            update_result.is_ok(),
9826            "failed to handle drag in second destination window: {update_result:?}"
9827        );
9828
9829        let update_result = cx.update_window(successful.window, |_, window, cx| {
9830            window.dispatch_event(
9831                FileDropEvent::Entered {
9832                    position: reentry_position,
9833                    paths: external_paths(),
9834                }
9835                .to_platform_input(),
9836                cx,
9837            );
9838            assert!(
9839                cx.active_drag
9840                    .as_ref()
9841                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9842            );
9843            assert_eq!(
9844                successful.observed_drag_moves.borrow().last(),
9845                Some(&reentry_position)
9846            );
9847
9848            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9849            assert!(cx.active_drag.is_none());
9850
9851            window.dispatch_event(
9852                FileDropEvent::Entered {
9853                    position: reentry_position,
9854                    paths: external_paths(),
9855                }
9856                .to_platform_input(),
9857                cx,
9858            );
9859            assert!(
9860                cx.active_drag
9861                    .as_ref()
9862                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9863            );
9864
9865            window.dispatch_event(
9866                FileDropEvent::Submit {
9867                    position: reentry_position,
9868                }
9869                .to_platform_input(),
9870                cx,
9871            );
9872            assert_eq!(
9873                successful.observed_drops.borrow().as_slice(),
9874                std::slice::from_ref(&successful_path)
9875            );
9876            assert!(cx.active_drag.is_none());
9877
9878            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9879            assert!(cx.active_drag.is_none());
9880            window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
9881            assert!(cx.active_drag.is_none());
9882
9883            window.dispatch_event(
9884                FileDropEvent::Entered {
9885                    position: reentry_position,
9886                    paths: external_paths(),
9887                }
9888                .to_platform_input(),
9889                cx,
9890            );
9891            assert!(
9892                cx.active_drag
9893                    .as_ref()
9894                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9895            );
9896            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9897        });
9898        assert!(
9899            update_result.is_ok(),
9900            "failed to restore drag in source window: {update_result:?}"
9901        );
9902
9903        let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
9904        let cancelled = start_drag(cx, cancelled_path.clone(), true);
9905        let update_result = cx.update_window(cancelled.window, |_, window, cx| {
9906            window.dispatch_event(
9907                MouseMoveEvent {
9908                    position: outside_position,
9909                    pressed_button: Some(MouseButton::Left),
9910                    modifiers: Default::default(),
9911                }
9912                .to_platform_input(),
9913                cx,
9914            );
9915            assert!(cx.active_drag.is_none());
9916
9917            window.dispatch_event(
9918                FileDropEvent::Entered {
9919                    position: reentry_position,
9920                    paths: ExternalPaths([cancelled_path].into_iter().collect()),
9921                }
9922                .to_platform_input(),
9923                cx,
9924            );
9925            assert!(
9926                cx.active_drag
9927                    .as_ref()
9928                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9929            );
9930            assert!(cx.stop_active_drag(window));
9931            assert!(cx.active_drag.is_none());
9932        });
9933        assert!(
9934            update_result.is_ok(),
9935            "failed to cancel restored drag: {update_result:?}"
9936        );
9937        assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
9938
9939        let removed_path = PathBuf::from("/tmp/removed-window-drag");
9940        let removed = start_drag(cx, removed_path, true);
9941        let removed_window_id = removed.window.window_id();
9942        let update_result = cx.update_window(removed.window, |_, window, cx| {
9943            window.dispatch_event(
9944                MouseMoveEvent {
9945                    position: outside_position,
9946                    pressed_button: Some(MouseButton::Left),
9947                    modifiers: Default::default(),
9948                }
9949                .to_platform_input(),
9950                cx,
9951            );
9952            assert!(cx.active_drag.is_none());
9953            window.remove_window();
9954        });
9955        assert!(
9956            update_result.is_ok(),
9957            "failed to remove drag source window: {update_result:?}"
9958        );
9959        assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
9960
9961        let failed_path = PathBuf::from("/tmp/failed-drag");
9962        let failed = start_drag(cx, failed_path.clone(), false);
9963        let update_result = cx.update_window(failed.window, |_, window, cx| {
9964            for x_position in [-1., -2.] {
9965                window.dispatch_event(
9966                    MouseMoveEvent {
9967                        position: point(px(x_position), px(20.)),
9968                        pressed_button: Some(MouseButton::Left),
9969                        modifiers: Default::default(),
9970                    }
9971                    .to_platform_input(),
9972                    cx,
9973                );
9974            }
9975            assert!(cx.active_drag.is_some());
9976        });
9977        assert!(
9978            update_result.is_ok(),
9979            "failed to retain drag after platform failure: {update_result:?}"
9980        );
9981        assert_eq!(
9982            cx.test_window(failed.window).external_drag_files(),
9983            [(failed_path, true)]
9984        );
9985    }
9986
9987    struct FocusForwarder {
9988        a: FocusHandle,
9989        b: FocusHandle,
9990    }
9991
9992    impl Render for FocusForwarder {
9993        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9994            div()
9995                .size_full()
9996                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
9997                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
9998        }
9999    }
10000
10001    /// When a focus listener moves focus again (e.g. a dock forwarding focus to its
10002    /// active panel), the resulting focus events must be dispatched without waiting
10003    /// for an unrelated redraw of the window.
10004    #[gpui::test]
10005    fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
10006        let b_focus_count = Rc::new(Cell::new(0));
10007        let window = cx.add_window({
10008            let b_focus_count = b_focus_count.clone();
10009            move |window, cx| {
10010                let a = cx.focus_handle();
10011                let b = cx.focus_handle();
10012                cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
10013                    let b = this.b.clone();
10014                    window.focus(&b, cx);
10015                })
10016                .detach();
10017                cx.on_focus(&b, window, move |_, _, _| {
10018                    b_focus_count.set(b_focus_count.get() + 1);
10019                })
10020                .detach();
10021                FocusForwarder { a, b }
10022            }
10023        });
10024
10025        window
10026            .update(cx, |_, window, _| window.activate_window())
10027            .unwrap();
10028        cx.executor().run_until_parked();
10029
10030        window
10031            .update(cx, |this, window, cx| {
10032                let a = this.a.clone();
10033                window.focus(&a, cx);
10034            })
10035            .unwrap();
10036        cx.executor().run_until_parked();
10037
10038        window
10039            .update(cx, |this, window, _| {
10040                assert!(this.b.is_focused(window));
10041            })
10042            .unwrap();
10043        assert_eq!(b_focus_count.get(), 1);
10044    }
10045
10046    #[gpui::test]
10047    fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
10048        let events = Rc::new(RefCell::new(Vec::new()));
10049        let window = cx.add_window({
10050            let events = events.clone();
10051            move |_, _| TouchDragListener { events }
10052        });
10053        let touch = TouchId(1);
10054
10055        dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
10056        dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
10057        dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
10058
10059        assert_eq!(
10060            events.borrow().as_slice(),
10061            [
10062                (TouchPhase::Started, px(10.)),
10063                (TouchPhase::Moved, px(30.)),
10064                (TouchPhase::Ended, px(40.)),
10065            ]
10066        );
10067    }
10068
10069    #[gpui::test]
10070    fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
10071        let claims = Rc::new(RefCell::new(Vec::new()));
10072        let window = cx.add_window({
10073            let claims = claims.clone();
10074            move |_, _| BackListeners { claims }
10075        });
10076        let dispatch_back = |cx: &mut TestAppContext, x: f32| {
10077            window
10078                .update(cx, |_, window, cx| {
10079                    window
10080                        .dispatch_event(
10081                            BackGestureEvent {
10082                                phase: BackGesturePhase::Started,
10083                                start_position: point(px(x), px(10.)),
10084                                progress: 0.,
10085                            }
10086                            .to_platform_input(),
10087                            cx,
10088                        )
10089                        .default_prevented
10090                })
10091                .unwrap()
10092        };
10093        assert!(dispatch_back(cx, 10.));
10094        assert!(dispatch_back(cx, 80.));
10095        assert!(!dispatch_back(cx, 150.));
10096        assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
10097    }
10098
10099    struct BackListeners {
10100        claims: Rc<RefCell<Vec<&'static str>>>,
10101    }
10102
10103    impl Render for BackListeners {
10104        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
10105            let claim = |name: &'static str| {
10106                let claims = self.claims.clone();
10107                move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
10108                    claims.borrow_mut().push(name)
10109                }
10110            };
10111            div().size_full().child(
10112                div()
10113                    .w(px(100.))
10114                    .h_full()
10115                    .on_back_gesture(claim("outer"))
10116                    .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
10117            )
10118        }
10119    }
10120
10121    struct TouchDragListener {
10122        events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
10123    }
10124
10125    impl Render for TouchDragListener {
10126        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
10127            let events = self.events.clone();
10128            canvas(
10129                |_, _, _| {},
10130                move |_, _, window, _| {
10131                    window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
10132                        if phase != DispatchPhase::Bubble {
10133                            return;
10134                        }
10135                        events.borrow_mut().push((event.phase, event.position.x));
10136                        if event.phase == TouchPhase::Started {
10137                            window.prevent_default();
10138                        }
10139                    });
10140                },
10141            )
10142        }
10143    }
10144
10145    #[gpui::test]
10146    fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
10147        for response in [
10148            LongPressResponse::PreventDefault,
10149            LongPressResponse::StopPropagation,
10150            LongPressResponse::None,
10151        ] {
10152            let phases = Rc::new(RefCell::new(Vec::new()));
10153            let window = cx.add_window({
10154                let phases = phases.clone();
10155                move |_, _| LongPressListener { phases, response }
10156            });
10157            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
10158            cx.executor().advance_clock(Duration::from_millis(501));
10159            cx.executor().run_until_parked();
10160            window
10161                .update(cx, |_, window, _| {
10162                    assert_eq!(
10163                        window.long_press_capture.is_some(),
10164                        response == LongPressResponse::PreventDefault
10165                    );
10166                })
10167                .unwrap();
10168            dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
10169            dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
10170            window
10171                .update(cx, |_, window, _| {
10172                    assert!(window.long_press_capture.is_none());
10173                })
10174                .unwrap();
10175
10176            let phases = phases.borrow();
10177            if response == LongPressResponse::PreventDefault {
10178                assert_eq!(
10179                    phases.as_slice(),
10180                    [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
10181                );
10182            } else {
10183                assert_eq!(phases.as_slice(), [TouchPhase::Started]);
10184            }
10185        }
10186    }
10187
10188    #[gpui::test]
10189    fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
10190        let phases = Rc::new(RefCell::new(Vec::new()));
10191        let window = cx.add_window({
10192            let phases = phases.clone();
10193            move |_, _| LongPressListener {
10194                phases,
10195                response: LongPressResponse::None,
10196            }
10197        });
10198        window
10199            .update(cx, |_, window, _| {
10200                window.prevent_default();
10201            })
10202            .unwrap();
10203
10204        dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
10205        cx.executor().advance_clock(Duration::from_millis(501));
10206        cx.executor().run_until_parked();
10207        dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
10208
10209        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
10210    }
10211
10212    #[gpui::test]
10213    fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
10214        for (phase, position) in [
10215            (TouchPhase::Ended, 0.),
10216            (TouchPhase::Cancelled, 0.),
10217            (TouchPhase::Moved, 20.),
10218        ] {
10219            let phases = Rc::new(RefCell::new(Vec::new()));
10220            let window = cx.add_window({
10221                let phases = phases.clone();
10222                move |_, _| LongPressListener {
10223                    phases,
10224                    response: LongPressResponse::PreventDefault,
10225                }
10226            });
10227            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
10228            dispatch_touch(window, cx, TouchId(1), phase, position);
10229            cx.executor().advance_clock(Duration::from_millis(501));
10230            cx.executor().run_until_parked();
10231
10232            assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
10233        }
10234    }
10235
10236    #[gpui::test]
10237    fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
10238        let phases = Rc::new(RefCell::new(Vec::new()));
10239        let window = cx.add_window({
10240            let phases = phases.clone();
10241            move |_, _| LongPressListener {
10242                phases,
10243                response: LongPressResponse::PreventDefault,
10244            }
10245        });
10246        let first_touch = TouchId(1);
10247        dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
10248        cx.executor().advance_clock(Duration::from_millis(250));
10249        dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
10250        dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
10251
10252        cx.executor().advance_clock(Duration::from_millis(251));
10253        cx.executor().run_until_parked();
10254        assert!(phases.borrow().is_empty());
10255
10256        cx.executor().advance_clock(Duration::from_millis(250));
10257        cx.executor().run_until_parked();
10258        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
10259    }
10260
10261    #[gpui::test]
10262    fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
10263        test_paint_at_scales(cx, |window| {
10264            let (numerator, denominator) = match window.scale_factor() {
10265                1.0 => (1, 1),
10266                1.25 => (5, 4),
10267                1.5 => (3, 2),
10268                2.0 => (2, 1),
10269                3.0 => (3, 1),
10270                scale => panic!("unexpected scale {scale}"),
10271            };
10272            let snap = |quarters: i32| {
10273                let scaled = quarters * numerator;
10274                let divisor = 4 * denominator;
10275                let rounded =
10276                    scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
10277                ScaledPixels((scaled.signum() * rounded) as f32)
10278            };
10279            let stroke = |quarters| {
10280                if quarters == 0 {
10281                    ScaledPixels(0.)
10282                } else {
10283                    snap(quarters).max(ScaledPixels(1.))
10284                }
10285            };
10286
10287            for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
10288                for width in [0, 1, 3, 84] {
10289                    for thickness in [0, 1, 4, 7] {
10290                        for wavy in [false, true] {
10291                            let style = UnderlineStyle {
10292                                thickness: px(thickness as f32 / 4.),
10293                                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
10294                                wavy,
10295                            };
10296                            let bounds = Bounds::new(
10297                                point(snap(origin), snap(-origin)),
10298                                size(
10299                                    stroke(width),
10300                                    stroke(thickness) * if wavy { 3. } else { 1. },
10301                                ),
10302                            );
10303                            let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
10304                            let width = px(width as f32 / 4.);
10305                            assert_eq!(window.underline_bounds(origin, width, &style), bounds);
10306                            let original = paint_test_underlines(window, |window| {
10307                                window.paint_underline(origin, width, &style);
10308                            })
10309                            .to_vec();
10310                            assert_eq!(original.len(), usize::from(!bounds.is_empty()));
10311                            if let Some(underline) = original.first() {
10312                                assert_eq!(underline.bounds, bounds);
10313                                assert_eq!(underline.thickness, stroke(thickness));
10314                                assert_eq!(underline.wavy, wavy.into());
10315                                assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
10316                            }
10317
10318                            let underlines = paint_test_underlines(window, |window| {
10319                                window.paint_underline_with_exclusions(origin, width, &style, &[]);
10320                            });
10321                            assert_eq!(underlines.len(), original.len());
10322                            for (actual, original) in underlines.iter().zip(&original) {
10323                                assert_same_underline_geometry(actual, original);
10324                                assert_eq!(actual.content_mask, original.content_mask);
10325                            }
10326
10327                            let left = bounds.left().0 as i32;
10328                            let right = bounds.right().0 as i32;
10329                            let exclusions = [
10330                                (15, 25),
10331                                (3, 7),
10332                                (5, 10),
10333                                (10, 12),
10334                                (0, 0),
10335                                (4, 2),
10336                                (-50, -1),
10337                                (70, 100),
10338                            ]
10339                            .map(|(start, end)| {
10340                                ScaledPixels((left + start) as f32)
10341                                    ..ScaledPixels((left + end) as f32)
10342                            });
10343                            let underlines = paint_test_underlines(window, |window| {
10344                                window.paint_underline_with_exclusions(
10345                                    origin,
10346                                    width,
10347                                    &style,
10348                                    &exclusions,
10349                                );
10350                            });
10351                            let expected = (left..right)
10352                                .filter(|column| {
10353                                    !bounds.is_empty()
10354                                        && !exclusions.iter().any(|span| {
10355                                            span.contains(&ScaledPixels(*column as f32))
10356                                        })
10357                                })
10358                                .collect::<Vec<_>>();
10359                            assert_eq!(underline_device_columns(underlines), expected);
10360                            for underline in underlines {
10361                                assert_same_underline_geometry(underline, &original[0]);
10362                            }
10363                        }
10364                    }
10365                }
10366            }
10367        });
10368    }
10369
10370    #[gpui::test]
10371    fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
10372        test_paint_at_scales(cx, |window| {
10373            if window.scale_factor() != 2.0 {
10374                return;
10375            }
10376            let style = UnderlineStyle {
10377                thickness: px(1.),
10378                color: None,
10379                wavy: true,
10380            };
10381            let origin = point(px(2.888_183_8), px(15.357_917));
10382            let width = px(23.848_145) - origin.x;
10383            let original = paint_test_underlines(window, |window| {
10384                window.paint_underline(origin, width, &style);
10385            })[0];
10386            assert_eq!(original.bounds.left(), ScaledPixels(6.));
10387            assert_eq!(original.bounds.right(), ScaledPixels(48.));
10388            let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
10389            assert_eq!(point_bounds.left(), ScaledPixels(6.));
10390            assert_eq!(point_bounds.right(), ScaledPixels(28.));
10391
10392            let underlines = paint_test_underlines(window, |window| {
10393                window.paint_underline_with_exclusions(
10394                    origin,
10395                    width,
10396                    &style,
10397                    &[point_bounds.left()..point_bounds.right()],
10398                );
10399            });
10400            assert_eq!(underlines.len(), 1);
10401            assert_same_underline_geometry(&underlines[0], &original);
10402            assert_eq!(
10403                underline_device_columns(underlines),
10404                (28..48).collect::<Vec<_>>()
10405            );
10406        });
10407    }
10408
10409    #[gpui::test]
10410    fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
10411        test_paint_at_scales(cx, |window| {
10412            let scale = window.scale_factor();
10413            let original_mask = window.content_mask();
10414            let original_opacity = window.element_opacity();
10415            let mask = ContentMask {
10416                bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
10417            };
10418            let style = UnderlineStyle {
10419                thickness: px(2.),
10420                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
10421                wavy: true,
10422            };
10423            let origin = point(px(-1.25), px(9.25));
10424            let width = px(24.);
10425            window.with_content_mask(Some(mask), |window| {
10426                window.with_element_opacity(Some(0.5), |window| {
10427                    window.with_element_opacity(Some(0.5), |window| {
10428                        let original = paint_test_underlines(window, |window| {
10429                            window.paint_underline(origin, width, &style);
10430                        })[0];
10431                        assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
10432                        let underlines = paint_test_underlines(window, |window| {
10433                            window.paint_underline_with_exclusions(
10434                                origin,
10435                                width,
10436                                &style,
10437                                &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
10438                            );
10439                        });
10440                        assert_eq!(underlines.len(), 2);
10441                        let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
10442                            |(left, right)| {
10443                                Bounds::from_corners(
10444                                    point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
10445                                    point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
10446                                )
10447                            },
10448                        );
10449                        assert_eq!(
10450                            underlines
10451                                .iter()
10452                                .map(|underline| underline.content_mask.bounds)
10453                                .collect::<Vec<_>>(),
10454                            expected
10455                        );
10456                        for underline in underlines {
10457                            assert_same_underline_geometry(underline, &original);
10458                        }
10459                    });
10460                });
10461            });
10462            assert_eq!(window.content_mask(), original_mask);
10463            assert_eq!(window.element_opacity(), original_opacity);
10464        });
10465    }
10466
10467    #[gpui::test]
10468    fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
10469        test_paint_at_scales(cx, |window| {
10470            let style = UnderlineStyle {
10471                thickness: px(1.),
10472                color: None,
10473                wavy: true,
10474            };
10475            let origin = point(px(-4.), px(-1.));
10476            let width = px(8.);
10477            let left = (-4. * window.scale_factor()) as i32;
10478            let right = (4. * window.scale_factor()) as i32;
10479            let endpoints = [-16, -8, -1, 0, 1, 8, 16];
10480            for first_start in endpoints {
10481                for first_end in endpoints {
10482                    for second_start in endpoints {
10483                        for second_end in endpoints {
10484                            let exclusions = [first_start..first_end, second_start..second_end];
10485                            let expected = (left..right)
10486                                .filter(|column| {
10487                                    !exclusions.iter().any(|span| span.contains(column))
10488                                })
10489                                .collect::<Vec<_>>();
10490                            let exclusions = exclusions.map(|span| {
10491                                ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
10492                            });
10493                            let underlines = paint_test_underlines(window, |window| {
10494                                window.paint_underline_with_exclusions(
10495                                    origin,
10496                                    width,
10497                                    &style,
10498                                    &exclusions,
10499                                );
10500                            });
10501                            assert_eq!(
10502                                underline_device_columns(underlines),
10503                                expected,
10504                                "{exclusions:?}"
10505                            );
10506                        }
10507                    }
10508                }
10509            }
10510        });
10511    }
10512
10513    #[gpui::test]
10514    fn test_empty_content_masks_remain_empty_when_snapped(cx: &mut TestAppContext) {
10515        test_paint_at_scales(cx, |window| {
10516            let viewport = ContentMask {
10517                bounds: Bounds::from_corners(point(px(20.), px(20.)), point(px(100.), px(100.))),
10518            };
10519            for fraction in [0., 0.25, 0.5, 0.75] {
10520                for bounds in [
10521                    Bounds::new(point(px(30.), px(120. + fraction)), size(px(40.), px(20.))),
10522                    Bounds::new(point(px(120. + fraction), px(30.)), size(px(20.), px(40.))),
10523                    Bounds::new(
10524                        point(px(120. + fraction), px(120. + fraction)),
10525                        size(px(20.), px(20.)),
10526                    ),
10527                    Bounds::new(
10528                        point(px(30. + fraction), px(40. + fraction)),
10529                        size(px(0.), px(20.)),
10530                    ),
10531                    Bounds::new(
10532                        point(px(30. + fraction), px(40. + fraction)),
10533                        size(px(20.), px(0.)),
10534                    ),
10535                ] {
10536                    window.with_content_mask(Some(viewport), |window| {
10537                        window.with_content_mask(Some(ContentMask { bounds }), |window| {
10538                            assert!(window.content_mask().bounds.is_empty());
10539                            assert!(
10540                                window.snapped_content_mask().bounds.is_empty(),
10541                                "scale={}, bounds={bounds:?}",
10542                                window.scale_factor(),
10543                            );
10544                            let count = window.next_frame.scene.len();
10545                            window.paint_quad(crate::fill(bounds, crate::red()));
10546                            window.paint_quad(crate::outline(
10547                                bounds,
10548                                crate::red(),
10549                                Default::default(),
10550                            ));
10551                            assert_eq!(window.next_frame.scene.len(), count);
10552                        });
10553                    });
10554                }
10555            }
10556        });
10557    }
10558
10559    #[gpui::test]
10560    fn test_nonempty_content_masks_keep_covering_fractional_edges(cx: &mut TestAppContext) {
10561        test_paint_at_scales(cx, |window| {
10562            let bounds = Bounds::new(point(px(30.25), px(40.25)), size(px(0.125), px(0.125)));
10563            window.with_content_mask(Some(ContentMask { bounds }), |window| {
10564                let snapped = window.snapped_content_mask().bounds;
10565                let scale = window.scale_factor();
10566                assert_eq!(snapped, window.cover_bounds(bounds));
10567                assert!(!snapped.is_empty());
10568                assert_eq!(snapped.left().0, (30.25 * scale).floor());
10569                assert_eq!(snapped.top().0, (40.25 * scale).floor());
10570                assert_eq!(snapped.right().0, (30.375 * scale).ceil());
10571                assert_eq!(snapped.bottom().0, (40.375 * scale).ceil());
10572            });
10573        });
10574    }
10575
10576    #[gpui::test]
10577    fn test_empty_shadow_bounds_are_not_painted(cx: &mut TestAppContext) {
10578        test_paint_at_scales(cx, |window| {
10579            let shadow = crate::BoxShadow::new(px(0.25), px(0.5), crate::red()).blur_radius(px(4.));
10580            for origin in [point(px(30.25), px(40.25)), point(px(-30.25), px(-40.25))] {
10581                for size in [
10582                    size(px(20.), px(0.)),
10583                    size(px(0.), px(20.)),
10584                    size(px(0.), px(0.)),
10585                ] {
10586                    let bounds = Bounds::new(origin, size);
10587                    let count = window.next_frame.scene.len();
10588                    window.paint_drop_shadows(
10589                        bounds,
10590                        Default::default(),
10591                        std::slice::from_ref(&shadow),
10592                    );
10593                    assert_eq!(
10594                        window.next_frame.scene.len(),
10595                        count,
10596                        "scale={}, bounds={bounds:?}",
10597                        window.scale_factor()
10598                    );
10599                    assert!(window.cover_bounds(bounds).is_empty());
10600                }
10601            }
10602            let bounds = Bounds::new(point(px(30.25), px(40.25)), size(px(20.), px(20.)));
10603            let collapsed_shadow = shadow.clone().spread_radius(px(-10.));
10604            let shape_bounds =
10605                (bounds + collapsed_shadow.offset).dilate(collapsed_shadow.spread_radius);
10606            let count = window.next_frame.scene.len();
10607            window.paint_drop_shadows(bounds, Default::default(), &[collapsed_shadow]);
10608            assert_eq!(window.next_frame.scene.len(), count);
10609            assert!(window.cover_bounds(shape_bounds).is_empty());
10610
10611            window.paint_drop_shadows(bounds, Default::default(), &[shadow]);
10612            assert_eq!(window.next_frame.scene.len(), count + 1);
10613        });
10614    }
10615
10616    #[gpui::test]
10617    fn test_collapsed_inset_shadow_hole_is_an_empty_point_on_the_pixel_grid(
10618        cx: &mut TestAppContext,
10619    ) {
10620        test_paint_at_scales(cx, |window| {
10621            let bounds = Bounds::new(point(px(30.25), px(40.25)), size(px(20.), px(20.)));
10622            for blur_radius in [px(0.), px(4.)] {
10623                for spread_radius in [px(10.), px(12.3), px(15.), px(30.)] {
10624                    let shadow = crate::BoxShadow::new(px(0.), px(0.), crate::red())
10625                        .blur_radius(blur_radius)
10626                        .spread_radius(spread_radius)
10627                        .inset();
10628                    window.next_frame.scene.clear();
10629                    window.paint_inset_shadows(bounds, Default::default(), &[shadow]);
10630                    let shadows = &window.next_frame.scene.shadows;
10631                    assert_eq!(shadows.len(), 1);
10632                    let hole = shadows[0].shape_bounds;
10633                    let message = format!(
10634                        "scale={}, blur={blur_radius:?}, spread={spread_radius:?}, hole={hole:?}",
10635                        window.scale_factor()
10636                    );
10637                    assert_eq!(hole.size, crate::Size::default(), "{message}");
10638                    assert_eq!(hole.origin.x.0.fract(), 0., "{message}");
10639                    assert_eq!(hole.origin.y.0.fract(), 0., "{message}");
10640                }
10641            }
10642        });
10643    }
10644
10645    struct PaintTestView(Rc<dyn Fn(&mut Window)>);
10646
10647    impl Render for PaintTestView {
10648        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10649            let paint = self.0.clone();
10650            canvas(
10651                |_, _, _| {},
10652                move |_, _, window, _| {
10653                    window.content_mask_stack.push(ContentMask {
10654                        bounds: Bounds::from_corners(
10655                            point(px(-1000.), px(-1000.)),
10656                            point(px(1000.), px(1000.)),
10657                        ),
10658                    });
10659                    paint(window);
10660                    window.content_mask_stack.pop();
10661                },
10662            )
10663            .size_full()
10664        }
10665    }
10666
10667    fn test_paint_at_scales(cx: &mut TestAppContext, paint: impl Fn(&mut Window) + 'static) {
10668        let window = cx.add_window(move |_, _| PaintTestView(Rc::new(paint)));
10669        for scale in [1., 1.25, 1.5, 2., 3.] {
10670            cx.simulate_window_scale_factor_change(window.into(), scale);
10671            cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
10672                .unwrap();
10673        }
10674    }
10675
10676    #[derive(Clone, Copy, PartialEq)]
10677    enum LongPressResponse {
10678        PreventDefault,
10679        StopPropagation,
10680        None,
10681    }
10682
10683    struct LongPressListener {
10684        phases: Rc<RefCell<Vec<TouchPhase>>>,
10685        response: LongPressResponse,
10686    }
10687
10688    impl Render for LongPressListener {
10689        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
10690            let entity = cx.entity();
10691            let phases = self.phases.clone();
10692            let response = self.response;
10693            canvas(
10694                |_, _, _| {},
10695                move |_, _, window, _| {
10696                    window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
10697                        if phase != DispatchPhase::Bubble {
10698                            return;
10699                        }
10700                        phases.borrow_mut().push(event.phase);
10701                        match response {
10702                            LongPressResponse::PreventDefault => {
10703                                window.capture_long_press(&entity);
10704                                window.prevent_default();
10705                            }
10706                            LongPressResponse::StopPropagation => cx.stop_propagation(),
10707                            LongPressResponse::None => {}
10708                        }
10709                    });
10710                },
10711            )
10712        }
10713    }
10714
10715    fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
10716        window.next_frame.scene.clear();
10717        paint(window);
10718        &window.next_frame.scene.underlines
10719    }
10720
10721    fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
10722        assert_eq!(actual.bounds, expected.bounds);
10723        assert_eq!(actual.thickness, expected.thickness);
10724        assert_eq!(actual.wavy, expected.wavy);
10725        assert_eq!(actual.color, expected.color);
10726        assert_eq!(actual.pad, expected.pad);
10727    }
10728
10729    fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
10730        underlines
10731            .iter()
10732            .flat_map(|underline| {
10733                let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
10734                bounds.left().0 as i32..bounds.right().0 as i32
10735            })
10736            .collect()
10737    }
10738
10739    actions!(window_test, [StandaloneModifierAction]);
10740
10741    struct StandaloneModifierView {
10742        focus_handle: FocusHandle,
10743        action_count: usize,
10744    }
10745
10746    impl Render for StandaloneModifierView {
10747        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
10748            div()
10749                .key_context("StandaloneModifier")
10750                .track_focus(&self.focus_handle)
10751                .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
10752                    this.action_count += 1;
10753                }))
10754        }
10755    }
10756
10757    #[gpui::test]
10758    fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
10759        use crate::{KeyBinding, Modifiers};
10760
10761        cx.update(|cx| {
10762            cx.bind_keys([KeyBinding::new(
10763                "shift shift",
10764                StandaloneModifierAction,
10765                Some("StandaloneModifier"),
10766            )]);
10767        });
10768        let (view, cx) = cx.add_window_view(|window, cx| {
10769            let focus_handle = cx.focus_handle();
10770            window.focus(&focus_handle, cx);
10771            StandaloneModifierView {
10772                focus_handle,
10773                action_count: 0,
10774            }
10775        });
10776        let shift = Modifiers {
10777            shift: true,
10778            ..Modifiers::default()
10779        };
10780        cx.simulate_modifiers_change(shift);
10781        cx.simulate_modifiers_change(Modifiers::default());
10782        cx.update(|window, _| {
10783            assert_eq!(
10784                window.pending_input_keystrokes(),
10785                Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
10786            );
10787        });
10788        cx.background_executor.advance_clock(Duration::from_secs(2));
10789        cx.run_until_parked();
10790        cx.update(|window, cx| {
10791            assert!(!window.has_pending_keystrokes());
10792            assert_eq!(view.read(cx).action_count, 0);
10793        });
10794
10795        cx.simulate_modifiers_change(shift);
10796        cx.simulate_modifiers_change(Modifiers::default());
10797        cx.update(|window, cx| {
10798            assert!(window.has_pending_keystrokes());
10799            assert_eq!(view.read(cx).action_count, 0);
10800        });
10801
10802        cx.simulate_modifiers_change(shift);
10803        cx.simulate_modifiers_change(Modifiers::default());
10804        cx.update(|window, cx| {
10805            assert!(!window.has_pending_keystrokes());
10806            assert_eq!(view.read(cx).action_count, 1);
10807        });
10808    }
10809
10810    #[gpui::test]
10811    fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
10812        use crate::{KeyBinding, Modifiers};
10813
10814        cx.update(|cx| {
10815            cx.bind_keys([KeyBinding::new(
10816                "shift shift",
10817                StandaloneModifierAction,
10818                Some("StandaloneModifier"),
10819            )]);
10820        });
10821        let (view, cx) = cx.add_window_view(|window, cx| {
10822            let focus_handle = cx.focus_handle();
10823            window.focus(&focus_handle, cx);
10824            StandaloneModifierView {
10825                focus_handle,
10826                action_count: 0,
10827            }
10828        });
10829        let shift = Modifiers {
10830            shift: true,
10831            ..Modifiers::default()
10832        };
10833        cx.simulate_modifiers_change(shift);
10834        cx.simulate_modifiers_change(Modifiers::default());
10835        cx.background_executor
10836            .advance_clock(Duration::from_millis(500));
10837        cx.update(|window, cx| {
10838            assert!(window.has_pending_keystrokes());
10839            assert_eq!(view.read(cx).action_count, 0);
10840        });
10841        cx.simulate_modifiers_change(shift);
10842        cx.simulate_modifiers_change(Modifiers::default());
10843        cx.update(|window, cx| {
10844            assert!(!window.has_pending_keystrokes());
10845            assert_eq!(view.read(cx).action_count, 1);
10846        });
10847        cx.background_executor.advance_clock(Duration::from_secs(2));
10848        cx.run_until_parked();
10849        cx.update(|window, cx| {
10850            assert!(!window.has_pending_keystrokes());
10851            assert_eq!(view.read(cx).action_count, 1);
10852        });
10853    }
10854
10855    fn dispatch_touch<T: 'static>(
10856        window: crate::WindowHandle<T>,
10857        cx: &mut TestAppContext,
10858        id: TouchId,
10859        phase: TouchPhase,
10860        x: f32,
10861    ) {
10862        window
10863            .update(cx, |_, window, cx| {
10864                window.dispatch_event(
10865                    TouchEvent {
10866                        id,
10867                        phase,
10868                        position: point(px(x), px(0.)),
10869                        predicted_position: None,
10870                        force: None,
10871                    }
10872                    .to_platform_input(),
10873                    cx,
10874                );
10875            })
10876            .unwrap();
10877    }
10878
10879    #[gpui::test]
10880    fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
10881        struct Child {
10882            renders: usize,
10883        }
10884
10885        impl Render for Child {
10886            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10887                self.renders += 1;
10888                div().size_full().bg(crate::rgb(0xff0000))
10889            }
10890        }
10891
10892        struct Root {
10893            opacity: f32,
10894            width: Pixels,
10895            child: crate::Entity<Child>,
10896        }
10897
10898        impl Render for Root {
10899            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10900                div()
10901                    .w(self.width)
10902                    .h(px(200.))
10903                    .opacity(self.opacity)
10904                    .hover(|style| style.opacity(1.))
10905                    .child(
10906                        self.child
10907                            .clone()
10908                            .cached(crate::StyleRefinement::default().size(px(100.))),
10909                    )
10910            }
10911        }
10912
10913        /// Updates the root, draws until no more frames are requested, and returns the
10914        /// child's painted alpha and how many times it has rendered.
10915        fn update_and_draw(
10916            window: crate::WindowHandle<Root>,
10917            child: &crate::Entity<Child>,
10918            cx: &mut TestAppContext,
10919            update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
10920        ) -> (f32, usize) {
10921            window
10922                .update(cx, |root, window, cx| {
10923                    update(root, window, cx);
10924                    cx.notify();
10925                })
10926                .expect("update root");
10927            for _ in 0..3 {
10928                let (alpha, renders, requested_frames) = cx
10929                    .update_window(window.into(), |_, window, cx| {
10930                        window.draw(cx).clear(cx);
10931                        let quads = &window.rendered_frame.scene.quads;
10932                        assert_eq!(quads.len(), 1);
10933                        let alpha = quads.first().expect("child quad").background.solid.a;
10934                        (
10935                            alpha,
10936                            child.read(cx).renders,
10937                            window.simulate_next_frame(cx),
10938                        )
10939                    })
10940                    .expect("draw window");
10941                if requested_frames == 0 {
10942                    return (alpha, renders);
10943                }
10944            }
10945            panic!("cached child kept requesting frames");
10946        }
10947
10948        let child = cx.new(|_| Child { renders: 0 });
10949        let window = cx.add_window(|_, _| Root {
10950            opacity: 1.,
10951            width: px(200.),
10952            child: child.clone(),
10953        });
10954        let outside = point(px(500.), px(500.));
10955        let inside = point(px(50.), px(50.));
10956        let beside = point(px(250.), px(50.));
10957
10958        // Changing the wrapper's opacity redraws the child; unchanged opacity reuses it.
10959        let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
10960            window.simulate_mouse_move(outside, cx)
10961        };
10962        assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
10963        assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
10964        let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
10965        assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
10966        assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
10967
10968        // Hover opacity applies when the mouse enters and leaves.
10969        let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
10970            window.simulate_mouse_move(inside, cx)
10971        };
10972        assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
10973        let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
10974            window.simulate_mouse_move(beside, cx)
10975        };
10976        assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
10977
10978        // Widening the wrapper puts it under a still mouse, so only paint's hit test sees
10979        // the hover.
10980        let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
10981        assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
10982    }
10983
10984    #[gpui::test]
10985    fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
10986        struct ResizeHandle;
10987
10988        impl Render for ResizeHandle {
10989            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10990                div().size_full().cursor_text().child(
10991                    div()
10992                        .id("resize-handle")
10993                        .w(px(4.))
10994                        .h_full()
10995                        .cursor_col_resize()
10996                        .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
10997                )
10998            }
10999        }
11000
11001        let window = cx.add_window(|_, _| ResizeHandle);
11002        let handle_position = point(px(1.), px(10.));
11003        let drag_position = point(px(20.), px(10.));
11004        let cursor_observer = cx.clone();
11005
11006        let update_result = cx.update_window(window.into(), |_, window, cx| {
11007            window.hovered.set(true);
11008            window.active.set(true);
11009            window.draw(cx).clear(cx);
11010            window.dispatch_event(
11011                MouseMoveEvent {
11012                    position: handle_position,
11013                    ..Default::default()
11014                }
11015                .to_platform_input(),
11016                cx,
11017            );
11018            window.dispatch_event(
11019                MouseDownEvent {
11020                    position: handle_position,
11021                    button: MouseButton::Left,
11022                    ..Default::default()
11023                }
11024                .to_platform_input(),
11025                cx,
11026            );
11027            window.dispatch_event(
11028                MouseMoveEvent {
11029                    position: drag_position,
11030                    pressed_button: Some(MouseButton::Left),
11031                    ..Default::default()
11032                }
11033                .to_platform_input(),
11034                cx,
11035            );
11036            assert!(cx.has_active_drag());
11037            // Asserted here because leaving this update flushes effects, which paints a frame.
11038            assert_eq!(
11039                cursor_observer.test_platform().cursor_style(),
11040                CursorStyle::ResizeColumn
11041            );
11042
11043            window.draw(cx).clear(cx);
11044            window.dispatch_event(
11045                MouseUpEvent {
11046                    position: drag_position,
11047                    button: MouseButton::Left,
11048                    ..Default::default()
11049                }
11050                .to_platform_input(),
11051                cx,
11052            );
11053            window.draw(cx).clear(cx);
11054        });
11055        assert!(
11056            update_result.is_ok(),
11057            "failed to run drag: {update_result:?}"
11058        );
11059        assert_eq!(
11060            cursor_observer.test_platform().cursor_style(),
11061            CursorStyle::IBeam
11062        );
11063    }
11064}
11065
11066#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
11067mod inspector_tests {
11068    use super::*;
11069    use crate::{
11070        DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
11071    };
11072
11073    #[gpui::test]
11074    fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
11075        let windows = [
11076            cx.add_window(|_, cx| InspectorTestRoot {
11077                child: cx.new(|_| InspectorTestView::default()),
11078            }),
11079            cx.add_window(|_, cx| InspectorTestRoot {
11080                child: cx.new(|_| InspectorTestView::default()),
11081            }),
11082        ];
11083        for window in windows {
11084            assert_closed_inspector(window.into(), cx);
11085        }
11086        for _ in 0..2 {
11087            cx.update_window(windows[0].into(), |root, window, cx| {
11088                let root = root.downcast::<InspectorTestRoot>().expect("test root");
11089                let child_widths = root.read(cx).child.read(cx).child_widths.clone();
11090                window.toggle_inspector(cx);
11091                window.draw(cx).clear(cx);
11092                assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
11093                let path = window
11094                    .rendered_frame
11095                    .next_inspector_instance_ids
11096                    .iter()
11097                    .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
11098                    .expect("anonymous siblings share an inspector path");
11099                let selected_id = InspectorElementId {
11100                    path,
11101                    instance_id: 1,
11102                };
11103                let position = window
11104                    .rendered_frame
11105                    .hitboxes
11106                    .iter()
11107                    .find(|hitbox| {
11108                        window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
11109                            == Some(&selected_id)
11110                    })
11111                    .expect("middle sibling is pickable")
11112                    .bounds
11113                    .center();
11114                window.simulate_mouse_move(position, cx);
11115                window.dispatch_event(
11116                    PlatformInput::MouseDown(MouseDownEvent {
11117                        position,
11118                        button: MouseButton::Left,
11119                        modifiers: Modifiers::default(),
11120                        click_count: 1,
11121                        first_mouse: false,
11122                    }),
11123                    cx,
11124                );
11125                window.dispatch_event(
11126                    PlatformInput::MouseUp(MouseUpEvent {
11127                        position,
11128                        button: MouseButton::Left,
11129                        modifiers: Modifiers::default(),
11130                        click_count: 1,
11131                    }),
11132                    cx,
11133                );
11134                assert!(!window.is_inspector_picking(cx));
11135                assert_eq!(
11136                    window
11137                        .inspector
11138                        .as_ref()
11139                        .expect("open inspector")
11140                        .read(cx)
11141                        .active_element_id(),
11142                    Some(&selected_id)
11143                );
11144                window.draw(cx).clear(cx);
11145                window.with_inspector_state::<DivInspectorState, _>(
11146                    Some(&selected_id),
11147                    cx,
11148                    |state, _| {
11149                        let state = state.as_mut().expect("selected div has style state");
11150                        assert_eq!(
11151                            state.base_style.size.width,
11152                            Some(crate::Length::from(px(10.)))
11153                        );
11154                        state.base_style.size.width = Some(crate::Length::from(px(25.)));
11155                    },
11156                );
11157                window.refresh();
11158                window.draw(cx).clear(cx);
11159                assert_eq!(
11160                    child_widths.borrow().as_slice(),
11161                    &[px(10.), px(25.), px(10.)]
11162                );
11163            })
11164            .expect("pick and edit a cached child");
11165            assert_closed_inspector(windows[1].into(), cx);
11166            windows[0]
11167                .update(cx, |_, window, cx| window.toggle_inspector(cx))
11168                .expect("close inspector");
11169            assert_closed_inspector(windows[0].into(), cx);
11170        }
11171    }
11172
11173    struct InspectorTestRoot {
11174        child: Entity<InspectorTestView>,
11175    }
11176
11177    impl Render for InspectorTestRoot {
11178        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
11179            self.child
11180                .clone()
11181                .cached(StyleRefinement::default().size(px(100.)))
11182        }
11183    }
11184
11185    #[derive(Default)]
11186    struct InspectorTestView {
11187        child_widths: Rc<RefCell<Vec<Pixels>>>,
11188    }
11189
11190    impl Render for InspectorTestView {
11191        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
11192            let child_widths = self.child_widths.clone();
11193            div()
11194                .on_children_prepainted(move |bounds, _, _| {
11195                    *child_widths.borrow_mut() =
11196                        bounds.iter().map(|bounds| bounds.size.width).collect();
11197                })
11198                .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
11199                .id("inspector-root")
11200                .flex()
11201                .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
11202        }
11203    }
11204
11205    fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
11206        cx.update_window(window, |root, window, cx| {
11207            window.draw(cx).clear(cx);
11208            window.draw(cx).clear(cx);
11209            let root = root.downcast::<InspectorTestRoot>().expect("test root");
11210            assert_eq!(
11211                root.read(cx)
11212                    .child
11213                    .read(cx)
11214                    .child_widths
11215                    .borrow()
11216                    .as_slice(),
11217                &[px(10.); 3]
11218            );
11219            for frame in [&window.rendered_frame, &window.next_frame] {
11220                assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
11221                assert_eq!(frame.inspector_hitboxes.capacity(), 0);
11222            }
11223        })
11224        .expect("closed inspector has no bookkeeping and no style overrides");
11225    }
11226}