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