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