Skip to main content

gpui/
window.rs

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