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