Skip to main content

gpui/
window.rs

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