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        crate::fast::composition::begin_base_prepaint(self);
3741        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3742
3743        #[cfg(any(feature = "inspector", debug_assertions))]
3744        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3745
3746        crate::fast::composition::begin_overlay_prepaint(self);
3747        self.prepaint_deferred_draws(cx);
3748
3749        let mut prompt_element = None;
3750        let mut active_drag_element = None;
3751        let mut tooltip_element = None;
3752        if let Some(prompt) = self.prompt.take() {
3753            let mut element = prompt.view.any_view().into_any_element();
3754            let prompt_layout_id = element.request_layout(self, cx);
3755            self.layout_engine
3756                .as_mut()
3757                .unwrap()
3758                .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3759            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3760            prompt_element = Some(element);
3761            self.prompt = Some(prompt);
3762        } else if let Some(active_drag) = cx.active_drag.take() {
3763            let mut element = active_drag.view.clone().into_any_element();
3764            let offset = self.mouse_position() - active_drag.cursor_offset;
3765            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3766            active_drag_element = Some(element);
3767            cx.active_drag = Some(active_drag);
3768        } else {
3769            tooltip_element = self.prepaint_tooltip(cx);
3770        }
3771
3772        crate::fast::stats::FramePhaseTimes::end_prepaint(&mut self.fast_layout.phase_times);
3773        self.mouse_hit_test = crate::fast::layers::hover_freeze::hit_test(self);
3774
3775        // Now actually paint the elements.
3776        #[cfg(feature = "profiler")]
3777        let paint_start = Instant::now();
3778        self.invalidator.set_phase(DrawPhase::Paint);
3779        crate::fast::composition::begin_base(self);
3780        root_element.paint(self, cx);
3781
3782        #[cfg(any(feature = "inspector", debug_assertions))]
3783        self.paint_inspector(inspector_element, cx);
3784
3785        crate::fast::composition::begin_overlay(self);
3786        self.paint_deferred_draws(cx);
3787
3788        if let Some(mut prompt_element) = prompt_element {
3789            prompt_element.paint(self, cx);
3790        } else if let Some(mut drag_element) = active_drag_element {
3791            drag_element.paint(self, cx);
3792        } else if let Some(mut tooltip_element) = tooltip_element {
3793            tooltip_element.paint(self, cx);
3794        }
3795
3796        #[cfg(any(feature = "inspector", debug_assertions))]
3797        self.paint_inspector_hitbox(cx);
3798        crate::fast::stats::FramePhaseTimes::end_paint(&mut self.fast_layout.phase_times);
3799
3800        #[cfg(feature = "profiler")]
3801        self.window_profiler
3802            .record_draw_phases(profiler::DrawPhases {
3803                request_layout: prepaint_start.duration_since(request_layout_start),
3804                prepaint: paint_start.duration_since(prepaint_start),
3805                paint: Instant::now().duration_since(paint_start),
3806            });
3807
3808        // a11y may have been activated/deactivated halfway through the frame
3809        let a11y_active_start_of_frame = self.a11y.is_active();
3810        self.a11y.sync_active_flag();
3811        let a11y_active_end_of_frame = self.a11y.is_active();
3812
3813        let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3814
3815        if a11y_active_start_of_frame {
3816            // Harvest frame metadata for the debug dump while the live window
3817            // and frame are still in scope.
3818            let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3819                viewport_size: self.viewport_size,
3820                scale_factor: self.scale_factor,
3821                tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3822            };
3823            // clear the builder state regardless
3824            let tree_update = self.a11y.end_frame(frame_info);
3825
3826            if should_send_a11y_update {
3827                log::debug!(
3828                    "Sending a11y tree update: {} nodes",
3829                    tree_update.nodes.len()
3830                );
3831                self.platform_window.a11y_tree_update(tree_update);
3832            }
3833        }
3834    }
3835
3836    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3837        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
3838        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3839            let Some(Some(tooltip_request)) = self
3840                .next_frame
3841                .tooltip_requests
3842                .get(tooltip_request_index)
3843                .cloned()
3844            else {
3845                log::error!("Unexpectedly absent TooltipRequest");
3846                continue;
3847            };
3848            let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3849            let mouse_position = tooltip_request.tooltip.mouse_position;
3850            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3851
3852            let mut tooltip_bounds =
3853                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3854            let window_bounds = Bounds {
3855                origin: Point::default(),
3856                size: self.viewport_size(),
3857            };
3858
3859            if tooltip_bounds.right() > window_bounds.right() {
3860                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3861                if new_x >= Pixels::ZERO {
3862                    tooltip_bounds.origin.x = new_x;
3863                } else {
3864                    tooltip_bounds.origin.x = cmp::max(
3865                        Pixels::ZERO,
3866                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3867                    );
3868                }
3869            }
3870
3871            if tooltip_bounds.bottom() > window_bounds.bottom() {
3872                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3873                if new_y >= Pixels::ZERO {
3874                    tooltip_bounds.origin.y = new_y;
3875                } else {
3876                    tooltip_bounds.origin.y = cmp::max(
3877                        Pixels::ZERO,
3878                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3879                    );
3880                }
3881            }
3882
3883            // It's possible for an element to have an active tooltip while not being painted (e.g.
3884            // via the `visible_on_hover` method). Since mouse listeners are not active in this
3885            // case, instead update the tooltip's visibility here.
3886            let is_visible =
3887                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3888            if !is_visible {
3889                continue;
3890            }
3891
3892            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3893                element.prepaint(window, cx)
3894            });
3895
3896            self.tooltip_bounds = Some(TooltipBounds {
3897                id: tooltip_request.id,
3898                bounds: tooltip_bounds,
3899            });
3900            return Some(element);
3901        }
3902        None
3903    }
3904
3905    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3906        assert_eq!(self.element_id_stack.len(), 0);
3907
3908        // Process deferred draws in multiple rounds to support nesting.
3909        // Each round processes all current deferred draws, which may push new ones.
3910        //
3911        // The draws are processed in place rather than being moved out of
3912        // `next_frame.deferred_draws`: `prepaint_index` snapshots that vector's
3913        // length, so any prepaint range recorded during a round (view caches,
3914        // nested deferred draws) must index the same vector `reuse_prepaint`
3915        // slices on the next frame. Moving the draws out and re-appending them
3916        // shifts the indices of nested draws, causing reused subtrees to graft
3917        // the wrong deferred draws and panic in the dispatch tree.
3918        let mut round_start = 0;
3919        let mut depth = 0;
3920        loop {
3921            let round_end = self.next_frame.deferred_draws.len();
3922            if round_start == round_end {
3923                break;
3924            }
3925            // Limit maximum nesting depth to prevent infinite loops.
3926            assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3927            depth += 1;
3928
3929            // Sort this round by priority.
3930            let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3931            traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3932
3933            for deferred_draw_ix in traversal_order {
3934                let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3935                    let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3936                    self.element_id_stack
3937                        .clone_from(&deferred_draw.element_id_stack);
3938                    self.text_style_stack
3939                        .clone_from(&deferred_draw.text_style_stack);
3940                    (
3941                        deferred_draw.element.take(),
3942                        deferred_draw.parent_node,
3943                        deferred_draw.current_view,
3944                        deferred_draw.rem_size,
3945                        deferred_draw.absolute_offset,
3946                        deferred_draw.prepaint_range.clone(),
3947                    )
3948                };
3949                self.next_frame.dispatch_tree.set_active_node(parent_node);
3950
3951                let prepaint_start = self.prepaint_index();
3952                if let Some(mut element) = element {
3953                    let recording =
3954                        crate::fast::retained::begin_deferred_prepaint(self, deferred_draw_ix, cx);
3955                    self.with_rendered_view(current_view, |window| {
3956                        window.with_rem_size(Some(rem_size), |window| {
3957                            window.with_absolute_element_offset(absolute_offset, |window| {
3958                                element.prepaint(window, cx);
3959                            });
3960                        });
3961                    });
3962                    crate::fast::retained::finish_deferred(self, recording, cx);
3963                    self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3964                } else {
3965                    self.reuse_prepaint(prepaint_range);
3966                }
3967                let prepaint_end = self.prepaint_index();
3968                self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3969                    prepaint_start..prepaint_end;
3970            }
3971
3972            self.element_id_stack.clear();
3973            self.text_style_stack.clear();
3974            round_start = round_end;
3975        }
3976    }
3977
3978    fn paint_deferred_draws(&mut self, cx: &mut App) {
3979        assert_eq!(self.element_id_stack.len(), 0);
3980
3981        // Paint all deferred draws in priority order.
3982        // Since prepaint has already processed nested deferreds, we just paint them all.
3983        if self.next_frame.deferred_draws.len() == 0 {
3984            return;
3985        }
3986
3987        let traversal_order = self.deferred_draw_traversal_order();
3988        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3989        for deferred_draw_ix in traversal_order {
3990            let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3991            self.element_id_stack
3992                .clone_from(&deferred_draw.element_id_stack);
3993            self.next_frame
3994                .dispatch_tree
3995                .set_active_node(deferred_draw.parent_node);
3996
3997            let paint_start = self.paint_index();
3998            let content_mask = deferred_draw.content_mask;
3999            if let Some(element) = deferred_draw.element.as_mut() {
4000                let enclosing = &deferred_draw.enclosing_retained;
4001                let recording = crate::fast::retained::begin_deferred_paint(self, enclosing, cx);
4002                self.with_rendered_view(deferred_draw.current_view, |window| {
4003                    window.with_content_mask(content_mask, |window| {
4004                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
4005                            element.paint(window, cx);
4006                        });
4007                    })
4008                });
4009                crate::fast::retained::finish_deferred(self, recording, cx);
4010            } else {
4011                self.reuse_paint(deferred_draw.paint_range.clone());
4012            }
4013            let paint_end = self.paint_index();
4014            deferred_draw.paint_range = paint_start..paint_end;
4015        }
4016        self.next_frame.deferred_draws = deferred_draws;
4017        self.element_id_stack.clear();
4018    }
4019
4020    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
4021        let deferred_count = self.next_frame.deferred_draws.len();
4022        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
4023        sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
4024        sorted_indices
4025    }
4026
4027    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
4028        PrepaintStateIndex {
4029            hitboxes_index: self.next_frame.hitboxes.len(),
4030            tooltips_index: self.next_frame.tooltip_requests.len(),
4031            deferred_draws_index: self.next_frame.deferred_draws.len(),
4032            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
4033            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4034            line_layout_index: self.text_system.layout_index(),
4035            fast_a11y_index: crate::fast::a11y::ops_index(self),
4036        }
4037    }
4038
4039    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
4040        crate::fast::a11y::reuse_prepaint(self, &range);
4041        self.next_frame.hitboxes.extend(
4042            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
4043                .iter()
4044                .cloned(),
4045        );
4046        self.next_frame.tooltip_requests.extend(
4047            self.rendered_frame.tooltip_requests
4048                [range.start.tooltips_index..range.end.tooltips_index]
4049                .iter_mut()
4050                .map(|request| request.take()),
4051        );
4052        self.next_frame.accessed_element_states.extend(
4053            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4054                ..range.end.accessed_element_states_index]
4055                .iter()
4056                .map(|(id, type_id)| (id.clone(), *type_id)),
4057        );
4058        self.text_system
4059            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4060
4061        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
4062            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
4063            &mut self.rendered_frame.dispatch_tree,
4064            self.focus,
4065        );
4066
4067        if reused_subtree.contains_focus() {
4068            self.next_frame.focus = self.focus;
4069        }
4070
4071        self.next_frame.deferred_draws.extend(
4072            self.rendered_frame.deferred_draws
4073                [range.start.deferred_draws_index..range.end.deferred_draws_index]
4074                .iter()
4075                .map(|deferred_draw| DeferredDraw {
4076                    current_view: deferred_draw.current_view,
4077                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
4078                    element_id_stack: deferred_draw.element_id_stack.clone(),
4079                    text_style_stack: deferred_draw.text_style_stack.clone(),
4080                    content_mask: deferred_draw.content_mask,
4081                    rem_size: deferred_draw.rem_size,
4082                    priority: deferred_draw.priority,
4083                    element: None,
4084                    absolute_offset: deferred_draw.absolute_offset,
4085                    prepaint_range: deferred_draw.prepaint_range.clone(),
4086                    paint_range: deferred_draw.paint_range.clone(),
4087                    enclosing_retained: crate::fast::retained::EnclosingRetained::default(),
4088                }),
4089        );
4090    }
4091
4092    pub(crate) fn paint_index(&self) -> PaintIndex {
4093        PaintIndex {
4094            scene_index: self.next_frame.scene.len(),
4095            #[cfg(any(test, feature = "test-support"))]
4096            debug_bounds_index: self.next_frame.debug_bounds_records.len(),
4097            fast: crate::fast::retained::FastPaintIndex::new(self),
4098            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
4099            input_handlers_index: self.next_frame.input_handlers.len(),
4100            cursor_styles_index: self.next_frame.cursor_styles.len(),
4101            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4102            tab_handle_index: self.next_frame.tab_stops.paint_index(),
4103            line_layout_index: self.text_system.layout_index(),
4104        }
4105    }
4106
4107    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
4108        crate::fast::retained::reuse_paint_records(self, &range);
4109        crate::fast::composition::reuse_starts(self, &range);
4110        // Cached elements still exist in the frame even when their paint methods don't run.
4111        #[cfg(any(test, feature = "test-support"))]
4112        for (selector, bounds) in &self.rendered_frame.debug_bounds_records
4113            [range.start.debug_bounds_index..range.end.debug_bounds_index]
4114        {
4115            self.next_frame
4116                .record_debug_bounds(selector.clone(), *bounds);
4117        }
4118        self.next_frame.cursor_styles.extend(
4119            self.rendered_frame.cursor_styles
4120                [range.start.cursor_styles_index..range.end.cursor_styles_index]
4121                .iter()
4122                .cloned(),
4123        );
4124        self.next_frame.input_handlers.extend(
4125            self.rendered_frame.input_handlers
4126                [range.start.input_handlers_index..range.end.input_handlers_index]
4127                .iter_mut()
4128                .map(|handler| handler.take()),
4129        );
4130        self.next_frame.mouse_listeners.extend(
4131            self.rendered_frame.mouse_listeners
4132                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
4133                .iter_mut()
4134                .map(|listener| listener.take()),
4135        );
4136        self.next_frame.accessed_element_states.extend(
4137            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4138                ..range.end.accessed_element_states_index]
4139                .iter()
4140                .map(|(id, type_id)| (id.clone(), *type_id)),
4141        );
4142        self.next_frame.tab_stops.replay(
4143            &self.rendered_frame.tab_stops.insertion_history
4144                [range.start.tab_handle_index..range.end.tab_handle_index],
4145        );
4146
4147        self.text_system
4148            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4149        self.next_frame.scene.replay(
4150            range.start.scene_index..range.end.scene_index,
4151            &self.rendered_frame.scene,
4152        );
4153    }
4154
4155    /// Push a text style onto the stack, and call a function with that style active.
4156    /// Use [`Window::text_style`] to get the current, combined text style. This method
4157    /// should only be called as part of element drawing.
4158    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
4159    where
4160        F: FnOnce(&mut Self) -> R,
4161    {
4162        self.invalidator.debug_assert_paint_or_prepaint();
4163        if let Some(style) = style {
4164            self.text_style_stack.push(style);
4165            let result = f(self);
4166            self.text_style_stack.pop();
4167            result
4168        } else {
4169            f(self)
4170        }
4171    }
4172
4173    /// Updates the cursor style at the platform level. This method should only be called
4174    /// during the paint phase of element drawing.
4175    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
4176        self.invalidator.debug_assert_paint();
4177        self.next_frame.cursor_styles.push(CursorStyleRequest {
4178            hitbox_id: Some(hitbox.id),
4179            style,
4180        });
4181    }
4182
4183    /// Updates the cursor style for the entire window at the platform level. A cursor
4184    /// style using this method will have precedence over any cursor style set using
4185    /// `set_cursor_style`. This method should only be called during the paint
4186    /// phase of element drawing.
4187    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
4188        self.invalidator.debug_assert_paint();
4189        self.next_frame.cursor_styles.push(CursorStyleRequest {
4190            hitbox_id: None,
4191            style,
4192        })
4193    }
4194
4195    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
4196    /// during the paint phase of element drawing.
4197    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
4198        self.invalidator.debug_assert_prepaint();
4199        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
4200        self.next_frame
4201            .tooltip_requests
4202            .push(Some(TooltipRequest { id, tooltip }));
4203        id
4204    }
4205
4206    /// Invoke the given function with the given content mask after intersecting it
4207    /// with the current mask. This method should only be called during element drawing.
4208    // This function is called in a highly recursive manner in editor
4209    // prepainting, make sure its inlined to reduce the stack burden
4210    #[inline]
4211    pub fn with_content_mask<R>(
4212        &mut self,
4213        mask: Option<ContentMask<Pixels>>,
4214        f: impl FnOnce(&mut Self) -> R,
4215    ) -> R {
4216        self.invalidator.debug_assert_paint_or_prepaint();
4217        if let Some(mask) = mask {
4218            let mask = mask.intersect(&self.content_mask());
4219            self.content_mask_stack.push(mask);
4220            let result = f(self);
4221            self.content_mask_stack.pop();
4222            result
4223        } else {
4224            f(self)
4225        }
4226    }
4227
4228    /// Updates the global element offset relative to the current offset. This is used to implement
4229    /// scrolling. This method should only be called during the prepaint phase of element drawing.
4230    pub fn with_element_offset<R>(
4231        &mut self,
4232        offset: Point<Pixels>,
4233        f: impl FnOnce(&mut Self) -> R,
4234    ) -> R {
4235        self.invalidator.debug_assert_prepaint();
4236
4237        if offset.is_zero() {
4238            return f(self);
4239        };
4240
4241        let abs_offset = self.element_offset() + offset;
4242        self.with_absolute_element_offset(abs_offset, f)
4243    }
4244
4245    /// Updates the global element offset based on the given offset. This is used to implement
4246    /// drag handles and other manual painting of elements. This method should only be called during
4247    /// the prepaint phase of element drawing.
4248    pub fn with_absolute_element_offset<R>(
4249        &mut self,
4250        offset: Point<Pixels>,
4251        f: impl FnOnce(&mut Self) -> R,
4252    ) -> R {
4253        self.invalidator.debug_assert_prepaint();
4254        self.element_offset_stack.push(offset);
4255        let result = f(self);
4256        self.element_offset_stack.pop();
4257        result
4258    }
4259
4260    pub(crate) fn with_element_opacity<R>(
4261        &mut self,
4262        opacity: Option<f32>,
4263        f: impl FnOnce(&mut Self) -> R,
4264    ) -> R {
4265        self.invalidator.debug_assert_paint_or_prepaint();
4266
4267        let Some(opacity) = opacity else {
4268            return f(self);
4269        };
4270
4271        let previous_opacity = self.element_opacity;
4272        self.element_opacity = previous_opacity * opacity;
4273        let result = f(self);
4274        self.element_opacity = previous_opacity;
4275        result
4276    }
4277
4278    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
4279    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
4280    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
4281    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
4282    /// called during the prepaint phase of element drawing.
4283    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
4284        self.invalidator.debug_assert_prepaint();
4285        let index = self.prepaint_index();
4286        let result = f(self);
4287        if result.is_err() {
4288            self.next_frame.hitboxes.truncate(index.hitboxes_index);
4289            self.next_frame
4290                .tooltip_requests
4291                .truncate(index.tooltips_index);
4292            self.next_frame
4293                .deferred_draws
4294                .truncate(index.deferred_draws_index);
4295            self.next_frame
4296                .dispatch_tree
4297                .truncate(index.dispatch_tree_index);
4298            self.next_frame
4299                .accessed_element_states
4300                .truncate(index.accessed_element_states_index);
4301            self.text_system.truncate_layouts(index.line_layout_index);
4302        }
4303        result
4304    }
4305
4306    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
4307    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
4308    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
4309    /// that supports this method being called on the elements it contains. This method should only be
4310    /// called during the prepaint phase of element drawing.
4311    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
4312        self.invalidator.debug_assert_prepaint();
4313        self.requested_autoscroll = Some(bounds);
4314    }
4315
4316    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
4317    /// described in [`Self::request_autoscroll`].
4318    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
4319        self.invalidator.debug_assert_prepaint();
4320        self.requested_autoscroll.take()
4321    }
4322
4323    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
4324    /// Your view will be re-drawn once the asset has finished loading.
4325    ///
4326    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
4327    /// time.
4328    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4329        cx.asset_entry::<A>(source).use_by(self.current_view())
4330    }
4331
4332    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
4333    /// Your view will not be re-drawn once the asset has finished loading.
4334    ///
4335    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
4336    /// time.
4337    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4338        cx.fetch_asset::<A>(source)
4339    }
4340    /// Obtain the current element offset. This method should only be called during the
4341    /// prepaint phase of element drawing.
4342    pub fn element_offset(&self) -> Point<Pixels> {
4343        self.invalidator.debug_assert_prepaint();
4344        self.element_offset_stack
4345            .last()
4346            .copied()
4347            .unwrap_or_default()
4348    }
4349
4350    /// Obtain the current element opacity. This method should only be called during the
4351    /// prepaint phase of element drawing.
4352    #[inline]
4353    pub(crate) fn element_opacity(&self) -> f32 {
4354        self.invalidator.debug_assert_paint_or_prepaint();
4355        self.element_opacity
4356    }
4357
4358    /// Obtain the current content mask. This method should only be called during element drawing.
4359    pub fn content_mask(&self) -> ContentMask<Pixels> {
4360        self.invalidator.debug_assert_paint_or_prepaint();
4361        self.content_mask_stack
4362            .last()
4363            .cloned()
4364            .unwrap_or_else(|| ContentMask {
4365                bounds: Bounds {
4366                    origin: Point::default(),
4367                    size: self.viewport_size,
4368                },
4369            })
4370    }
4371
4372    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
4373    /// This can be used within a custom element to distinguish multiple sets of child elements.
4374    pub fn with_element_namespace<R>(
4375        &mut self,
4376        element_id: impl Into<ElementId>,
4377        f: impl FnOnce(&mut Self) -> R,
4378    ) -> R {
4379        self.element_id_stack.push(element_id.into());
4380        let result = f(self);
4381        self.element_id_stack.pop();
4382        result
4383    }
4384
4385    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
4386    pub fn use_keyed_state<S: 'static>(
4387        &mut self,
4388        key: impl Into<ElementId>,
4389        cx: &mut App,
4390        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4391    ) -> Entity<S> {
4392        let current_view = self.current_view();
4393        self.with_global_id(key.into(), |global_id, window| {
4394            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
4395                if let Some(state) = state {
4396                    (state.clone(), state)
4397                } else {
4398                    let new_state = cx.new(|cx| init(window, cx));
4399                    Self::observe_keyed_state(&new_state, current_view, cx);
4400                    (new_state.clone(), new_state)
4401                }
4402            })
4403        })
4404    }
4405
4406    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
4407    ///
4408    /// NOTE: This method uses the location of the caller to generate an ID for this state.
4409    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
4410    ///       you can provide a custom ElementID using the `use_keyed_state` method.
4411    #[track_caller]
4412    pub fn use_state<S: 'static>(
4413        &mut self,
4414        cx: &mut App,
4415        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4416    ) -> Entity<S> {
4417        self.use_keyed_state(
4418            ElementId::CodeLocation(*core::panic::Location::caller()),
4419            cx,
4420            init,
4421        )
4422    }
4423
4424    /// Updates or initializes state for an element with the given id that lives across multiple
4425    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
4426    /// to the given closure. The state returned by the closure will be stored so it can be referenced
4427    /// when drawing the next frame. This method should only be called as part of element drawing.
4428    #[inline(always)]
4429    pub fn with_element_state<S, R>(
4430        &mut self,
4431        global_id: &GlobalElementId,
4432        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4433    ) -> R
4434    where
4435        S: 'static,
4436    {
4437        self.invalidator.debug_assert_paint_or_prepaint();
4438
4439        let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
4440
4441        if let Some(any) = state {
4442            let ElementStateBox {
4443                inner,
4444                #[cfg(debug_assertions)]
4445                type_name,
4446            } = any;
4447            // Using the extra inner option to avoid needing to reallocate a new box.
4448            let mut state_box = inner
4449                .downcast::<Option<S>>()
4450                .map_err(|_| {
4451                    #[cfg(debug_assertions)]
4452                    {
4453                        anyhow::anyhow!(
4454                            "invalid element state type for id, requested {:?}, actual: {:?}",
4455                            std::any::type_name::<S>(),
4456                            type_name
4457                        )
4458                    }
4459
4460                    #[cfg(not(debug_assertions))]
4461                    {
4462                        anyhow::anyhow!(
4463                            "invalid element state type for id, requested {:?}",
4464                            std::any::type_name::<S>(),
4465                        )
4466                    }
4467                })
4468                .unwrap();
4469
4470            let state = state_box.take().expect(
4471                "reentrant call to with_element_state for the same state type and element id",
4472            );
4473            let (result, state) = f(Some(state), self);
4474            state_box.replace(state);
4475            self.insert_element_state(
4476                key,
4477                ElementStateBox {
4478                    inner: state_box,
4479                    #[cfg(debug_assertions)]
4480                    type_name,
4481                },
4482            );
4483            result
4484        } else {
4485            let (result, state) = f(None, self);
4486            self.insert_element_state(
4487                key,
4488                ElementStateBox {
4489                    inner: Box::new(Some(state)),
4490                    #[cfg(debug_assertions)]
4491                    type_name: std::any::type_name::<S>(),
4492                },
4493            );
4494            result
4495        }
4496    }
4497
4498    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
4499    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
4500    /// when the element is guaranteed to have an id.
4501    ///
4502    /// The first option means 'no ID provided'
4503    /// The second option means 'not yet initialized'
4504    pub fn with_optional_element_state<S, R>(
4505        &mut self,
4506        global_id: Option<&GlobalElementId>,
4507        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4508    ) -> R
4509    where
4510        S: 'static,
4511    {
4512        self.invalidator.debug_assert_paint_or_prepaint();
4513
4514        if let Some(global_id) = global_id {
4515            self.with_element_state(global_id, |state, cx| {
4516                let (result, state) = f(Some(state), cx);
4517                let state =
4518                    state.expect("you must return some state when you pass some element id");
4519                (result, state)
4520            })
4521        } else {
4522            let (result, state) = f(None, self);
4523            debug_assert!(
4524                state.is_none(),
4525                "you must not return an element state when passing None for the global id"
4526            );
4527            result
4528        }
4529    }
4530
4531    /// Executes the given closure within the context of a tab group.
4532    #[inline]
4533    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4534        if let Some(index) = index {
4535            self.next_frame.tab_stops.begin_group(index);
4536            let result = f(self);
4537            self.next_frame.tab_stops.end_group();
4538            result
4539        } else {
4540            f(self)
4541        }
4542    }
4543
4544    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
4545    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
4546    /// with higher values being drawn on top.
4547    ///
4548    /// When `content_mask` is provided, the deferred element will be clipped to that region during
4549    /// both prepaint and paint. When `None`, no additional clipping is applied.
4550    ///
4551    /// This method should only be called as part of the prepaint phase of element drawing.
4552    pub fn defer_draw(
4553        &mut self,
4554        element: AnyElement,
4555        absolute_offset: Point<Pixels>,
4556        priority: usize,
4557        content_mask: Option<ContentMask<Pixels>>,
4558    ) {
4559        self.invalidator.debug_assert_prepaint();
4560        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4561        self.next_frame.deferred_draws.push(DeferredDraw {
4562            current_view: self.current_view(),
4563            parent_node,
4564            element_id_stack: self.element_id_stack.clone(),
4565            text_style_stack: self.text_style_stack.clone(),
4566            content_mask,
4567            rem_size: self.rem_size(),
4568            priority,
4569            element: Some(element),
4570            absolute_offset,
4571            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4572            paint_range: PaintIndex::default()..PaintIndex::default(),
4573            enclosing_retained: crate::fast::retained::enclosing_retained(self),
4574        });
4575    }
4576
4577    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
4578    /// of geometry that are non-overlapping and have the same draw order. This is typically used
4579    /// for performance reasons.
4580    ///
4581    /// This method should only be called as part of the paint phase of element drawing.
4582    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4583        self.invalidator.debug_assert_paint();
4584
4585        let content_mask = self.content_mask();
4586        let clipped_bounds = bounds.intersect(&content_mask.bounds);
4587        if !clipped_bounds.is_empty() {
4588            self.next_frame
4589                .scene
4590                .push_layer(self.cover_bounds(clipped_bounds));
4591        }
4592
4593        let result = f(self);
4594
4595        if !clipped_bounds.is_empty() {
4596            self.next_frame.scene.pop_layer();
4597        }
4598
4599        result
4600    }
4601
4602    /// Paint the drop (non-inset) shadows from `shadows` into the scene at the current
4603    /// z-index. Inset shadows are skipped; paint those with [`Self::paint_inset_shadows`]
4604    /// after the element's background so they layer on top of the fill.
4605    ///
4606    /// This method should only be called as part of the paint phase of element drawing.
4607    pub fn paint_drop_shadows(
4608        &mut self,
4609        bounds: Bounds<Pixels>,
4610        corner_radii: Corners<Pixels>,
4611        shadows: &[BoxShadow],
4612    ) {
4613        self.invalidator.debug_assert_paint();
4614
4615        let scale_factor = self.scale_factor();
4616        let content_mask = self.snapped_content_mask();
4617        let opacity = self.element_opacity();
4618        let element_bounds = self.cover_bounds(bounds);
4619        let element_corner_radii = corner_radii.scale(scale_factor);
4620        for shadow in shadows {
4621            if shadow.inset {
4622                continue;
4623            }
4624            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4625            self.next_frame.scene.insert_primitive(Shadow {
4626                order: 0,
4627                blur_radius: shadow.blur_radius.scale(scale_factor),
4628                bounds: self.cover_bounds(shadow_bounds),
4629                content_mask,
4630                corner_radii: corner_radii.scale(scale_factor),
4631                color: shadow.color.opacity(opacity),
4632                element_bounds,
4633                element_corner_radii,
4634                inset: 0,
4635                pad: 0,
4636            });
4637        }
4638    }
4639
4640    /// Paint the inset shadows from `shadows` into the scene at the current z-index. Should
4641    /// be called after the element's background so the shadow layers on top of the fill.
4642    /// Drop shadows are skipped; paint those with [`Self::paint_drop_shadows`] before the background.
4643    pub fn paint_inset_shadows(
4644        &mut self,
4645        bounds: Bounds<Pixels>,
4646        corner_radii: Corners<Pixels>,
4647        shadows: &[BoxShadow],
4648    ) {
4649        self.invalidator.debug_assert_paint();
4650
4651        let scale_factor = self.scale_factor();
4652        let content_mask = self.snapped_content_mask();
4653        let opacity = self.element_opacity();
4654        let element_bounds = self.cover_bounds(bounds);
4655        let element_corner_radii = corner_radii.scale(scale_factor);
4656        for shadow in shadows {
4657            if !shadow.inset {
4658                continue;
4659            }
4660            let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4661            // Clamp at zero so a large spread can't produce negative radii, which would
4662            // break the SDF in the shader.
4663            let zero = Pixels::ZERO;
4664            let hole_corner_radii = Corners {
4665                top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4666                top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4667                bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4668                bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4669            };
4670            self.next_frame.scene.insert_primitive(Shadow {
4671                order: 0,
4672                blur_radius: shadow.blur_radius.scale(scale_factor),
4673                bounds: self.cover_bounds(hole),
4674                content_mask,
4675                corner_radii: hole_corner_radii.scale(scale_factor),
4676                color: shadow.color.opacity(opacity),
4677                element_bounds,
4678                element_corner_radii,
4679                inset: 1,
4680                pad: 0,
4681            });
4682        }
4683    }
4684
4685    fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4686        let radii = &quad.corner_radii;
4687        let widths = &quad.border_widths;
4688        let edge_radii = Edges {
4689            top: radii.top_left.max(radii.top_right),
4690            right: radii.top_right.max(radii.bottom_right),
4691            bottom: radii.bottom_left.max(radii.bottom_right),
4692            left: radii.top_left.max(radii.bottom_left),
4693        };
4694
4695        let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4696        let inset_bounds = |top_left_inset, bottom_right_inset| {
4697            Bounds::from_corners(
4698                quad.bounds.origin + top_left_inset + antialias_inset,
4699                quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4700            )
4701        };
4702
4703        // Rounded corners need only be excluded on one axis. Either candidate
4704        // is empty of border pixels, so use the larger interior.
4705        let horizontal_band = inset_bounds(
4706            point(widths.left, widths.top.max(edge_radii.top)),
4707            point(widths.right, widths.bottom.max(edge_radii.bottom)),
4708        );
4709        let vertical_band = inset_bounds(
4710            point(widths.left.max(edge_radii.left), widths.top),
4711            point(widths.right.max(edge_radii.right), widths.bottom),
4712        );
4713
4714        let area = |bounds: &Bounds<ScaledPixels>| {
4715            bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4716        };
4717        if area(&horizontal_band) >= area(&vertical_band) {
4718            horizontal_band
4719        } else {
4720            vertical_band
4721        }
4722    }
4723
4724    /// Paint one or more quads into the scene for the next frame at the current stacking context.
4725    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
4726    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
4727    ///
4728    /// This method should only be called as part of the paint phase of element drawing.
4729    ///
4730    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
4731    /// where the circular arcs meet. This will not display well when combined with dashed borders.
4732    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
4733    pub fn paint_quad(&mut self, quad: PaintQuad) {
4734        self.invalidator.debug_assert_paint();
4735
4736        let opacity = self.element_opacity();
4737        let snapped_bounds = self.snap_bounds(quad.bounds);
4738        let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4739        let quad = Quad {
4740            order: 0,
4741            bounds: snapped_bounds,
4742            content_mask: self.snapped_content_mask(),
4743            background: quad.background.opacity(opacity),
4744            border_color: quad.border_color.opacity(opacity),
4745            corner_radii: quad.corner_radii.scale(self.scale_factor()),
4746            border_widths: snapped_border_widths,
4747            border_style: quad.border_style,
4748        };
4749
4750        if !quad.background.is_transparent() {
4751            self.next_frame.scene.insert_primitive(quad);
4752            return;
4753        }
4754
4755        // Splitting a border-only quad around its empty interior avoids shading
4756        // every transparent pixel inside large outlines.
4757        let outer_bounds = quad.bounds;
4758        let inner_bounds = Self::largest_border_interior(&quad);
4759
4760        if inner_bounds.is_empty() {
4761            self.next_frame.scene.insert_primitive(quad);
4762            return;
4763        }
4764
4765        let strips = [
4766            // Top
4767            Bounds::from_corners(
4768                outer_bounds.origin,
4769                point(outer_bounds.right(), inner_bounds.top()),
4770            ),
4771            // Bottom
4772            Bounds::from_corners(
4773                point(outer_bounds.left(), inner_bounds.bottom()),
4774                outer_bounds.bottom_right(),
4775            ),
4776            // Left
4777            Bounds::from_corners(
4778                point(outer_bounds.left(), inner_bounds.top()),
4779                inner_bounds.bottom_left(),
4780            ),
4781            // Right
4782            Bounds::from_corners(
4783                inner_bounds.top_right(),
4784                point(outer_bounds.right(), inner_bounds.bottom()),
4785            ),
4786        ];
4787
4788        for strip in strips {
4789            let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4790            if !content_mask_bounds.is_empty() {
4791                self.next_frame.scene.insert_primitive(Quad {
4792                    content_mask: ContentMask {
4793                        bounds: content_mask_bounds,
4794                    },
4795                    ..quad
4796                });
4797            }
4798        }
4799    }
4800
4801    /// Paint the given `Path` into the scene for the next frame at the current z-index.
4802    ///
4803    /// This method should only be called as part of the paint phase of element drawing.
4804    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4805        self.invalidator.debug_assert_paint();
4806
4807        let scale_factor = self.scale_factor();
4808        let content_mask = self.content_mask();
4809        let opacity = self.element_opacity();
4810        path.content_mask = content_mask;
4811        let color: Background = color.into();
4812        path.color = color.opacity(opacity);
4813        self.next_frame
4814            .scene
4815            .insert_primitive(crate::fast::layers::paint::snap_path(
4816                path.scale(scale_factor),
4817            ));
4818    }
4819
4820    /// Paint an underline into the scene for the next frame at the current z-index.
4821    ///
4822    /// This method should only be called as part of the paint phase of element drawing.
4823    pub fn paint_underline(
4824        &mut self,
4825        origin: Point<Pixels>,
4826        width: Pixels,
4827        style: &UnderlineStyle,
4828    ) {
4829        self.invalidator.debug_assert_paint();
4830        let underline = self.underline(origin, width, style);
4831        self.next_frame.scene.insert_primitive(underline);
4832    }
4833
4834    /// Paint a strikethrough into the scene for the next frame at the current z-index.
4835    ///
4836    /// This method should only be called as part of the paint phase of element drawing.
4837    pub fn paint_strikethrough(
4838        &mut self,
4839        origin: Point<Pixels>,
4840        width: Pixels,
4841        style: &StrikethroughStyle,
4842    ) {
4843        self.invalidator.debug_assert_paint();
4844
4845        let scale_factor = self.scale_factor();
4846        let height = style.thickness;
4847        let bounds = Bounds {
4848            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4849            size: size(self.snap_stroke(width), self.snap_stroke(height)),
4850        };
4851        let opacity = self.element_opacity();
4852
4853        self.next_frame.scene.insert_primitive(Underline {
4854            order: 0,
4855            pad: 0,
4856            bounds,
4857            content_mask: self.snapped_content_mask(),
4858            thickness: self.snap_stroke(style.thickness),
4859            color: style.color.unwrap_or_default().opacity(opacity),
4860            wavy: false.into(),
4861        });
4862    }
4863
4864    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
4865    ///
4866    /// The y component of the origin is the baseline of the glyph.
4867    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
4868    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
4869    /// This method is only useful if you need to paint a single glyph that has already been shaped.
4870    ///
4871    /// This method should only be called as part of the paint phase of element drawing.
4872    pub fn paint_glyph(
4873        &mut self,
4874        origin: Point<Pixels>,
4875        font_id: FontId,
4876        glyph_id: GlyphId,
4877        font_size: Pixels,
4878        color: Hsla,
4879    ) -> Result<()> {
4880        self.invalidator.debug_assert_paint();
4881
4882        let element_opacity = self.element_opacity();
4883        let scale_factor = self.scale_factor();
4884        let glyph_origin = origin.scale(scale_factor);
4885
4886        let (integer_origin, subpixel_variant) = crate::fast::glyphs::quantize_origin(glyph_origin);
4887        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4888        let dilation = self.text_system().glyph_dilation_for_color(color);
4889        let params = RenderGlyphParams {
4890            font_id,
4891            glyph_id,
4892            font_size,
4893            subpixel_variant,
4894            scale_factor,
4895            is_emoji: false,
4896            subpixel_rendering,
4897            dilation,
4898        };
4899
4900        let raster_bounds = self.text_system().raster_bounds(&params)?;
4901        if !raster_bounds.is_zero() {
4902            let tile = self
4903                .sprite_atlas
4904                .get_or_insert_with(params.clone().into(), &mut || {
4905                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
4906                    Ok(Some((size, Cow::Owned(bytes))))
4907                })?
4908                .expect("Callback above only errors or returns Some");
4909            let bounds = Bounds {
4910                origin: integer_origin + raster_bounds.origin.map(Into::into),
4911                size: tile.bounds.size.map(Into::into),
4912            };
4913            let content_mask = self.snapped_content_mask();
4914
4915            if subpixel_rendering {
4916                self.next_frame.scene.insert_primitive(SubpixelSprite {
4917                    order: 0,
4918                    pad: 0,
4919                    bounds,
4920                    content_mask,
4921                    color: color.opacity(element_opacity),
4922                    tile,
4923                    transformation: TransformationMatrix::unit(),
4924                });
4925            } else {
4926                self.next_frame.scene.insert_primitive(MonochromeSprite {
4927                    order: 0,
4928                    pad: 0,
4929                    bounds,
4930                    content_mask,
4931                    color: color.opacity(element_opacity),
4932                    tile,
4933                    transformation: TransformationMatrix::unit(),
4934                });
4935            }
4936        }
4937        Ok(())
4938    }
4939
4940    pub(crate) fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4941        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4942            return false;
4943        }
4944
4945        if !self.platform_window.is_subpixel_rendering_supported() {
4946            return false;
4947        }
4948
4949        let mode = match self.text_rendering_mode.get() {
4950            TextRenderingMode::PlatformDefault => self
4951                .text_system()
4952                .recommended_rendering_mode(font_id, font_size),
4953            mode => mode,
4954        };
4955
4956        mode == TextRenderingMode::Subpixel
4957    }
4958
4959    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
4960    ///
4961    /// The y component of the origin is the baseline of the glyph.
4962    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
4963    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
4964    /// This method is only useful if you need to paint a single emoji that has already been shaped.
4965    ///
4966    /// This method should only be called as part of the paint phase of element drawing.
4967    pub fn paint_emoji(
4968        &mut self,
4969        origin: Point<Pixels>,
4970        font_id: FontId,
4971        glyph_id: GlyphId,
4972        font_size: Pixels,
4973    ) -> Result<()> {
4974        self.invalidator.debug_assert_paint();
4975
4976        let scale_factor = self.scale_factor();
4977        let glyph_origin = origin.scale(scale_factor);
4978        let integer_origin = crate::fast::glyphs::quantize_emoji_origin(glyph_origin);
4979        let params = RenderGlyphParams {
4980            font_id,
4981            glyph_id,
4982            font_size,
4983            subpixel_variant: Default::default(),
4984            scale_factor,
4985            is_emoji: true,
4986            subpixel_rendering: false,
4987            dilation: 0,
4988        };
4989
4990        let raster_bounds = self.text_system().raster_bounds(&params)?;
4991        if !raster_bounds.is_zero() {
4992            let tile = self
4993                .sprite_atlas
4994                .get_or_insert_with(params.clone().into(), &mut || {
4995                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
4996                    Ok(Some((size, Cow::Owned(bytes))))
4997                })?
4998                .expect("Callback above only errors or returns Some");
4999
5000            let bounds = Bounds {
5001                origin: integer_origin + raster_bounds.origin.map(Into::into),
5002                size: tile.bounds.size.map(Into::into),
5003            };
5004            let content_mask = self.snapped_content_mask();
5005            let opacity = self.element_opacity();
5006
5007            self.next_frame.scene.insert_primitive(PolychromeSprite {
5008                order: 0,
5009                pad: 0,
5010                grayscale: false.into(),
5011                bounds,
5012                corner_radii: Default::default(),
5013                content_mask,
5014                tile,
5015                opacity,
5016            });
5017        }
5018        Ok(())
5019    }
5020
5021    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
5022    ///
5023    /// This method should only be called as part of the paint phase of element drawing.
5024    pub fn paint_svg(
5025        &mut self,
5026        bounds: Bounds<Pixels>,
5027        path: SharedString,
5028        mut data: Option<&[u8]>,
5029        transformation: TransformationMatrix,
5030        color: Hsla,
5031        cx: &App,
5032    ) -> Result<()> {
5033        self.invalidator.debug_assert_paint();
5034
5035        let element_opacity = self.element_opacity();
5036        let bounds = self.snap_bounds(bounds);
5037
5038        let params = RenderSvgParams {
5039            path,
5040            size: bounds.size.map(|pixels| {
5041                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
5042            }),
5043        };
5044
5045        let Some(tile) =
5046            self.sprite_atlas
5047                .get_or_insert_with(params.clone().into(), &mut || {
5048                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
5049                    else {
5050                        return Ok(None);
5051                    };
5052                    Ok(Some((size, Cow::Owned(bytes))))
5053                })?
5054        else {
5055            return Ok(());
5056        };
5057        let content_mask = self.snapped_content_mask();
5058        let svg_bounds = Bounds {
5059            origin: bounds.center()
5060                - Point::new(
5061                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5062                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5063                ),
5064            size: tile
5065                .bounds
5066                .size
5067                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
5068        };
5069        let final_bounds = svg_bounds
5070            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
5071            .map_size(|size| size.ceil());
5072
5073        self.next_frame.scene.insert_primitive(MonochromeSprite {
5074            order: 0,
5075            pad: 0,
5076            bounds: final_bounds,
5077            content_mask,
5078            color: color.opacity(element_opacity),
5079            tile,
5080            transformation,
5081        });
5082
5083        Ok(())
5084    }
5085
5086    /// Paint an image into the scene for the next frame at the current z-index.
5087    /// This method will panic if the frame_index is not valid
5088    ///
5089    /// This method should only be called as part of the paint phase of element drawing.
5090    /// Paint an image into `bounds`, positioning and scaling it according to `image_bounds`.
5091    ///
5092    /// The visible region rendered is `bounds.intersect(&image_bounds)`, with `corner_radii`
5093    /// applied to `bounds`.
5094    pub fn paint_image(
5095        &mut self,
5096        bounds: Bounds<Pixels>,
5097        image_bounds: Bounds<Pixels>,
5098        corner_radii: Corners<Pixels>,
5099        data: Arc<RenderImage>,
5100        frame_index: usize,
5101        grayscale: bool,
5102    ) -> Result<()> {
5103        self.invalidator.debug_assert_paint();
5104
5105        let visible_bounds = bounds.intersect(&image_bounds);
5106        if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
5107            return Ok(());
5108        }
5109        if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
5110            return Ok(());
5111        }
5112
5113        let params = RenderImageParams {
5114            image_id: data.id,
5115            frame_index,
5116        };
5117
5118        let tile = self
5119            .sprite_atlas
5120            .get_or_insert_with(params.into(), &mut || {
5121                Ok(Some((
5122                    data.size(frame_index),
5123                    Cow::Borrowed(
5124                        data.as_bytes(frame_index)
5125                            .expect("It's the caller's job to pass a valid frame index"),
5126                    ),
5127                )))
5128            })?
5129            .expect("Callback above only returns Some");
5130
5131        let visible_bounds_snapped = self.snap_bounds(visible_bounds);
5132
5133        let sub_tile = if visible_bounds == image_bounds {
5134            tile
5135        } else {
5136            let x_offset_ratio =
5137                (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
5138            let y_offset_ratio =
5139                (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
5140            let width_ratio = visible_bounds.size.width / image_bounds.size.width;
5141            let height_ratio = visible_bounds.size.height / image_bounds.size.height;
5142
5143            let tile_origin_x = tile.bounds.origin.x.0;
5144            let tile_origin_y = tile.bounds.origin.y.0;
5145            let tile_width = tile.bounds.size.width.0;
5146            let tile_height = tile.bounds.size.height.0;
5147
5148            let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
5149            let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
5150            let sub_width = (width_ratio * tile_width as f32).round() as i32;
5151            let sub_height = (height_ratio * tile_height as f32).round() as i32;
5152
5153            let max_x = tile_origin_x + tile_width;
5154            let max_y = tile_origin_y + tile_height;
5155
5156            let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
5157            let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
5158            let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
5159            let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
5160
5161            AtlasTile {
5162                bounds: Bounds {
5163                    origin: point(
5164                        DevicePixels(clamped_origin_x),
5165                        DevicePixels(clamped_origin_y),
5166                    ),
5167                    size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
5168                },
5169                ..tile
5170            }
5171        };
5172
5173        let content_mask = self.snapped_content_mask();
5174        let corner_radii = corner_radii
5175            .clamp_radii_for_quad_size(visible_bounds.size)
5176            .scale(self.scale_factor());
5177        let opacity = self.element_opacity();
5178
5179        self.next_frame.scene.insert_primitive(PolychromeSprite {
5180            order: 0,
5181            pad: 0,
5182            grayscale: grayscale.into(),
5183            bounds: visible_bounds_snapped,
5184            content_mask,
5185            corner_radii,
5186            tile: sub_tile,
5187            opacity,
5188        });
5189        Ok(())
5190    }
5191
5192    /// Paint a surface into the scene for the next frame at the current z-index.
5193    ///
5194    /// This method should only be called as part of the paint phase of element drawing.
5195    #[cfg(any(target_os = "macos", target_os = "ios"))]
5196    pub fn paint_surface(
5197        &mut self,
5198        bounds: Bounds<Pixels>,
5199        image_buffer: CFRetained<CVPixelBuffer>,
5200    ) {
5201        use crate::PaintSurface;
5202
5203        self.invalidator.debug_assert_paint();
5204
5205        let bounds = self.snap_bounds(bounds);
5206        let content_mask = self.snapped_content_mask();
5207        self.next_frame.scene.insert_primitive(PaintSurface {
5208            order: 0,
5209            bounds,
5210            content_mask,
5211            image_buffer,
5212        });
5213    }
5214
5215    /// Removes an image from the sprite atlas.
5216    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
5217        for frame_index in 0..data.frame_count() {
5218            let params = RenderImageParams {
5219                image_id: data.id,
5220                frame_index,
5221            };
5222
5223            self.sprite_atlas.remove(&params.clone().into());
5224        }
5225
5226        Ok(())
5227    }
5228
5229    /// Returns whether every frame of an image is present in the sprite atlas.
5230    #[cfg(any(test, feature = "test-support"))]
5231    pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
5232        data.frame_count() > 0
5233            && (0..data.frame_count()).all(|frame_index| {
5234                self.sprite_atlas.contains(
5235                    &RenderImageParams {
5236                        image_id: data.id,
5237                        frame_index,
5238                    }
5239                    .into(),
5240                )
5241            })
5242    }
5243
5244    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
5245    /// layout is being requested, along with the layout ids of any children. This method is called during
5246    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
5247    ///
5248    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
5249    #[must_use]
5250    pub fn request_layout(
5251        &mut self,
5252        style: Style,
5253        children: impl IntoIterator<Item = LayoutId>,
5254        cx: &mut App,
5255    ) -> LayoutId {
5256        self.invalidator.debug_assert_prepaint();
5257
5258        cx.layout_id_buffer.clear();
5259        cx.layout_id_buffer.extend(children);
5260        let rem_size = self.rem_size();
5261        let scale_factor = self.scale_factor();
5262
5263        let fast_key = crate::fast::layout_key::layout_key(self);
5264        self.layout_engine.as_mut().unwrap().request_layout(
5265            fast_key,
5266            style,
5267            rem_size,
5268            scale_factor,
5269            &cx.layout_id_buffer,
5270        )
5271    }
5272
5273    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
5274    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
5275    /// determine the element's size. One place this is used internally is when measuring text.
5276    ///
5277    /// The given closure is invoked at layout time with the known dimensions and available space and
5278    /// returns a `Size`.
5279    ///
5280    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
5281    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5282    where
5283        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5284            + 'static,
5285    {
5286        self.invalidator.debug_assert_prepaint();
5287
5288        let rem_size = self.rem_size();
5289        let scale_factor = self.scale_factor();
5290        let fast_key = crate::fast::layout_key::layout_key(self);
5291        self.layout_engine
5292            .as_mut()
5293            .unwrap()
5294            .request_measured_layout(fast_key, style, rem_size, scale_factor, measure)
5295    }
5296
5297    /// Compute the layout for the given id within the given available space.
5298    /// This method is called for its side effect, typically by the framework prior to painting.
5299    /// After calling it, you can request the bounds of the given layout node id or any descendant.
5300    ///
5301    /// This method should only be called as part of the prepaint phase of element drawing.
5302    pub fn compute_layout(
5303        &mut self,
5304        layout_id: LayoutId,
5305        available_space: Size<AvailableSpace>,
5306        cx: &mut App,
5307    ) {
5308        self.invalidator.debug_assert_prepaint();
5309
5310        let mut layout_engine = self.layout_engine.take().unwrap();
5311        layout_engine.compute_layout(layout_id, available_space, self, cx);
5312        self.layout_engine = Some(layout_engine);
5313    }
5314
5315    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
5316    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
5317    ///
5318    /// This method should only be called as part of element drawing.
5319    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5320        self.invalidator.debug_assert_prepaint();
5321
5322        let scale_factor = self.scale_factor();
5323        let mut bounds = self
5324            .layout_engine
5325            .as_mut()
5326            .unwrap()
5327            .layout_bounds(layout_id, scale_factor)
5328            .map(Into::into);
5329        let snapped_offset = self.pixel_snap_point(self.element_offset());
5330        bounds.origin += snapped_offset;
5331        bounds
5332    }
5333
5334    /// This method should be called during `prepaint`. You can use
5335    /// the returned [Hitbox] during `paint` or in an event handler
5336    /// to determine whether the inserted hitbox was the topmost.
5337    ///
5338    /// This method should only be called as part of the prepaint phase of element drawing.
5339    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5340        self.invalidator.debug_assert_prepaint();
5341
5342        let content_mask = crate::fast::layers::input::hitbox_mask(self);
5343        let mut id = self.next_hitbox_id;
5344        self.next_hitbox_id = self.next_hitbox_id.next();
5345        let hitbox = Hitbox {
5346            id,
5347            bounds,
5348            content_mask,
5349            behavior,
5350        };
5351        self.next_frame.hitboxes.push(hitbox.clone());
5352        hitbox
5353    }
5354
5355    /// Set a hitbox which will act as a control area of the platform window.
5356    ///
5357    /// This method should only be called as part of the paint phase of element drawing.
5358    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5359        self.invalidator.debug_assert_paint();
5360        self.next_frame.window_control_hitboxes.push((area, hitbox));
5361    }
5362
5363    /// Sets the key context for the current element. This context will be used to translate
5364    /// keybindings into actions.
5365    ///
5366    /// This method should only be called as part of the paint phase of element drawing.
5367    pub fn set_key_context(&mut self, context: KeyContext) {
5368        self.invalidator.debug_assert_paint();
5369        self.next_frame.dispatch_tree.set_key_context(context);
5370    }
5371
5372    /// Sets the focus handle for the current element. This handle will be used to manage focus state
5373    /// and keyboard event dispatch for the element.
5374    ///
5375    /// This method should only be called as part of the prepaint phase of element drawing.
5376    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5377        self.invalidator.debug_assert_prepaint();
5378        if focus_handle.is_focused(self) {
5379            self.next_frame.focus = Some(focus_handle.id);
5380        }
5381        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5382    }
5383
5384    /// Sets the view id for the current element, which will be used to manage view caching.
5385    ///
5386    /// This method should only be called as part of element prepaint. We plan on removing this
5387    /// method eventually when we solve some issues that require us to construct editor elements
5388    /// directly instead of always using editors via views.
5389    pub fn set_view_id(&mut self, view_id: EntityId) {
5390        self.invalidator.debug_assert_prepaint();
5391        self.next_frame.dispatch_tree.set_view_id(view_id);
5392    }
5393
5394    /// Get the entity ID for the currently rendering view
5395    pub fn current_view(&self) -> EntityId {
5396        self.invalidator.debug_assert_paint_or_prepaint();
5397        self.rendered_entity_stack.last().copied().unwrap()
5398    }
5399
5400    #[inline]
5401    pub(crate) fn with_rendered_view<R>(
5402        &mut self,
5403        id: EntityId,
5404        f: impl FnOnce(&mut Self) -> R,
5405    ) -> R {
5406        self.rendered_entity_stack.push(id);
5407        let result = f(self);
5408        self.rendered_entity_stack.pop();
5409        result
5410    }
5411
5412    /// Executes the provided function with the specified image cache.
5413    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5414    where
5415        F: FnOnce(&mut Self) -> R,
5416    {
5417        if let Some(image_cache) = image_cache {
5418            self.image_cache_stack.push(image_cache);
5419            let result = f(self);
5420            self.image_cache_stack.pop();
5421            result
5422        } else {
5423            f(self)
5424        }
5425    }
5426
5427    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
5428    /// platform to receive textual input with proper integration with concerns such
5429    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
5430    /// rendered.
5431    ///
5432    /// This method should only be called as part of the paint phase of element drawing.
5433    ///
5434    /// [element_input_handler]: crate::ElementInputHandler
5435    pub fn handle_input(
5436        &mut self,
5437        focus_handle: &FocusHandle,
5438        input_handler: impl InputHandler,
5439        cx: &App,
5440    ) {
5441        self.invalidator.debug_assert_paint();
5442
5443        if focus_handle.is_focused(self) {
5444            let cx = self.to_async(cx);
5445            self.next_frame
5446                .input_handlers
5447                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
5448        }
5449    }
5450
5451    /// Forwards the focused input handler's [`TextInputConfiguration`] to the
5452    /// platform window when it differs from the last forwarded value. With no
5453    /// input handler the default configuration applies, so a field's
5454    /// preferences don't outlive its focus.
5455    fn apply_text_input_configuration(&mut self, cx: &mut App) {
5456        let configuration = match self.platform_window.take_input_handler() {
5457            Some(mut input_handler) => {
5458                let configuration = input_handler.text_input_configuration(self, cx);
5459                self.platform_window.set_input_handler(input_handler);
5460                configuration
5461            }
5462            None => TextInputConfiguration::default(),
5463        };
5464        if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5465            self.platform_window
5466                .set_text_input_configuration(configuration.clone());
5467            self.last_text_input_configuration = Some(configuration);
5468        }
5469    }
5470
5471    /// Register a mouse event listener on the window for the next frame. The type of event
5472    /// is determined by the first parameter of the given listener. When the next frame is rendered
5473    /// the listener will be cleared.
5474    ///
5475    /// This method should only be called as part of the paint phase of element drawing.
5476    pub fn on_mouse_event<Event: MouseEvent>(
5477        &mut self,
5478        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5479    ) {
5480        self.invalidator.debug_assert_paint();
5481
5482        self.next_frame.mouse_listeners.push(Some(Box::new(
5483            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5484                if let Some(event) = event.downcast_ref() {
5485                    listener(event, phase, window, cx)
5486                }
5487            },
5488        )));
5489    }
5490
5491    /// Register a key event listener on this node for the next frame. The type of event
5492    /// is determined by the first parameter of the given listener. When the next frame is rendered
5493    /// the listener will be cleared.
5494    ///
5495    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
5496    /// a specific need to register a listener yourself.
5497    ///
5498    /// This method should only be called as part of the paint phase of element drawing.
5499    pub fn on_key_event<Event: KeyEvent>(
5500        &mut self,
5501        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5502    ) {
5503        self.invalidator.debug_assert_paint();
5504
5505        self.next_frame.dispatch_tree.on_key_event(Rc::new(
5506            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5507                if let Some(event) = event.downcast_ref::<Event>() {
5508                    listener(event, phase, window, cx)
5509                }
5510            },
5511        ));
5512    }
5513
5514    /// Register a modifiers changed event listener on the window for the next frame.
5515    ///
5516    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
5517    /// a specific need to register a global listener.
5518    ///
5519    /// This method should only be called as part of the paint phase of element drawing.
5520    pub fn on_modifiers_changed(
5521        &mut self,
5522        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5523    ) {
5524        self.invalidator.debug_assert_paint();
5525
5526        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
5527            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5528                listener(event, window, cx)
5529            },
5530        ));
5531    }
5532
5533    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
5534    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
5535    /// Returns a subscription and persists until the subscription is dropped.
5536    pub fn on_focus_in(
5537        &mut self,
5538        handle: &FocusHandle,
5539        cx: &mut App,
5540        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5541    ) -> Subscription {
5542        let focus_id = handle.id;
5543        let (subscription, activate) =
5544            self.new_focus_listener(Box::new(move |event, window, cx| {
5545                if event.is_focus_in(focus_id) {
5546                    listener(window, cx);
5547                }
5548                true
5549            }));
5550        cx.defer(move |_| activate());
5551        subscription
5552    }
5553
5554    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
5555    /// Returns a subscription and persists until the subscription is dropped.
5556    pub fn on_focus_out(
5557        &mut self,
5558        handle: &FocusHandle,
5559        cx: &mut App,
5560        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5561    ) -> Subscription {
5562        let focus_id = handle.id;
5563        let (subscription, activate) =
5564            self.new_focus_listener(Box::new(move |event, window, cx| {
5565                if let Some(blurred_id) = event.previous_focus_path.last().copied()
5566                    && event.is_focus_out(focus_id)
5567                {
5568                    let event = FocusOutEvent {
5569                        blurred: WeakFocusHandle {
5570                            id: blurred_id,
5571                            handles: Arc::downgrade(&cx.focus_handles),
5572                        },
5573                    };
5574                    listener(event, window, cx)
5575                }
5576                true
5577            }));
5578        cx.defer(move |_| activate());
5579        subscription
5580    }
5581
5582    fn reset_cursor_style(&self, cx: &mut App) {
5583        // Set the cursor only if we're the active window.
5584        if self.is_window_hovered() {
5585            let style = self
5586                .rendered_frame
5587                .cursor_style(self)
5588                .unwrap_or(CursorStyle::Arrow);
5589            cx.platform.set_cursor_style(style);
5590        }
5591    }
5592
5593    /// Dispatch a given keystroke as though the user had typed it.
5594    /// You can create a keystroke with Keystroke::parse("").
5595    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5596        let keystroke = keystroke.with_simulated_ime();
5597        let result = self.dispatch_event(
5598            PlatformInput::KeyDown(KeyDownEvent {
5599                keystroke: keystroke.clone(),
5600                is_held: false,
5601                prefer_character_input: false,
5602            }),
5603            cx,
5604        );
5605        if !result.propagate {
5606            return true;
5607        }
5608
5609        if let Some(input) = keystroke.key_char
5610            && let Some(mut input_handler) = self.platform_window.take_input_handler()
5611        {
5612            input_handler.dispatch_input(&input, self, cx);
5613            self.platform_window.set_input_handler(input_handler);
5614            return true;
5615        }
5616
5617        false
5618    }
5619
5620    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
5621    /// binding for the action (last binding added to the keymap).
5622    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
5623        self.highest_precedence_binding_for_action(action)
5624            .map(|binding| {
5625                binding
5626                    .keystrokes()
5627                    .iter()
5628                    .map(ToString::to_string)
5629                    .collect::<Vec<_>>()
5630                    .join(" ")
5631            })
5632            .unwrap_or_else(|| action.name().to_string())
5633    }
5634
5635    /// Dispatch a mouse, keyboard, or touch event on the window.
5636    #[profiling::function]
5637    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5638        #[cfg(feature = "profiler")]
5639        self.window_profiler.begin_input(event.kind_name());
5640        let update_count_before = self.invalidator.update_count();
5641        // Track input modality for focus-visible styling and hover suppression.
5642        // Hover is suppressed during keyboard modality so that keyboard navigation
5643        // doesn't show hover highlights on the item under the mouse cursor.
5644        let old_modality = self.last_input_modality;
5645        self.last_input_modality = match &event {
5646            PlatformInput::KeyDown(_) => InputModality::Keyboard,
5647            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5648            PlatformInput::Touch(_) => InputModality::Touch,
5649            _ => self.last_input_modality,
5650        };
5651        if self.last_input_modality != old_modality {
5652            self.refresh();
5653        }
5654
5655        let ambient = crate::fast::dependencies::AmbientInput::of(self);
5656        // Handlers may set this to false by calling `stop_propagation`.
5657        cx.propagate_event = true;
5658        // Handlers may set this to true by calling `prevent_default`.
5659        self.default_prevented = false;
5660
5661        let event = match event {
5662            // Track the mouse position with our own state, since accessing the platform
5663            // API for the mouse position can only occur on the main thread.
5664            PlatformInput::MouseMove(mouse_move) => {
5665                self.mouse_position = mouse_move.position;
5666                self.modifiers = mouse_move.modifiers;
5667                PlatformInput::MouseMove(mouse_move)
5668            }
5669            PlatformInput::MouseDown(mouse_down) => {
5670                self.mouse_position = mouse_down.position;
5671                self.modifiers = mouse_down.modifiers;
5672                PlatformInput::MouseDown(mouse_down)
5673            }
5674            PlatformInput::MouseUp(mouse_up) => {
5675                self.mouse_position = mouse_up.position;
5676                self.modifiers = mouse_up.modifiers;
5677                PlatformInput::MouseUp(mouse_up)
5678            }
5679            PlatformInput::MousePressure(mouse_pressure) => {
5680                PlatformInput::MousePressure(mouse_pressure)
5681            }
5682            PlatformInput::MouseExited(mouse_exited) => {
5683                self.modifiers = mouse_exited.modifiers;
5684                PlatformInput::MouseExited(mouse_exited)
5685            }
5686            PlatformInput::ModifiersChanged(modifiers_changed) => {
5687                self.modifiers = modifiers_changed.modifiers;
5688                self.capslock = modifiers_changed.capslock;
5689                PlatformInput::ModifiersChanged(modifiers_changed)
5690            }
5691            PlatformInput::ScrollWheel(scroll_wheel) => {
5692                self.mouse_position = scroll_wheel.position;
5693                self.modifiers = scroll_wheel.modifiers;
5694                PlatformInput::ScrollWheel(scroll_wheel)
5695            }
5696            PlatformInput::Pinch(pinch) => {
5697                self.mouse_position = pinch.position;
5698                self.modifiers = pinch.modifiers;
5699                PlatformInput::Pinch(pinch)
5700            }
5701            // Translate dragging and dropping of external files from the operating system
5702            // to internal drag and drop events.
5703            PlatformInput::FileDrop(file_drop) => match file_drop {
5704                FileDropEvent::Entered { position, paths } => {
5705                    self.mouse_position = position;
5706                    let source_window = self.handle.window_id();
5707                    if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5708                        cx.active_drag = Some(AnyDrag {
5709                            value: Arc::new(paths.clone()),
5710                            view: cx.new(|_| paths).into(),
5711                            cursor_offset: position,
5712                            cursor_style: None,
5713                            external_payload_source: None,
5714                        });
5715                    }
5716                    PlatformInput::MouseMove(MouseMoveEvent {
5717                        position,
5718                        pressed_button: Some(MouseButton::Left),
5719                        modifiers: Modifiers::default(),
5720                    })
5721                }
5722                FileDropEvent::Pending { position } => {
5723                    self.mouse_position = position;
5724                    PlatformInput::MouseMove(MouseMoveEvent {
5725                        position,
5726                        pressed_button: Some(MouseButton::Left),
5727                        modifiers: Modifiers::default(),
5728                    })
5729                }
5730                FileDropEvent::Submit { position } => {
5731                    cx.activate(true);
5732                    self.mouse_position = position;
5733                    PlatformInput::MouseUp(MouseUpEvent {
5734                        button: MouseButton::Left,
5735                        position,
5736                        modifiers: Modifiers::default(),
5737                        click_count: 1,
5738                    })
5739                }
5740                FileDropEvent::Exited => {
5741                    if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5742                        cx.active_drag.take();
5743                    }
5744                    self.refresh();
5745                    PlatformInput::FileDrop(FileDropEvent::Exited)
5746                }
5747                FileDropEvent::Ended => {
5748                    cx.end_platform_drag(self.handle.window_id());
5749                    self.refresh();
5750                    PlatformInput::FileDrop(FileDropEvent::Ended)
5751                }
5752            },
5753            PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5754            PlatformInput::LongPress(long_press) => {
5755                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5756                    long_press.start_position
5757                } else {
5758                    long_press.position
5759                };
5760                if long_press.phase == crate::TouchPhase::Started {
5761                    self.long_press_capture = None;
5762                }
5763                PlatformInput::LongPress(long_press)
5764            }
5765            PlatformInput::TouchDrag(touch_drag) => {
5766                self.mouse_position = touch_drag.start_position;
5767                PlatformInput::TouchDrag(touch_drag)
5768            }
5769            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5770        };
5771        crate::fast::dependencies::AmbientInput::stamp_changes(ambient, self, cx);
5772        crate::fast::layers::input::before_dispatch(self, cx, &event);
5773
5774        if let Some(any_mouse_event) = event.mouse_event() {
5775            self.dispatch_mouse_event(any_mouse_event, cx);
5776        } else if let Some(any_key_event) = event.keyboard_event() {
5777            self.dispatch_key_event(any_key_event, cx);
5778        } else if let Some(touch_event) = event.touch_event() {
5779            self.dispatch_touch_event(touch_event, cx);
5780        }
5781        crate::fast::layers::wheel::end_dispatch(self, cx);
5782        if let PlatformInput::LongPress(long_press) = &event {
5783            match long_press.phase {
5784                crate::TouchPhase::Started if !self.default_prevented => {
5785                    self.long_press_capture = None;
5786                }
5787                crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
5788                    self.long_press_capture = None;
5789                }
5790                crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
5791            }
5792        }
5793
5794        // Must run after the move is dispatched: the platform owns the gesture afterwards, so this
5795        // is the last chance for drag listeners to see the pointer leave and reset their state.
5796        self.promote_external_drag_to_platform(&event, cx);
5797
5798        let caused_invalidation = self.invalidator.update_count() > update_count_before;
5799        if caused_invalidation {
5800            self.input_rate_tracker.borrow_mut().record_input();
5801        }
5802        #[cfg(feature = "profiler")]
5803        self.window_profiler.end_input(caused_invalidation);
5804
5805        DispatchEventResult {
5806            propagate: cx.propagate_event,
5807            default_prevented: self.default_prevented,
5808        }
5809    }
5810
5811    fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5812        let PlatformInput::MouseMove(mouse_move) = event else {
5813            return;
5814        };
5815        if mouse_move.pressed_button != Some(MouseButton::Left) {
5816            return;
5817        }
5818        if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5819            return;
5820        }
5821        if !self.platform_window.can_start_external_drag() {
5822            return;
5823        }
5824        let Some(payload_source) = cx
5825            .active_drag
5826            .as_mut()
5827            .and_then(|drag| drag.external_payload_source.take())
5828        else {
5829            return;
5830        };
5831        let Some(payload) = payload_source(self, cx) else {
5832            return;
5833        };
5834        if self.platform_window.start_external_drag(&payload)
5835            && cx.hand_active_drag_to_platform(self.handle.window_id())
5836        {
5837            self.refresh();
5838        }
5839    }
5840
5841    /// Whether recognized touch pans may use the platform's predicted touch
5842    /// positions ([`TouchEvent::predicted_position`]) to compensate for input
5843    /// latency. Defaults to true.
5844    pub fn touch_prediction_enabled(&self) -> bool {
5845        self.touch_prediction_enabled
5846    }
5847
5848    /// Sets whether recognized touch pans may use the platform's predicted
5849    /// touch positions. Disabling drops [`TouchEvent::predicted_position`]
5850    /// before gesture recognition, so pans track only raw touch positions.
5851    pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
5852        self.touch_prediction_enabled = enabled;
5853    }
5854
5855    /// Runs the portable gesture recognizer over a raw touch event and
5856    /// dispatches whatever it resolves (scroll steps, synthesized taps)
5857    /// through the ordinary mouse-event path.
5858    fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
5859        let mut event = event.clone();
5860        if !self.touch_prediction_enabled {
5861            event.predicted_position = None;
5862        }
5863        let recognized_gestures = self.touch_gestures.handle_event(&event);
5864        if event.phase == crate::TouchPhase::Started
5865            && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
5866        {
5867            self.dispatch_recognized_touch_gesture(touch_drag, cx);
5868        }
5869        if event.phase == crate::TouchPhase::Started
5870            && self.touch_gestures.pending_long_press().is_some()
5871        {
5872            self.long_press_capture = None;
5873        }
5874        let mut tapped = false;
5875        for gesture in recognized_gestures {
5876            tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
5877            self.dispatch_recognized_touch_gesture(gesture, cx);
5878        }
5879        if event.phase == crate::TouchPhase::Started {
5880            self.schedule_long_press_timer(cx);
5881        } else if self.touch_gestures.pending_long_press().is_none() {
5882            self.long_press_timer.take();
5883        }
5884        // The platform's touch-release handler may inspect the input handler
5885        // as soon as this dispatch returns (the web platform decides virtual
5886        // keyboard visibility there, inside the user gesture). Input handlers
5887        // are registered during draw, so draw now to make them reflect any
5888        // focus change the tap just caused.
5889        if tapped && self.invalidator.is_dirty() {
5890            self.draw(cx).clear(cx);
5891        }
5892        if self.touch_gestures.has_momentum() {
5893            self.schedule_touch_momentum_tick();
5894        }
5895    }
5896
5897    fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
5898        match gesture {
5899            RecognizedTouchGesture::Scroll(scroll_wheel) => {
5900                self.mouse_position = scroll_wheel.position;
5901                cx.propagate_event = true;
5902                self.dispatch_mouse_event(&scroll_wheel, cx);
5903            }
5904            RecognizedTouchGesture::Tap { down, up } => {
5905                self.mouse_position = up.position;
5906                cx.propagate_event = true;
5907                self.dispatch_mouse_event(&down, cx);
5908                cx.propagate_event = true;
5909                self.dispatch_mouse_event(&up, cx);
5910            }
5911            RecognizedTouchGesture::TouchDrag(touch_drag) => {
5912                self.mouse_position = touch_drag.start_position;
5913                cx.propagate_event = true;
5914                self.default_prevented = false;
5915                let started = touch_drag.phase == crate::TouchPhase::Started;
5916                self.dispatch_mouse_event(&touch_drag, cx);
5917                if started {
5918                    self.touch_gestures
5919                        .resolve_touch_drag(self.default_prevented);
5920                }
5921            }
5922            RecognizedTouchGesture::LongPress(long_press) => {
5923                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5924                    long_press.start_position
5925                } else {
5926                    long_press.position
5927                };
5928                cx.propagate_event = true;
5929                self.default_prevented = false;
5930                let started = long_press.phase == crate::TouchPhase::Started;
5931                let ended = matches!(
5932                    long_press.phase,
5933                    crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
5934                );
5935                self.dispatch_mouse_event(&long_press, cx);
5936                if started {
5937                    let claimed = self.default_prevented;
5938                    self.touch_gestures.resolve_long_press(claimed);
5939                    if !claimed {
5940                        self.long_press_capture = None;
5941                    }
5942                }
5943                if ended {
5944                    self.long_press_capture = None;
5945                }
5946            }
5947        }
5948    }
5949
5950    fn schedule_long_press_timer(&mut self, cx: &mut App) {
5951        self.long_press_timer.take();
5952        let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
5953            return;
5954        };
5955        self.long_press_timer = Some(self.spawn(cx, async move |cx| {
5956            cx.background_executor.timer(duration).await;
5957            cx.update(move |window, cx| {
5958                window.long_press_timer.take();
5959                if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
5960                    window.dispatch_recognized_touch_gesture(gesture, cx);
5961                }
5962            })
5963            .log_err();
5964        }));
5965    }
5966
5967    fn schedule_touch_momentum_tick(&mut self) {
5968        self.on_next_frame(|window, cx| {
5969            if let Some(gesture) = window.touch_gestures.tick_momentum() {
5970                window.dispatch_recognized_touch_gesture(gesture, cx);
5971            }
5972            if window.touch_gestures.has_momentum() {
5973                window.schedule_touch_momentum_tick();
5974            }
5975        });
5976    }
5977
5978    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5979        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
5980        if hit_test != self.mouse_hit_test {
5981            self.mouse_hit_test = hit_test;
5982            self.reset_cursor_style(cx);
5983        }
5984
5985        #[cfg(any(feature = "inspector", debug_assertions))]
5986        if self.is_inspector_picking(cx) {
5987            self.handle_inspector_mouse_event(event, cx);
5988            // When inspector is picking, all other mouse handling is skipped.
5989            return;
5990        }
5991
5992        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
5993
5994        // Capture phase, events bubble from back to front. Handlers for this phase are used for
5995        // special purposes, such as detecting events outside of a given Bounds.
5996        for listener in &mut mouse_listeners {
5997            let listener = listener.as_mut().unwrap();
5998            listener(event, DispatchPhase::Capture, self, cx);
5999            if !cx.propagate_event {
6000                break;
6001            }
6002        }
6003
6004        // Bubble phase, where most normal handlers do their work.
6005        if cx.propagate_event {
6006            for listener in mouse_listeners.iter_mut().rev() {
6007                let listener = listener.as_mut().unwrap();
6008                listener(event, DispatchPhase::Bubble, self, cx);
6009                if !cx.propagate_event {
6010                    break;
6011                }
6012            }
6013        }
6014
6015        self.rendered_frame.mouse_listeners = mouse_listeners;
6016
6017        if cx.has_active_drag() {
6018            if event.is::<MouseMoveEvent>() {
6019                // If this was a mouse move event, redraw the window so that the
6020                // active drag can follow the mouse cursor.
6021                self.refresh();
6022            } else if event.is::<MouseUpEvent>() {
6023                // If this was a mouse up event, cancel the active drag and redraw
6024                // the window.
6025                cx.active_drag = None;
6026                self.refresh();
6027            }
6028        }
6029
6030        // Auto-release pointer capture on mouse up
6031        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
6032            self.captured_hitbox = None;
6033        }
6034    }
6035
6036    // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
6037    // we prefer the text input over bindings.
6038    fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
6039        let prefer_character_input = event
6040            .downcast_ref::<KeyDownEvent>()
6041            .is_some_and(|key_down_event| key_down_event.prefer_character_input);
6042        if !prefer_character_input {
6043            return InputPreference::KeyBindings;
6044        }
6045        let Some(mut input_handler) = self.platform_window.take_input_handler() else {
6046            return InputPreference::KeyBindings;
6047        };
6048        let accepts_text_input = input_handler.accepts_text_input(self, cx);
6049        self.platform_window.set_input_handler(input_handler);
6050        if accepts_text_input {
6051            InputPreference::CharacterInput
6052        } else {
6053            InputPreference::KeyBindings
6054        }
6055    }
6056
6057    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
6058        if self.invalidator.is_dirty() {
6059            self.draw(cx).clear(cx);
6060        }
6061
6062        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6063        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6064
6065        let mut keystroke: Option<Keystroke> = None;
6066
6067        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
6068            if event.modifiers.number_of_modifiers() == 0
6069                && self.pending_modifier.modifiers.number_of_modifiers() == 1
6070                && !self.pending_modifier.saw_other_input
6071            {
6072                let key = match self.pending_modifier.modifiers {
6073                    modifiers if modifiers.shift => Some("shift"),
6074                    modifiers if modifiers.control => Some("control"),
6075                    modifiers if modifiers.alt => Some("alt"),
6076                    modifiers if modifiers.platform => Some("platform"),
6077                    modifiers if modifiers.function => Some("function"),
6078                    _ => None,
6079                };
6080                if let Some(key) = key {
6081                    keystroke = Some(Keystroke {
6082                        key: key.to_string(),
6083                        key_char: None,
6084                        modifiers: Modifiers::default(),
6085                    });
6086                }
6087            }
6088
6089            if self.pending_modifier.modifiers.number_of_modifiers() == 0
6090                && event.modifiers.number_of_modifiers() == 1
6091            {
6092                self.pending_modifier.saw_other_input = false
6093            } else if event.modifiers.number_of_modifiers() > 1 {
6094                self.pending_modifier.saw_other_input = true
6095            }
6096            self.pending_modifier.modifiers = event.modifiers
6097        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
6098            self.pending_modifier.saw_other_input = true;
6099            keystroke = Some(key_down_event.keystroke.clone());
6100            if key_down_event.keystroke.key_char.is_some()
6101                && matches!(
6102                    cx.cursor_hide_mode,
6103                    CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
6104                )
6105            {
6106                cx.platform.hide_cursor_until_mouse_moves();
6107            }
6108        }
6109
6110        let Some(keystroke) = keystroke else {
6111            self.finish_dispatch_key_event(
6112                event,
6113                None,
6114                InputPreference::KeyBindings,
6115                dispatch_path,
6116                self.context_stack(),
6117                cx,
6118            );
6119            return;
6120        };
6121
6122        let input_preference = self.input_preference(event, cx);
6123
6124        cx.propagate_event = true;
6125        self.dispatch_keystroke_interceptors(
6126            &keystroke,
6127            input_preference,
6128            self.context_stack(),
6129            cx,
6130        );
6131        if !cx.propagate_event {
6132            self.finish_dispatch_key_event(
6133                event,
6134                Some(&keystroke),
6135                input_preference,
6136                dispatch_path,
6137                self.context_stack(),
6138                cx,
6139            );
6140            return;
6141        }
6142
6143        let mut currently_pending = self.pending_input.take().unwrap_or_default();
6144        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
6145            currently_pending = PendingInput::default();
6146        }
6147
6148        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
6149            currently_pending.keystrokes,
6150            keystroke.clone(),
6151            &dispatch_path,
6152        );
6153
6154        if !match_result.to_replay.is_empty() {
6155            self.replay_pending_input(match_result.to_replay, cx);
6156            cx.propagate_event = true;
6157        }
6158
6159        if !match_result.pending.is_empty() {
6160            let previous_timeout = currently_pending.timeout.take();
6161            currently_pending.keystrokes = match_result.pending;
6162            currently_pending.focus = self.focus;
6163
6164            let text_input_requires_timeout = event
6165                .downcast_ref::<KeyDownEvent>()
6166                .filter(|key_down| key_down.keystroke.key_char.is_some())
6167                .and_then(|_| self.platform_window.take_input_handler())
6168                .map_or(false, |mut input_handler| {
6169                    let accepts = input_handler.accepts_text_input(self, cx);
6170                    self.platform_window.set_input_handler(input_handler);
6171                    accepts
6172                });
6173
6174            let needs_timeout = previous_timeout.is_some()
6175                || match_result.pending_has_binding
6176                || text_input_requires_timeout;
6177            currently_pending.timeout = if needs_timeout {
6178                match previous_timeout {
6179                    Some(mut timeout) if timeout.is_paused() => {
6180                        timeout.reset_duration(PENDING_INPUT_TIMEOUT);
6181                        Some(timeout)
6182                    }
6183                    previous_timeout => {
6184                        drop(previous_timeout);
6185                        Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
6186                    }
6187                }
6188            } else {
6189                None
6190            };
6191            self.pending_input = Some(currently_pending);
6192            self.pending_input_changed(cx);
6193            cx.propagate_event = false;
6194            return;
6195        }
6196
6197        // Interceptors or replayed actions may have changed whether the input handler accepts text.
6198        let input_preference = self.input_preference(event, cx);
6199        if input_preference == InputPreference::KeyBindings {
6200            for binding in match_result.bindings {
6201                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6202                if !cx.propagate_event {
6203                    self.dispatch_keystroke_observers(
6204                        &keystroke,
6205                        input_preference,
6206                        Some(binding.action.as_ref()),
6207                        match_result.context_stack,
6208                        cx,
6209                    );
6210                    self.pending_input_changed(cx);
6211                    return;
6212                }
6213            }
6214        }
6215
6216        self.finish_dispatch_key_event(
6217            event,
6218            Some(&keystroke),
6219            input_preference,
6220            dispatch_path,
6221            match_result.context_stack,
6222            cx,
6223        );
6224        self.pending_input_changed(cx);
6225    }
6226
6227    fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6228        let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6229        PendingInputTimeout {
6230            duration,
6231            remaining: duration,
6232            state: PendingInputTimeoutState::Running { started_at, task },
6233        }
6234    }
6235
6236    fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6237        let started_at = cx.background_executor().now();
6238        let task = self.spawn(cx, async move |cx| {
6239            cx.background_executor.timer(remaining).await;
6240            cx.update(move |window, cx| {
6241                let Some(currently_pending) = window
6242                    .pending_input
6243                    .take()
6244                    .filter(|pending| pending.focus == window.focus)
6245                else {
6246                    return;
6247                };
6248
6249                let node_id = window.focus_node_id_in_rendered_frame(window.focus);
6250                let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
6251
6252                let to_replay = window
6253                    .rendered_frame
6254                    .dispatch_tree
6255                    .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6256
6257                window.pending_input_changed(cx);
6258                window.replay_pending_input(to_replay, cx)
6259            })
6260            .log_err();
6261        });
6262        (started_at, task)
6263    }
6264
6265    fn finish_dispatch_key_event(
6266        &mut self,
6267        event: &dyn Any,
6268        recognized_keystroke: Option<&Keystroke>,
6269        input_preference: InputPreference,
6270        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6271        context_stack: Vec<KeyContext>,
6272        cx: &mut App,
6273    ) {
6274        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6275        if !cx.propagate_event {
6276            return;
6277        }
6278
6279        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6280        if !cx.propagate_event {
6281            return;
6282        }
6283
6284        if let Some(keystroke) = recognized_keystroke {
6285            self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
6286        }
6287    }
6288
6289    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6290        self.pending_input_observers
6291            .clone()
6292            .retain(&(), |callback| callback(self, cx));
6293    }
6294
6295    fn defer_pending_input_changed(&self, cx: &mut App) {
6296        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
6297        // current effect cycle, and only for this window.
6298        let window_handle = self.handle;
6299        cx.defer(move |cx| {
6300            window_handle
6301                .update(cx, |_, window, cx| {
6302                    window.pending_input_changed(cx);
6303                })
6304                .ok();
6305        });
6306    }
6307
6308    fn dispatch_key_down_up_event(
6309        &mut self,
6310        event: &dyn Any,
6311        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6312        cx: &mut App,
6313    ) {
6314        // Capture phase
6315        for node_id in dispatch_path {
6316            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6317
6318            for key_listener in node.key_listeners.clone() {
6319                key_listener(event, DispatchPhase::Capture, self, cx);
6320                if !cx.propagate_event {
6321                    return;
6322                }
6323            }
6324        }
6325
6326        // Bubble phase
6327        for node_id in dispatch_path.iter().rev() {
6328            // Handle low level key events
6329            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6330            for key_listener in node.key_listeners.clone() {
6331                key_listener(event, DispatchPhase::Bubble, self, cx);
6332                if !cx.propagate_event {
6333                    return;
6334                }
6335            }
6336        }
6337    }
6338
6339    fn dispatch_modifiers_changed_event(
6340        &mut self,
6341        event: &dyn Any,
6342        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6343        cx: &mut App,
6344    ) {
6345        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6346            return;
6347        };
6348        for node_id in dispatch_path.iter().rev() {
6349            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6350            for listener in node.modifiers_changed_listeners.clone() {
6351                listener(event, self, cx);
6352                if !cx.propagate_event {
6353                    return;
6354                }
6355            }
6356        }
6357    }
6358
6359    /// Determine whether a potential multi-stroke key binding is in progress on this window.
6360    pub fn has_pending_keystrokes(&self) -> bool {
6361        self.pending_input().is_some()
6362    }
6363
6364    #[cfg(test)]
6365    pub(crate) fn pending_input_is_none(&self) -> bool {
6366        self.pending_input.is_none()
6367    }
6368
6369    pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6370        if self.pending_input.take().is_some() {
6371            self.defer_pending_input_changed(cx);
6372        }
6373    }
6374
6375    /// Returns pending input that can still complete a multi-stroke key binding. Input left over
6376    /// from a previous focus can never complete one.
6377    pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6378        self.pending_input
6379            .as_ref()
6380            .filter(|pending_input| pending_input.focus == self.focus)
6381            .map(|pending_input| PendingInputStatus {
6382                keystrokes: pending_input.keystrokes.as_slice(),
6383                timeout: pending_input
6384                    .timeout
6385                    .as_ref()
6386                    .map(PendingInputTimeout::status),
6387            })
6388    }
6389
6390    /// Pauses or resumes the current pending input timeout on behalf of `owner`.
6391    ///
6392    /// A paused timeout resumes automatically if `owner` is released. Returns whether the timeout
6393    /// state changed. A timeout paused by one owner cannot be resumed by another.
6394    pub fn set_pending_input_timeout_paused<T: 'static>(
6395        &mut self,
6396        owner: &Entity<T>,
6397        paused: bool,
6398        cx: &mut App,
6399    ) -> bool {
6400        let owner_id = owner.entity_id();
6401        if !paused {
6402            return self.resume_pending_input_timeout(owner_id, cx);
6403        }
6404
6405        let timeout = self
6406            .pending_input
6407            .as_ref()
6408            .filter(|pending_input| pending_input.focus == self.focus)
6409            .and_then(|pending_input| pending_input.timeout.as_ref());
6410        let Some(timeout) = timeout else {
6411            return false;
6412        };
6413        if timeout.is_paused() {
6414            return false;
6415        }
6416
6417        let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
6418            window.resume_pending_input_timeout(owner_id, cx);
6419        });
6420        let now = cx.background_executor().now();
6421        let changed = self
6422            .pending_input
6423            .as_mut()
6424            .filter(|pending_input| pending_input.focus == self.focus)
6425            .and_then(|pending_input| pending_input.timeout.as_mut())
6426            .is_some_and(|timeout| {
6427                timeout.pause(
6428                    PendingInputTimeoutPause {
6429                        owner_id,
6430                        _release_subscription: release_subscription,
6431                    },
6432                    now,
6433                )
6434            });
6435
6436        if changed {
6437            self.defer_pending_input_changed(cx);
6438        }
6439        changed
6440    }
6441
6442    fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
6443        let Some(remaining) = self
6444            .pending_input
6445            .as_ref()
6446            .and_then(|pending_input| pending_input.timeout.as_ref())
6447            .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
6448            .map(|timeout| timeout.remaining)
6449        else {
6450            return false;
6451        };
6452
6453        let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
6454        let changed = self
6455            .pending_input
6456            .as_mut()
6457            .and_then(|pending_input| pending_input.timeout.as_mut())
6458            .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
6459
6460        if changed {
6461            self.defer_pending_input_changed(cx);
6462        }
6463        changed
6464    }
6465
6466    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
6467    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
6468        self.pending_input()
6469            .map(|pending_input| pending_input.keystrokes())
6470    }
6471
6472    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
6473        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6474        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6475
6476        'replay: for replay in replays {
6477            let event = KeyDownEvent {
6478                keystroke: replay.keystroke.clone(),
6479                is_held: false,
6480                prefer_character_input: true,
6481            };
6482
6483            cx.propagate_event = true;
6484            for binding in replay.bindings {
6485                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6486                if !cx.propagate_event {
6487                    self.dispatch_keystroke_observers(
6488                        &replay.keystroke,
6489                        InputPreference::KeyBindings,
6490                        Some(binding.action.as_ref()),
6491                        Vec::default(),
6492                        cx,
6493                    );
6494                    continue 'replay;
6495                }
6496            }
6497
6498            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
6499            if !cx.propagate_event {
6500                continue 'replay;
6501            }
6502            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
6503                && let Some(mut input_handler) = self.platform_window.take_input_handler()
6504            {
6505                input_handler.dispatch_input(&input, self, cx);
6506                self.platform_window.set_input_handler(input_handler)
6507            }
6508        }
6509    }
6510
6511    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
6512        focus_id
6513            .and_then(|focus_id| {
6514                self.rendered_frame
6515                    .dispatch_tree
6516                    .focusable_node_id(focus_id)
6517            })
6518            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
6519    }
6520
6521    fn dispatch_action_on_node(
6522        &mut self,
6523        node_id: DispatchNodeId,
6524        action: &dyn Action,
6525        cx: &mut App,
6526    ) {
6527        self.dispatch_action_on_node_inner(node_id, action, cx);
6528
6529        if !cx.propagate_event
6530            && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6531            && self.last_input_was_keyboard()
6532        {
6533            cx.platform.hide_cursor_until_mouse_moves();
6534        }
6535    }
6536
6537    fn dispatch_action_on_node_inner(
6538        &mut self,
6539        node_id: DispatchNodeId,
6540        action: &dyn Action,
6541        cx: &mut App,
6542    ) {
6543        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6544
6545        // Capture phase for global actions.
6546        cx.propagate_event = true;
6547        if let Some(mut global_listeners) = cx
6548            .global_action_listeners
6549            .remove(&action.as_any().type_id())
6550        {
6551            for listener in &global_listeners {
6552                #[cfg(feature = "profiler")]
6553                self.window_profiler.begin_action_handler(action, cx);
6554                listener(action.as_any(), DispatchPhase::Capture, cx);
6555                #[cfg(feature = "profiler")]
6556                self.window_profiler.end_action_handler();
6557                if !cx.propagate_event {
6558                    break;
6559                }
6560            }
6561
6562            global_listeners.extend(
6563                cx.global_action_listeners
6564                    .remove(&action.as_any().type_id())
6565                    .unwrap_or_default(),
6566            );
6567
6568            cx.global_action_listeners
6569                .insert(action.as_any().type_id(), global_listeners);
6570        }
6571
6572        if !cx.propagate_event {
6573            return;
6574        }
6575
6576        // Capture phase for window actions.
6577        for node_id in &dispatch_path {
6578            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6579            for DispatchActionListener {
6580                action_type,
6581                listener,
6582            } in node.action_listeners.clone()
6583            {
6584                let any_action = action.as_any();
6585                if action_type == any_action.type_id() {
6586                    #[cfg(feature = "profiler")]
6587                    self.window_profiler.begin_action_handler(action, cx);
6588                    listener(any_action, DispatchPhase::Capture, self, cx);
6589                    #[cfg(feature = "profiler")]
6590                    self.window_profiler.end_action_handler();
6591
6592                    if !cx.propagate_event {
6593                        return;
6594                    }
6595                }
6596            }
6597        }
6598
6599        // Bubble phase for window actions.
6600        for node_id in dispatch_path.iter().rev() {
6601            let node = self.rendered_frame.dispatch_tree.node(*node_id);
6602            for DispatchActionListener {
6603                action_type,
6604                listener,
6605            } in node.action_listeners.clone()
6606            {
6607                let any_action = action.as_any();
6608                if action_type == any_action.type_id() {
6609                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
6610                    #[cfg(feature = "profiler")]
6611                    self.window_profiler.begin_action_handler(action, cx);
6612                    listener(any_action, DispatchPhase::Bubble, self, cx);
6613                    #[cfg(feature = "profiler")]
6614                    self.window_profiler.end_action_handler();
6615
6616                    if !cx.propagate_event {
6617                        return;
6618                    }
6619                }
6620            }
6621        }
6622
6623        // Bubble phase for global actions.
6624        if let Some(mut global_listeners) = cx
6625            .global_action_listeners
6626            .remove(&action.as_any().type_id())
6627        {
6628            for listener in global_listeners.iter().rev() {
6629                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
6630
6631                #[cfg(feature = "profiler")]
6632                self.window_profiler.begin_action_handler(action, cx);
6633                listener(action.as_any(), DispatchPhase::Bubble, cx);
6634                #[cfg(feature = "profiler")]
6635                self.window_profiler.end_action_handler();
6636                if !cx.propagate_event {
6637                    break;
6638                }
6639            }
6640
6641            global_listeners.extend(
6642                cx.global_action_listeners
6643                    .remove(&action.as_any().type_id())
6644                    .unwrap_or_default(),
6645            );
6646
6647            cx.global_action_listeners
6648                .insert(action.as_any().type_id(), global_listeners);
6649        }
6650    }
6651
6652    /// Register the given handler to be invoked whenever the global of the given type
6653    /// is updated.
6654    pub fn observe_global<G: Global>(
6655        &mut self,
6656        cx: &mut App,
6657        f: impl Fn(&mut Window, &mut App) + 'static,
6658    ) -> Subscription {
6659        let window_handle = self.handle;
6660        let (subscription, activate) = cx.global_observers.insert(
6661            TypeId::of::<G>(),
6662            Box::new(move |cx| {
6663                window_handle
6664                    .update(cx, |_, window, cx| f(window, cx))
6665                    .is_ok()
6666            }),
6667        );
6668        cx.defer(move |_| activate());
6669        subscription
6670    }
6671
6672    /// Focus the current window and bring it to the foreground at the platform level.
6673    pub fn activate_window(&self) {
6674        self.platform_window.activate();
6675    }
6676
6677    /// Requests that the operating system draw attention to this window.
6678    pub fn request_attention(&self) {
6679        self.platform_window.request_attention();
6680    }
6681
6682    /// Minimize the current window at the platform level.
6683    pub fn minimize_window(&self) {
6684        self.platform_window.minimize();
6685    }
6686
6687    /// Toggle full screen status on the current window at the platform level.
6688    pub fn toggle_fullscreen(&self) {
6689        self.platform_window.toggle_fullscreen();
6690    }
6691
6692    /// Toggle simple (borderless) fullscreen, where the window covers the entire
6693    /// screen including the menu bar and, on notched displays, the area around the
6694    /// notch. Unlike [`Window::toggle_fullscreen`], this does not move the window
6695    /// into its own Mission Control space. Only has an effect on macOS.
6696    pub fn toggle_simple_fullscreen(&self) {
6697        self.platform_window.toggle_simple_fullscreen();
6698    }
6699
6700    /// Updates the IME panel position suggestions for languages like japanese, chinese.
6701    pub fn invalidate_character_coordinates(&self) {
6702        self.on_next_frame(|window, cx| {
6703            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
6704                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6705                    window.platform_window.update_ime_position(bounds);
6706                }
6707                window.platform_window.set_input_handler(input_handler);
6708            }
6709        });
6710    }
6711
6712    /// Present a platform dialog.
6713    /// The provided message will be presented, along with buttons for each answer.
6714    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
6715    pub fn prompt<T>(
6716        &mut self,
6717        level: PromptLevel,
6718        message: &str,
6719        detail: Option<&str>,
6720        answers: &[T],
6721        cx: &mut App,
6722    ) -> oneshot::Receiver<usize>
6723    where
6724        T: Clone + Into<PromptButton>,
6725    {
6726        let prompt_builder = cx.prompt_builder.take();
6727        let Some(prompt_builder) = prompt_builder else {
6728            unreachable!("Re-entrant window prompting is not supported by GPUI");
6729        };
6730
6731        let answers = answers
6732            .iter()
6733            .map(|answer| answer.clone().into())
6734            .collect::<Vec<_>>();
6735
6736        let receiver = match &prompt_builder {
6737            PromptBuilder::Default => self
6738                .platform_window
6739                .prompt(level, message, detail, &answers)
6740                .unwrap_or_else(|| {
6741                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6742                }),
6743            PromptBuilder::Custom(_) => {
6744                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6745            }
6746        };
6747
6748        cx.prompt_builder = Some(prompt_builder);
6749
6750        receiver
6751    }
6752
6753    fn build_custom_prompt(
6754        &mut self,
6755        prompt_builder: &PromptBuilder,
6756        level: PromptLevel,
6757        message: &str,
6758        detail: Option<&str>,
6759        answers: &[PromptButton],
6760        cx: &mut App,
6761    ) -> oneshot::Receiver<usize> {
6762        let (sender, receiver) = oneshot::channel();
6763        let handle = PromptHandle::new(sender);
6764        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6765        self.prompt = Some(handle);
6766        receiver
6767    }
6768
6769    /// Returns whether a prompt rendered by GPUI is currently active in this window.
6770    ///
6771    /// This is only true for prompts rendered in the window (see
6772    /// [`App::set_prompt_builder`]), not for platform-native prompt dialogs.
6773    pub fn has_active_prompt(&self) -> bool {
6774        self.prompt.is_some()
6775    }
6776
6777    /// Returns the current context stack.
6778    pub fn context_stack(&self) -> Vec<KeyContext> {
6779        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6780        let dispatch_tree = &self.rendered_frame.dispatch_tree;
6781        dispatch_tree
6782            .dispatch_path(node_id)
6783            .iter()
6784            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6785            .collect()
6786    }
6787
6788    /// Returns all available actions for the focused element.
6789    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6790        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6791        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
6792        for action_type in cx.global_action_listeners.keys() {
6793            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
6794                let action = cx.actions.build_action_type(action_type).ok();
6795                if let Some(action) = action {
6796                    actions.insert(ix, action);
6797                }
6798            }
6799        }
6800        actions
6801    }
6802
6803    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
6804    /// returned in the order they were added. For display, the last binding should take precedence.
6805    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
6806        self.rendered_frame
6807            .dispatch_tree
6808            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
6809    }
6810
6811    /// Returns the highest precedence key binding that invokes an action on the currently focused
6812    /// element. This is more efficient than getting the last result of `bindings_for_action`.
6813    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
6814        self.rendered_frame
6815            .dispatch_tree
6816            .highest_precedence_binding_for_action(
6817                action,
6818                &self.rendered_frame.dispatch_tree.context_stack,
6819            )
6820    }
6821
6822    /// Returns the key bindings for an action in a context.
6823    pub fn bindings_for_action_in_context(
6824        &self,
6825        action: &dyn Action,
6826        context: KeyContext,
6827    ) -> Vec<KeyBinding> {
6828        let dispatch_tree = &self.rendered_frame.dispatch_tree;
6829        dispatch_tree.bindings_for_action(action, &[context])
6830    }
6831
6832    /// Returns the highest precedence key binding for an action in a context. This is more
6833    /// efficient than getting the last result of `bindings_for_action_in_context`.
6834    pub fn highest_precedence_binding_for_action_in_context(
6835        &self,
6836        action: &dyn Action,
6837        context: KeyContext,
6838    ) -> Option<KeyBinding> {
6839        let dispatch_tree = &self.rendered_frame.dispatch_tree;
6840        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
6841    }
6842
6843    /// Returns any bindings that would invoke an action on the given focus handle if it were
6844    /// focused. Bindings are returned in the order they were added. For display, the last binding
6845    /// should take precedence.
6846    pub fn bindings_for_action_in(
6847        &self,
6848        action: &dyn Action,
6849        focus_handle: &FocusHandle,
6850    ) -> Vec<KeyBinding> {
6851        let dispatch_tree = &self.rendered_frame.dispatch_tree;
6852        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
6853            return vec![];
6854        };
6855        dispatch_tree.bindings_for_action(action, &context_stack)
6856    }
6857
6858    /// Returns the highest precedence key binding that would invoke an action on the given focus
6859    /// handle if it were focused. This is more efficient than getting the last result of
6860    /// `bindings_for_action_in`.
6861    pub fn highest_precedence_binding_for_action_in(
6862        &self,
6863        action: &dyn Action,
6864        focus_handle: &FocusHandle,
6865    ) -> Option<KeyBinding> {
6866        let dispatch_tree = &self.rendered_frame.dispatch_tree;
6867        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
6868        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
6869    }
6870
6871    /// Find the bindings that can follow the current input sequence for the current context stack.
6872    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
6873        self.rendered_frame
6874            .dispatch_tree
6875            .possible_next_bindings_for_input(input, &self.context_stack())
6876    }
6877
6878    fn context_stack_for_focus_handle(
6879        &self,
6880        focus_handle: &FocusHandle,
6881    ) -> Option<Vec<KeyContext>> {
6882        let dispatch_tree = &self.rendered_frame.dispatch_tree;
6883        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
6884        let context_stack: Vec<_> = dispatch_tree
6885            .dispatch_path(node_id)
6886            .into_iter()
6887            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
6888            .collect();
6889        Some(context_stack)
6890    }
6891
6892    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
6893    pub fn listener_for<T: 'static, E>(
6894        &self,
6895        view: &Entity<T>,
6896        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
6897    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
6898        let view = view.downgrade();
6899        move |e: &E, window: &mut Window, cx: &mut App| {
6900            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
6901        }
6902    }
6903
6904    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
6905    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
6906        &self,
6907        entity: &Entity<E>,
6908        f: Callback,
6909    ) -> impl Fn(&mut Window, &mut App) + 'static {
6910        let entity = entity.downgrade();
6911        move |window: &mut Window, cx: &mut App| {
6912            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
6913        }
6914    }
6915
6916    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
6917    /// If the callback returns false, the window won't be closed.
6918    pub fn on_window_should_close(
6919        &self,
6920        cx: &App,
6921        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
6922    ) {
6923        let mut cx = self.to_async(cx);
6924        self.platform_window.on_should_close(Box::new(move || {
6925            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
6926        }))
6927    }
6928
6929    /// Register an action listener on this node for the next frame. The type of action
6930    /// is determined by the first parameter of the given listener. When the next frame is rendered
6931    /// the listener will be cleared.
6932    ///
6933    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
6934    /// a specific need to register a listener yourself.
6935    ///
6936    /// This method should only be called as part of the paint phase of element drawing.
6937    pub fn on_action(
6938        &mut self,
6939        action_type: TypeId,
6940        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6941    ) {
6942        self.invalidator.debug_assert_paint();
6943
6944        self.next_frame
6945            .dispatch_tree
6946            .on_action(action_type, Rc::new(listener));
6947    }
6948
6949    /// Register a capturing action listener on this node for the next frame if the condition is true.
6950    /// The type of action is determined by the first parameter of the given listener. When the next
6951    /// frame is rendered the listener will be cleared.
6952    ///
6953    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
6954    /// a specific need to register a listener yourself.
6955    ///
6956    /// This method should only be called as part of the paint phase of element drawing.
6957    pub fn on_action_when(
6958        &mut self,
6959        condition: bool,
6960        action_type: TypeId,
6961        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6962    ) {
6963        self.invalidator.debug_assert_paint();
6964
6965        if condition {
6966            self.next_frame
6967                .dispatch_tree
6968                .on_action(action_type, Rc::new(listener));
6969        }
6970    }
6971
6972    /// Read information about the GPU backing this window.
6973    /// Currently returns None on Mac and Windows.
6974    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
6975        self.platform_window.gpu_specs()
6976    }
6977
6978    /// Perform titlebar double-click action.
6979    /// This is macOS specific.
6980    pub fn titlebar_double_click(&self) {
6981        self.platform_window
6982            .titlebar_double_click(self.is_resizable, self.is_minimizable);
6983    }
6984
6985    /// Gets the window's title at the platform level.
6986    /// This is macOS specific.
6987    pub fn window_title(&self) -> String {
6988        self.platform_window.get_title()
6989    }
6990
6991    /// Returns a list of all tabbed windows and their titles.
6992    /// This is macOS specific.
6993    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
6994        self.platform_window.tabbed_windows()
6995    }
6996
6997    /// Returns the tab bar visibility.
6998    /// This is macOS specific.
6999    pub fn tab_bar_visible(&self) -> bool {
7000        self.platform_window.tab_bar_visible()
7001    }
7002
7003    /// Merges all open windows into a single tabbed window.
7004    /// This is macOS specific.
7005    pub fn merge_all_windows(&self) {
7006        self.platform_window.merge_all_windows()
7007    }
7008
7009    /// Moves the tab to a new containing window.
7010    /// This is macOS specific.
7011    pub fn move_tab_to_new_window(&self) {
7012        self.platform_window.move_tab_to_new_window()
7013    }
7014
7015    /// Shows or hides the window tab overview.
7016    /// This is macOS specific.
7017    pub fn toggle_window_tab_overview(&self) {
7018        self.platform_window.toggle_window_tab_overview()
7019    }
7020
7021    /// Sets the tabbing identifier for the window.
7022    /// This is macOS specific.
7023    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
7024        self.platform_window
7025            .set_tabbing_identifier(tabbing_identifier)
7026    }
7027
7028    /// Request the OS to play an alert sound. On some platforms this is associated
7029    /// with the window, for others it's just a simple global function call.
7030    pub fn play_system_bell(&self) {
7031        self.platform_window.play_system_bell()
7032    }
7033
7034    /// Returns whether accessibility support is enabled for this window.
7035    ///
7036    /// This is false when the app was created with [`crate::Application::new_inaccessible`].
7037    /// Unlike [`Self::is_a11y_active`], this does not depend on whether assistive
7038    /// technology is currently connected, so it can be used to gate subscriptions
7039    /// that are only needed for accessibility.
7040    pub fn is_a11y_enabled(&self) -> bool {
7041        self.a11y.is_enabled()
7042    }
7043
7044    /// Returns whether accessibility features are active for this frame,
7045    /// i.e. whether assistive technology (such as a screen reader) is
7046    /// connected and an accessibility tree is being built.
7047    ///
7048    /// Use this to skip computing data during rendering that is only
7049    /// observable through the accessibility tree. When accessibility is
7050    /// activated, a redraw is forced, so gated work is recomputed before the
7051    /// next tree update is sent to the platform.
7052    ///
7053    /// See the [accessibility guide](crate::_accessibility) for an overview.
7054    pub fn is_a11y_active(&self) -> bool {
7055        self.a11y.is_active()
7056    }
7057
7058    /// Debug representation of the last frame's accessibility information.
7059    pub fn debug_a11y_tree_json(&self) -> Option<String> {
7060        self.a11y.debug_tree_json()
7061    }
7062
7063    /// Register a listener for an accessibility action on a specific node.
7064    /// The listener will be called when a screen reader requests the given
7065    /// action on the node identified by `node_id`.
7066    ///
7067    /// See the [accessibility guide](crate::_accessibility) for an overview.
7068    pub fn on_a11y_action(
7069        &mut self,
7070        node_id: accesskit::NodeId,
7071        action: accesskit::Action,
7072        listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
7073    ) {
7074        crate::fast::a11y::A11yLog::action(&mut self.a11y.nodes.fast, node_id, action);
7075        self.a11y
7076            .action_listeners
7077            .entry(node_id)
7078            .or_default()
7079            .push((action, Box::new(listener)));
7080    }
7081
7082    #[cfg(not(target_family = "wasm"))]
7083    pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
7084        // Take listeners out temporarily so the closures can borrow Window
7085        // mutably, then restore them afterward.
7086        if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
7087            let extra_data = request.data.as_ref();
7088            let mut matched = false;
7089            for (action, listener) in &mut listeners {
7090                if *action == request.action {
7091                    listener(extra_data, self, cx);
7092                    matched = true;
7093                }
7094            }
7095            self.a11y
7096                .action_listeners
7097                .insert(request.target_node, listeners);
7098            if matched {
7099                return;
7100            }
7101        }
7102
7103        // Fall back to built-in action handling.
7104        match request.action {
7105            accesskit::Action::Click => {
7106                if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
7107                    let center = bounds.center();
7108                    let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
7109                        button: MouseButton::Left,
7110                        position: center,
7111                        modifiers: Modifiers::default(),
7112                        click_count: 1,
7113                        first_mouse: false,
7114                    });
7115                    let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
7116                        button: MouseButton::Left,
7117                        position: center,
7118                        modifiers: Modifiers::default(),
7119                        click_count: 1,
7120                    });
7121                    self.dispatch_event(mouse_down, cx);
7122                    self.dispatch_event(mouse_up, cx);
7123                }
7124            }
7125            accesskit::Action::Focus => {
7126                if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
7127                    && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
7128                {
7129                    self.focus(&handle, cx);
7130                }
7131            }
7132            accesskit::Action::Blur => {
7133                self.blur(cx);
7134            }
7135            _ => {
7136                log::debug!(
7137                    "Unhandled a11y action: {:?} on {:?}",
7138                    request.action,
7139                    request.target_node
7140                );
7141            }
7142        }
7143    }
7144
7145    /// Toggles the inspector mode on this window.
7146    #[cfg(any(feature = "inspector", debug_assertions))]
7147    pub fn toggle_inspector(&mut self, cx: &mut App) {
7148        self.inspector = match self.inspector {
7149            None => Some(cx.new(|_| Inspector::new())),
7150            Some(_) => {
7151                self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
7152                self.rendered_frame.inspector_hitboxes = FxHashMap::default();
7153                self.next_frame.next_inspector_instance_ids = FxHashMap::default();
7154                self.next_frame.inspector_hitboxes = FxHashMap::default();
7155                None
7156            }
7157        };
7158        self.refresh();
7159    }
7160
7161    /// Returns true if the window is in inspector mode.
7162    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
7163        #[cfg(any(feature = "inspector", debug_assertions))]
7164        {
7165            if let Some(inspector) = &self.inspector {
7166                return inspector.read(_cx).is_picking();
7167            }
7168        }
7169        false
7170    }
7171
7172    /// Executes the provided function with mutable access to an inspector state.
7173    #[cfg(any(feature = "inspector", debug_assertions))]
7174    pub fn with_inspector_state<T: 'static, R>(
7175        &mut self,
7176        inspector_id: Option<&crate::InspectorElementId>,
7177        cx: &mut App,
7178        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7179    ) -> Option<R> {
7180        let inspector_id = inspector_id?;
7181        let inspector = self.inspector.as_ref()?;
7182        if inspector.read(cx).active_element_id() != Some(inspector_id) {
7183            return None;
7184        }
7185        let inspector = inspector.clone();
7186        Some(inspector.update(cx, |inspector, _cx| {
7187            inspector.with_active_element_state(self, f)
7188        }))
7189    }
7190
7191    #[cfg(any(feature = "inspector", debug_assertions))]
7192    pub(crate) fn inspector_enabled(&self) -> bool {
7193        self.inspector.is_some()
7194    }
7195
7196    #[cfg(any(feature = "inspector", debug_assertions))]
7197    pub(crate) fn build_inspector_element_id(
7198        &mut self,
7199        path: crate::InspectorElementPath,
7200    ) -> crate::InspectorElementId {
7201        self.invalidator.debug_assert_paint_or_prepaint();
7202        let path = Rc::new(path);
7203        let next_instance_id = self
7204            .next_frame
7205            .next_inspector_instance_ids
7206            .entry(path.clone())
7207            .or_insert(0);
7208        let instance_id = *next_instance_id;
7209        *next_instance_id += 1;
7210        crate::InspectorElementId { path, instance_id }
7211    }
7212
7213    #[cfg(any(feature = "inspector", debug_assertions))]
7214    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
7215        if let Some(inspector) = self.inspector.take() {
7216            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
7217            inspector_element.prepaint_as_root(
7218                point(self.viewport_size.width - inspector_width, px(0.0)),
7219                size(inspector_width, self.viewport_size.height).into(),
7220                self,
7221                cx,
7222            );
7223            self.inspector = Some(inspector);
7224            Some(inspector_element)
7225        } else {
7226            None
7227        }
7228    }
7229
7230    #[cfg(any(feature = "inspector", debug_assertions))]
7231    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
7232        if let Some(mut inspector_element) = inspector_element {
7233            inspector_element.paint(self, cx);
7234        };
7235    }
7236
7237    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
7238    /// inspect UI elements by clicking on them.
7239    #[cfg(any(feature = "inspector", debug_assertions))]
7240    pub fn insert_inspector_hitbox(
7241        &mut self,
7242        hitbox_id: HitboxId,
7243        inspector_id: Option<&crate::InspectorElementId>,
7244        cx: &App,
7245    ) {
7246        self.invalidator.debug_assert_paint_or_prepaint();
7247        if !self.is_inspector_picking(cx) {
7248            return;
7249        }
7250        if let Some(inspector_id) = inspector_id {
7251            self.next_frame
7252                .inspector_hitboxes
7253                .insert(hitbox_id, inspector_id.clone());
7254        }
7255    }
7256
7257    #[cfg(any(feature = "inspector", debug_assertions))]
7258    fn paint_inspector_hitbox(&mut self, cx: &App) {
7259        if let Some(inspector) = self.inspector.as_ref() {
7260            let inspector = inspector.read(cx);
7261            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
7262                && let Some(hitbox) = self
7263                    .next_frame
7264                    .hitboxes
7265                    .iter()
7266                    .find(|hitbox| hitbox.id == hitbox_id)
7267            {
7268                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7269            }
7270        }
7271    }
7272
7273    #[cfg(any(feature = "inspector", debug_assertions))]
7274    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7275        let Some(inspector) = self.inspector.clone() else {
7276            return;
7277        };
7278        if event.downcast_ref::<MouseMoveEvent>().is_some() {
7279            inspector.update(cx, |inspector, _cx| {
7280                if let Some((_, inspector_id)) =
7281                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7282                {
7283                    inspector.hover(inspector_id, self);
7284                }
7285            });
7286        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7287            inspector.update(cx, |inspector, _cx| {
7288                if let Some((_, inspector_id)) =
7289                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7290                {
7291                    inspector.select(inspector_id, self);
7292                }
7293            });
7294        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
7295            // This should be kept in sync with SCROLL_LINES in x11 platform.
7296            const SCROLL_LINES: f32 = 3.0;
7297            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7298            let delta_y = event
7299                .delta
7300                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7301                .y;
7302            if let Some(inspector) = self.inspector.clone() {
7303                inspector.update(cx, |inspector, _cx| {
7304                    if let Some(depth) = inspector.pick_depth.as_mut() {
7305                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7306                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
7307                        if *depth < 0.0 {
7308                            *depth = 0.0;
7309                        } else if *depth > max_depth {
7310                            *depth = max_depth;
7311                        }
7312                        if let Some((_, inspector_id)) =
7313                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7314                        {
7315                            inspector.set_active_element_id(inspector_id, self);
7316                        }
7317                    }
7318                });
7319            }
7320        }
7321    }
7322
7323    #[cfg(any(feature = "inspector", debug_assertions))]
7324    fn hovered_inspector_hitbox(
7325        &self,
7326        inspector: &Inspector,
7327        frame: &Frame,
7328    ) -> Option<(HitboxId, crate::InspectorElementId)> {
7329        if let Some(pick_depth) = inspector.pick_depth {
7330            let depth = (pick_depth as i64).try_into().unwrap_or(0);
7331            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
7332            let skip_count = (depth as usize).min(max_skipped);
7333            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
7334                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7335                    return Some((*hitbox_id, inspector_id.clone()));
7336                }
7337            }
7338        }
7339        None
7340    }
7341
7342    /// For testing: set the current modifier keys state.
7343    /// This does not generate any events.
7344    #[cfg(any(test, feature = "test-support"))]
7345    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7346        self.modifiers = modifiers;
7347    }
7348
7349    /// For testing: simulate a mouse move event to the given position.
7350    /// This dispatches the event through the normal event handling path,
7351    /// which will trigger hover states and tooltips.
7352    #[cfg(any(test, feature = "test-support"))]
7353    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7354        let event = PlatformInput::MouseMove(MouseMoveEvent {
7355            position,
7356            modifiers: self.modifiers,
7357            pressed_button: None,
7358        });
7359        let _ = self.dispatch_event(event, cx);
7360    }
7361
7362    #[inline(never)]
7363    fn take_element_state(
7364        &mut self,
7365        global_id: &GlobalElementId,
7366        state_type: TypeId,
7367    ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
7368        let key = (global_id.clone(), state_type);
7369        self.next_frame.accessed_element_states.push(key.clone());
7370        let state = self
7371            .next_frame
7372            .element_states
7373            .remove(&key)
7374            .or_else(|| self.rendered_frame.element_states.remove(&key));
7375        (key, state)
7376    }
7377
7378    #[inline(never)]
7379    fn insert_element_state(
7380        &mut self,
7381        key: (GlobalElementId, TypeId),
7382        state: ElementStateBox,
7383    ) -> Option<ElementStateBox> {
7384        self.next_frame.element_states.insert(key, state)
7385    }
7386
7387    #[inline(never)]
7388    fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
7389        cx.observe(state, move |_, cx| {
7390            cx.notify(current_view);
7391        })
7392        .detach();
7393    }
7394}
7395
7396// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
7397slotmap::new_key_type! {
7398    /// A unique identifier for a window.
7399    pub struct WindowId;
7400}
7401
7402impl WindowId {
7403    /// Converts this window ID to a `u64`.
7404    pub fn as_u64(&self) -> u64 {
7405        self.0.as_ffi()
7406    }
7407}
7408
7409impl From<u64> for WindowId {
7410    fn from(value: u64) -> Self {
7411        WindowId(slotmap::KeyData::from_ffi(value))
7412    }
7413}
7414
7415/// A handle to a window with a specific root view type.
7416/// Note that this does not keep the window alive on its own.
7417#[derive(Deref, DerefMut)]
7418pub struct WindowHandle<V> {
7419    #[deref]
7420    #[deref_mut]
7421    pub(crate) any_handle: AnyWindowHandle,
7422    state_type: PhantomData<fn(V) -> V>,
7423}
7424
7425impl<V> Debug for WindowHandle<V> {
7426    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7427        f.debug_struct("WindowHandle")
7428            .field("any_handle", &self.any_handle.id.as_u64())
7429            .finish()
7430    }
7431}
7432
7433impl<V: 'static + Render> WindowHandle<V> {
7434    /// Creates a new handle from a window ID.
7435    /// This does not check if the root type of the window is `V`.
7436    pub fn new(id: WindowId) -> Self {
7437        WindowHandle {
7438            any_handle: AnyWindowHandle {
7439                id,
7440                state_type: TypeId::of::<V>(),
7441                root_entity_type_name: std::any::type_name::<V>(),
7442            },
7443            state_type: PhantomData,
7444        }
7445    }
7446
7447    /// Get the root view out of this window.
7448    ///
7449    /// This will fail if the window is closed or if the root view's type does not match `V`.
7450    #[cfg(any(test, feature = "test-support"))]
7451    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
7452    where
7453        C: AppContext,
7454    {
7455        cx.update_window(self.any_handle, |root_view, _, _| {
7456            root_view
7457                .downcast::<V>()
7458                .map_err(|_| anyhow!("the type of the window's root view has changed"))
7459        })?
7460    }
7461
7462    /// Updates the root view of this window.
7463    ///
7464    /// This will fail if the window has been closed or if the root view's type does not match
7465    pub fn update<C, R>(
7466        &self,
7467        cx: &mut C,
7468        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
7469    ) -> Result<R>
7470    where
7471        C: AppContext,
7472    {
7473        cx.update_window(self.any_handle, |root_view, window, cx| {
7474            let view = root_view
7475                .downcast::<V>()
7476                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7477
7478            Ok(view.update(cx, |view, cx| update(view, window, cx)))
7479        })?
7480    }
7481
7482    /// Read the root view out of this window.
7483    ///
7484    /// This will fail if the window is closed or if the root view's type does not match `V`.
7485    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
7486        let x = cx
7487            .windows
7488            .get(self.id)
7489            .and_then(|window| {
7490                window
7491                    .as_deref()
7492                    .and_then(|window| window.root.clone())
7493                    .map(|root_view| root_view.downcast::<V>())
7494            })
7495            .context("window not found")?
7496            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7497
7498        Ok(x.read(cx))
7499    }
7500
7501    /// Read the root view out of this window, with a callback
7502    ///
7503    /// This will fail if the window is closed or if the root view's type does not match `V`.
7504    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
7505    where
7506        C: AppContext,
7507    {
7508        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
7509    }
7510
7511    /// Read the root view pointer off of this window.
7512    ///
7513    /// This will fail if the window is closed or if the root view's type does not match `V`.
7514    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
7515    where
7516        C: AppContext,
7517    {
7518        cx.read_window(self, |root_view, _cx| root_view)
7519    }
7520
7521    /// Check if this window is 'active'.
7522    ///
7523    /// Will return `None` if the window is closed or currently
7524    /// borrowed.
7525    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
7526        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
7527            .ok()
7528    }
7529}
7530
7531impl<V> Copy for WindowHandle<V> {}
7532
7533impl<V> Clone for WindowHandle<V> {
7534    fn clone(&self) -> Self {
7535        *self
7536    }
7537}
7538
7539impl<V> PartialEq for WindowHandle<V> {
7540    fn eq(&self, other: &Self) -> bool {
7541        self.any_handle == other.any_handle
7542    }
7543}
7544
7545impl<V> Eq for WindowHandle<V> {}
7546
7547impl<V> Hash for WindowHandle<V> {
7548    fn hash<H: Hasher>(&self, state: &mut H) {
7549        self.any_handle.hash(state);
7550    }
7551}
7552
7553impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
7554    fn from(val: WindowHandle<V>) -> Self {
7555        val.any_handle
7556    }
7557}
7558
7559/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
7560#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
7561pub struct AnyWindowHandle {
7562    pub(crate) id: WindowId,
7563    state_type: TypeId,
7564    root_entity_type_name: &'static str,
7565}
7566
7567impl AnyWindowHandle {
7568    /// Get the ID of this window.
7569    pub fn window_id(&self) -> WindowId {
7570        self.id
7571    }
7572
7573    /// Returns the name of the window's declared root entity type.
7574    pub fn root_entity_type_name(&self) -> &'static str {
7575        self.root_entity_type_name
7576    }
7577
7578    /// Attempt to convert this handle to a window handle with a specific root view type.
7579    /// If the types do not match, this will return `None`.
7580    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7581        if TypeId::of::<T>() == self.state_type {
7582            Some(WindowHandle {
7583                any_handle: *self,
7584                state_type: PhantomData,
7585            })
7586        } else {
7587            None
7588        }
7589    }
7590
7591    /// Updates the state of the root view of this window.
7592    ///
7593    /// This will fail if the window has been closed.
7594    pub fn update<C, R>(
7595        self,
7596        cx: &mut C,
7597        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7598    ) -> Result<R>
7599    where
7600        C: AppContext,
7601    {
7602        cx.update_window(self, update)
7603    }
7604
7605    /// Read the state of the root view of this window.
7606    ///
7607    /// This will fail if the window has been closed.
7608    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7609    where
7610        C: AppContext,
7611        T: 'static,
7612    {
7613        let view = self
7614            .downcast::<T>()
7615            .context("the type of the window's root view has changed")?;
7616
7617        cx.read_window(&view, read)
7618    }
7619}
7620
7621impl HasWindowHandle for Window {
7622    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7623        self.platform_window.window_handle()
7624    }
7625}
7626
7627impl HasDisplayHandle for Window {
7628    fn display_handle(
7629        &self,
7630    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7631        self.platform_window.display_handle()
7632    }
7633}
7634
7635/// An identifier for an [`Element`].
7636///
7637/// Can be constructed with a string, a number, or both, as well
7638/// as other internal representations.
7639#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7640pub enum ElementId {
7641    /// The ID of a View element
7642    View(EntityId),
7643    /// An integer ID.
7644    Integer(u64),
7645    /// A string based ID.
7646    Name(SharedString),
7647    /// A UUID.
7648    Uuid(Uuid),
7649    /// An ID that's equated with a focus handle.
7650    FocusHandle(FocusId),
7651    /// A combination of a name and an integer.
7652    NamedInteger(SharedString, u64),
7653    /// A path.
7654    Path(Arc<std::path::Path>),
7655    /// A code location.
7656    CodeLocation(core::panic::Location<'static>),
7657    /// A labeled child of an element.
7658    NamedChild(Arc<ElementId>, SharedString),
7659    /// A byte array ID (used for text-anchors)
7660    OpaqueId([u8; 20]),
7661}
7662
7663impl ElementId {
7664    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
7665    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7666        Self::NamedInteger(name.into(), integer as u64)
7667    }
7668}
7669
7670impl Display for ElementId {
7671    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7672        match self {
7673            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7674            ElementId::Integer(ix) => write!(f, "{}", ix)?,
7675            ElementId::Name(name) => write!(f, "{}", name)?,
7676            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7677            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7678            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7679            ElementId::Path(path) => write!(f, "{}", path.display())?,
7680            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7681            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7682            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7683        }
7684
7685        Ok(())
7686    }
7687}
7688
7689impl TryInto<SharedString> for ElementId {
7690    type Error = anyhow::Error;
7691
7692    fn try_into(self) -> anyhow::Result<SharedString> {
7693        if let ElementId::Name(name) = self {
7694            Ok(name)
7695        } else {
7696            anyhow::bail!("element id is not string")
7697        }
7698    }
7699}
7700
7701impl From<u64> for ElementId {
7702    fn from(id: u64) -> Self {
7703        ElementId::Integer(id)
7704    }
7705}
7706
7707impl From<usize> for ElementId {
7708    fn from(id: usize) -> Self {
7709        ElementId::Integer(id as u64)
7710    }
7711}
7712
7713impl From<i32> for ElementId {
7714    fn from(id: i32) -> Self {
7715        Self::Integer(id as u64)
7716    }
7717}
7718
7719impl From<SharedString> for ElementId {
7720    fn from(name: SharedString) -> Self {
7721        ElementId::Name(name)
7722    }
7723}
7724
7725impl From<String> for ElementId {
7726    fn from(name: String) -> Self {
7727        ElementId::Name(name.into())
7728    }
7729}
7730
7731impl From<Arc<str>> for ElementId {
7732    fn from(name: Arc<str>) -> Self {
7733        ElementId::Name(name.into())
7734    }
7735}
7736
7737impl From<Arc<std::path::Path>> for ElementId {
7738    fn from(path: Arc<std::path::Path>) -> Self {
7739        ElementId::Path(path)
7740    }
7741}
7742
7743impl From<&'static str> for ElementId {
7744    fn from(name: &'static str) -> Self {
7745        ElementId::Name(SharedString::new_static(name))
7746    }
7747}
7748
7749impl<'a> From<&'a FocusHandle> for ElementId {
7750    fn from(handle: &'a FocusHandle) -> Self {
7751        ElementId::FocusHandle(handle.id)
7752    }
7753}
7754
7755impl From<(&'static str, EntityId)> for ElementId {
7756    fn from((name, id): (&'static str, EntityId)) -> Self {
7757        ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7758    }
7759}
7760
7761impl From<(&'static str, usize)> for ElementId {
7762    fn from((name, id): (&'static str, usize)) -> Self {
7763        ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7764    }
7765}
7766
7767impl From<(SharedString, usize)> for ElementId {
7768    fn from((name, id): (SharedString, usize)) -> Self {
7769        ElementId::NamedInteger(name, id as u64)
7770    }
7771}
7772
7773impl From<(&'static str, u64)> for ElementId {
7774    fn from((name, id): (&'static str, u64)) -> Self {
7775        ElementId::NamedInteger(SharedString::new_static(name), id)
7776    }
7777}
7778
7779impl From<Uuid> for ElementId {
7780    fn from(value: Uuid) -> Self {
7781        Self::Uuid(value)
7782    }
7783}
7784
7785impl From<(&'static str, u32)> for ElementId {
7786    fn from((name, id): (&'static str, u32)) -> Self {
7787        ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7788    }
7789}
7790
7791impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7792    fn from((id, name): (ElementId, T)) -> Self {
7793        ElementId::NamedChild(Arc::new(id), name.into())
7794    }
7795}
7796
7797impl From<&'static core::panic::Location<'static>> for ElementId {
7798    fn from(location: &'static core::panic::Location<'static>) -> Self {
7799        ElementId::CodeLocation(*location)
7800    }
7801}
7802
7803impl From<[u8; 20]> for ElementId {
7804    fn from(opaque_id: [u8; 20]) -> Self {
7805        ElementId::OpaqueId(opaque_id)
7806    }
7807}
7808
7809/// A rectangle to be rendered in the window at the given position and size.
7810/// Passed as an argument [`Window::paint_quad`].
7811#[derive(Clone)]
7812pub struct PaintQuad {
7813    /// The bounds of the quad within the window.
7814    pub bounds: Bounds<Pixels>,
7815    /// The radii of the quad's corners.
7816    pub corner_radii: Corners<Pixels>,
7817    /// The background color of the quad.
7818    pub background: Background,
7819    /// The widths of the quad's borders.
7820    pub border_widths: Edges<Pixels>,
7821    /// The color of the quad's borders.
7822    pub border_color: Hsla,
7823    /// The style of the quad's borders.
7824    pub border_style: BorderStyle,
7825}
7826
7827impl PaintQuad {
7828    /// Sets the corner radii of the quad.
7829    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
7830        PaintQuad {
7831            corner_radii: corner_radii.into(),
7832            ..self
7833        }
7834    }
7835
7836    /// Sets the border widths of the quad.
7837    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
7838        PaintQuad {
7839            border_widths: border_widths.into(),
7840            ..self
7841        }
7842    }
7843
7844    /// Sets the border color of the quad.
7845    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
7846        PaintQuad {
7847            border_color: border_color.into(),
7848            ..self
7849        }
7850    }
7851
7852    /// Sets the background color of the quad.
7853    pub fn background(self, background: impl Into<Background>) -> Self {
7854        PaintQuad {
7855            background: background.into(),
7856            ..self
7857        }
7858    }
7859}
7860
7861/// Creates a quad with the given parameters.
7862pub fn quad(
7863    bounds: Bounds<Pixels>,
7864    corner_radii: impl Into<Corners<Pixels>>,
7865    background: impl Into<Background>,
7866    border_widths: impl Into<Edges<Pixels>>,
7867    border_color: impl Into<Hsla>,
7868    border_style: BorderStyle,
7869) -> PaintQuad {
7870    PaintQuad {
7871        bounds,
7872        corner_radii: corner_radii.into(),
7873        background: background.into(),
7874        border_widths: border_widths.into(),
7875        border_color: border_color.into(),
7876        border_style,
7877    }
7878}
7879
7880/// Creates a filled quad with the given bounds and background color.
7881pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
7882    PaintQuad {
7883        bounds: bounds.into(),
7884        corner_radii: (0.).into(),
7885        background: background.into(),
7886        border_widths: (0.).into(),
7887        border_color: transparent_black(),
7888        border_style: BorderStyle::default(),
7889    }
7890}
7891
7892/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
7893pub fn outline(
7894    bounds: impl Into<Bounds<Pixels>>,
7895    border_color: impl Into<Hsla>,
7896    border_style: BorderStyle,
7897) -> PaintQuad {
7898    PaintQuad {
7899        bounds: bounds.into(),
7900        corner_radii: (0.).into(),
7901        background: transparent_black().into(),
7902        border_widths: (1.).into(),
7903        border_color: border_color.into(),
7904        border_style,
7905    }
7906}
7907
7908#[inline(never)]
7909fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
7910    if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
7911        // SAFETY: The pointer is valid for the duration of the draw operation
7912        // that set it, and we're being called during that same draw.
7913        let arena_cell = unsafe { &*arena_pointer };
7914        callback(&mut arena_cell.borrow_mut());
7915        Ok(())
7916    } else {
7917        ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
7918    }
7919}
7920
7921#[cfg(test)]
7922mod tests {
7923    use std::{
7924        cell::{Cell, RefCell},
7925        path::PathBuf,
7926        rc::Rc,
7927        time::Duration,
7928    };
7929
7930    use crate::{
7931        AnyWindowHandle, AppContext as _, Bounds, ContentMask, Context, DispatchPhase,
7932        DragMoveEvent, Empty, ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent,
7933        FocusHandle, InputEvent as _, InteractiveElement as _, IntoElement, KeyDownEvent,
7934        Keystroke, LongPressEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement,
7935        Pixels, PlatformInput, Point, Render, RequestFrameOptions, ScaledPixels,
7936        StatefulInteractiveElement as _, Styled, TestAppContext, TouchDragEvent, TouchEvent,
7937        TouchId, TouchPhase, Underline, UnderlineStyle, Window, WindowAppearance, WindowOptions,
7938        canvas, div, hsla, point, px, size,
7939    };
7940
7941    #[cfg(feature = "profiler")]
7942    #[gpui::test]
7943    fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
7944        use crate::FrameRequestSource;
7945        use crate::profiler::journal::{
7946            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
7947        };
7948        use scheduler::Instant;
7949
7950        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
7951        let window = cx.add_window(|_, _| EmptyView);
7952        let platform_window = cx.test_window(window.into());
7953        platform_window.simulate_frame_request(RequestFrameOptions::default());
7954        let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
7955        let mut collector = journal.collector();
7956
7957        for (signal_at, source) in [
7958            (Some(Instant::now()), FrameRequestSource::NativeCallback),
7959            (Some(Instant::now()), FrameRequestSource::LocalSchedule),
7960            (None, FrameRequestSource::NativeCallback),
7961        ] {
7962            platform_window.simulate_frame_request(RequestFrameOptions {
7963                signal_at,
7964                signal_source: source,
7965                require_presentation: true,
7966                ..Default::default()
7967            });
7968            let entries = collector.collect_unseen().entries;
7969            let signal_index = entries
7970                .iter()
7971                .position(|entry| {
7972                    matches!(
7973                        entry,
7974                        ForegroundJournalEntry::PlatformSignal(signal)
7975                            if signal.window_id == window.window_id()
7976                                && signal.signal_at == signal_at
7977                                && signal.source == source
7978                                && signal_at.is_none_or(|at| signal.handled_at >= at)
7979                    )
7980                })
7981                .expect("frame request metadata");
7982            let skip_index = entries
7983                .iter()
7984                .position(|entry| {
7985                    matches!(
7986                        entry,
7987                        ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
7988                            if skipped.window_id == window.window_id()
7989                                && skipped.reason == FrameSkipReason::NoRenderNeeded
7990                    )
7991                })
7992                .expect("completed no-render boundary");
7993            assert!(signal_index < skip_index);
7994        }
7995    }
7996
7997    #[cfg(feature = "profiler")]
7998    #[gpui::test]
7999    fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
8000        use crate::profiler::journal::{
8001            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8002        };
8003        use scheduler::Instant;
8004
8005        // Test mode draws during effect flushing, bypassing platform frame throttling.
8006        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8007        let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
8008        let mut collector = journal.collector();
8009        for initially_dirty in [true, false] {
8010            // Keep the throttle closed without depending on short wall-clock deadlines.
8011            let window = cx
8012                .app
8013                .borrow_mut()
8014                .open_window(
8015                    WindowOptions {
8016                        inactive_frame_interval: Some(Duration::from_secs(3600)),
8017                        ..Default::default()
8018                    },
8019                    |_, cx| cx.new(|_| EmptyView),
8020                )
8021                .expect("open inactive test window");
8022            let platform_window = cx.test_window(window.into());
8023            platform_window.simulate_active_status_change(false);
8024            platform_window.simulate_frame_request(RequestFrameOptions::default());
8025            let callback_ran = Rc::new(Cell::new(false));
8026            let draws_before = window
8027                .update(cx, |_, window, _| {
8028                    let draws_before = window
8029                        .frame_duration_snapshot()
8030                        .draw_duration_histogram
8031                        .len();
8032                    if initially_dirty {
8033                        window.refresh();
8034                    }
8035                    window.on_next_frame({
8036                        let callback_ran = callback_ran.clone();
8037                        move |window, _| {
8038                            callback_ran.set(true);
8039                            window.refresh();
8040                        }
8041                    });
8042                    draws_before
8043                })
8044                .expect("schedule throttled frame");
8045            // Skips only seal retained work, so give the throttled skip some.
8046            let input_at = Instant::now();
8047            journal::record_input(journal::InputTiming {
8048                kind: "test",
8049                start: input_at,
8050                end: input_at,
8051                caused_invalidation: false,
8052            });
8053            collector.collect_unseen();
8054            platform_window.simulate_frame_request(RequestFrameOptions {
8055                signal_at: Some(Instant::now()),
8056                ..Default::default()
8057            });
8058            window
8059                .update(cx, |_, window, _| {
8060                    assert_eq!(
8061                        window
8062                            .frame_duration_snapshot()
8063                            .draw_duration_histogram
8064                            .len(),
8065                        draws_before,
8066                    );
8067                })
8068                .expect("inspect deferred frame");
8069            assert!(!callback_ran.get());
8070            assert!(collector.collect_unseen().entries.iter().any(|entry| {
8071                matches!(
8072                    entry,
8073                    ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8074                        if skipped.window_id == window.window_id()
8075                            && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
8076                )
8077            }));
8078            platform_window.simulate_frame_request(RequestFrameOptions {
8079                signal_at: Some(Instant::now()),
8080                require_presentation: true,
8081                ..Default::default()
8082            });
8083            window
8084                .update(cx, |_, window, _| {
8085                    assert_eq!(
8086                        window
8087                            .frame_duration_snapshot()
8088                            .draw_duration_histogram
8089                            .len(),
8090                        draws_before + 1,
8091                    );
8092                })
8093                .expect("inspect presented frame");
8094            assert!(callback_ran.get());
8095        }
8096    }
8097
8098    /// Visibility transitions reach observers exactly once each, with the new
8099    /// state already stored on the window, and never wake the platform for a
8100    /// frame: the platform requests one itself when it resumes presenting.
8101    #[gpui::test]
8102    fn test_window_visibility(cx: &mut TestAppContext) {
8103        use crate::WindowVisibility;
8104
8105        let window = cx.add_window(|_, _| EmptyView);
8106        let observed = Rc::new(RefCell::new(Vec::new()));
8107        let _subscription = window
8108            .update(cx, {
8109                let observed = observed.clone();
8110                move |_, window, _| {
8111                    assert_eq!(window.visibility(), WindowVisibility::Visible);
8112                    assert!(window.is_visible());
8113                    window.observe_window_visibility(move |visibility, window, _| {
8114                        assert_eq!(window.visibility(), visibility);
8115                        observed.borrow_mut().push(visibility);
8116                    })
8117                }
8118            })
8119            .unwrap();
8120        let test_window = cx.test_window(window.into());
8121        let frame_wake_count = test_window.frame_wake_count();
8122
8123        test_window.simulate_visibility_change(WindowVisibility::Hidden);
8124        assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
8125        window
8126            .update(cx, |_, window, _| assert!(!window.is_visible()))
8127            .unwrap();
8128
8129        // Platforms may report the same state again; observers only see changes.
8130        test_window.simulate_visibility_change(WindowVisibility::Hidden);
8131        assert_eq!(observed.borrow().len(), 1);
8132
8133        test_window.simulate_visibility_change(WindowVisibility::Visible);
8134        assert_eq!(
8135            *observed.borrow(),
8136            [WindowVisibility::Hidden, WindowVisibility::Visible]
8137        );
8138        window
8139            .update(cx, |_, window, _| assert!(window.is_visible()))
8140            .unwrap();
8141        assert_eq!(test_window.frame_wake_count(), frame_wake_count);
8142    }
8143
8144    /// App learns display state from the platform's display notifications,
8145    /// and a window from the platform's report of which display it is on.
8146    #[gpui::test]
8147    fn test_display_tracking(cx: &mut TestAppContext) {
8148        use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
8149
8150        let sixty_hertz = Duration::from_secs(1) / 60;
8151        let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
8152        let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
8153
8154        let display_events = Rc::new(RefCell::new(Vec::new()));
8155        let _display_subscription = cx.update({
8156            let display_events = display_events.clone();
8157            move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
8158        });
8159
8160        let window = cx.add_window(|window, cx| DisplayTracker {
8161            refresh_intervals: Vec::new(),
8162            _subscription: cx.observe_window_display(
8163                window,
8164                |tracker: &mut DisplayTracker, window, cx| {
8165                    tracker.refresh_intervals.push(window.refresh_interval(cx));
8166                },
8167            ),
8168        });
8169        let window_notifications = Rc::new(RefCell::new(Vec::new()));
8170        let _window_subscription = window
8171            .update(cx, {
8172                let window_notifications = window_notifications.clone();
8173                move |_, window, cx| {
8174                    assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
8175                    window.observe_window_display(move |window, cx| {
8176                        window_notifications
8177                            .borrow_mut()
8178                            .push((window.display_id, window.refresh_interval(cx)));
8179                    })
8180                }
8181            })
8182            .unwrap();
8183        let test_window = cx.test_window(window.into());
8184
8185        // The window may hear that it moved before App hears the display was
8186        // connected. App learns about the display before the window's
8187        // observers run, and the platform's later notification changes
8188        // nothing.
8189        cx.test_platform()
8190            .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
8191        test_window.simulate_move_to_display(DisplayId(2));
8192        assert_eq!(
8193            window_notifications.take(),
8194            [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
8195        );
8196        assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
8197        cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
8198        assert!(window_notifications.borrow().is_empty());
8199
8200        // Platforms may report a move that isn't one.
8201        test_window.simulate_move_to_display(DisplayId(2));
8202        assert!(window_notifications.borrow().is_empty());
8203
8204        cx.simulate_display_refresh_interval_change(
8205            DisplayId(2),
8206            Some(one_hundred_forty_four_hertz),
8207        );
8208        assert_eq!(
8209            window_notifications.take(),
8210            [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
8211        );
8212
8213        // Changes to a display the window isn't on don't notify it.
8214        cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
8215        cx.simulate_display_removed(DisplayId(1));
8216        assert!(window_notifications.borrow().is_empty());
8217
8218        assert_eq!(
8219            display_events.take(),
8220            [
8221                DisplayEvent::Changed {
8222                    id: DisplayId(2),
8223                    changes: DisplayChanges::REFRESH_INTERVAL,
8224                },
8225                DisplayEvent::Changed {
8226                    id: DisplayId(1),
8227                    changes: DisplayChanges::REFRESH_INTERVAL,
8228                },
8229                DisplayEvent::Removed(DisplayId(1)),
8230            ]
8231        );
8232        window
8233            .update(cx, |tracker, _, _| {
8234                assert_eq!(
8235                    tracker.refresh_intervals,
8236                    [
8237                        Some(one_hundred_twenty_hertz),
8238                        Some(one_hundred_forty_four_hertz)
8239                    ]
8240                );
8241            })
8242            .unwrap();
8243
8244        struct DisplayTracker {
8245            refresh_intervals: Vec<Option<Duration>>,
8246            _subscription: Subscription,
8247        }
8248
8249        impl Render for DisplayTracker {
8250            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8251                Empty
8252            }
8253        }
8254    }
8255
8256    #[gpui::test]
8257    fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
8258        let window = cx.add_window(|_, _| EmptyView);
8259        let mut platform_window = cx.test_window(window.into());
8260        platform_window.simulate_resize(size(px(400.), px(800.)));
8261        window
8262            .update(cx, |_, window, _| {
8263                assert_eq!(
8264                    window.visual_viewport_bounds(),
8265                    Bounds::new(Point::default(), size(px(400.), px(800.)))
8266                );
8267                assert_eq!(
8268                    window.fully_visible_bounds(),
8269                    window.visual_viewport_bounds()
8270                );
8271            })
8272            .unwrap();
8273
8274        platform_window.simulate_frame_request(RequestFrameOptions::default());
8275        let wakes = platform_window.frame_wake_count();
8276        let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
8277        platform_window.simulate_visual_viewport_change(visual_bounds);
8278        assert!(platform_window.frame_wake_count() > wakes);
8279        platform_window.simulate_frame_request(RequestFrameOptions::default());
8280        let wakes = platform_window.frame_wake_count();
8281        platform_window.simulate_insets_change(crate::WindowInsets {
8282            safe_area: crate::Edges {
8283                top: px(60.),
8284                right: px(20.),
8285                bottom: px(30.),
8286                left: px(-10.),
8287            },
8288            ime: crate::Edges {
8289                bottom: px(350.),
8290                ..Default::default()
8291            },
8292        });
8293        assert!(platform_window.frame_wake_count() > wakes);
8294        window
8295            .update(cx, |_, window, _| {
8296                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8297                assert_eq!(window.visual_viewport_bounds(), visual_bounds);
8298                assert_eq!(
8299                    window.fully_visible_bounds(),
8300                    Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
8301                );
8302                window.request_virtual_keyboard();
8303                window.dismiss_virtual_keyboard();
8304                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8305            })
8306            .unwrap();
8307        assert_eq!(platform_window.virtual_keyboard_requests(), 1);
8308        assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
8309
8310        platform_window.simulate_insets_change(crate::WindowInsets {
8311            safe_area: crate::Edges {
8312                top: px(900.),
8313                left: px(500.),
8314                ..Default::default()
8315            },
8316            ..Default::default()
8317        });
8318        window
8319            .update(cx, |_, window, _| {
8320                assert_eq!(
8321                    window.fully_visible_bounds().size,
8322                    size(Pixels::ZERO, Pixels::ZERO)
8323                );
8324            })
8325            .unwrap();
8326    }
8327
8328    struct EmptyView;
8329
8330    impl Render for EmptyView {
8331        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8332            div()
8333        }
8334    }
8335
8336    struct OpensWindowOnPaint {
8337        opened: Rc<Cell<bool>>,
8338    }
8339
8340    impl Render for OpensWindowOnPaint {
8341        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8342            let opened = self.opened.clone();
8343            div()
8344                .size_full()
8345                .child(canvas(
8346                    |_, _, _| {},
8347                    move |_, _, _window, cx| {
8348                        if !opened.replace(true) {
8349                            cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
8350                                .unwrap();
8351                        }
8352                    },
8353                ))
8354                // Siblings painted after the canvas: their elements were
8355                // allocated in the arena before the nested draw, so they detect
8356                // a mid-draw arena clear when painted afterwards.
8357                .child(div().child("after"))
8358        }
8359    }
8360
8361    /// Opening a window synchronously draws it and requests an element arena
8362    /// clear. When that happens from within another window's draw (here: from
8363    /// an element's paint), the clear must be deferred until the outer draw
8364    /// finishes, or the outer draw's arena-allocated elements would be freed
8365    /// out from under it.
8366    #[test]
8367    fn test_window_opened_during_draw_defers_arena_clear() {
8368        let mut cx = TestAppContext::single();
8369
8370        let opened = Rc::new(Cell::new(false));
8371        // add_window draws once, which runs the nested open_window mid-draw.
8372        let window = cx.add_window({
8373            let opened = opened.clone();
8374            move |_, _| OpensWindowOnPaint { opened }
8375        });
8376
8377        assert!(opened.get());
8378        assert_eq!(cx.windows().len(), 2);
8379
8380        // The deferred clear must actually run once the outer draw unwinds:
8381        // subsequent draws of both windows work against a fresh arena.
8382        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8383            .unwrap();
8384    }
8385
8386    #[test]
8387    fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
8388        let mut cx = TestAppContext::single();
8389        let window = cx.add_window(|_, _| EmptyView);
8390        let handle: AnyWindowHandle = window.into();
8391        let window_state = |cx: &mut TestAppContext| {
8392            cx.update_window(handle, |_, window, _| {
8393                (
8394                    window.scale_factor(),
8395                    window.bounds(),
8396                    window.viewport_size(),
8397                )
8398            })
8399            .unwrap()
8400        };
8401
8402        let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
8403        assert_eq!(scale_factor, 2.0);
8404
8405        for (scale_factor, resized_size) in [
8406            (1.0, size(px(800.), px(600.))),
8407            (1.25, size(px(640.), px(480.))),
8408            (2.0, size(px(1024.), px(768.))),
8409        ] {
8410            cx.simulate_window_scale_factor_change(handle, scale_factor);
8411            assert_eq!(
8412                window_state(&mut cx),
8413                (scale_factor, expected_bounds, expected_bounds.size)
8414            );
8415
8416            cx.simulate_window_resize(handle, resized_size);
8417            expected_bounds.size = resized_size;
8418            assert_eq!(
8419                window_state(&mut cx),
8420                (scale_factor, expected_bounds, resized_size)
8421            );
8422        }
8423    }
8424
8425    /// Platforms that stop requesting frames for idle windows (currently web)
8426    /// rely on the frame waker firing whenever frame demand arises; a demand
8427    /// source that skips the waker shows up there as a window that silently
8428    /// stops repainting until unrelated activity wakes it.
8429    #[gpui::test]
8430    fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
8431        let window = cx.add_window(|_, _| EmptyView);
8432        let test_window = cx.test_window(window.into());
8433
8434        // Windows start dirty, and that can predate waker installation;
8435        // installing the waker must deliver the pending wake or the first
8436        // frame would never be requested.
8437        assert!(
8438            test_window.frame_wake_count() >= 1,
8439            "opening a window must wake the frame source for the initial frame"
8440        );
8441
8442        // Serve outstanding demand (present the frame drawn by `add_window`).
8443        test_window.simulate_frame_request(RequestFrameOptions::default());
8444
8445        // An idle window must not wake on clean frames or plain updates, or
8446        // the frame source could never stop.
8447        let baseline = test_window.frame_wake_count();
8448        test_window.simulate_frame_request(RequestFrameOptions::default());
8449        window.update(cx, |_, _, _| {}).unwrap();
8450        assert_eq!(
8451            test_window.frame_wake_count(),
8452            baseline,
8453            "clean frames and non-notifying updates must not wake the frame source"
8454        );
8455
8456        // Notifying a view in an idle window is the core demand signal.
8457        window.update(cx, |_, _, cx| cx.notify()).unwrap();
8458        assert!(
8459            test_window.frame_wake_count() > baseline,
8460            "notifying a view in an idle window must wake the frame source"
8461        );
8462
8463        // Serving that demand returns to idle without further wakes.
8464        test_window.simulate_frame_request(RequestFrameOptions::default());
8465        let baseline = test_window.frame_wake_count();
8466        test_window.simulate_frame_request(RequestFrameOptions::default());
8467        assert_eq!(
8468            test_window.frame_wake_count(),
8469            baseline,
8470            "serving demand must return the window to idle"
8471        );
8472
8473        // Next-frame callbacks create demand without dirtying the window.
8474        window
8475            .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
8476            .unwrap();
8477        assert!(
8478            test_window.frame_wake_count() > baseline,
8479            "scheduling a next-frame callback in an idle window must wake the frame source"
8480        );
8481    }
8482
8483    /// A frame request that arrives while next-frame callbacks are pending
8484    /// must never strand them: either the frame runs them, or (when the
8485    /// inactive-window frame-rate throttle defers the frame) the waker fires
8486    /// so another request is delivered.
8487    #[gpui::test]
8488    fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
8489        let window = cx.add_window(|_, _| EmptyView);
8490        let test_window = cx.test_window(window.into());
8491        // Establish a recent last-frame time so the inactive-window throttle
8492        // can engage on the next request.
8493        test_window.simulate_frame_request(RequestFrameOptions::default());
8494
8495        let callback_ran = Rc::new(Cell::new(false));
8496        window
8497            .update(cx, {
8498                let callback_ran = callback_ran.clone();
8499                move |_, window, _| {
8500                    window.on_next_frame(move |_, _| callback_ran.set(true));
8501                }
8502            })
8503            .unwrap();
8504
8505        let baseline = test_window.frame_wake_count();
8506        test_window.simulate_frame_request(RequestFrameOptions::default());
8507        // The test window is inactive, so this request throttles to ~30fps
8508        // when it lands within the throttle interval of the previous frame
8509        // (the common case here, but timing-dependent): the callback is
8510        // deferred and the waker must re-arm the frame source. On a slow run
8511        // the request instead lands outside the interval and runs the
8512        // callback directly.
8513        assert!(
8514            test_window.frame_wake_count() > baseline || callback_ran.get(),
8515            "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
8516        );
8517    }
8518
8519    #[gpui::test]
8520    fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
8521        use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
8522
8523        let window = cx.add_window(|_, _| EmptyView);
8524        window
8525            .update(cx, |_, window, _| {
8526                assert!(matches!(
8527                    window.window_handle(),
8528                    Err(HandleError::NotSupported)
8529                ));
8530                assert!(matches!(
8531                    window.display_handle(),
8532                    Err(HandleError::NotSupported)
8533                ));
8534            })
8535            .unwrap();
8536    }
8537
8538    #[gpui::test]
8539    fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
8540        let window = cx.add_window(|_, _| EmptyView);
8541        let observed_appearance = Rc::new(Cell::new(None));
8542        let _subscription = window
8543            .update(cx, {
8544                let observed_appearance = observed_appearance.clone();
8545                move |_, window, _| {
8546                    window.observe_window_appearance(move |window, _| {
8547                        observed_appearance.set(Some(window.appearance()));
8548                    })
8549                }
8550            })
8551            .unwrap();
8552        let test_window = cx.test_window(window.into());
8553
8554        cx.update(|_| {
8555            test_window.simulate_appearance_change(WindowAppearance::Dark);
8556            assert_eq!(observed_appearance.get(), None);
8557        });
8558        cx.run_until_parked();
8559
8560        assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
8561    }
8562
8563    #[gpui::test]
8564    fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8565        let window = cx.add_window(|_, _| Empty);
8566        let test_window = cx.test_window(window.into());
8567
8568        assert!(test_window.simulate_scheduled_frame());
8569        assert!(test_window.simulate_scheduled_frame());
8570        assert!(!test_window.frame_scheduled());
8571
8572        cx.update_window(window.into(), |_, window, _| {
8573            window.active.set(true);
8574            window.on_next_frame(|_, _| {});
8575        })
8576        .unwrap();
8577        assert!(
8578            test_window.frame_scheduled(),
8579            "queuing work on a parked window must wake the render loop"
8580        );
8581
8582        assert!(test_window.simulate_scheduled_frame());
8583        assert!(
8584            test_window.frame_scheduled(),
8585            "presenting the frame must await one compositor callback"
8586        );
8587        assert!(test_window.simulate_scheduled_frame());
8588        assert!(!test_window.frame_scheduled());
8589    }
8590
8591    #[gpui::test]
8592    fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8593        let window = cx.add_window(|_, _| Empty);
8594        let test_window = cx.test_window(window.into());
8595
8596        assert!(test_window.simulate_scheduled_frame());
8597        assert!(test_window.simulate_scheduled_frame());
8598        assert!(!test_window.frame_scheduled());
8599
8600        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8601            .unwrap();
8602
8603        assert!(
8604            test_window.frame_scheduled(),
8605            "a rendered scene awaiting presentation must wake the render loop"
8606        );
8607    }
8608
8609    #[gpui::test]
8610    fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
8611        let window = cx.add_window(|_, _| Empty);
8612        let test_window = cx.test_window(window.into());
8613
8614        let callback_ran = Rc::new(Cell::new(false));
8615        cx.update_window(window.into(), |_, window, _| {
8616            // Inactive windows are frame-rate throttled, which would defer the
8617            // ticks this test drives manually.
8618            window.active.set(true);
8619            let callback_ran = callback_ran.clone();
8620            window.on_next_frame(move |window, _| {
8621                window.on_next_frame(move |_, _| callback_ran.set(true));
8622            });
8623        })
8624        .unwrap();
8625
8626        assert!(test_window.simulate_scheduled_frame());
8627        assert!(!callback_ran.get());
8628        assert!(
8629            test_window.frame_scheduled(),
8630            "a callback queued mid-frame must schedule a follow-up before the loop parks"
8631        );
8632
8633        assert!(test_window.simulate_scheduled_frame());
8634        assert!(callback_ran.get());
8635    }
8636
8637    struct RootView {
8638        explicit_size: bool,
8639        child_bounds: Rc<Cell<Bounds<Pixels>>>,
8640    }
8641
8642    impl Render for RootView {
8643        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8644            let child_bounds = self.child_bounds.clone();
8645            let root = div().flex().flex_col().child(
8646                canvas(
8647                    move |bounds, _, _| child_bounds.set(bounds),
8648                    |_, _, _, _| {},
8649                )
8650                .size_full(),
8651            );
8652            if self.explicit_size {
8653                root.w(px(300.)).h(px(200.))
8654            } else {
8655                root
8656            }
8657        }
8658    }
8659
8660    #[test]
8661    fn auto_sized_window_root_fills_the_window() {
8662        let mut cx = TestAppContext::single();
8663        let child_bounds = Rc::new(Cell::new(Bounds::default()));
8664        let window = cx.add_window({
8665            let child_bounds = child_bounds.clone();
8666            move |_, _| RootView {
8667                explicit_size: false,
8668                child_bounds,
8669            }
8670        });
8671
8672        let viewport_size = cx
8673            .update_window(window.into(), |_, window, cx| {
8674                window.draw(cx).clear(cx);
8675                window.viewport_size()
8676            })
8677            .unwrap();
8678
8679        assert_eq!(child_bounds.get().size, viewport_size);
8680    }
8681
8682    #[test]
8683    fn explicitly_sized_window_root_keeps_its_size() {
8684        let mut cx = TestAppContext::single();
8685        let child_bounds = Rc::new(Cell::new(Bounds::default()));
8686        let window = cx.add_window({
8687            let child_bounds = child_bounds.clone();
8688            move |_, _| RootView {
8689                explicit_size: true,
8690                child_bounds,
8691            }
8692        });
8693
8694        cx.update_window(window.into(), |_, window, cx| {
8695            window.draw(cx).clear(cx);
8696        })
8697        .unwrap();
8698
8699        assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
8700    }
8701
8702    struct FileDragView {
8703        path: PathBuf,
8704        observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8705        observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8706    }
8707
8708    struct FileDropExitView(Rc<Cell<usize>>);
8709
8710    impl Render for FileDropExitView {
8711        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8712            div().size_full().on_file_drop_exit({
8713                let observed_file_drop_exit = self.0.clone();
8714                move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
8715            })
8716        }
8717    }
8718
8719    impl Render for FileDragView {
8720        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8721            div()
8722                .id("file-drag")
8723                .size_full()
8724                .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
8725                .external_drag_payload(|path: &PathBuf, _, _| {
8726                    Some(ExternalDragPayload::Files(FileDragPaths::new([(
8727                        path.clone(),
8728                        true,
8729                    )])))
8730                })
8731                .on_drag_move({
8732                    let observed_drag_moves = self.observed_drag_moves.clone();
8733                    move |event: &DragMoveEvent<PathBuf>, _, _| {
8734                        observed_drag_moves.borrow_mut().push(event.event.position);
8735                    }
8736                })
8737                .on_drop({
8738                    let observed_drops = self.observed_drops.clone();
8739                    move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
8740                })
8741        }
8742    }
8743
8744    #[gpui::test]
8745    fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
8746        struct Drag {
8747            window: AnyWindowHandle,
8748            observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8749            observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8750        }
8751
8752        fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
8753            let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
8754            let observed_drops = Rc::new(RefCell::new(Vec::new()));
8755            let window: AnyWindowHandle = cx
8756                .add_window({
8757                    let observed_drag_moves = observed_drag_moves.clone();
8758                    let observed_drops = observed_drops.clone();
8759                    move |_, _| FileDragView {
8760                        path,
8761                        observed_drag_moves,
8762                        observed_drops,
8763                    }
8764                })
8765                .into();
8766            cx.test_window(window)
8767                .set_start_external_drag_result(platform_result);
8768
8769            let update_result = cx.update_window(window, |_, window, cx| {
8770                window.draw(cx).clear(cx);
8771                window.dispatch_event(
8772                    MouseDownEvent {
8773                        position: point(px(10.), px(10.)),
8774                        button: MouseButton::Left,
8775                        modifiers: Default::default(),
8776                        click_count: 1,
8777                        first_mouse: false,
8778                    }
8779                    .to_platform_input(),
8780                    cx,
8781                );
8782                window.dispatch_event(
8783                    MouseMoveEvent {
8784                        position: point(px(20.), px(20.)),
8785                        pressed_button: Some(MouseButton::Left),
8786                        modifiers: Default::default(),
8787                    }
8788                    .to_platform_input(),
8789                    cx,
8790                );
8791                assert!(cx.active_drag.is_some());
8792            });
8793            assert!(
8794                update_result.is_ok(),
8795                "failed to start drag: {update_result:?}"
8796            );
8797
8798            assert!(cx.test_window(window).external_drag_files().is_empty());
8799            Drag {
8800                window,
8801                observed_drag_moves,
8802                observed_drops,
8803            }
8804        }
8805
8806        let successful_path = PathBuf::from("/tmp/successful-drag");
8807        let successful = start_drag(cx, successful_path.clone(), true);
8808        let outside_position = point(px(-1.), px(20.));
8809        let update_result = cx.update_window(successful.window, |_, window, cx| {
8810            window.dispatch_event(
8811                MouseMoveEvent {
8812                    position: outside_position,
8813                    pressed_button: Some(MouseButton::Left),
8814                    modifiers: Default::default(),
8815                }
8816                .to_platform_input(),
8817                cx,
8818            );
8819            assert!(cx.active_drag.is_none());
8820        });
8821        assert!(
8822            update_result.is_ok(),
8823            "failed to promote drag: {update_result:?}"
8824        );
8825        assert_eq!(
8826            cx.test_window(successful.window).external_drag_files(),
8827            [(successful_path.clone(), true)]
8828        );
8829        // Views must still see the move that leaves the window, otherwise they never learn to tear
8830        // down the drag state they built up while the pointer was inside.
8831        assert_eq!(
8832            successful.observed_drag_moves.borrow().last(),
8833            Some(&outside_position)
8834        );
8835
8836        let first_destination_exit_count = Rc::new(Cell::new(0));
8837        let first_destination: AnyWindowHandle = cx
8838            .add_window({
8839                let first_destination_exit_count = first_destination_exit_count.clone();
8840                move |_, _| FileDropExitView(first_destination_exit_count)
8841            })
8842            .into();
8843        let second_destination_exit_count = Rc::new(Cell::new(0));
8844        let second_destination: AnyWindowHandle = cx
8845            .add_window({
8846                let second_destination_exit_count = second_destination_exit_count.clone();
8847                move |_, _| FileDropExitView(second_destination_exit_count)
8848            })
8849            .into();
8850        let reentry_position = point(px(30.), px(30.));
8851        let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
8852        let update_result = cx.update_window(first_destination, |_, window, cx| {
8853            window.draw(cx).clear(cx);
8854            window.dispatch_event(
8855                FileDropEvent::Entered {
8856                    position: reentry_position,
8857                    paths: external_paths(),
8858                }
8859                .to_platform_input(),
8860                cx,
8861            );
8862            assert!(
8863                cx.active_drag
8864                    .as_ref()
8865                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
8866            );
8867            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8868            assert!(cx.active_drag.is_none());
8869            assert_eq!(first_destination_exit_count.get(), 1);
8870            assert_eq!(second_destination_exit_count.get(), 0);
8871        });
8872        assert!(
8873            update_result.is_ok(),
8874            "failed to handle drag in first destination window: {update_result:?}"
8875        );
8876
8877        let update_result = cx.update_window(second_destination, |_, window, cx| {
8878            window.draw(cx).clear(cx);
8879            window.dispatch_event(
8880                PlatformInput::KeyDown(KeyDownEvent {
8881                    keystroke: Keystroke::parse("down").expect("valid keystroke"),
8882                    is_held: false,
8883                    prefer_character_input: false,
8884                }),
8885                cx,
8886            );
8887            window.dispatch_event(
8888                FileDropEvent::Entered {
8889                    position: reentry_position,
8890                    paths: external_paths(),
8891                }
8892                .to_platform_input(),
8893                cx,
8894            );
8895            assert!(
8896                cx.active_drag
8897                    .as_ref()
8898                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
8899            );
8900            assert_eq!(first_destination_exit_count.get(), 1);
8901            assert_eq!(second_destination_exit_count.get(), 0);
8902
8903            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8904            assert!(cx.active_drag.is_none());
8905            assert_eq!(first_destination_exit_count.get(), 1);
8906            assert_eq!(second_destination_exit_count.get(), 1);
8907        });
8908        assert!(
8909            update_result.is_ok(),
8910            "failed to handle drag in second destination window: {update_result:?}"
8911        );
8912
8913        let update_result = cx.update_window(successful.window, |_, window, cx| {
8914            window.dispatch_event(
8915                FileDropEvent::Entered {
8916                    position: reentry_position,
8917                    paths: external_paths(),
8918                }
8919                .to_platform_input(),
8920                cx,
8921            );
8922            assert!(
8923                cx.active_drag
8924                    .as_ref()
8925                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
8926            );
8927            assert_eq!(
8928                successful.observed_drag_moves.borrow().last(),
8929                Some(&reentry_position)
8930            );
8931
8932            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8933            assert!(cx.active_drag.is_none());
8934
8935            window.dispatch_event(
8936                FileDropEvent::Entered {
8937                    position: reentry_position,
8938                    paths: external_paths(),
8939                }
8940                .to_platform_input(),
8941                cx,
8942            );
8943            assert!(
8944                cx.active_drag
8945                    .as_ref()
8946                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
8947            );
8948
8949            window.dispatch_event(
8950                FileDropEvent::Submit {
8951                    position: reentry_position,
8952                }
8953                .to_platform_input(),
8954                cx,
8955            );
8956            assert_eq!(
8957                successful.observed_drops.borrow().as_slice(),
8958                std::slice::from_ref(&successful_path)
8959            );
8960            assert!(cx.active_drag.is_none());
8961
8962            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8963            assert!(cx.active_drag.is_none());
8964            window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
8965            assert!(cx.active_drag.is_none());
8966
8967            window.dispatch_event(
8968                FileDropEvent::Entered {
8969                    position: reentry_position,
8970                    paths: external_paths(),
8971                }
8972                .to_platform_input(),
8973                cx,
8974            );
8975            assert!(
8976                cx.active_drag
8977                    .as_ref()
8978                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
8979            );
8980            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8981        });
8982        assert!(
8983            update_result.is_ok(),
8984            "failed to restore drag in source window: {update_result:?}"
8985        );
8986
8987        let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
8988        let cancelled = start_drag(cx, cancelled_path.clone(), true);
8989        let update_result = cx.update_window(cancelled.window, |_, window, cx| {
8990            window.dispatch_event(
8991                MouseMoveEvent {
8992                    position: outside_position,
8993                    pressed_button: Some(MouseButton::Left),
8994                    modifiers: Default::default(),
8995                }
8996                .to_platform_input(),
8997                cx,
8998            );
8999            assert!(cx.active_drag.is_none());
9000
9001            window.dispatch_event(
9002                FileDropEvent::Entered {
9003                    position: reentry_position,
9004                    paths: ExternalPaths([cancelled_path].into_iter().collect()),
9005                }
9006                .to_platform_input(),
9007                cx,
9008            );
9009            assert!(
9010                cx.active_drag
9011                    .as_ref()
9012                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9013            );
9014            assert!(cx.stop_active_drag(window));
9015            assert!(cx.active_drag.is_none());
9016        });
9017        assert!(
9018            update_result.is_ok(),
9019            "failed to cancel restored drag: {update_result:?}"
9020        );
9021        assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
9022
9023        let removed_path = PathBuf::from("/tmp/removed-window-drag");
9024        let removed = start_drag(cx, removed_path, true);
9025        let removed_window_id = removed.window.window_id();
9026        let update_result = cx.update_window(removed.window, |_, window, cx| {
9027            window.dispatch_event(
9028                MouseMoveEvent {
9029                    position: outside_position,
9030                    pressed_button: Some(MouseButton::Left),
9031                    modifiers: Default::default(),
9032                }
9033                .to_platform_input(),
9034                cx,
9035            );
9036            assert!(cx.active_drag.is_none());
9037            window.remove_window();
9038        });
9039        assert!(
9040            update_result.is_ok(),
9041            "failed to remove drag source window: {update_result:?}"
9042        );
9043        assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
9044
9045        let failed_path = PathBuf::from("/tmp/failed-drag");
9046        let failed = start_drag(cx, failed_path.clone(), false);
9047        let update_result = cx.update_window(failed.window, |_, window, cx| {
9048            for x_position in [-1., -2.] {
9049                window.dispatch_event(
9050                    MouseMoveEvent {
9051                        position: point(px(x_position), px(20.)),
9052                        pressed_button: Some(MouseButton::Left),
9053                        modifiers: Default::default(),
9054                    }
9055                    .to_platform_input(),
9056                    cx,
9057                );
9058            }
9059            assert!(cx.active_drag.is_some());
9060        });
9061        assert!(
9062            update_result.is_ok(),
9063            "failed to retain drag after platform failure: {update_result:?}"
9064        );
9065        assert_eq!(
9066            cx.test_window(failed.window).external_drag_files(),
9067            [(failed_path, true)]
9068        );
9069    }
9070
9071    struct FocusForwarder {
9072        a: FocusHandle,
9073        b: FocusHandle,
9074    }
9075
9076    impl Render for FocusForwarder {
9077        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9078            div()
9079                .size_full()
9080                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
9081                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
9082        }
9083    }
9084
9085    /// When a focus listener moves focus again (e.g. a dock forwarding focus to its
9086    /// active panel), the resulting focus events must be dispatched without waiting
9087    /// for an unrelated redraw of the window.
9088    #[gpui::test]
9089    fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
9090        let b_focus_count = Rc::new(Cell::new(0));
9091        let window = cx.add_window({
9092            let b_focus_count = b_focus_count.clone();
9093            move |window, cx| {
9094                let a = cx.focus_handle();
9095                let b = cx.focus_handle();
9096                cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
9097                    let b = this.b.clone();
9098                    window.focus(&b, cx);
9099                })
9100                .detach();
9101                cx.on_focus(&b, window, move |_, _, _| {
9102                    b_focus_count.set(b_focus_count.get() + 1);
9103                })
9104                .detach();
9105                FocusForwarder { a, b }
9106            }
9107        });
9108
9109        window
9110            .update(cx, |_, window, _| window.activate_window())
9111            .unwrap();
9112        cx.executor().run_until_parked();
9113
9114        window
9115            .update(cx, |this, window, cx| {
9116                let a = this.a.clone();
9117                window.focus(&a, cx);
9118            })
9119            .unwrap();
9120        cx.executor().run_until_parked();
9121
9122        window
9123            .update(cx, |this, window, _| {
9124                assert!(this.b.is_focused(window));
9125            })
9126            .unwrap();
9127        assert_eq!(b_focus_count.get(), 1);
9128    }
9129
9130    #[gpui::test]
9131    fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
9132        let events = Rc::new(RefCell::new(Vec::new()));
9133        let window = cx.add_window({
9134            let events = events.clone();
9135            move |_, _| TouchDragListener { events }
9136        });
9137        let touch = TouchId(1);
9138
9139        dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
9140        dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
9141        dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
9142
9143        assert_eq!(
9144            events.borrow().as_slice(),
9145            [
9146                (TouchPhase::Started, px(10.)),
9147                (TouchPhase::Moved, px(30.)),
9148                (TouchPhase::Ended, px(40.)),
9149            ]
9150        );
9151    }
9152
9153    struct TouchDragListener {
9154        events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
9155    }
9156
9157    impl Render for TouchDragListener {
9158        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9159            let events = self.events.clone();
9160            canvas(
9161                |_, _, _| {},
9162                move |_, _, window, _| {
9163                    window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
9164                        if phase != DispatchPhase::Bubble {
9165                            return;
9166                        }
9167                        events.borrow_mut().push((event.phase, event.position.x));
9168                        if event.phase == TouchPhase::Started {
9169                            window.prevent_default();
9170                        }
9171                    });
9172                },
9173            )
9174        }
9175    }
9176
9177    #[gpui::test]
9178    fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
9179        for response in [
9180            LongPressResponse::PreventDefault,
9181            LongPressResponse::StopPropagation,
9182            LongPressResponse::None,
9183        ] {
9184            let phases = Rc::new(RefCell::new(Vec::new()));
9185            let window = cx.add_window({
9186                let phases = phases.clone();
9187                move |_, _| LongPressListener { phases, response }
9188            });
9189            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9190            cx.executor().advance_clock(Duration::from_millis(501));
9191            cx.executor().run_until_parked();
9192            window
9193                .update(cx, |_, window, _| {
9194                    assert_eq!(
9195                        window.long_press_capture.is_some(),
9196                        response == LongPressResponse::PreventDefault
9197                    );
9198                })
9199                .unwrap();
9200            dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9201            dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
9202            window
9203                .update(cx, |_, window, _| {
9204                    assert!(window.long_press_capture.is_none());
9205                })
9206                .unwrap();
9207
9208            let phases = phases.borrow();
9209            if response == LongPressResponse::PreventDefault {
9210                assert_eq!(
9211                    phases.as_slice(),
9212                    [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
9213                );
9214            } else {
9215                assert_eq!(phases.as_slice(), [TouchPhase::Started]);
9216            }
9217        }
9218    }
9219
9220    #[gpui::test]
9221    fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
9222        let phases = Rc::new(RefCell::new(Vec::new()));
9223        let window = cx.add_window({
9224            let phases = phases.clone();
9225            move |_, _| LongPressListener {
9226                phases,
9227                response: LongPressResponse::None,
9228            }
9229        });
9230        window
9231            .update(cx, |_, window, _| {
9232                window.prevent_default();
9233            })
9234            .unwrap();
9235
9236        dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9237        cx.executor().advance_clock(Duration::from_millis(501));
9238        cx.executor().run_until_parked();
9239        dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9240
9241        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9242    }
9243
9244    #[gpui::test]
9245    fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
9246        for (phase, position) in [
9247            (TouchPhase::Ended, 0.),
9248            (TouchPhase::Cancelled, 0.),
9249            (TouchPhase::Moved, 20.),
9250        ] {
9251            let phases = Rc::new(RefCell::new(Vec::new()));
9252            let window = cx.add_window({
9253                let phases = phases.clone();
9254                move |_, _| LongPressListener {
9255                    phases,
9256                    response: LongPressResponse::PreventDefault,
9257                }
9258            });
9259            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9260            dispatch_touch(window, cx, TouchId(1), phase, position);
9261            cx.executor().advance_clock(Duration::from_millis(501));
9262            cx.executor().run_until_parked();
9263
9264            assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
9265        }
9266    }
9267
9268    #[gpui::test]
9269    fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
9270        let phases = Rc::new(RefCell::new(Vec::new()));
9271        let window = cx.add_window({
9272            let phases = phases.clone();
9273            move |_, _| LongPressListener {
9274                phases,
9275                response: LongPressResponse::PreventDefault,
9276            }
9277        });
9278        let first_touch = TouchId(1);
9279        dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
9280        cx.executor().advance_clock(Duration::from_millis(250));
9281        dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
9282        dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
9283
9284        cx.executor().advance_clock(Duration::from_millis(251));
9285        cx.executor().run_until_parked();
9286        assert!(phases.borrow().is_empty());
9287
9288        cx.executor().advance_clock(Duration::from_millis(250));
9289        cx.executor().run_until_parked();
9290        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9291    }
9292
9293    #[gpui::test]
9294    fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
9295        test_underline_paint_at_scales(cx, |window| {
9296            let (numerator, denominator) = match window.scale_factor() {
9297                1.0 => (1, 1),
9298                1.25 => (5, 4),
9299                1.5 => (3, 2),
9300                2.0 => (2, 1),
9301                3.0 => (3, 1),
9302                scale => panic!("unexpected scale {scale}"),
9303            };
9304            let snap = |quarters: i32| {
9305                let scaled = quarters * numerator;
9306                let divisor = 4 * denominator;
9307                let rounded =
9308                    scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
9309                ScaledPixels((scaled.signum() * rounded) as f32)
9310            };
9311            let stroke = |quarters| {
9312                if quarters == 0 {
9313                    ScaledPixels(0.)
9314                } else {
9315                    snap(quarters).max(ScaledPixels(1.))
9316                }
9317            };
9318
9319            for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
9320                for width in [0, 1, 3, 84] {
9321                    for thickness in [0, 1, 4, 7] {
9322                        for wavy in [false, true] {
9323                            let style = UnderlineStyle {
9324                                thickness: px(thickness as f32 / 4.),
9325                                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
9326                                wavy,
9327                            };
9328                            let bounds = Bounds::new(
9329                                point(snap(origin), snap(-origin)),
9330                                size(
9331                                    stroke(width),
9332                                    stroke(thickness) * if wavy { 3. } else { 1. },
9333                                ),
9334                            );
9335                            let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
9336                            let width = px(width as f32 / 4.);
9337                            assert_eq!(window.underline_bounds(origin, width, &style), bounds);
9338                            let original = paint_test_underlines(window, |window| {
9339                                window.paint_underline(origin, width, &style);
9340                            })
9341                            .to_vec();
9342                            assert_eq!(original.len(), usize::from(!bounds.is_empty()));
9343                            if let Some(underline) = original.first() {
9344                                assert_eq!(underline.bounds, bounds);
9345                                assert_eq!(underline.thickness, stroke(thickness));
9346                                assert_eq!(underline.wavy, wavy.into());
9347                                assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
9348                            }
9349
9350                            let underlines = paint_test_underlines(window, |window| {
9351                                window.paint_underline_with_exclusions(origin, width, &style, &[]);
9352                            });
9353                            assert_eq!(underlines.len(), original.len());
9354                            for (actual, original) in underlines.iter().zip(&original) {
9355                                assert_same_underline_geometry(actual, original);
9356                                assert_eq!(actual.content_mask, original.content_mask);
9357                            }
9358
9359                            let left = bounds.left().0 as i32;
9360                            let right = bounds.right().0 as i32;
9361                            let exclusions = [
9362                                (15, 25),
9363                                (3, 7),
9364                                (5, 10),
9365                                (10, 12),
9366                                (0, 0),
9367                                (4, 2),
9368                                (-50, -1),
9369                                (70, 100),
9370                            ]
9371                            .map(|(start, end)| {
9372                                ScaledPixels((left + start) as f32)
9373                                    ..ScaledPixels((left + end) as f32)
9374                            });
9375                            let underlines = paint_test_underlines(window, |window| {
9376                                window.paint_underline_with_exclusions(
9377                                    origin,
9378                                    width,
9379                                    &style,
9380                                    &exclusions,
9381                                );
9382                            });
9383                            let expected = (left..right)
9384                                .filter(|column| {
9385                                    !bounds.is_empty()
9386                                        && !exclusions.iter().any(|span| {
9387                                            span.contains(&ScaledPixels(*column as f32))
9388                                        })
9389                                })
9390                                .collect::<Vec<_>>();
9391                            assert_eq!(underline_device_columns(underlines), expected);
9392                            for underline in underlines {
9393                                assert_same_underline_geometry(underline, &original[0]);
9394                            }
9395                        }
9396                    }
9397                }
9398            }
9399        });
9400    }
9401
9402    #[gpui::test]
9403    fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
9404        test_underline_paint_at_scales(cx, |window| {
9405            if window.scale_factor() != 2.0 {
9406                return;
9407            }
9408            let style = UnderlineStyle {
9409                thickness: px(1.),
9410                color: None,
9411                wavy: true,
9412            };
9413            let origin = point(px(2.888_183_8), px(15.357_917));
9414            let width = px(23.848_145) - origin.x;
9415            let original = paint_test_underlines(window, |window| {
9416                window.paint_underline(origin, width, &style);
9417            })[0];
9418            assert_eq!(original.bounds.left(), ScaledPixels(6.));
9419            assert_eq!(original.bounds.right(), ScaledPixels(48.));
9420            let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
9421            assert_eq!(point_bounds.left(), ScaledPixels(6.));
9422            assert_eq!(point_bounds.right(), ScaledPixels(28.));
9423
9424            let underlines = paint_test_underlines(window, |window| {
9425                window.paint_underline_with_exclusions(
9426                    origin,
9427                    width,
9428                    &style,
9429                    &[point_bounds.left()..point_bounds.right()],
9430                );
9431            });
9432            assert_eq!(underlines.len(), 1);
9433            assert_same_underline_geometry(&underlines[0], &original);
9434            assert_eq!(
9435                underline_device_columns(underlines),
9436                (28..48).collect::<Vec<_>>()
9437            );
9438        });
9439    }
9440
9441    #[gpui::test]
9442    fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
9443        test_underline_paint_at_scales(cx, |window| {
9444            let scale = window.scale_factor();
9445            let original_mask = window.content_mask();
9446            let original_opacity = window.element_opacity();
9447            let mask = ContentMask {
9448                bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
9449            };
9450            let style = UnderlineStyle {
9451                thickness: px(2.),
9452                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
9453                wavy: true,
9454            };
9455            let origin = point(px(-1.25), px(9.25));
9456            let width = px(24.);
9457            window.with_content_mask(Some(mask), |window| {
9458                window.with_element_opacity(Some(0.5), |window| {
9459                    window.with_element_opacity(Some(0.5), |window| {
9460                        let original = paint_test_underlines(window, |window| {
9461                            window.paint_underline(origin, width, &style);
9462                        })[0];
9463                        assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
9464                        let underlines = paint_test_underlines(window, |window| {
9465                            window.paint_underline_with_exclusions(
9466                                origin,
9467                                width,
9468                                &style,
9469                                &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
9470                            );
9471                        });
9472                        assert_eq!(underlines.len(), 2);
9473                        let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
9474                            |(left, right)| {
9475                                Bounds::from_corners(
9476                                    point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
9477                                    point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
9478                                )
9479                            },
9480                        );
9481                        assert_eq!(
9482                            underlines
9483                                .iter()
9484                                .map(|underline| underline.content_mask.bounds)
9485                                .collect::<Vec<_>>(),
9486                            expected
9487                        );
9488                        for underline in underlines {
9489                            assert_same_underline_geometry(underline, &original);
9490                        }
9491                    });
9492                });
9493            });
9494            assert_eq!(window.content_mask(), original_mask);
9495            assert_eq!(window.element_opacity(), original_opacity);
9496        });
9497    }
9498
9499    #[gpui::test]
9500    fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
9501        test_underline_paint_at_scales(cx, |window| {
9502            let style = UnderlineStyle {
9503                thickness: px(1.),
9504                color: None,
9505                wavy: true,
9506            };
9507            let origin = point(px(-4.), px(-1.));
9508            let width = px(8.);
9509            let left = (-4. * window.scale_factor()) as i32;
9510            let right = (4. * window.scale_factor()) as i32;
9511            let endpoints = [-16, -8, -1, 0, 1, 8, 16];
9512            for first_start in endpoints {
9513                for first_end in endpoints {
9514                    for second_start in endpoints {
9515                        for second_end in endpoints {
9516                            let exclusions = [first_start..first_end, second_start..second_end];
9517                            let expected = (left..right)
9518                                .filter(|column| {
9519                                    !exclusions.iter().any(|span| span.contains(column))
9520                                })
9521                                .collect::<Vec<_>>();
9522                            let exclusions = exclusions.map(|span| {
9523                                ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
9524                            });
9525                            let underlines = paint_test_underlines(window, |window| {
9526                                window.paint_underline_with_exclusions(
9527                                    origin,
9528                                    width,
9529                                    &style,
9530                                    &exclusions,
9531                                );
9532                            });
9533                            assert_eq!(
9534                                underline_device_columns(underlines),
9535                                expected,
9536                                "{exclusions:?}"
9537                            );
9538                        }
9539                    }
9540                }
9541            }
9542        });
9543    }
9544
9545    #[derive(Clone, Copy, PartialEq)]
9546    enum LongPressResponse {
9547        PreventDefault,
9548        StopPropagation,
9549        None,
9550    }
9551
9552    struct LongPressListener {
9553        phases: Rc<RefCell<Vec<TouchPhase>>>,
9554        response: LongPressResponse,
9555    }
9556
9557    impl Render for LongPressListener {
9558        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
9559            let entity = cx.entity();
9560            let phases = self.phases.clone();
9561            let response = self.response;
9562            canvas(
9563                |_, _, _| {},
9564                move |_, _, window, _| {
9565                    window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
9566                        if phase != DispatchPhase::Bubble {
9567                            return;
9568                        }
9569                        phases.borrow_mut().push(event.phase);
9570                        match response {
9571                            LongPressResponse::PreventDefault => {
9572                                window.capture_long_press(&entity);
9573                                window.prevent_default();
9574                            }
9575                            LongPressResponse::StopPropagation => cx.stop_propagation(),
9576                            LongPressResponse::None => {}
9577                        }
9578                    });
9579                },
9580            )
9581        }
9582    }
9583
9584    struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
9585
9586    impl Render for UnderlineTestView {
9587        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9588            let paint = self.0.clone();
9589            canvas(
9590                |_, _, _| {},
9591                move |_, _, window, _| {
9592                    window.content_mask_stack.push(ContentMask {
9593                        bounds: Bounds::from_corners(
9594                            point(px(-1000.), px(-1000.)),
9595                            point(px(1000.), px(1000.)),
9596                        ),
9597                    });
9598                    paint(window);
9599                    window.content_mask_stack.pop();
9600                },
9601            )
9602            .size_full()
9603        }
9604    }
9605
9606    fn test_underline_paint_at_scales(
9607        cx: &mut TestAppContext,
9608        paint: impl Fn(&mut Window) + 'static,
9609    ) {
9610        let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
9611        for scale in [1., 1.25, 1.5, 2., 3.] {
9612            cx.simulate_window_scale_factor_change(window.into(), scale);
9613            cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9614                .unwrap();
9615        }
9616    }
9617
9618    fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
9619        window.next_frame.scene.clear();
9620        paint(window);
9621        &window.next_frame.scene.underlines
9622    }
9623
9624    fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
9625        assert_eq!(actual.bounds, expected.bounds);
9626        assert_eq!(actual.thickness, expected.thickness);
9627        assert_eq!(actual.wavy, expected.wavy);
9628        assert_eq!(actual.color, expected.color);
9629        assert_eq!(actual.pad, expected.pad);
9630    }
9631
9632    fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
9633        underlines
9634            .iter()
9635            .flat_map(|underline| {
9636                let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
9637                bounds.left().0 as i32..bounds.right().0 as i32
9638            })
9639            .collect()
9640    }
9641
9642    fn dispatch_touch<T: 'static>(
9643        window: crate::WindowHandle<T>,
9644        cx: &mut TestAppContext,
9645        id: TouchId,
9646        phase: TouchPhase,
9647        x: f32,
9648    ) {
9649        window
9650            .update(cx, |_, window, cx| {
9651                window.dispatch_event(
9652                    TouchEvent {
9653                        id,
9654                        phase,
9655                        position: point(px(x), px(0.)),
9656                        predicted_position: None,
9657                        force: None,
9658                    }
9659                    .to_platform_input(),
9660                    cx,
9661                );
9662            })
9663            .unwrap();
9664    }
9665}
9666
9667#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
9668mod inspector_tests {
9669    use super::*;
9670    use crate::{
9671        DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
9672    };
9673
9674    #[gpui::test]
9675    fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
9676        let windows = [
9677            cx.add_window(|_, cx| InspectorTestRoot {
9678                child: cx.new(|_| InspectorTestView::default()),
9679            }),
9680            cx.add_window(|_, cx| InspectorTestRoot {
9681                child: cx.new(|_| InspectorTestView::default()),
9682            }),
9683        ];
9684        for window in windows {
9685            assert_closed_inspector(window.into(), cx);
9686        }
9687        for _ in 0..2 {
9688            cx.update_window(windows[0].into(), |root, window, cx| {
9689                let root = root.downcast::<InspectorTestRoot>().expect("test root");
9690                let child_widths = root.read(cx).child.read(cx).child_widths.clone();
9691                window.toggle_inspector(cx);
9692                window.draw(cx).clear(cx);
9693                assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
9694                let path = window
9695                    .rendered_frame
9696                    .next_inspector_instance_ids
9697                    .iter()
9698                    .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
9699                    .expect("anonymous siblings share an inspector path");
9700                let selected_id = InspectorElementId {
9701                    path,
9702                    instance_id: 1,
9703                };
9704                let position = window
9705                    .rendered_frame
9706                    .hitboxes
9707                    .iter()
9708                    .find(|hitbox| {
9709                        window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
9710                            == Some(&selected_id)
9711                    })
9712                    .expect("middle sibling is pickable")
9713                    .bounds
9714                    .center();
9715                window.simulate_mouse_move(position, cx);
9716                window.dispatch_event(
9717                    PlatformInput::MouseDown(MouseDownEvent {
9718                        position,
9719                        button: MouseButton::Left,
9720                        modifiers: Modifiers::default(),
9721                        click_count: 1,
9722                        first_mouse: false,
9723                    }),
9724                    cx,
9725                );
9726                window.dispatch_event(
9727                    PlatformInput::MouseUp(MouseUpEvent {
9728                        position,
9729                        button: MouseButton::Left,
9730                        modifiers: Modifiers::default(),
9731                        click_count: 1,
9732                    }),
9733                    cx,
9734                );
9735                assert!(!window.is_inspector_picking(cx));
9736                assert_eq!(
9737                    window
9738                        .inspector
9739                        .as_ref()
9740                        .expect("open inspector")
9741                        .read(cx)
9742                        .active_element_id(),
9743                    Some(&selected_id)
9744                );
9745                window.draw(cx).clear(cx);
9746                window.with_inspector_state::<DivInspectorState, _>(
9747                    Some(&selected_id),
9748                    cx,
9749                    |state, _| {
9750                        let state = state.as_mut().expect("selected div has style state");
9751                        assert_eq!(
9752                            state.base_style.size.width,
9753                            Some(crate::Length::from(px(10.)))
9754                        );
9755                        state.base_style.size.width = Some(crate::Length::from(px(25.)));
9756                    },
9757                );
9758                window.refresh();
9759                window.draw(cx).clear(cx);
9760                assert_eq!(
9761                    child_widths.borrow().as_slice(),
9762                    &[px(10.), px(25.), px(10.)]
9763                );
9764            })
9765            .expect("pick and edit a cached child");
9766            assert_closed_inspector(windows[1].into(), cx);
9767            windows[0]
9768                .update(cx, |_, window, cx| window.toggle_inspector(cx))
9769                .expect("close inspector");
9770            assert_closed_inspector(windows[0].into(), cx);
9771        }
9772    }
9773
9774    struct InspectorTestRoot {
9775        child: Entity<InspectorTestView>,
9776    }
9777
9778    impl Render for InspectorTestRoot {
9779        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9780            self.child
9781                .clone()
9782                .cached(StyleRefinement::default().size(px(100.)))
9783        }
9784    }
9785
9786    #[derive(Default)]
9787    struct InspectorTestView {
9788        child_widths: Rc<RefCell<Vec<Pixels>>>,
9789    }
9790
9791    impl Render for InspectorTestView {
9792        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9793            let child_widths = self.child_widths.clone();
9794            div()
9795                .on_children_prepainted(move |bounds, _, _| {
9796                    *child_widths.borrow_mut() =
9797                        bounds.iter().map(|bounds| bounds.size.width).collect();
9798                })
9799                .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
9800                .id("inspector-root")
9801                .flex()
9802                .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
9803        }
9804    }
9805
9806    fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
9807        cx.update_window(window, |root, window, cx| {
9808            window.draw(cx).clear(cx);
9809            window.draw(cx).clear(cx);
9810            let root = root.downcast::<InspectorTestRoot>().expect("test root");
9811            assert_eq!(
9812                root.read(cx)
9813                    .child
9814                    .read(cx)
9815                    .child_widths
9816                    .borrow()
9817                    .as_slice(),
9818                &[px(10.); 3]
9819            );
9820            for frame in [&window.rendered_frame, &window.next_frame] {
9821                assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
9822                assert_eq!(frame.inspector_hitboxes.capacity(), 0);
9823            }
9824        })
9825        .expect("closed inspector has no bookkeeping and no style overrides");
9826    }
9827}