Skip to main content

gpui/
window.rs

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