Skip to main content

gpui/
window.rs

1#[cfg(feature = "profiler")]
2use crate::DebugFrameOverlayMode;
3#[cfg(any(feature = "inspector", debug_assertions))]
4use crate::Inspector;
5#[cfg(feature = "profiler")]
6use crate::profiler;
7use crate::subscription::SingleSubscriberSet;
8use crate::taffy::TaffyLayoutEngine;
9use crate::{
10    Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
11    AsyncWindowContext, AtlasKey, AtlasStats, AtlasTile, AvailableSpace, BackdropBlurRect, Background, BorderStyle,
12    EffectQuad, EffectSpec,
13    Bounds, BoxShadow,
14    Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
15    DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
16    EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
17    GlyphShadowParams, GpuTextureHandle,
18    Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
19    Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
20    MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path,
21    Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
22    Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
23    RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
24    SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
25    SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style, SubpixelSprite, Subscription,
26    SystemWindowTab, SystemWindowTabController, TabStopMap, Task, TextInputConfiguration,
27    TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
28    TileSource, TileWrite, TransformationMatrix, Underline, UnderlineStyle, WindowAppearance,
29    WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations, WindowInsets,
30    WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, blur_glyph_coverage, point,
31    prelude::*, px, rems, size, transparent_black,
32};
33
34use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
35use crate::interactive::TouchEvent;
36use crate::util::impl_deref;
37use anyhow::{Context as _, Result, anyhow};
38use collections::{FxHashMap, FxHashSet};
39use futures::channel::oneshot;
40use gpui_util::post_inc;
41use gpui_util::{ResultExt, measure};
42use itertools::FoldWhile::{Continue, Done};
43use itertools::Itertools;
44#[cfg(any(target_os = "macos", target_os = "ios"))]
45use objc2_core_foundation::CFRetained;
46#[cfg(any(target_os = "macos", target_os = "ios"))]
47use objc2_core_video::CVPixelBuffer;
48use parking_lot::{RwLock, RwLockUpgradableReadGuard};
49use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
50use refineable::Refineable;
51use scheduler::Instant;
52use slotmap::SlotMap;
53use smallvec::SmallVec;
54use std::{
55    any::{Any, TypeId},
56    borrow::Cow,
57    cell::{Cell, RefCell},
58    cmp,
59    fmt::{Debug, Display},
60    hash::{Hash, Hasher},
61    marker::PhantomData,
62    mem,
63    ops::{Add, Div, Range, Sub},
64    rc::Rc,
65    sync::{
66        Arc, Weak,
67        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
68    },
69    thread::AccessError,
70    time::Duration,
71};
72use uuid::Uuid;
73
74pub(crate) mod a11y;
75mod prompts;
76
77pub use a11y::A11ySubtreeBuilder;
78
79use self::a11y::A11y;
80#[cfg(not(target_family = "wasm"))]
81use self::a11y::ROOT_NODE_ID;
82use crate::util::{
83    atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
84    round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
85};
86pub use prompts::*;
87
88/// Default window size used when no explicit size is provided.
89pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
90
91/// A 6:5 aspect ratio minimum window size to be used for functional,
92/// additional-to-main-Zed windows, like the settings and rules library windows.
93pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
94    width: Pixels(900.),
95    height: Pixels(750.),
96};
97
98/// Represents the two different phases when dispatching events.
99#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
100pub enum DispatchPhase {
101    /// After the capture phase comes the bubble phase, in which mouse event listeners are
102    /// invoked front to back and keyboard event listeners are invoked from the focused element
103    /// to the root of the element tree. This is the phase you'll most commonly want to use when
104    /// registering event listeners.
105    #[default]
106    Bubble,
107    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
108    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
109    /// is used for special purposes such as clearing the "pressed" state for click events. If
110    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
111    /// outside of the immediate region may rely on detecting non-local events during this phase.
112    Capture,
113}
114
115impl DispatchPhase {
116    /// Returns true if this represents the "bubble" phase.
117    #[inline]
118    pub fn bubble(self) -> bool {
119        self == DispatchPhase::Bubble
120    }
121
122    /// Returns true if this represents the "capture" phase.
123    #[inline]
124    pub fn capture(self) -> bool {
125        self == DispatchPhase::Capture
126    }
127}
128
129struct WindowInvalidatorInner {
130    #[cfg(feature = "profiler")]
131    pub window_id: WindowId,
132    pub dirty: bool,
133    pub draw_phase: DrawPhase,
134    pub dirty_views: FxHashSet<EntityId>,
135    pub update_count: usize,
136    #[cfg(feature = "profiler")]
137    pub frame_dirty: FrameDirtyAccumulator,
138    pub platform_waker: Option<Rc<dyn Fn()>>,
139}
140
141/// Per-frame invalidation bookkeeping, drained at draw time and emitted to the
142/// frame profiler. Tracks when the current frame first became dirty and how
143/// many invalidations were coalesced into it, whenever the profiler is
144/// compiled in. Retention of the resulting per-frame records is what
145/// `profiler::trace_enabled()` controls, not this measurement.
146#[cfg(feature = "profiler")]
147#[derive(Default)]
148struct FrameDirtyAccumulator {
149    dirty_at: Option<Instant>,
150    invalidations: u64,
151}
152
153#[derive(Clone)]
154pub(crate) struct WindowInvalidator {
155    inner: Rc<RefCell<WindowInvalidatorInner>>,
156}
157
158impl WindowInvalidator {
159    pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
160        WindowInvalidator {
161            inner: Rc::new(RefCell::new(WindowInvalidatorInner {
162                #[cfg(feature = "profiler")]
163                window_id,
164                dirty: true,
165                draw_phase: DrawPhase::None,
166                dirty_views: FxHashSet::default(),
167                update_count: 0,
168                #[cfg(feature = "profiler")]
169                frame_dirty: FrameDirtyAccumulator::default(),
170                platform_waker: None,
171            })),
172        }
173    }
174
175    pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
176        let mut inner = self.inner.borrow_mut();
177        inner.update_count += 1;
178        inner.dirty_views.insert(entity);
179        if inner.draw_phase == DrawPhase::None {
180            #[cfg(feature = "profiler")]
181            let dirty_at = Self::record_frame_dirty(&mut inner);
182            let became_dirty = !inner.dirty;
183            inner.dirty = true;
184            let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
185            #[cfg(feature = "profiler")]
186            let window_id = inner.window_id;
187            drop(inner);
188            #[cfg(feature = "profiler")]
189            if became_dirty {
190                profiler::journal::record_frame_pending(window_id, dirty_at);
191            }
192            cx.push_effect(Effect::Notify { emitter: entity });
193            if let Some(waker) = waker {
194                waker();
195            }
196            true
197        } else {
198            false
199        }
200    }
201
202    pub fn is_dirty(&self) -> bool {
203        self.inner.borrow().dirty
204    }
205
206    pub fn set_dirty(&self, dirty: bool) {
207        let mut inner = self.inner.borrow_mut();
208        let became_dirty = dirty && !inner.dirty;
209        inner.dirty = dirty;
210        if dirty {
211            inner.update_count += 1;
212        }
213        #[cfg(feature = "profiler")]
214        let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
215        let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
216        #[cfg(feature = "profiler")]
217        let window_id = inner.window_id;
218        drop(inner);
219        #[cfg(feature = "profiler")]
220        if became_dirty && let Some(dirty_at) = dirty_at {
221            profiler::journal::record_frame_pending(window_id, dirty_at);
222        }
223        if let Some(waker) = waker {
224            waker();
225        }
226    }
227
228    pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
229        let mut inner = self.inner.borrow_mut();
230        inner.platform_waker = waker;
231        let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
232        drop(inner);
233        if let Some(waker) = waker {
234            waker();
235        }
236    }
237
238    /// Wakes the platform's frame-request source so a frame request is
239    /// delivered even if the platform stops requesting frames for idle
240    /// windows. No-op on platforms without a frame waker.
241    pub fn wake_platform(&self) {
242        let waker = self.inner.borrow().platform_waker.clone();
243        if let Some(waker) = waker {
244            waker();
245        }
246    }
247
248    pub fn set_phase(&self, phase: DrawPhase) {
249        self.inner.borrow_mut().draw_phase = phase
250    }
251
252    pub fn update_count(&self) -> usize {
253        self.inner.borrow().update_count
254    }
255
256    #[cfg(feature = "profiler")]
257    fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
258        let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
259        inner.frame_dirty.invalidations += 1;
260        dirty_at
261    }
262
263    #[cfg(feature = "profiler")]
264    fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
265        mem::take(&mut self.inner.borrow_mut().frame_dirty)
266    }
267
268    pub fn take_views(&self) -> FxHashSet<EntityId> {
269        mem::take(&mut self.inner.borrow_mut().dirty_views)
270    }
271
272    pub fn replace_views(&self, views: FxHashSet<EntityId>) {
273        self.inner.borrow_mut().dirty_views = views;
274    }
275
276    pub fn not_drawing(&self) -> bool {
277        self.inner.borrow().draw_phase == DrawPhase::None
278    }
279
280    /// vue-native fork: whether the window is in its paint phase.
281    pub fn is_painting(&self) -> bool {
282        self.inner.borrow().draw_phase == DrawPhase::Paint
283    }
284
285    #[track_caller]
286    pub fn debug_assert_paint(&self) {
287        debug_assert!(
288            matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
289            "this method can only be called during paint"
290        );
291    }
292
293    #[track_caller]
294    pub fn debug_assert_prepaint(&self) {
295        debug_assert!(
296            matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
297            "this method can only be called during request_layout, or prepaint"
298        );
299    }
300
301    #[track_caller]
302    pub fn debug_assert_paint_or_prepaint(&self) {
303        debug_assert!(
304            matches!(
305                self.inner.borrow().draw_phase,
306                DrawPhase::Paint | DrawPhase::Prepaint
307            ),
308            "this method can only be called during request_layout, prepaint, or paint"
309        );
310    }
311}
312
313type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
314
315pub(crate) type AnyWindowFocusListener =
316    Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
317
318pub(crate) struct WindowFocusEvent {
319    pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
320    pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
321}
322
323impl WindowFocusEvent {
324    pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
325        !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
326    }
327
328    pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
329        self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
330    }
331}
332
333/// This is provided when subscribing for `Context::on_focus_out` events.
334pub struct FocusOutEvent {
335    /// A weak focus handle representing what was blurred.
336    pub blurred: WeakFocusHandle,
337}
338
339slotmap::new_key_type! {
340    /// A globally unique identifier for a focusable element.
341    pub struct FocusId;
342}
343
344thread_local! {
345    /// Fallback arena used when no app-specific arena is active.
346    /// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena.
347    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
348
349    /// Points to the current App's element arena during draw operations.
350    /// This allows multiple test Apps to have isolated arenas, preventing
351    /// cross-session corruption when the scheduler interleaves their tasks.
352    static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
353}
354
355/// Whether a window draw is currently in progress on this thread.
356///
357/// This holds exactly while an `ElementArenaScope` is active: nested scopes
358/// restore the previous (still set) arena pointer, so `CURRENT_ELEMENT_ARENA`
359/// is `Some` from the outermost draw's start to its end.
360///
361/// The `on_request_frame` callback uses this to defer draw requests that
362/// arrive re-entrantly while a draw is already on the stack (e.g. via nested
363/// message pumping in the Windows window procedure), instead of running a
364/// nested draw or panicking on the already-borrowed App.
365pub(crate) fn draw_in_progress() -> bool {
366    CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
367}
368
369/// vue-native fork: how a window's frame request went, for an embedder's frame meter.
370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub enum FrameOutcome {
372    /// The window was drawn and presented.
373    Drew,
374    /// Next-frame callbacks ran (or a present), with nothing to redraw.
375    NoDraw,
376    /// Held back by the frame-rate limit: an inactive window, low power or thermal state.
377    Throttled,
378}
379
380/// One frame request: `started..ended` is the time it took on this thread.
381#[derive(Clone, Copy, Debug)]
382pub struct FrameWork {
383    /// The window whose frame this was.
384    pub window_id: WindowId,
385    /// When the request began.
386    pub started: Instant,
387    /// When it finished, presented or not.
388    pub ended: Instant,
389    /// What the request did.
390    pub outcome: FrameOutcome,
391}
392
393static FRAME_OBSERVER: std::sync::OnceLock<fn(FrameWork)> = std::sync::OnceLock::new();
394
395/// vue-native fork: `observer` hears about every frame request that did work or was throttled.
396/// The first call wins.
397pub fn observe_frames(observer: fn(FrameWork)) {
398    let _ = FRAME_OBSERVER.set(observer);
399}
400
401fn report_frame(window_id: WindowId, started: Instant, outcome: FrameOutcome) {
402    if let Some(observer) = FRAME_OBSERVER.get() {
403        observer(FrameWork { window_id, started, ended: Instant::now(), outcome });
404    }
405}
406
407/// Allocates an element in the current arena. Uses the app-specific arena if one
408/// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA.
409#[inline(always)]
410pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
411    let mut callback = Some(callback);
412    let mut result = None;
413    let access = with_element_arena_erased(&mut |arena| {
414        result = Some(callback.take().expect("arena callback runs once")(arena));
415    });
416    drop(callback);
417    access.expect("cannot access a Thread Local Storage value during or after destruction");
418    result.expect("arena callback produces a result")
419}
420
421/// Scope guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw
422/// operation and tracks the arena's scope depth, so that a nested draw's
423/// `ArenaClearNeeded::clear` is deferred rather than freeing memory the outer
424/// draw still references (see `Arena::clear`).
425///
426/// Call [`ElementArenaScope::exit`] with the same arena that was entered to
427/// obtain the [`ArenaClearNeeded`] token the draw now owes; requiring `exit`
428/// makes it impossible to request a clear before the scope has ended. The
429/// scope's teardown — restoring the thread-local and balancing `begin_scope`
430/// with `end_scope` — happens in `Drop`, so the arena's scope depth stays
431/// balanced on every path, including when a panic unwinds a draw before `exit`
432/// is reached. (If teardown lived only in `exit`, such a panic would leave the
433/// scope depth permanently elevated and defer every future clear, leaking
434/// memory unboundedly.)
435pub(crate) struct ElementArenaScope {
436    /// The entered arena: compared against the argument in `exit`, and
437    /// dereferenced in `Drop` to end its scope (see the SAFETY note there).
438    entered: *const RefCell<Arena>,
439    previous: Option<*const RefCell<Arena>>,
440    exited: bool,
441}
442
443impl ElementArenaScope {
444    /// Enter a scope where element allocations use the given arena.
445    pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
446        arena.borrow_mut().begin_scope();
447        let previous = CURRENT_ELEMENT_ARENA.with(|current| {
448            let prev = current.get();
449            current.set(Some(arena as *const RefCell<Arena>));
450            prev
451        });
452        Self {
453            entered: arena as *const RefCell<Arena>,
454            previous,
455            exited: false,
456        }
457    }
458
459    /// End the scope: restores the previously-current arena and ends the
460    /// arena's clear-deferral scope. Returns the token for the arena clear the
461    /// draw now owes; producing it here makes it impossible to request a clear
462    /// before the scope has ended (which would be silently deferred forever).
463    ///
464    /// Panics if passed a different arena than was entered: ending the scope
465    /// of the wrong arena would unbalance two arenas' scope depths, allowing
466    /// one of them to clear while a draw still references its memory.
467    pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
468        assert!(
469            std::ptr::eq(self.entered, arena),
470            "ElementArenaScope::exit called with a different arena than was entered"
471        );
472        self.exited = true;
473        // Teardown (restoring the thread-local and ending the arena's
474        // clear-deferral scope) runs in `Drop`, which fires both here — `self`
475        // is dropped as `exit` returns, before the token reaches the caller —
476        // and when a panic unwinds the draw before `exit` is reached.
477        ArenaClearNeeded::new(arena)
478    }
479}
480
481impl Drop for ElementArenaScope {
482    fn drop(&mut self) {
483        // Teardown lives here (rather than in `exit`) so it runs exactly once on
484        // every path: `exit` consumes and drops the guard on the normal path,
485        // and unwinding drops it on the panic path. Balancing `begin_scope` here
486        // keeps the arena's scope depth correct even when a draw panics; if this
487        // only happened in `exit`, a panic between `enter` and `exit` would leave
488        // the depth elevated and defer every future clear.
489        CURRENT_ELEMENT_ARENA.with(|current| {
490            current.set(self.previous);
491        });
492        // SAFETY: `entered` came from a `&RefCell<Arena>` in `enter`, and the
493        // arena (owned by the `App` being drawn) outlives this guard on both the
494        // normal and unwinding paths, since the guard is a local of the draw.
495        unsafe { &*self.entered }.borrow_mut().end_scope();
496        if !self.exited && !std::thread::panicking() {
497            debug_assert!(false, "ElementArenaScope dropped without calling exit()");
498            log::error!(
499                "ElementArenaScope dropped without calling exit(); \
500                 the arena clear for this draw was never requested"
501            );
502        }
503    }
504}
505
506/// Returned when the element arena has been used and so must be cleared before the next draw.
507#[must_use]
508pub struct ArenaClearNeeded {
509    /// Identity of the arena that was drawn into. Only ever compared against
510    /// another pointer in `clear`; never dereferenced.
511    arena: *const RefCell<Arena>,
512}
513
514impl ArenaClearNeeded {
515    /// Create a new ArenaClearNeeded token for the App whose arena was drawn
516    /// into. Private: the only way to obtain one is [`ElementArenaScope::exit`].
517    fn new(arena: &RefCell<Arena>) -> Self {
518        Self {
519            arena: arena as *const RefCell<Arena>,
520        }
521    }
522
523    /// Clear the element arena of the App the draw ran against. If an enclosing
524    /// draw is still in progress (this draw was nested inside it), the clear is
525    /// deferred to the enclosing draw's own `ArenaClearNeeded` so that its live
526    /// allocations aren't freed.
527    ///
528    /// Panics if passed a different App than the draw ran against, since
529    /// clearing another App's arena could free memory its draws still
530    /// reference.
531    pub fn clear(self, cx: &mut App) {
532        assert!(
533            std::ptr::eq(self.arena, &*cx.element_arena),
534            "ArenaClearNeeded::clear called with a different App than the draw ran against"
535        );
536        RefCell::borrow_mut(&cx.element_arena).clear();
537    }
538}
539
540#[derive(Default)]
541pub(crate) struct FocusMap {
542    pub(crate) handles: SlotMap<FocusId, FocusRef>,
543    pub(crate) dropped_handles: Vec<FocusId>,
544}
545
546pub(crate) struct FocusRef {
547    pub(crate) ref_count: AtomicUsize,
548    pub(crate) tab_index: isize,
549    pub(crate) tab_stop: bool,
550}
551
552impl FocusId {
553    /// Obtains whether the element associated with this handle is currently focused.
554    pub fn is_focused(&self, window: &Window) -> bool {
555        window.focus == Some(*self)
556    }
557
558    /// Obtains whether the element associated with this handle contains the focused
559    /// element or is itself focused.
560    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
561        window
562            .focused(cx)
563            .is_some_and(|focused| self.contains(focused.id, window))
564    }
565
566    /// Obtains whether the element associated with this handle is contained within the
567    /// focused element or is itself focused.
568    pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
569        let focused = window.focused(cx);
570        focused.is_some_and(|focused| focused.id.contains(*self, window))
571    }
572
573    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
574    pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
575        window
576            .rendered_frame
577            .dispatch_tree
578            .focus_contains(*self, other)
579    }
580}
581
582/// A handle which can be used to track and manipulate the focused element in a window.
583pub struct FocusHandle {
584    pub(crate) id: FocusId,
585    handles: Arc<RwLock<FocusMap>>,
586    /// The index of this element in the tab order.
587    pub tab_index: isize,
588    /// Whether this element can be focused by tab navigation.
589    pub tab_stop: bool,
590}
591
592impl std::fmt::Debug for FocusHandle {
593    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
595    }
596}
597
598impl FocusHandle {
599    pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
600        let id = handles.write().handles.insert(FocusRef {
601            ref_count: AtomicUsize::new(1),
602            tab_index: 0,
603            tab_stop: false,
604        });
605
606        Self {
607            id,
608            tab_index: 0,
609            tab_stop: false,
610            handles: handles.clone(),
611        }
612    }
613
614    pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
615        let lock = handles.read();
616        let focus = lock.handles.get(id)?;
617        if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
618            return None;
619        }
620        Some(Self {
621            id,
622            tab_index: focus.tab_index,
623            tab_stop: focus.tab_stop,
624            handles: handles.clone(),
625        })
626    }
627
628    /// Sets the tab index of the element associated with this handle.
629    pub fn tab_index(mut self, index: isize) -> Self {
630        self.tab_index = index;
631        if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
632            focus.tab_index = index;
633        }
634        self
635    }
636
637    /// Sets whether the element associated with this handle is a tab stop.
638    ///
639    /// When `false`, the element will not be included in the tab order.
640    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
641        self.tab_stop = tab_stop;
642        if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
643            focus.tab_stop = tab_stop;
644        }
645        self
646    }
647
648    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
649    pub fn downgrade(&self) -> WeakFocusHandle {
650        WeakFocusHandle {
651            id: self.id,
652            handles: Arc::downgrade(&self.handles),
653        }
654    }
655
656    /// Moves the focus to the element associated with this handle.
657    pub fn focus(&self, window: &mut Window, cx: &mut App) {
658        window.focus(self, cx)
659    }
660
661    /// Obtains whether the element associated with this handle is currently focused.
662    pub fn is_focused(&self, window: &Window) -> bool {
663        self.id.is_focused(window)
664    }
665
666    /// Obtains whether the element associated with this handle contains the focused
667    /// element or is itself focused.
668    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
669        self.id.contains_focused(window, cx)
670    }
671
672    /// Obtains whether the element associated with this handle is contained within the
673    /// focused element or is itself focused.
674    pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
675        self.id.within_focused(window, cx)
676    }
677
678    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
679    pub fn contains(&self, other: &Self, window: &Window) -> bool {
680        self.id.contains(other.id, window)
681    }
682
683    /// Obtains whether the element associated with this handle is part of the most recently rendered frame.
684    pub fn is_rendered(&self, window: &Window) -> bool {
685        window
686            .rendered_frame
687            .dispatch_tree
688            .focusable_node_id(self.id)
689            .is_some()
690    }
691
692    /// Dispatch an action on the element that rendered this focus handle
693    pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
694        if let Some(node_id) = window
695            .rendered_frame
696            .dispatch_tree
697            .focusable_node_id(self.id)
698        {
699            window.dispatch_action_on_node(node_id, action, cx)
700        }
701    }
702}
703
704impl Clone for FocusHandle {
705    fn clone(&self) -> Self {
706        Self::for_id(self.id, &self.handles).unwrap()
707    }
708}
709
710impl PartialEq for FocusHandle {
711    fn eq(&self, other: &Self) -> bool {
712        self.id == other.id
713    }
714}
715
716impl Eq for FocusHandle {}
717
718impl Drop for FocusHandle {
719    fn drop(&mut self) {
720        let handles = self.handles.upgradable_read();
721        let focus = handles.handles.get(self.id).expect("focus handle missing");
722        let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
723        assert_ne!(previous_count, 0, "over-released focus handle");
724        if previous_count == 1 {
725            RwLockUpgradableReadGuard::upgrade(handles)
726                .dropped_handles
727                .push(self.id);
728        }
729    }
730}
731
732/// A weak reference to a focus handle.
733#[derive(Clone, Debug)]
734pub struct WeakFocusHandle {
735    pub(crate) id: FocusId,
736    pub(crate) handles: Weak<RwLock<FocusMap>>,
737}
738
739impl WeakFocusHandle {
740    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
741    pub fn upgrade(&self) -> Option<FocusHandle> {
742        let handles = self.handles.upgrade()?;
743        FocusHandle::for_id(self.id, &handles)
744    }
745}
746
747impl PartialEq for WeakFocusHandle {
748    fn eq(&self, other: &WeakFocusHandle) -> bool {
749        self.id == other.id
750    }
751}
752
753impl Eq for WeakFocusHandle {}
754
755impl PartialEq<FocusHandle> for WeakFocusHandle {
756    fn eq(&self, other: &FocusHandle) -> bool {
757        self.id == other.id
758    }
759}
760
761impl PartialEq<WeakFocusHandle> for FocusHandle {
762    fn eq(&self, other: &WeakFocusHandle) -> bool {
763        self.id == other.id
764    }
765}
766
767/// Focusable allows users of your view to easily
768/// focus it (using window.focus_view(cx, view))
769pub trait Focusable: 'static {
770    /// Returns the focus handle associated with this view.
771    fn focus_handle(&self, cx: &App) -> FocusHandle;
772}
773
774impl<V: Focusable> Focusable for Entity<V> {
775    fn focus_handle(&self, cx: &App) -> FocusHandle {
776        self.read(cx).focus_handle(cx)
777    }
778}
779
780/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
781/// where the lifecycle of the view is handled by another view.
782pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
783
784impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
785
786/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
787pub struct DismissEvent;
788
789type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
790
791pub(crate) type AnyMouseListener =
792    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
793
794#[derive(Clone)]
795pub(crate) struct CursorStyleRequest {
796    pub(crate) hitbox_id: Option<HitboxId>,
797    pub(crate) style: CursorStyle,
798}
799
800#[derive(Default, Eq, PartialEq)]
801pub(crate) struct HitTest {
802    pub(crate) ids: SmallVec<[HitboxId; 8]>,
803    pub(crate) hover_hitbox_count: usize,
804}
805
806/// A type of window control area that corresponds to the platform window.
807#[derive(Clone, Copy, Debug, Eq, PartialEq)]
808pub enum WindowControlArea {
809    /// An area that allows dragging of the platform window.
810    Drag,
811    /// An area that allows closing of the platform window.
812    Close,
813    /// An area that allows maximizing of the platform window.
814    Max,
815    /// An area that allows minimizing of the platform window.
816    Min,
817    /// An area that is explicitly NOT a window control: ordinary client
818    /// content, even when an ancestor declared [`WindowControlArea::Drag`].
819    ///
820    /// This is what makes CSS `window-drag: none` (`-webkit-app-region:
821    /// no-drag`) expressible: without a positive "not a control" answer, a
822    /// descendant can only opt out of an ancestor's drag region by blocking
823    /// the mouse entirely (`.occlude()`), which also swallows every event
824    /// meant for content painted behind it.
825    NoDrag,
826}
827
828/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
829#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
830pub struct HitboxId(u64);
831
832#[cfg(feature = "test-support")]
833impl HitboxId {
834    /// A placeholder HitboxId exclusively for integration testing API's that
835    /// need a hitbox but where the value of the hitbox does not matter. The
836    /// alternative is to make the Hitbox optional but that complicates the
837    /// implementation.
838    pub const fn placeholder() -> Self {
839        Self(0)
840    }
841}
842
843impl HitboxId {
844    /// vue-native fork: the id of a PICK record ([`Window::vn_insert_pick`]),
845    /// which is in [`Frame::vn_tagged_hitboxes`] but never in
846    /// [`Frame::hitboxes`], so no hit test of gpui's own ever hovers it.
847    pub const VN_PICK: HitboxId = HitboxId(u64::MAX);
848
849    /// Checks if the hitbox with this ID is currently hovered. Returns `false` during keyboard
850    /// input modality so that keyboard navigation suppresses hover highlights. Except when handling
851    /// `ScrollEvent`, this is typically what you want when determining whether to handle mouse
852    /// events or paint hover styles.
853    ///
854    /// See [`Hitbox::is_hovered`] for details.
855    pub fn is_hovered(self, window: &Window) -> bool {
856        // If this hitbox has captured the pointer, it's always considered hovered
857        if window.captured_hitbox == Some(self) {
858            return true;
859        }
860        if window.last_input_was_keyboard() {
861            return false;
862        }
863        self.hit_test(window)
864    }
865
866    /// Checks if the hitbox with this ID is currently hovered, regardless of the last
867    /// input modality used.
868    ///
869    /// See [`HitboxId::is_hovered`] for more details.
870    pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
871        // If this hitbox has captured the pointer, it's always considered hovered
872        if window.captured_hitbox == Some(self) {
873            return true;
874        }
875        self.hit_test(window)
876    }
877
878    fn hit_test(self, window: &Window) -> bool {
879        // vue-native fork: a pointer that is not in the window hovers nothing,
880        // wherever `mouse_position` says it is (`Window::pointer_inside`). A
881        // browser shows no `:hover` under a cursor that is over another
882        // window, or that has left this one.
883        if !window.pointer_inside {
884            return false;
885        }
886        let hit_test = &window.mouse_hit_test;
887        for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
888            if self == *id {
889                return true;
890            }
891        }
892        false
893    }
894
895    /// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
896    /// Typically this should only be used when handling `ScrollEvent`, and otherwise
897    /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
898    /// this distinction.
899    pub fn should_handle_scroll(self, window: &Window) -> bool {
900        window.mouse_hit_test.ids.contains(&self)
901    }
902
903    fn next(self) -> HitboxId {
904        HitboxId(self.0.wrapping_add(1))
905    }
906}
907
908/// The axis-aligned bounding box of `bounds` after `matrix`.
909///
910/// `matrix` is a DEVICE-space transform (that is what the primitives carry)
911/// and `bounds` are logical pixels, so the corners are scaled in and back
912/// out again; at scale 1 the two cancel. Exact for a translation, a
913/// superset for a rotation — see the caller in
914/// [`Window::with_content_mask`].
915#[inline]
916fn transform_bounds(
917    matrix: TransformationMatrix,
918    bounds: Bounds<Pixels>,
919    scale_factor: f32,
920) -> Bounds<Pixels> {
921    if matrix.is_unit() {
922        return bounds;
923    }
924    // `TransformationMatrix::apply` is unit-agnostic (it multiplies the raw
925    // floats), so the conversion is explicit: logical in, device through the
926    // matrix, logical out.
927    let map = |p: Point<Pixels>| {
928        let d = matrix.apply(Point::new(px(p.x.0 * scale_factor), px(p.y.0 * scale_factor)));
929        Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
930    };
931    let corners = [
932        map(bounds.origin),
933        map(bounds.top_right()),
934        map(bounds.bottom_left()),
935        map(bounds.bottom_right()),
936    ];
937    let min_x = corners.iter().map(|p| p.x).fold(Pixels::MAX, Pixels::min);
938    let max_x = corners.iter().map(|p| p.x).fold(Pixels::MIN, Pixels::max);
939    let min_y = corners.iter().map(|p| p.y).fold(Pixels::MAX, Pixels::min);
940    let max_y = corners.iter().map(|p| p.y).fold(Pixels::MIN, Pixels::max);
941    Bounds::from_corners(Point::new(min_x, min_y), Point::new(max_x, max_y))
942}
943
944/// vue-native fork: a content mask mapped like [`transform_bounds`]. Its radii
945/// survive a translation and a positive scale. A non-uniform scale takes the
946/// smaller factor, a circular corner inside the elliptical one, so the clip
947/// shows a little more rather than less. A rotation, skew or flip drops the
948/// radii, leaving the square bounding box that `transform_bounds` gives.
949/// The key of `spec`'s history on `element`, 0 for none.
950fn vn_history_key(element: u64, spec: &EffectSpec) -> u64 {
951    use std::hash::{Hash, Hasher};
952    if element == 0 || spec.flags & crate::EFFECT_FLAG_HISTORY == 0 {
953        return 0;
954    }
955    let mut hasher = collections::FxHasher::default();
956    (element, spec.id).hash(&mut hasher);
957    hasher.finish().max(1)
958}
959
960/// The phase an effect's `[SkAnimated]` speed has accumulated: its integral
961/// over the effect clock, so a change of speed bends the motion instead of
962/// rescaling all the time elapsed since the clock's zero. It starts at
963/// `speed * time`, which is what an unchanged speed gives anyway.
964#[derive(Clone, Copy, Debug, PartialEq)]
965struct VnEffectPhase {
966    at: f32,
967    phase: f64,
968}
969
970impl VnEffectPhase {
971    /// Seconds an element may go unpainted before its phase is forgotten.
972    const KEEP: f32 = 10.;
973
974    fn advance(previous: Option<Self>, speed: f32, now: f32) -> Self {
975        match previous {
976            None => Self {
977                at: now,
978                phase: f64::from(speed) * f64::from(now),
979            },
980            Some(previous) if now > previous.at => Self {
981                at: now,
982                phase: previous.phase + f64::from(speed) * f64::from(now - previous.at),
983            },
984            Some(previous) => previous,
985        }
986    }
987
988    /// The speed the shader reads in place of the authored one: `time` times
989    /// it is the phase.
990    fn speed(&self, now: f32) -> Option<f32> {
991        (now > 1e-3).then(|| (self.phase / f64::from(now)) as f32)
992    }
993}
994
995fn vn_phase_key(element: u64, spec: &EffectSpec) -> u64 {
996    use std::hash::{Hash, Hasher};
997    let mut hasher = collections::FxHasher::default();
998    (element, spec.id, "phase").hash(&mut hasher);
999    hasher.finish()
1000}
1001
1002fn transform_mask(
1003    matrix: TransformationMatrix,
1004    mask: ContentMask<Pixels>,
1005    scale_factor: f32,
1006) -> ContentMask<Pixels> {
1007    let bounds = transform_bounds(matrix, mask.bounds, scale_factor);
1008    if !mask.is_rounded() || matrix.is_unit() {
1009        return ContentMask {
1010            bounds,
1011            corner_radii: mask.corner_radii,
1012        };
1013    }
1014    let [[a, b], [c, d]] = matrix.rotation_scale;
1015    let corner_radii = if b == 0. && c == 0. && a > 0. && d > 0. {
1016        let factor = a.min(d);
1017        mask.corner_radii
1018            .map(|radius| *radius * factor)
1019            .clamp_radii_for_quad_size(bounds.size)
1020    } else {
1021        Corners::default()
1022    };
1023    ContentMask {
1024        bounds,
1025        corner_radii,
1026    }
1027}
1028
1029/// A rectangular region that potentially blocks hitboxes inserted prior.
1030/// See [Window::insert_hitbox] for more details.
1031#[derive(Clone, Debug)]
1032pub struct Hitbox {
1033    /// A unique identifier for the hitbox.
1034    pub id: HitboxId,
1035    /// The bounds of the hitbox.
1036    pub bounds: Bounds<Pixels>,
1037    /// The content mask when the hitbox was inserted.
1038    pub content_mask: ContentMask<Pixels>,
1039    /// Flags that specify hitbox behavior.
1040    pub behavior: HitboxBehavior,
1041    /// The composed CSS `transform` in force when the hitbox was inserted, in
1042    /// DEVICE space (the same matrix the primitives carry).
1043    ///
1044    /// `bounds` stays the UNTRANSFORMED rect, because that is the frame the
1045    /// element and everything that reads a hitbox (autoscroll, tooltip
1046    /// placement, `Hitbox::bounds`) thinks in. Hit-testing therefore maps the
1047    /// pointer BACKWARDS through this rather than mapping the rect forwards —
1048    /// see [`Frame::hit_test`].
1049    pub transformation: TransformationMatrix,
1050    /// vue-native fork: the `clip-path` shapes that are no rounded rectangle
1051    /// around the hitbox when it was inserted, in window device pixels. A
1052    /// point outside any of them does not hit it (CSS Masking 1 §5).
1053    pub vn_clip: Option<Arc<crate::VnClipNode>>,
1054}
1055
1056impl_deref!([] Hitbox => bounds: Bounds<Pixels>);
1057
1058impl Hitbox {
1059    /// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality
1060    /// so that keyboard navigation suppresses hover highlights. Except when handling
1061    /// `ScrollEvent`, this is typically what you want when determining whether to handle mouse
1062    /// events or paint hover styles.
1063    ///
1064    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
1065    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
1066    /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`),
1067    /// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]).
1068    ///
1069    /// Handling of `ScrollEvent` should typically use `should_handle_scroll` instead.
1070    /// Concretely, this is due to use-cases like overlays that cause the elements under to be
1071    /// non-interactive while still allowing scrolling. More abstractly, this is because
1072    /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
1073    /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
1074    /// container.
1075    pub fn is_hovered(&self, window: &Window) -> bool {
1076        self.id.is_hovered(window)
1077    }
1078
1079    /// Checks whether this hitbox would be hovered at `position`, regardless of the current input
1080    /// modality or mouse position.
1081    pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
1082        // Our hit test maps the pointer back through each hitbox's transform, so
1083        // it needs the window's scale factor (see `Frame::hit_test`).
1084        let hit_test = window
1085            .rendered_frame
1086            .hit_test(position, window.scale_factor);
1087        hit_test
1088            .ids
1089            .iter()
1090            .take(hit_test.hover_hitbox_count)
1091            .any(|id| self.id == *id)
1092    }
1093
1094    /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
1095    /// should only be used when handling `ScrollEvent`, and otherwise `is_hovered` should be
1096    /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
1097    ///
1098    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
1099    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
1100    pub fn should_handle_scroll(&self, window: &Window) -> bool {
1101        self.id.should_handle_scroll(window)
1102    }
1103}
1104
1105/// vue-native fork: the bit an embedder ORs into a hitbox tag
1106/// ([`Window::set_hitbox_tag`]) for a box that belongs to the node but is not
1107/// where the node is — a scroll container's wheel viewport, inserted after
1108/// the content it covers. [`Window::vn_tags_at`] leaves such boxes out;
1109/// [`Window::vn_restrict_mouse_hit`] judges them by the node.
1110pub const VN_TAG_PASSIVE: u32 = 1 << 31;
1111
1112/// vue-native fork: which mouse event a [`VnHitRefiner`] is refining.
1113#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1114pub enum VnHitKind {
1115    /// A [`MouseDownEvent`](crate::MouseDownEvent).
1116    Down,
1117    /// A [`MouseUpEvent`].
1118    Up,
1119    /// A [`ScrollEvent`](crate::ScrollEvent).
1120    Scroll,
1121}
1122
1123/// vue-native fork: the embedder's say over which hitboxes a mouse event is
1124/// for, run once per press, release and wheel before any listener sees it.
1125/// See [`Window::set_vn_hit_refiner`].
1126pub type VnHitRefiner = Rc<dyn Fn(VnHitKind, Point<Pixels>, &mut Window, &mut App)>;
1127
1128/// vue-native fork: how [`Window::vn_lock_pointer`] holds the pointer.
1129#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1130pub enum VnPointerLock {
1131    /// The platform hides and holds the cursor ([`PlatformWindow::lock_pointer`]).
1132    System {
1133        /// The device's own counts, without pointer acceleration.
1134        unadjusted: bool,
1135    },
1136    /// gpui's half alone, for tests: mouse events hold still at the lock position and moves
1137    /// report how far their own position moved. The cursor is left alone.
1138    Simulated,
1139}
1140
1141/// How the hitbox affects mouse behavior.
1142#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1143pub enum HitboxBehavior {
1144    /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
1145    #[default]
1146    Normal,
1147
1148    /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
1149    /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
1150    /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
1151    /// [`InteractiveElement::occlude`].
1152    ///
1153    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
1154    /// bubble-phase handler for every mouse event type:
1155    ///
1156    /// ```ignore
1157    /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
1158    ///     if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
1159    ///         cx.stop_propagation();
1160    ///     }
1161    /// })
1162    /// ```
1163    ///
1164    /// This has effects beyond event handling - any use of hitbox checking, such as hover
1165    /// styles and tooltips. These other behaviors are the main point of this mechanism. An
1166    /// alternative might be to not affect mouse event handling - but this would allow
1167    /// inconsistent UI where clicks and moves interact with elements that are not considered to
1168    /// be hovered.
1169    BlockMouse,
1170
1171    /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
1172    /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
1173    /// interaction except scroll events to be ignored - see the documentation of
1174    /// [`Hitbox::is_hovered`] for details. This flag is set by
1175    /// [`InteractiveElement::block_mouse_except_scroll`].
1176    ///
1177    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
1178    /// bubble-phase handler for every mouse event type **except** `ScrollEvent`:
1179    ///
1180    /// ```ignore
1181    /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
1182    ///     if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
1183    ///         cx.stop_propagation();
1184    ///     }
1185    /// })
1186    /// ```
1187    ///
1188    /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollEvent` is
1189    /// handled differently than other mouse events. If also blocking these scroll events is
1190    /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
1191    ///
1192    /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
1193    /// hover styles and tooltips. These other behaviors are the main point of this mechanism.
1194    /// An alternative might be to not affect mouse event handling - but this would allow
1195    /// inconsistent UI where clicks and moves interact with elements that are not considered to
1196    /// be hovered.
1197    BlockMouseExceptScroll,
1198}
1199
1200/// An identifier for a tooltip.
1201#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1202pub struct TooltipId(usize);
1203
1204impl TooltipId {
1205    /// Checks if the tooltip is currently hovered.
1206    pub fn is_hovered(&self, window: &Window) -> bool {
1207        window
1208            .tooltip_bounds
1209            .as_ref()
1210            .is_some_and(|tooltip_bounds| {
1211                tooltip_bounds.id == *self
1212                    && tooltip_bounds.bounds.contains(&window.mouse_position())
1213            })
1214    }
1215}
1216
1217pub(crate) struct TooltipBounds {
1218    id: TooltipId,
1219    bounds: Bounds<Pixels>,
1220}
1221
1222#[derive(Clone)]
1223pub(crate) struct TooltipRequest {
1224    id: TooltipId,
1225    tooltip: AnyTooltip,
1226}
1227
1228/// The ids of the elements being drawn, root first, with the hash of every
1229/// prefix alongside: a [`GlobalElementId`] for the current element is then
1230/// the ids cloned out and the hash on top of the stack, without walking the
1231/// path — the ids of every ancestor, string names byte by byte — for each
1232/// element on every frame.
1233#[derive(Clone, Default)]
1234pub(crate) struct ElementIdStack {
1235    ids: SmallVec<[ElementId; 32]>,
1236    hashes: SmallVec<[u64; 32]>,
1237}
1238
1239impl ElementIdStack {
1240    pub(crate) fn push(&mut self, id: ElementId) {
1241        self.hashes.push(crate::extend_path_hash(self.hash(), &id));
1242        self.ids.push(id);
1243    }
1244
1245    pub(crate) fn pop(&mut self) -> Option<ElementId> {
1246        self.hashes.pop();
1247        self.ids.pop()
1248    }
1249
1250    pub(crate) fn clear(&mut self) {
1251        self.ids.clear();
1252        self.hashes.clear();
1253    }
1254
1255    /// The hash of the whole path on the stack.
1256    fn hash(&self) -> u64 {
1257        self.hashes
1258            .last()
1259            .copied()
1260            .unwrap_or(crate::EMPTY_PATH_HASH)
1261    }
1262
1263    pub(crate) fn global_id(&self) -> GlobalElementId {
1264        GlobalElementId::with_hash(&self.ids, self.hash())
1265    }
1266}
1267
1268impl std::ops::Deref for ElementIdStack {
1269    type Target = [ElementId];
1270
1271    fn deref(&self) -> &Self::Target {
1272        &self.ids
1273    }
1274}
1275
1276pub(crate) struct DeferredDraw {
1277    current_view: EntityId,
1278    priority: usize,
1279    parent_node: DispatchNodeId,
1280    element_id_stack: ElementIdStack,
1281    text_style_stack: Vec<TextStyleRefinement>,
1282    content_mask: Option<ContentMask<Pixels>>,
1283    rem_size: Pixels,
1284    element: Option<AnyElement>,
1285    absolute_offset: Point<Pixels>,
1286    /// The CSS `transform` in force where the element was deferred FROM.
1287    ///
1288    /// A deferred draw is replayed at the top of the frame, where the transform
1289    /// stack is empty — so without this, an element that escapes its siblings'
1290    /// paint order (`position: fixed`, `z-index`) also escapes its ancestors'
1291    /// transforms and paints somewhere nobody asked for. A `z-10` sticky header
1292    /// inside a `translate(-50%, -50%)` dialog landed half the window away from
1293    /// the dialog it belongs to.
1294    element_transform: TransformationMatrix,
1295    /// vue-native fork: the accessibility node on top of the stack where the
1296    /// element was deferred FROM, which its nodes belong under
1297    /// (`A11yNodeBuilder::begin_adopted`). `None` when accessibility was off.
1298    a11y_parent: Option<accesskit::NodeId>,
1299    /// vue-native fork: where the draw sorts among draws of equal `priority`,
1300    /// compared lexicographically — see [`crate::Deferred::with_stack_key`].
1301    /// `None` sorts first.
1302    vn_stack: Option<Rc<[u128]>>,
1303    /// vue-native fork: the opacity in force where the element was deferred
1304    /// FROM. Like the transform, it would otherwise be lost at the top of the
1305    /// frame: CSS applies an ancestor's `opacity` to everything inside it,
1306    /// out-of-flow descendants included.
1307    element_opacity: f32,
1308    /// vue-native fork: the `clip-path` shapes in force where the element
1309    /// was deferred FROM, taken with the content mask (none when the draw
1310    /// escapes its ancestors' clips). Its prepaint re-enters them, and its
1311    /// paint re-opens an isolated layer for each ([`Window::vn_with_clip_shape`]).
1312    vn_clip: Option<Arc<crate::VnClipNode>>,
1313    /// vue-native fork: the `[SkContent]` effect the draw was deferred from
1314    /// inside, which paints it into its content ([`VnDeferScope`]).
1315    vn_scope: Option<VnDeferScope>,
1316    prepaint_range: Range<PrepaintStateIndex>,
1317    paint_range: Range<PaintIndex>,
1318    /// The entities the deferred element accessed while it was last drawn, in
1319    /// any phase, restored when its prepaint is reused.
1320    accessed_entities: FxHashSet<EntityId>,
1321}
1322
1323/// vue-native fork: an element whose effect reads its own content. A draw
1324/// deferred from inside it (a positioned descendant) paints into that
1325/// content, after the element's in-flow subtree, rather than after the whole
1326/// tree where the effect never sees it. `id` is the element's
1327/// [`vn_element_key`]; `clip` the clip stack its subtree prepainted in, which
1328/// the content group is already inside of.
1329#[derive(Clone, Debug)]
1330pub(crate) struct VnDeferScope {
1331    id: u64,
1332    clip: Option<Arc<crate::VnClipNode>>,
1333}
1334
1335/// vue-native fork: an element's identity for per-element paint state, 0
1336/// for none. Views are left out: a cached subtree is painted inside its view
1337/// on one frame and replayed without it on the next.
1338pub(crate) fn vn_element_key(id: Option<&GlobalElementId>) -> u64 {
1339    use std::hash::{Hash, Hasher};
1340    id.map_or(0, |id| {
1341        let mut hasher = collections::FxHasher::default();
1342        for id in id.iter() {
1343            if !matches!(id, ElementId::View(_)) {
1344                id.hash(&mut hasher);
1345            }
1346        }
1347        hasher.finish().max(1)
1348    })
1349}
1350
1351impl DeferredDraw {
1352    /// The paint order: `priority`, then the embedder's stack key.
1353    fn order(&self) -> (usize, Option<&[u128]>) {
1354        (self.priority, self.vn_stack.as_deref())
1355    }
1356}
1357
1358pub(crate) struct Frame {
1359    pub(crate) focus: Option<FocusId>,
1360    pub(crate) window_active: bool,
1361    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1362    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1363    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1364    pub(crate) dispatch_tree: DispatchTree,
1365    pub(crate) scene: Scene,
1366    pub(crate) hitboxes: Vec<Hitbox>,
1367    /// vue-native fork: the hitboxes inserted while [`Window::hitbox_tag`] was
1368    /// non-zero, paired with the tag in force.
1369    ///
1370    /// An embedder that mirrors its own retained tree into gpui elements has no
1371    /// other way to get from one of ITS node ids to the hitbox gpui made for it
1372    /// — and without that, `Hitbox::is_hovered_at` (the only public door onto
1373    /// gpui's hit test) cannot be asked about a node. Insertion order is
1374    /// preserved, and an element's own hitbox is inserted before any of its
1375    /// descendants', so the FIRST entry for a tag is that node's own box.
1376    pub(crate) vn_tagged_hitboxes: Vec<(u32, Hitbox)>,
1377    /// vue-native fork: [`Frame::hitboxes`]' indices in PAINT order, which
1378    /// [`Frame::hit_test`] walks topmost-first. Empty means insertion order.
1379    ///
1380    /// Hitboxes are inserted in prepaint order, and deferred draws prepaint in
1381    /// nesting rounds: a draw nested one round deeper is inserted after every
1382    /// draw of the round before, wherever it paints. Hit-testing by insertion
1383    /// let a box that paints UNDER a later overlay take its clicks. The vector
1384    /// itself is not reordered, because cached views replay ranges of it.
1385    pub(crate) vn_hit_order: Vec<u32>,
1386    /// vue-native fork: the slice of [`Frame::vn_tagged_hitboxes`] the
1387    /// deferred draws' prepaint inserted — what
1388    /// [`Frame::vn_tagged_paint_order`] reorders, as `vn_hit_order` does the
1389    /// hitboxes.
1390    pub(crate) vn_deferred_tagged: Range<usize>,
1391    /// vue-native fork: [`Frame::vn_tagged_paint_order`], worked out on the
1392    /// first question about this frame and kept until it is cleared.
1393    vn_tagged_order: std::cell::OnceCell<Option<Vec<u32>>>,
1394    pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1395    pub(crate) deferred_draws: Vec<DeferredDraw>,
1396    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1397    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1398    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1399    #[cfg(any(test, feature = "test-support"))]
1400    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1401    #[cfg(any(test, feature = "test-support"))]
1402    debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1403    #[cfg(any(feature = "inspector", debug_assertions))]
1404    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1405    #[cfg(any(feature = "inspector", debug_assertions))]
1406    pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1407    pub(crate) tab_stops: TabStopMap,
1408}
1409
1410#[derive(Clone, Default)]
1411pub(crate) struct PrepaintStateIndex {
1412    hitboxes_index: usize,
1413    /// vue-native fork: the embedder's tagged-hitbox list is a frame structure
1414    /// like `hitboxes` beside it, so a reused prepaint span has to carry its
1415    /// slice forward too — see [`Window::reuse_prepaint`].
1416    vn_tagged_hitboxes_index: usize,
1417    tooltips_index: usize,
1418    deferred_draws_index: usize,
1419    dispatch_tree_index: usize,
1420    accessed_element_states_index: usize,
1421    line_layout_index: LineLayoutIndex,
1422}
1423
1424#[derive(Clone, Default)]
1425pub(crate) struct PaintIndex {
1426    scene_index: usize,
1427    #[cfg(any(test, feature = "test-support"))]
1428    debug_bounds_index: usize,
1429    mouse_listeners_index: usize,
1430    input_handlers_index: usize,
1431    cursor_styles_index: usize,
1432    window_control_hitboxes_index: usize,
1433    accessed_element_states_index: usize,
1434    tab_handle_index: usize,
1435    line_layout_index: LineLayoutIndex,
1436}
1437
1438impl Frame {
1439    #[cfg(any(test, feature = "test-support"))]
1440    pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1441        self.debug_bounds.insert(selector.clone(), bounds);
1442        self.debug_bounds_records.push((selector, bounds));
1443    }
1444
1445    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1446        Frame {
1447            focus: None,
1448            window_active: false,
1449            element_states: FxHashMap::default(),
1450            accessed_element_states: Vec::new(),
1451            mouse_listeners: Vec::new(),
1452            dispatch_tree,
1453            scene: Scene::default(),
1454            hitboxes: Vec::new(),
1455            vn_tagged_hitboxes: Vec::new(),
1456            vn_hit_order: Vec::new(),
1457            vn_deferred_tagged: 0..0,
1458            vn_tagged_order: std::cell::OnceCell::new(),
1459            window_control_hitboxes: Vec::new(),
1460            deferred_draws: Vec::new(),
1461            input_handlers: Vec::new(),
1462            tooltip_requests: Vec::new(),
1463            cursor_styles: Vec::new(),
1464
1465            #[cfg(any(test, feature = "test-support"))]
1466            debug_bounds: FxHashMap::default(),
1467            #[cfg(any(test, feature = "test-support"))]
1468            debug_bounds_records: Vec::new(),
1469
1470            #[cfg(any(feature = "inspector", debug_assertions))]
1471            next_inspector_instance_ids: FxHashMap::default(),
1472
1473            #[cfg(any(feature = "inspector", debug_assertions))]
1474            inspector_hitboxes: FxHashMap::default(),
1475            tab_stops: TabStopMap::default(),
1476        }
1477    }
1478
1479    pub(crate) fn clear(&mut self) {
1480        self.element_states.clear();
1481        self.accessed_element_states.clear();
1482        self.mouse_listeners.clear();
1483        self.dispatch_tree.clear();
1484        self.scene.clear();
1485        self.input_handlers.clear();
1486        self.tooltip_requests.clear();
1487        self.cursor_styles.clear();
1488        self.hitboxes.clear();
1489        self.vn_tagged_hitboxes.clear();
1490        self.vn_hit_order.clear();
1491        self.vn_deferred_tagged = 0..0;
1492        self.vn_tagged_order = std::cell::OnceCell::new();
1493        self.window_control_hitboxes.clear();
1494        self.deferred_draws.clear();
1495        self.tab_stops.clear();
1496        self.focus = None;
1497
1498        #[cfg(any(test, feature = "test-support"))]
1499        {
1500            self.debug_bounds.clear();
1501            self.debug_bounds_records.clear();
1502        }
1503
1504        #[cfg(any(feature = "inspector", debug_assertions))]
1505        {
1506            self.next_inspector_instance_ids.clear();
1507            self.inspector_hitboxes.clear();
1508        }
1509    }
1510
1511    pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1512        self.cursor_styles
1513            .iter()
1514            .rev()
1515            .fold_while(None, |style, request| match request.hitbox_id {
1516                None => Done(Some(request.style)),
1517                Some(hitbox_id) => Continue(style.or_else(|| {
1518                    hitbox_id
1519                        .is_hovered_ignoring_last_input(window)
1520                        .then_some(request.style)
1521                })),
1522            })
1523            .into_inner()
1524    }
1525
1526    /// Is `position` (window space) inside `hitbox`, as the hit test sees it?
1527    fn box_contains(hitbox: &Hitbox, position: Point<Pixels>, scale_factor: f32) -> bool {
1528        // A transformed element keeps its untransformed `bounds`, so the
1529        // POINTER is mapped back into the element's own frame rather than
1530        // the rect being mapped forward into a polygon. That keeps the test
1531        // a rectangle containment (exact for rotation and scale alike) and
1532        // costs nothing at all when there is no transform.
1533        //
1534        // The matrix is in DEVICE space (it is the same one the primitives
1535        // carry), so the pointer goes there and back; at scale 1 the two
1536        // conversions cancel and this is what it always was.
1537        //
1538        // A singular matrix (`scale(0)`) has no inverse, which is the right
1539        // answer: an element scaled to nothing is not hittable, exactly as
1540        // in a browser.
1541        let local = if hitbox.transformation.is_unit() {
1542            position
1543        } else {
1544            match hitbox.transformation.inverse() {
1545                Some(inverse) => {
1546                    let d = inverse.apply(Point::new(
1547                        px(position.x.0 * scale_factor),
1548                        px(position.y.0 * scale_factor),
1549                    ));
1550                    Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
1551                }
1552                None => return false,
1553            }
1554        };
1555        // The CONTENT MASK is a window-space rect (see
1556        // `Window::with_content_mask`, which maps it through the transform
1557        // in force when it was pushed), so it is tested against the pointer
1558        // as it came in — not against the element-local one. Testing both in
1559        // one intersected rect was only right while transforms did not
1560        // exist: a `translate(-50%, -50%)` dialog painted 500px to the left
1561        // of a clip rect that had not moved, and every clipping element
1562        // inside it hit-tested against a region it no longer covered.
1563        hitbox.content_mask.contains(&position)
1564            && hitbox.bounds.contains(&local)
1565            // vue-native fork: and inside every `clip-path` shape around it,
1566            // which is in window device pixels.
1567            && hitbox.vn_clip.as_ref().is_none_or(|clip| {
1568                clip.contains([position.x.0 * scale_factor, position.y.0 * scale_factor])
1569            })
1570    }
1571
1572    /// vue-native fork: [`Frame::vn_tagged_hitboxes`]' indices in PAINT
1573    /// order — what [`Frame::compute_hit_order`]-style reordering does for
1574    /// the hitboxes, done for the tagged list, which also holds the pick
1575    /// records no hitbox list has. `None` means insertion order is paint
1576    /// order (no deferred draw inserted anything). Worked out once per frame,
1577    /// on the first question.
1578    fn vn_tagged_paint_order(&self) -> Option<&[u32]> {
1579        self.vn_tagged_order
1580            .get_or_init(|| {
1581                let deferred = self.vn_deferred_tagged.clone();
1582                if deferred.is_empty() {
1583                    return None;
1584                }
1585                let len = self.vn_tagged_hitboxes.len();
1586                let mut order: Vec<u32> = Vec::with_capacity(len);
1587                order.extend(0..deferred.start as u32);
1588                let draws = &self.deferred_draws;
1589                let mut traversal = (0..draws.len()).collect::<Vec<_>>();
1590                traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
1591                for ix in traversal {
1592                    let range = &draws[ix].prepaint_range;
1593                    let (start, end) = (
1594                        range.start.vn_tagged_hitboxes_index,
1595                        range.end.vn_tagged_hitboxes_index,
1596                    );
1597                    if start >= deferred.start && end <= deferred.end && start < end {
1598                        order.extend(start as u32..end as u32);
1599                    }
1600                }
1601                order.extend(deferred.end as u32..len as u32);
1602                // Anything a draw's range did not account for keeps insertion
1603                // order rather than vanishing (as `compute_hit_order`).
1604                (order.len() == len).then_some(order)
1605            })
1606            .as_deref()
1607    }
1608
1609    // The iterator is stack-only: native WM_NCHITTEST can precede every mouse
1610    // move, so constructing its paint-order traversal must not allocate.
1611    fn topmost_hitboxes(&self) -> impl Iterator<Item = &Hitbox> {
1612        let in_paint_order = self.vn_hit_order.len() == self.hitboxes.len();
1613        (0..self.hitboxes.len()).rev().map(move |index| {
1614            let index = if in_paint_order { self.vn_hit_order[index] as usize } else { index };
1615            &self.hitboxes[index]
1616        })
1617    }
1618
1619    pub(crate) fn hit_test(&self, position: Point<Pixels>, scale_factor: f32) -> HitTest {
1620        let mut set_hover_hitbox_count = false;
1621        let mut hit_test = HitTest::default();
1622        for hitbox in self.topmost_hitboxes() {
1623            if Self::box_contains(hitbox, position, scale_factor) {
1624                hit_test.ids.push(hitbox.id);
1625                if !set_hover_hitbox_count
1626                    && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1627                {
1628                    hit_test.hover_hitbox_count = hit_test.ids.len();
1629                    set_hover_hitbox_count = true;
1630                }
1631                if hitbox.behavior == HitboxBehavior::BlockMouse {
1632                    break;
1633                }
1634            }
1635        }
1636        if !set_hover_hitbox_count {
1637            hit_test.hover_hitbox_count = hit_test.ids.len();
1638        }
1639        hit_test
1640    }
1641
1642    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1643        self.focus
1644            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1645            .unwrap_or_default()
1646    }
1647
1648    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1649        for element_state_key in &self.accessed_element_states {
1650            if let Some((element_state_key, element_state)) =
1651                prev_frame.element_states.remove_entry(element_state_key)
1652            {
1653                self.element_states.insert(element_state_key, element_state);
1654            }
1655        }
1656
1657        self.scene.finish();
1658    }
1659}
1660
1661#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1662enum InputModality {
1663    Mouse,
1664    Keyboard,
1665    Touch,
1666}
1667
1668/// vue-native fork: what an effect's host-filled pointer parameters read, and
1669/// the views whose effects read them.
1670struct VnEffectPointer {
1671    /// Effect-clock seconds of the last move, entry and exit; the pointer is
1672    /// inside while `entered > left`.
1673    moved: f32,
1674    entered: f32,
1675    left: f32,
1676    /// Notified on the next pointer change, and re-registered when they paint.
1677    views: FxHashSet<EntityId>,
1678}
1679
1680impl VnEffectPointer {
1681    /// Long enough ago for any fade an effect keys off these times to be over.
1682    const NEVER: f32 = -1.0e4;
1683
1684    fn new(inside: bool) -> Self {
1685        let (entered, left) = if inside {
1686            (Self::NEVER, Self::NEVER - 1.)
1687        } else {
1688            (Self::NEVER - 1., Self::NEVER)
1689        };
1690        Self {
1691            moved: Self::NEVER,
1692            entered,
1693            left,
1694            views: FxHashSet::default(),
1695        }
1696    }
1697
1698    fn update(&mut self, was_inside: bool, inside: bool, moved: bool, cx: &mut App) {
1699        if was_inside == inside && !moved {
1700            return;
1701        }
1702        let now = crate::effect_clock_seconds();
1703        if moved {
1704            self.moved = now;
1705        }
1706        if inside && !was_inside {
1707            self.entered = now;
1708        } else if was_inside && !inside {
1709            self.left = now;
1710        }
1711        for view in self.views.drain() {
1712            cx.notify(view);
1713        }
1714    }
1715}
1716
1717/// Holds the state for a specific window.
1718pub struct Window {
1719    pub(crate) handle: AnyWindowHandle,
1720    pub(crate) invalidator: WindowInvalidator,
1721    pub(crate) removed: bool,
1722    pub(crate) platform_window: Box<dyn PlatformWindow>,
1723    pub(crate) display_id: Option<DisplayId>,
1724    pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
1725    is_resizable: bool,
1726    is_minimizable: bool,
1727    last_window_bounds: WindowBounds,
1728    sprite_atlas: Arc<dyn PlatformAtlas>,
1729    text_system: Rc<WindowTextSystem>,
1730    text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1731    rem_size: Pixels,
1732    /// The stack of override values for the window's rem size.
1733    ///
1734    /// This is used by `with_rem_size` to allow rendering an element tree with
1735    /// a given rem size.
1736    rem_size_override_stack: SmallVec<[Pixels; 8]>,
1737    pub(crate) viewport_size: Size<Pixels>,
1738    layout_engine: Option<TaffyLayoutEngine>,
1739    pub(crate) root: Option<AnyView>,
1740    pub(crate) element_id_stack: ElementIdStack,
1741    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1742    pub(crate) rendered_entity_stack: Vec<EntityId>,
1743    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1744    pub(crate) element_opacity: f32,
1745    /// vue-native fork: the colour [`Window::paint_image`] tints with
1746    /// ([`Window::with_image_tint`]); transparent outside a tint scope.
1747    element_image_tint: Hsla,
1748    /// The composed CSS `transform` of every ancestor currently being painted,
1749    /// in DEVICE space. Identity outside a `Style::vn_transform`.
1750    ///
1751    /// A field rather than a stack, for the same reason `element_opacity` is:
1752    /// every push already has to compose with what is above it, so the "stack"
1753    /// is one saved value per frame of the paint recursion and lives on the
1754    /// Rust stack instead.
1755    pub(crate) element_transform: TransformationMatrix,
1756    /// vue-native fork: the embedder node id every hitbox inserted from here
1757    /// down is recorded under (0 = record nothing). See
1758    /// [`Frame::vn_tagged_hitboxes`].
1759    vn_hitbox_tag: u32,
1760    /// vue-native fork: no element has prepainted yet under the tag that
1761    /// [`Window::with_hitbox_tag`] set, so the next one is the tagged node's
1762    /// own. See [`Window::note_tagged_transform`].
1763    vn_tag_fresh: bool,
1764    /// vue-native fork: the tagged node's whole `transform` (ancestors' and
1765    /// its own), when it has one of its own.
1766    vn_tag_transform: Option<TransformationMatrix>,
1767    /// vue-native fork: while set, EVERY element gets a hitbox, not only an
1768    /// interactive one — the same thing gpui's own inspector does while it is
1769    /// picking, and for the same reason: a hit test can only answer for a node
1770    /// that has a hitbox.
1771    vn_tag_every_hitbox: bool,
1772    /// vue-native fork: while set, an element that gets no hitbox records a
1773    /// PICK instead ([`Window::vn_insert_pick`]).
1774    vn_pick_every_box: bool,
1775    /// vue-native fork: see [`Window::set_vn_hit_refiner`].
1776    vn_hit_refiner: Option<VnHitRefiner>,
1777    // Optional modal input interception, e.g. an external element inspector.
1778    input_interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
1779    /// vue-native fork: see [`Window::vn_key_event_seq`].
1780    vn_key_event_seq: u64,
1781    /// vue-native fork: [`Window::vn_lock_pointer`]'s mode and the position mouse events hold at.
1782    vn_pointer_lock: Option<(VnPointerLock, Point<Pixels>)>,
1783    /// vue-native fork: the last mouse move's position as delivered, before a lock pinned it.
1784    vn_raw_mouse_position: Option<Point<Pixels>>,
1785    /// vue-native fork: see [`Window::vn_mouse_movement`].
1786    vn_mouse_movement: Point<Pixels>,
1787    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1788    /// vue-native fork: the `clip-path` shapes in force that are no rounded
1789    /// rectangle, innermost first ([`Window::vn_with_clip_shape`]). A hitbox
1790    /// and a deferred draw take it as they take the content mask.
1791    pub(crate) vn_clip_stack: Option<Arc<crate::VnClipNode>>,
1792    /// vue-native fork: every capture drawn and not forgotten, with the
1793    /// pixels its snapshot covers ([Window::vn_with_capture]).
1794    vn_capture_records: FxHashMap<u64, (crate::VnCaptureInfo, Bounds<ScaledPixels>)>,
1795    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1796    /// The [`TextInputConfiguration`] most recently forwarded to the platform
1797    /// window, so that only actual changes are forwarded (reconfiguring a live
1798    /// input session can restart the IME connection).
1799    last_text_input_configuration: Option<TextInputConfiguration>,
1800    focused_text_input: Option<FocusId>,
1801    pub(crate) image_cache_stack: Vec<AnyImageCache>,
1802    pub(crate) rendered_frame: Frame,
1803    pub(crate) next_frame: Frame,
1804    next_hitbox_id: HitboxId,
1805    pub(crate) next_tooltip_id: TooltipId,
1806    pub(crate) tooltip_bounds: Option<TooltipBounds>,
1807    pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1808    /// Whether a queued next-frame callback asked for a frame (passive ones do
1809    /// not; see [`Window::on_next_frame_passive`]).
1810    pub(crate) next_frame_wanted: Rc<Cell<bool>>,
1811    pub(crate) dirty_views: FxHashSet<EntityId>,
1812    focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
1813    pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
1814    focus_lost_path: SmallVec<[FocusId; 8]>,
1815    default_prevented: bool,
1816    mouse_position: Point<Pixels>,
1817    mouse_hit_test: HitTest,
1818    modifiers: Modifiers,
1819    capslock: Capslock,
1820    scale_factor: f32,
1821    pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
1822    appearance: WindowAppearance,
1823    pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
1824    pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
1825    active: Rc<Cell<bool>>,
1826    /// vue-native fork: [`Window::set_assume_active`].
1827    assume_active: bool,
1828    visibility: WindowVisibility,
1829    pub(crate) visibility_observers:
1830        SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1831    hovered: Rc<Cell<bool>>,
1832    /// vue-native fork: is the pointer in this window, as far as the input
1833    /// gpui has seen says? Until it is, `mouse_position` is only where the OS
1834    /// cursor projects onto the client area (`Window::new` and
1835    /// `bounds_changed` read it from the platform). The cursor may be over
1836    /// another window that covers this one, or the position may be stale
1837    /// since the pointer left. No hitbox counts as hovered while this is
1838    /// false ([`HitboxId::is_hovered`]). The hit test itself is kept, because
1839    /// the platform's window-control hit test (`WM_NCHITTEST`) reads it.
1840    ///
1841    /// Any pointer input dispatched to the window sets it, a synthesized
1842    /// one included (a test harness or devtools moving the pointer means it).
1843    /// `MouseExited`, a file drag leaving, and the platform's hover-status
1844    /// change to false clear it. It starts as the platform's `is_hovered()`.
1845    pointer_inside: bool,
1846    vn_effect_pointer: VnEffectPointer,
1847    /// vue-native fork: the identity of the element whose style paints next,
1848    /// which keys an `[SkHistory]` effect's state; 0 when it has none.
1849    vn_effect_element: u64,
1850    /// vue-native fork: per element and effect, how far its `[SkAnimated]`
1851    /// speed has advanced it ([`VnEffectPhase`]).
1852    vn_effect_phases: FxHashMap<u64, VnEffectPhase>,
1853    /// vue-native fork: the scope a draw deferred now goes to, while
1854    /// prepainting.
1855    vn_defer_scope: Option<VnDeferScope>,
1856    /// vue-native fork: the scopes whose content painted their draws this
1857    /// frame.
1858    vn_scopes_painted: FxHashSet<u64>,
1859    pub(crate) needs_present: Rc<Cell<bool>>,
1860    /// The rendered scene's [`Scene::animation_frame_interval`]. While it is
1861    /// `Some`, the scene must keep being presented even when nothing is redrawn.
1862    scene_animation_interval: Rc<Cell<Option<Duration>>>,
1863    /// Tracks recent input event timestamps to determine if input is arriving at a high rate.
1864    /// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
1865    pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1866    #[cfg(feature = "profiler")]
1867    pub(crate) window_profiler: profiler::WindowProfiler,
1868    last_input_modality: InputModality,
1869    touch_gestures: TouchGestureRecognizer,
1870    touch_prediction_enabled: bool,
1871    long_press_timer: Option<Task<()>>,
1872    long_press_capture: Option<EntityId>,
1873    pub(crate) refreshing: bool,
1874    pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
1875    pub(crate) focus: Option<FocusId>,
1876    focus_enabled: bool,
1877    /// Incremented every time focus moves. Used to invalidate a
1878    /// pending keyboard activation state when focus changes.
1879    pub(crate) focus_generation: u64,
1880    pending_input: Option<PendingInput>,
1881    pending_modifier: ModifierState,
1882    pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
1883    prompt: Option<RenderablePromptHandle>,
1884    pub(crate) client_inset: Option<Pixels>,
1885    /// The hitbox that has captured the pointer, if any.
1886    /// While captured, mouse events route to this hitbox regardless of hit testing.
1887    captured_hitbox: Option<HitboxId>,
1888    #[cfg(any(feature = "inspector", debug_assertions))]
1889    inspector: Option<Entity<Inspector>>,
1890    #[cfg(feature = "profiler")]
1891    debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1892    pub(crate) a11y: A11y,
1893}
1894
1895#[derive(Clone, Debug, Default)]
1896struct ModifierState {
1897    modifiers: Modifiers,
1898    saw_other_input: bool,
1899}
1900
1901/// Tracks input event timestamps to determine if input is arriving at a high rate.
1902/// Used for selective VRR (Variable Refresh Rate) optimization.
1903#[derive(Clone, Debug)]
1904pub(crate) struct InputRateTracker {
1905    timestamps: Vec<Instant>,
1906    window: Duration,
1907    inputs_per_second: u32,
1908    sustain_until: Instant,
1909    sustain_duration: Duration,
1910}
1911
1912const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
1913
1914/// Keeps throttled frames on a stable cadence despite callback delivery jitter.
1915#[derive(Default)]
1916struct FramePacer {
1917    last_frame: Option<Instant>,
1918}
1919
1920impl FramePacer {
1921    fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
1922        if let Some(interval) = minimum_interval
1923            && let Some(last_frame) = self.last_frame
1924        {
1925            let deadline = last_frame + interval;
1926            if now + FRAME_INTERVAL_TOLERANCE < deadline {
1927                return true;
1928            }
1929            // Correct small dispatch delays without shifting subsequent deadlines,
1930            // but bound the correction to a quarter interval. Larger delays restart
1931            // the cadence so recovery cannot produce closely spaced catch-up frames.
1932            self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
1933                deadline
1934            } else {
1935                now
1936            });
1937        } else {
1938            self.last_frame = Some(now);
1939        }
1940        false
1941    }
1942}
1943
1944fn minimum_frame_interval(
1945    should_throttle: bool,
1946    inactive_without_high_rate_input: bool,
1947    inactive_frame_interval: Option<Duration>,
1948    low_power_frame_interval: Option<Duration>,
1949    thermal_frame_interval: Option<Duration>,
1950    thermal_state: ThermalState,
1951    power_mode: crate::PowerMode,
1952) -> Option<Duration> {
1953    if !should_throttle {
1954        return None;
1955    }
1956
1957    [
1958        inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
1959        low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
1960        thermal_frame_interval.filter(|_| {
1961            matches!(
1962                thermal_state,
1963                ThermalState::Critical | ThermalState::Serious
1964            )
1965        }),
1966    ]
1967    .into_iter()
1968    .flatten()
1969    .max()
1970}
1971
1972impl Default for InputRateTracker {
1973    fn default() -> Self {
1974        Self {
1975            timestamps: Vec::new(),
1976            window: Duration::from_millis(100),
1977            inputs_per_second: 60,
1978            sustain_until: Instant::now(),
1979            sustain_duration: Duration::from_secs(1),
1980        }
1981    }
1982}
1983
1984impl InputRateTracker {
1985    pub fn record_input(&mut self) {
1986        let now = Instant::now();
1987        self.timestamps.push(now);
1988        self.prune_old_timestamps(now);
1989
1990        let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1991        if self.timestamps.len() as u128 >= min_events {
1992            self.sustain_until = now + self.sustain_duration;
1993        }
1994    }
1995
1996    pub fn is_high_rate(&self) -> bool {
1997        Instant::now() < self.sustain_until
1998    }
1999
2000    fn prune_old_timestamps(&mut self, now: Instant) {
2001        self.timestamps
2002            .retain(|&t| now.duration_since(t) <= self.window);
2003    }
2004}
2005
2006#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2007pub(crate) enum DrawPhase {
2008    None,
2009    Prepaint,
2010    Paint,
2011    Focus,
2012}
2013
2014pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
2015
2016/// Pending input for a potential multi-stroke key binding.
2017pub struct PendingInputStatus<'a> {
2018    keystrokes: &'a [Keystroke],
2019    timeout: Option<PendingInputTimeoutStatus>,
2020}
2021
2022impl<'a> PendingInputStatus<'a> {
2023    /// Returns the keystrokes entered so far.
2024    pub fn keystrokes(&self) -> &'a [Keystroke] {
2025        self.keystrokes
2026    }
2027
2028    /// Returns the timeout state for flushing this input, if it needs a timeout.
2029    pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
2030        self.timeout
2031    }
2032}
2033
2034/// The timeout state for pending input.
2035#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2036pub struct PendingInputTimeoutStatus {
2037    duration: Duration,
2038    remaining: Duration,
2039    started_at: Option<Instant>,
2040    paused: bool,
2041}
2042
2043impl PendingInputTimeoutStatus {
2044    /// Returns the full timeout duration.
2045    pub fn duration(&self) -> Duration {
2046        self.duration
2047    }
2048
2049    /// Returns the duration remaining before pending input is flushed.
2050    pub fn remaining(&self, cx: &App) -> Duration {
2051        self.started_at
2052            .map(|started_at| {
2053                self.remaining
2054                    .saturating_sub(cx.background_executor().now() - started_at)
2055            })
2056            .unwrap_or(self.remaining)
2057    }
2058
2059    /// Returns whether the timeout is paused.
2060    pub fn is_paused(&self) -> bool {
2061        self.paused
2062    }
2063}
2064
2065#[derive(Debug)]
2066struct PendingInputTimeout {
2067    duration: Duration,
2068    remaining: Duration,
2069    state: PendingInputTimeoutState,
2070}
2071
2072#[derive(Debug)]
2073enum PendingInputTimeoutState {
2074    Running { started_at: Instant, task: Task<()> },
2075    Paused { pause: PendingInputTimeoutPause },
2076}
2077
2078#[derive(Debug)]
2079struct PendingInputTimeoutPause {
2080    owner_id: EntityId,
2081    _release_subscription: Subscription,
2082}
2083
2084impl PendingInputTimeout {
2085    fn is_paused(&self) -> bool {
2086        matches!(&self.state, PendingInputTimeoutState::Paused { .. })
2087    }
2088
2089    fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
2090        match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
2091            PendingInputTimeoutState::Running { started_at, task } => {
2092                self.remaining = self.remaining.saturating_sub(now - started_at);
2093                drop(task);
2094                true
2095            }
2096            previous_state @ PendingInputTimeoutState::Paused { .. } => {
2097                self.state = previous_state;
2098                false
2099            }
2100        }
2101    }
2102
2103    fn pause_owner_id(&self) -> Option<EntityId> {
2104        match &self.state {
2105            PendingInputTimeoutState::Running { .. } => None,
2106            PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
2107        }
2108    }
2109
2110    fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
2111        match std::mem::replace(
2112            &mut self.state,
2113            PendingInputTimeoutState::Running { started_at, task },
2114        ) {
2115            PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
2116            previous_state => {
2117                self.state = previous_state;
2118                false
2119            }
2120        }
2121    }
2122
2123    fn reset_duration(&mut self, duration: Duration) {
2124        self.duration = duration;
2125        self.remaining = duration;
2126    }
2127
2128    fn status(&self) -> PendingInputTimeoutStatus {
2129        let (started_at, paused) = match &self.state {
2130            PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
2131            PendingInputTimeoutState::Paused { .. } => (None, true),
2132        };
2133        PendingInputTimeoutStatus {
2134            duration: self.duration,
2135            remaining: self.remaining,
2136            started_at,
2137            paused,
2138        }
2139    }
2140}
2141
2142#[derive(Default, Debug)]
2143struct PendingInput {
2144    keystrokes: SmallVec<[Keystroke; 1]>,
2145    focus: Option<FocusId>,
2146    timeout: Option<PendingInputTimeout>,
2147}
2148
2149pub(crate) struct ElementStateBox {
2150    pub(crate) inner: Box<dyn Any>,
2151    #[cfg(debug_assertions)]
2152    pub(crate) type_name: &'static str,
2153}
2154
2155fn default_bounds(
2156    active_window_bounds: Option<WindowBounds>,
2157    display: Option<&dyn PlatformDisplay>,
2158) -> WindowBounds {
2159    const CASCADE_OFFSET: f32 = 25.0;
2160
2161    let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
2162
2163    // Use visible_bounds to exclude taskbar/dock areas
2164    let display_bounds = display
2165        .map(|d| d.visible_bounds())
2166        .unwrap_or_else(default_placement);
2167
2168    let (
2169        Bounds {
2170            origin: base_origin,
2171            size: base_size,
2172        },
2173        window_bounds_ctor,
2174    ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
2175        Some(bounds) => match bounds {
2176            WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
2177            WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
2178            WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
2179        },
2180        None => (
2181            display
2182                .map(|d| d.default_bounds())
2183                .unwrap_or_else(default_placement),
2184            WindowBounds::Windowed,
2185        ),
2186    };
2187
2188    let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
2189    let proposed_origin = base_origin + cascade_offset;
2190    let proposed_bounds = Bounds::new(proposed_origin, base_size);
2191
2192    let display_right = display_bounds.origin.x + display_bounds.size.width;
2193    let display_bottom = display_bounds.origin.y + display_bounds.size.height;
2194    let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
2195    let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
2196
2197    let fits_horizontally = window_right <= display_right;
2198    let fits_vertically = window_bottom <= display_bottom;
2199
2200    let final_origin = match (fits_horizontally, fits_vertically) {
2201        (true, true) => proposed_origin,
2202        (false, true) => point(display_bounds.origin.x, base_origin.y),
2203        (true, false) => point(base_origin.x, display_bounds.origin.y),
2204        (false, false) => display_bounds.origin,
2205    };
2206    window_bounds_ctor(Bounds::new(final_origin, base_size))
2207}
2208
2209impl Window {
2210    pub(crate) fn new(
2211        handle: AnyWindowHandle,
2212        options: WindowOptions,
2213        cx: &mut App,
2214    ) -> Result<Self> {
2215        let WindowOptions {
2216            window_bounds,
2217            titlebar,
2218            focus,
2219            show,
2220            kind,
2221            is_movable,
2222            app_owns_titlebar_drag,
2223            inactive_frame_interval,
2224            low_power_frame_interval,
2225            thermal_frame_interval,
2226            is_resizable,
2227            is_minimizable,
2228            display_id,
2229            window_background,
2230            app_id,
2231            window_min_size,
2232            window_decorations,
2233            #[cfg_attr(
2234                not(any(target_os = "linux", target_os = "freebsd")),
2235                allow(unused_variables)
2236            )]
2237            icon,
2238            #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2239            tabbing_identifier,
2240            #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2241            use_display_p3,
2242        } = options;
2243
2244        let initial_window_title = titlebar
2245            .as_ref()
2246            .and_then(|titlebar| titlebar.title.clone());
2247
2248        let active_window_placement = cx.active_window_placement();
2249        // Explicit bounds only make sense on the display they were computed for.
2250        let target_display_id = display_id.or_else(|| {
2251            active_window_placement
2252                .filter(|_| window_bounds.is_none())
2253                .and_then(|(display_id, _)| display_id)
2254        });
2255        let display = target_display_id
2256            .and_then(|display_id| cx.find_display(display_id))
2257            .or_else(|| cx.primary_display());
2258        let display_id = display
2259            .as_ref()
2260            .map(|display| display.id())
2261            .or(target_display_id);
2262        let active_window_bounds = active_window_placement
2263            .filter(|(active_display_id, _)| *active_display_id == display_id)
2264            .map(|(_, bounds)| bounds);
2265        let window_bounds = window_bounds
2266            .unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
2267        let mut platform_window = cx.platform.open_window(
2268            handle,
2269            WindowParams {
2270                bounds: window_bounds.get_bounds(),
2271                titlebar,
2272                kind,
2273                is_movable,
2274                app_owns_titlebar_drag,
2275                is_resizable,
2276                is_minimizable,
2277                focus,
2278                show,
2279                display_id,
2280                window_min_size,
2281                app_id: app_id.clone(),
2282                icon,
2283                #[cfg(target_os = "macos")]
2284                tabbing_identifier,
2285                #[cfg(target_os = "macos")]
2286                use_display_p3,
2287            },
2288        )?;
2289
2290        let tab_bar_visible = platform_window.tab_bar_visible();
2291        SystemWindowTabController::init_visible(cx, tab_bar_visible);
2292        if let Some(tabs) = platform_window.tabbed_windows() {
2293            SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
2294        }
2295
2296        let display_id = platform_window.display().map(|display| display.id());
2297        let sprite_atlas = platform_window.sprite_atlas();
2298        let mouse_position = platform_window.mouse_position();
2299        let modifiers = platform_window.modifiers();
2300        let capslock = platform_window.capslock();
2301        let content_size = platform_window.content_size();
2302        let scale_factor = platform_window.scale_factor();
2303        let appearance = platform_window.appearance();
2304        let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
2305        let invalidator = WindowInvalidator::new(handle.window_id());
2306        let active = Rc::new(Cell::new(platform_window.is_active()));
2307        let visibility = platform_window.visibility();
2308        #[cfg(feature = "profiler")]
2309        profiler::journal::record_window_visibility(handle.window_id(), visibility);
2310        let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
2311        let needs_present = Rc::new(Cell::new(false));
2312        let scene_animation_interval = Rc::new(Cell::new(None::<Duration>));
2313        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
2314        let next_frame_wanted: Rc<Cell<bool>> = Default::default();
2315        let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
2316
2317        platform_window
2318            .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
2319        platform_window.set_background_appearance(window_background);
2320
2321        match window_bounds {
2322            WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
2323            WindowBounds::Maximized(_) => platform_window.zoom(),
2324            WindowBounds::Windowed(_) => {}
2325        }
2326
2327        let accessibility_force_disabled = cx.accessibility_force_disabled;
2328        let a11y_active_flag = Arc::new(AtomicBool::new(false));
2329
2330        #[cfg(not(target_family = "wasm"))]
2331        if !accessibility_force_disabled {
2332            let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
2333            if let Some(title) = &initial_window_title {
2334                initial_root_node.set_label(title.to_string());
2335            }
2336            let initial_tree = accesskit::TreeUpdate {
2337                nodes: vec![(ROOT_NODE_ID, initial_root_node)],
2338                tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
2339                tree_id: accesskit::TreeId::ROOT,
2340                focus: ROOT_NODE_ID,
2341            };
2342            let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
2343            let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
2344            let (action_sender, action_receiver) =
2345                async_channel::unbounded::<accesskit::ActionRequest>();
2346
2347            platform_window.a11y_init(crate::A11yCallbacks {
2348                activation: {
2349                    let active_flag = a11y_active_flag.clone();
2350                    Box::new(move || {
2351                        log::info!("Accessibility activated");
2352                        active_flag.store(true, SeqCst);
2353                        activation_sender
2354                            .send_blocking(())
2355                            .with_context(|| {
2356                                format!(
2357                                    "queuing accessibility activation for window {:?}",
2358                                    handle.window_id()
2359                                )
2360                            })
2361                            .log_err();
2362                        Some(initial_tree.clone())
2363                    })
2364                },
2365                action: Box::new(move |request| {
2366                    action_sender
2367                        .send_blocking(request)
2368                        .with_context(|| {
2369                            format!(
2370                                "queuing accessibility action for window {:?}",
2371                                handle.window_id()
2372                            )
2373                        })
2374                        .log_err();
2375                }),
2376                deactivation: {
2377                    let active_flag = a11y_active_flag.clone();
2378                    Box::new(move || {
2379                        log::info!("Accessibility deactivated");
2380                        active_flag.store(false, SeqCst);
2381                        deactivation_sender
2382                            .send_blocking(())
2383                            .with_context(|| {
2384                                format!(
2385                                    "queuing accessibility deactivation for window {:?}",
2386                                    handle.window_id()
2387                                )
2388                            })
2389                            .log_err();
2390                    })
2391                },
2392            });
2393
2394            // A11y can be activated at any time, and so we cannot compute a
2395            // correct `TreeUpdate` on-demand. When this happens, we return a
2396            // default empty `TreeUpdate`.
2397            //
2398            // So we force a new frame, which will then send a correct `TreeUpdate`.
2399            let mut async_cx = cx.to_async();
2400            cx.foreground_executor()
2401                .spawn(async move {
2402                    while activation_receiver.recv().await.is_ok() {
2403                        handle
2404                            .update(&mut async_cx, |_, window, _| window.refresh())
2405                            .with_context(|| {
2406                                format!(
2407                                    "handling accessibility activation for window {:?}",
2408                                    handle.window_id()
2409                                )
2410                            })
2411                            .log_err();
2412                    }
2413                })
2414                .detach();
2415
2416            let mut async_cx = cx.to_async();
2417            cx.foreground_executor()
2418                .spawn(async move {
2419                    while deactivation_receiver.recv().await.is_ok() {
2420                        handle
2421                            .update(&mut async_cx, |_, window, _| window.refresh())
2422                            .with_context(|| {
2423                                format!(
2424                                    "handling accessibility deactivation for window {:?}",
2425                                    handle.window_id()
2426                                )
2427                            })
2428                            .log_err();
2429                    }
2430                })
2431                .detach();
2432
2433            let mut async_cx = cx.to_async();
2434            cx.foreground_executor()
2435                .spawn(async move {
2436                    while let Ok(request) = action_receiver.recv().await {
2437                        handle
2438                            .update(&mut async_cx, |_, window, cx| {
2439                                window.handle_a11y_action(request, cx);
2440                            })
2441                            .with_context(|| {
2442                                format!(
2443                                    "handling accessibility action for window {:?}",
2444                                    handle.window_id()
2445                                )
2446                            })
2447                            .log_err();
2448                    }
2449                })
2450                .detach();
2451        }
2452
2453        platform_window.on_close(Box::new({
2454            let window_id = handle.window_id();
2455            let cx = cx.to_async();
2456            move || {
2457                // Native destruction can re-enter while the app is borrowed.
2458                // Schedule both operations without borrowing the app here.
2459                cx.spawn(async move |cx| {
2460                    cx.update(|cx| {
2461                        // App-driven closure may already have removed the window.
2462                        if cx.windows.contains_key(window_id) {
2463                            handle
2464                                .update(cx, |_, window, _| window.remove_window())
2465                                .with_context(|| format!("handling close for window {window_id:?}"))
2466                                .log_err();
2467                        }
2468                        SystemWindowTabController::remove_tab(cx, window_id);
2469                    });
2470                })
2471                .detach();
2472            }
2473        }));
2474        platform_window.on_request_frame(Box::new({
2475            let mut cx = cx.to_async();
2476            let invalidator = invalidator.clone();
2477            let active = active.clone();
2478            let needs_present = needs_present.clone();
2479            let scene_animation_interval = scene_animation_interval.clone();
2480            let next_frame_callbacks = next_frame_callbacks.clone();
2481            let next_frame_wanted = next_frame_wanted.clone();
2482            let input_rate_tracker = input_rate_tracker.clone();
2483            let mut deferred_force_render = false;
2484            let mut frame_pacer = FramePacer::default();
2485            move |request_frame_options| {
2486                #[cfg(feature = "profiler")]
2487                let (_foreground_turn, window_id) = {
2488                    let foreground_turn = profiler::journal::foreground_turn();
2489                    let window_id = handle.window_id();
2490                    profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
2491                        window_id,
2492                        signal_at: request_frame_options.signal_at,
2493                        handled_at: Instant::now(),
2494                        source: request_frame_options.signal_source,
2495                    });
2496                    (foreground_turn, window_id)
2497                };
2498                // This must be checked before accessing App: if this request
2499                // arrived re-entrantly while a draw is on this thread's stack
2500                // (e.g. via a nested message pump in the Windows window
2501                // procedure), drawing would nest draws, and even touching the
2502                // App would panic on its already-mutable borrow. Skip instead;
2503                // the platform leaves the window invalidated (or re-invalidates
2504                // it), so a fresh request arrives once the in-progress draw
2505                // unwinds. Remember force_render so the deferred frame still
2506                // bypasses the view cache.
2507                //
2508                // Returning here skips `complete_frame`, which on Wayland would
2509                // stall the window's frame callbacks (no `surface.commit()`) —
2510                // but calling it would hit the App borrow panic above, and this
2511                // branch is unreachable there in practice: only Windows pumps
2512                // platform events (and thus requests frames) mid-draw.
2513                if draw_in_progress() {
2514                    log::debug!("deferring re-entrant window draw request");
2515                    deferred_force_render |= request_frame_options.force_render;
2516                    #[cfg(feature = "profiler")]
2517                    profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
2518                    return;
2519                }
2520                // Take the deferred flag first: `||` short-circuits, and leaving
2521                // the flag set when this request already forces a render would
2522                // force a second, redundant render on the next frame.
2523                let force_render =
2524                    mem::take(&mut deferred_force_render) || request_frame_options.force_render;
2525
2526                let power_state = handle
2527                    .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
2528                    .with_context(|| {
2529                        format!(
2530                            "reading power state for frame request for window {:?}",
2531                            handle.window_id()
2532                        )
2533                    })
2534                    .log_err();
2535
2536                // Keep presenting briefly after high-rate input to prevent display
2537                // underclocking, but subject to the same power limits as redraws.
2538                let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
2539                // vue-native: only macOS ProMotion underclocks an idle layer. On
2540                // Windows a present re-renders the whole unchanged scene, so the
2541                // sustain would cost a full GPU frame per refresh for a second.
2542                let present_for_high_rate_input = cfg!(target_os = "macos") && high_rate_input;
2543                let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
2544                // vue-native fork: demand that asks the platform for a frame.
2545                // Passive next-frame callbacks (`Window::on_next_frame_passive`)
2546                // are paced like any other frame work but never wake the frame
2547                // source on their own.
2548                let wants_frame_besides_animation = invalidator.is_dirty()
2549                    || force_render
2550                    || next_frame_wanted.get()
2551                    || request_frame_options.require_presentation
2552                    || needs_present.get()
2553                    || present_for_high_rate_input;
2554                let has_demand_besides_animation =
2555                    wants_frame_besides_animation || has_next_frame_callbacks;
2556                let wants_frame =
2557                    wants_frame_besides_animation || scene_animation_interval.get().is_some();
2558                let has_frame_demand = wants_frame || has_next_frame_callbacks;
2559
2560                let should_throttle = !request_frame_options.require_presentation;
2561                let inactive_without_high_rate_input =
2562                    should_throttle && !active.get() && !high_rate_input;
2563                let (thermal_state, power_mode) =
2564                    power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
2565                let min_frame_interval = minimum_frame_interval(
2566                    should_throttle,
2567                    inactive_without_high_rate_input,
2568                    inactive_frame_interval,
2569                    low_power_frame_interval,
2570                    thermal_frame_interval,
2571                    thermal_state,
2572                    power_mode,
2573                );
2574                let animation_frame_interval = scene_animation_interval
2575                    .get()
2576                    .filter(|interval| !has_demand_besides_animation && !interval.is_zero());
2577                let min_frame_interval = min_frame_interval.max(animation_frame_interval);
2578
2579                let now = Instant::now();
2580                // Idle display-link ticks must neither consume a frame slot nor
2581                // wake a demand-driven frame source.
2582                if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
2583                    // Don't lose a pending forced render to throttling.
2584                    deferred_force_render |= force_render;
2585                    // Passive callbacks alone wait for the next delivered frame.
2586                    if wants_frame {
2587                        // Deferred by throttling: ask demand-driven platforms to retry.
2588                        handle
2589                            .update(&mut cx, |_, window, _| {
2590                                window.platform_window.schedule_frame();
2591                            })
2592                            .with_context(|| {
2593                                format!(
2594                                    "rescheduling throttled frame for window {:?}",
2595                                    handle.window_id()
2596                                )
2597                            })
2598                            .log_err();
2599                        // The demand is still unserved; platforms that stop
2600                        // requesting frames for idle windows need a wakeup to retry.
2601                        invalidator.wake_platform();
2602                    }
2603                    #[cfg(feature = "profiler")]
2604                    profiler::journal::record_frame_skipped(
2605                        window_id,
2606                        Instant::now(),
2607                        if animation_frame_interval.is_some()
2608                            && animation_frame_interval == min_frame_interval
2609                        {
2610                            profiler::journal::FrameSkipReason::AnimationFrameRateLimit
2611                        } else if inactive_without_high_rate_input
2612                            && inactive_frame_interval == min_frame_interval
2613                        {
2614                            profiler::journal::FrameSkipReason::InactiveFrameRateLimit
2615                        } else if power_mode == crate::PowerMode::LowPower
2616                            && low_power_frame_interval == min_frame_interval
2617                        {
2618                            profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
2619                        } else {
2620                            profiler::journal::FrameSkipReason::ThermalFrameRateLimit
2621                        },
2622                    );
2623                    report_frame(handle.window_id(), now, FrameOutcome::Throttled);
2624                    return;
2625                }
2626
2627                if !next_frame_callbacks.borrow().is_empty() {
2628                    handle
2629                        .update(&mut cx, |_, window, cx| {
2630                            // A native frame request can re-enter while App is borrowed.
2631                            // Keep the callbacks queued if updating the window fails,
2632                            // or a self-rescheduling frame pump would be lost forever.
2633                            window.next_frame_wanted.set(false);
2634                            for callback in next_frame_callbacks.take() {
2635                                callback(window, cx);
2636                            }
2637                        })
2638                        .with_context(|| {
2639                            format!(
2640                                "running next-frame callbacks for window {:?}",
2641                                handle.window_id()
2642                            )
2643                        })
2644                        .log_err();
2645                }
2646
2647                let should_draw = invalidator.is_dirty() || force_render;
2648                let needs_present = request_frame_options.require_presentation
2649                    || needs_present.get()
2650                    || scene_animation_interval.get().is_some()
2651                    || present_for_high_rate_input;
2652                if should_draw {
2653                    measure("frame duration", || {
2654                        handle
2655                            .update(&mut cx, |_, window, cx| {
2656                                #[cfg(feature = "profiler")]
2657                                window
2658                                    .window_profiler
2659                                    .record_frame_signal(request_frame_options.signal_at);
2660                                if force_render {
2661                                    // Bypass cached view reuse so we don't replay stale
2662                                    // atlas tile references after a GPU device recovery.
2663                                    window.refresh();
2664                                }
2665                                let arena_clear_needed = window.draw(cx);
2666                                window.advance_scene_animations(cx);
2667                                window.present();
2668                                arena_clear_needed.clear(cx);
2669                            })
2670                            .with_context(|| {
2671                                format!(
2672                                    "drawing and presenting frame for window {:?}",
2673                                    handle.window_id()
2674                                )
2675                            })
2676                            .log_err();
2677                    })
2678                } else if needs_present {
2679                    handle
2680                        .update(&mut cx, |_, window, cx| {
2681                            window.advance_scene_animations(cx);
2682                            window.present();
2683                        })
2684                        .with_context(|| {
2685                            format!("presenting frame for window {:?}", handle.window_id())
2686                        })
2687                        .log_err();
2688                }
2689
2690                handle
2691                    .update(&mut cx, |_, window, _| {
2692                        if window.invalidator.is_dirty()
2693                            || window.next_frame_wanted.get()
2694                            || window.scene_animation_interval.get().is_some()
2695                        {
2696                            window.platform_window.schedule_frame();
2697                        }
2698                    })
2699                    .with_context(|| {
2700                        format!(
2701                            "scheduling follow-up frame for window {:?}",
2702                            handle.window_id()
2703                        )
2704                    })
2705                    .log_err();
2706
2707                // Platforms that stop requesting frames for idle windows only
2708                // deliver another request after a wakeup. If demand remains
2709                // after this frame (the window was re-invalidated mid-draw, or
2710                // animations scheduled next-frame callbacks), re-arm the frame
2711                // source explicitly. Passive callbacks are not demand.
2712                if invalidator.is_dirty()
2713                    || next_frame_wanted.get()
2714                    || scene_animation_interval.get().is_some()
2715                {
2716                    invalidator.wake_platform();
2717                }
2718                #[cfg(feature = "profiler")]
2719                if !should_draw {
2720                    profiler::journal::record_frame_skipped(
2721                        window_id,
2722                        Instant::now(),
2723                        profiler::journal::FrameSkipReason::NoRenderNeeded,
2724                    );
2725                }
2726                if should_draw {
2727                    report_frame(handle.window_id(), now, FrameOutcome::Drew);
2728                } else if has_next_frame_callbacks || needs_present {
2729                    report_frame(handle.window_id(), now, FrameOutcome::NoDraw);
2730                }
2731            }
2732        }));
2733        invalidator.set_platform_waker(platform_window.frame_waker());
2734        platform_window.on_visual_viewport_changed(Box::new({
2735            let mut cx = cx.to_async();
2736            move || {
2737                handle
2738                    .update(&mut cx, |_, window, _| window.refresh())
2739                    .with_context(|| {
2740                        format!(
2741                            "handling visual viewport change for window {:?}",
2742                            handle.window_id()
2743                        )
2744                    })
2745                    .log_err();
2746            }
2747        }));
2748        platform_window.on_insets_changed(Box::new({
2749            let mut cx = cx.to_async();
2750            move |_| {
2751                handle
2752                    .update(&mut cx, |_, window, _| window.refresh())
2753                    .with_context(|| {
2754                        format!("handling insets change for window {:?}", handle.window_id())
2755                    })
2756                    .log_err();
2757            }
2758        }));
2759        platform_window.on_resize(Box::new({
2760            let mut cx = cx.to_async();
2761            move |_, _| {
2762                handle
2763                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2764                    .with_context(|| format!("handling resize for window {:?}", handle.window_id()))
2765                    .log_err();
2766            }
2767        }));
2768        platform_window.on_moved(Box::new({
2769            let mut cx = cx.to_async();
2770            move || {
2771                handle
2772                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2773                    .with_context(|| format!("handling move for window {:?}", handle.window_id()))
2774                    .log_err();
2775            }
2776        }));
2777        platform_window.on_display_changed(Box::new({
2778            let cx = cx.to_async();
2779            move || cx.update(|cx| Window::display_changed(handle, cx))
2780        }));
2781        platform_window.on_appearance_changed(Box::new({
2782            let cx = cx.to_async();
2783            let foreground_executor = cx.foreground_executor().clone();
2784            move || {
2785                let mut cx = cx.clone();
2786                // Defer the update because changing the AppKit appearance may
2787                // synchronously invoke this callback while App is already borrowed.
2788                foreground_executor
2789                    .spawn(async move {
2790                        handle
2791                            .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2792                            .with_context(|| {
2793                                format!(
2794                                    "handling appearance change for window {:?}",
2795                                    handle.window_id()
2796                                )
2797                            })
2798                            .log_err();
2799                    })
2800                    .detach();
2801            }
2802        }));
2803        platform_window.on_button_layout_changed(Box::new({
2804            let mut cx = cx.to_async();
2805            move || {
2806                handle
2807                    .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2808                    .with_context(|| {
2809                        format!(
2810                            "handling button layout change for window {:?}",
2811                            handle.window_id()
2812                        )
2813                    })
2814                    .log_err();
2815            }
2816        }));
2817        platform_window.on_active_status_change(Box::new({
2818            let mut cx = cx.to_async();
2819            move |active| {
2820                handle
2821                    .update(&mut cx, |_, window, cx| {
2822                        // vue-native fork: an assumed-active window keeps
2823                        // reading as active whatever the OS says
2824                        // (`Window::set_assume_active`).
2825                        if window.assume_active {
2826                            return;
2827                        }
2828                        window.active.set(active);
2829                        window.modifiers = window.platform_window.modifiers();
2830                        window.capslock = window.platform_window.capslock();
2831                        window
2832                            .activation_observers
2833                            .clone()
2834                            .retain(|callback| callback(window, cx));
2835
2836                        window.bounds_changed(cx);
2837                        window.refresh();
2838
2839                        SystemWindowTabController::update_last_active(cx, window.handle.id);
2840                    })
2841                    .with_context(|| {
2842                        format!(
2843                            "handling active status change for window {:?}",
2844                            handle.window_id()
2845                        )
2846                    })
2847                    .log_err();
2848            }
2849        }));
2850        platform_window.on_visibility_change(Box::new({
2851            let mut cx = cx.to_async();
2852            move |_| {
2853                handle
2854                    .update(&mut cx, |_, window, cx| {
2855                        window.refresh_visibility(cx);
2856                    })
2857                    .with_context(|| {
2858                        format!(
2859                            "handling visibility change for window {:?}",
2860                            handle.window_id()
2861                        )
2862                    })
2863                    .log_err();
2864            }
2865        }));
2866        platform_window.on_hover_status_change(Box::new({
2867            let mut cx = cx.to_async();
2868            move |active| {
2869                handle
2870                    .update(&mut cx, |_, window, cx| {
2871                        window.hovered.set(active);
2872                        let was_inside = std::mem::replace(&mut window.pointer_inside, active);
2873                        window
2874                            .vn_effect_pointer
2875                            .update(was_inside, active, false, cx);
2876                        window.refresh();
2877                    })
2878                    .with_context(|| {
2879                        format!(
2880                            "handling hover status change for window {:?}",
2881                            handle.window_id()
2882                        )
2883                    })
2884                    .log_err();
2885            }
2886        }));
2887        platform_window.on_input({
2888            let mut cx = cx.to_async();
2889            Box::new(move |event| {
2890                handle
2891                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2892                    .with_context(|| {
2893                        format!("dispatching input for window {:?}", handle.window_id())
2894                    })
2895                    .log_err()
2896                    .unwrap_or(DispatchEventResult::default())
2897            })
2898        });
2899        platform_window.on_hit_test_window_control_at({
2900            let mut cx = cx.to_async();
2901            Box::new(move |position| {
2902                handle
2903                    .update(&mut cx, |_, window, _cx| {
2904                        // WM_NCHITTEST precedes the next mouse-move and can run
2905                        // after a cached repaint. The previous input's hit set
2906                        // may name another point/frame, or be narrowed to a DOM
2907                        // event path; it is not a native caption hit test.
2908                        let position = position.unwrap_or_else(|| window.platform_window.mouse_position());
2909                        window.window_control_area_at(position)
2910                    })
2911                    .with_context(|| {
2912                        format!(
2913                            "hit-testing window controls for window {:?}",
2914                            handle.window_id()
2915                        )
2916                    })
2917                    .log_err()
2918                    .unwrap_or(None)
2919            })
2920        });
2921        platform_window.on_move_tab_to_new_window({
2922            let mut cx = cx.to_async();
2923            Box::new(move || {
2924                handle
2925                    .update(&mut cx, |_, _window, cx| {
2926                        SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2927                    })
2928                    .with_context(|| {
2929                        format!(
2930                            "moving tab to new window from window {:?}",
2931                            handle.window_id()
2932                        )
2933                    })
2934                    .log_err();
2935            })
2936        });
2937        platform_window.on_merge_all_windows({
2938            let mut cx = cx.to_async();
2939            Box::new(move || {
2940                handle
2941                    .update(&mut cx, |_, _window, cx| {
2942                        SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2943                    })
2944                    .with_context(|| {
2945                        format!("merging all windows into window {:?}", handle.window_id())
2946                    })
2947                    .log_err();
2948            })
2949        });
2950        platform_window.on_select_next_tab({
2951            let mut cx = cx.to_async();
2952            Box::new(move || {
2953                handle
2954                    .update(&mut cx, |_, _window, cx| {
2955                        SystemWindowTabController::select_next_tab(cx, handle.window_id());
2956                    })
2957                    .with_context(|| {
2958                        format!("selecting next tab for window {:?}", handle.window_id())
2959                    })
2960                    .log_err();
2961            })
2962        });
2963        platform_window.on_select_previous_tab({
2964            let mut cx = cx.to_async();
2965            Box::new(move || {
2966                handle
2967                    .update(&mut cx, |_, _window, cx| {
2968                        SystemWindowTabController::select_previous_tab(cx, handle.window_id())
2969                    })
2970                    .with_context(|| {
2971                        format!("selecting previous tab for window {:?}", handle.window_id())
2972                    })
2973                    .log_err();
2974            })
2975        });
2976        platform_window.on_toggle_tab_bar({
2977            let mut cx = cx.to_async();
2978            Box::new(move || {
2979                handle
2980                    .update(&mut cx, |_, window, cx| {
2981                        let tab_bar_visible = window.platform_window.tab_bar_visible();
2982                        SystemWindowTabController::set_visible(cx, tab_bar_visible);
2983                    })
2984                    .with_context(|| {
2985                        format!("toggling tab bar for window {:?}", handle.window_id())
2986                    })
2987                    .log_err();
2988            })
2989        });
2990
2991        if let Some(app_id) = app_id {
2992            platform_window.set_app_id(&app_id);
2993        }
2994
2995        platform_window.map_window().unwrap();
2996
2997        Ok(Window {
2998            handle,
2999            invalidator,
3000            removed: false,
3001            platform_window,
3002            display_id,
3003            display_observers: SingleSubscriberSet::new(),
3004            is_resizable,
3005            is_minimizable,
3006            last_window_bounds: window_bounds,
3007            sprite_atlas,
3008            text_system,
3009            text_rendering_mode: cx.text_rendering_mode.clone(),
3010            rem_size: px(16.),
3011            rem_size_override_stack: SmallVec::new(),
3012            viewport_size: content_size,
3013            layout_engine: Some(TaffyLayoutEngine::new()),
3014            root: None,
3015            element_id_stack: ElementIdStack::default(),
3016            text_style_stack: Vec::new(),
3017            rendered_entity_stack: Vec::new(),
3018            element_offset_stack: Vec::new(),
3019            content_mask_stack: Vec::new(),
3020            vn_clip_stack: None,
3021            vn_capture_records: FxHashMap::default(),
3022            element_opacity: 1.0,
3023            element_image_tint: Hsla::transparent_black(),
3024            element_transform: TransformationMatrix::unit(),
3025            vn_hitbox_tag: 0,
3026            vn_tag_fresh: false,
3027            vn_tag_transform: None,
3028            vn_tag_every_hitbox: false,
3029            vn_pick_every_box: false,
3030            vn_hit_refiner: None,
3031            input_interceptor: None,
3032            vn_key_event_seq: 0,
3033            vn_pointer_lock: None,
3034            vn_raw_mouse_position: None,
3035            vn_mouse_movement: Point::default(),
3036            requested_autoscroll: None,
3037            last_text_input_configuration: None,
3038            focused_text_input: None,
3039            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3040            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3041            next_frame_callbacks,
3042            next_frame_wanted,
3043            next_hitbox_id: HitboxId(0),
3044            next_tooltip_id: TooltipId::default(),
3045            tooltip_bounds: None,
3046            dirty_views: FxHashSet::default(),
3047            focus_listeners: SingleSubscriberSet::new(),
3048            focus_lost_listeners: SingleSubscriberSet::new(),
3049            focus_lost_path: SmallVec::new(),
3050            default_prevented: true,
3051            mouse_position,
3052            mouse_hit_test: HitTest::default(),
3053            modifiers,
3054            capslock,
3055            scale_factor,
3056            bounds_observers: SingleSubscriberSet::new(),
3057            appearance,
3058            appearance_observers: SingleSubscriberSet::new(),
3059            button_layout_observers: SingleSubscriberSet::new(),
3060            active,
3061            assume_active: false,
3062            visibility,
3063            visibility_observers: SingleSubscriberSet::new(),
3064            vn_effect_pointer: VnEffectPointer::new(hovered.get()),
3065            vn_effect_element: 0,
3066            vn_effect_phases: FxHashMap::default(),
3067            vn_defer_scope: None,
3068            vn_scopes_painted: FxHashSet::default(),
3069            pointer_inside: hovered.get(),
3070            hovered,
3071            needs_present,
3072            scene_animation_interval,
3073            input_rate_tracker,
3074            #[cfg(feature = "profiler")]
3075            window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
3076            last_input_modality: InputModality::Mouse,
3077            touch_gestures: TouchGestureRecognizer::new(
3078                cx.platform
3079                    .gestures()
3080                    .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
3081            ),
3082            touch_prediction_enabled: true,
3083            long_press_timer: None,
3084            long_press_capture: None,
3085            refreshing: false,
3086            activation_observers: SingleSubscriberSet::new(),
3087            focus: None,
3088            focus_enabled: true,
3089            focus_generation: 0,
3090            pending_input: None,
3091            pending_modifier: ModifierState::default(),
3092            pending_input_observers: SingleSubscriberSet::new(),
3093            prompt: None,
3094            client_inset: None,
3095            image_cache_stack: Vec::new(),
3096            captured_hitbox: None,
3097            #[cfg(any(feature = "inspector", debug_assertions))]
3098            inspector: None,
3099            #[cfg(feature = "profiler")]
3100            debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
3101            a11y: A11y::new(
3102                a11y_active_flag,
3103                accessibility_force_disabled,
3104                initial_window_title,
3105            ),
3106        })
3107    }
3108
3109    pub(crate) fn new_focus_listener(
3110        &self,
3111        value: AnyWindowFocusListener,
3112    ) -> (Subscription, impl FnOnce() + use<>) {
3113        self.focus_listeners.insert_pending(value)
3114    }
3115}
3116
3117#[derive(Clone, Debug, Default, PartialEq, Eq)]
3118#[expect(missing_docs)]
3119pub struct DispatchEventResult {
3120    pub propagate: bool,
3121    pub default_prevented: bool,
3122}
3123
3124/// Indicates which region of the window is visible. Content falling outside of this mask will not be
3125/// rendered.
3126///
3127/// vue-native fork: the mask is a ROUNDED rect. All-zero `corner_radii` is the plain rectangle gpui
3128/// always had, and costs each fragment shader one uniform branch. With radii, every primitive's
3129/// fragment shader multiplies its coverage by the rounded rect's antialiased SDF
3130/// (`content_mask_coverage` in each backend), on top of the hardware clip to `bounds`. CSS
3131/// `overflow` under a `border-radius` is what pushes one ([`crate::Style::overflow_mask`]).
3132/// [`ContentMask::intersect`] says what nesting two masks keeps exact.
3133#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3134#[repr(C)]
3135pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
3136    /// The bounds
3137    pub bounds: Bounds<P>,
3138    /// vue-native fork: each corner's radius, zero for a square corner. Every
3139    /// primitive carries it right after `bounds`, so the shaders' structs do too.
3140    pub corner_radii: Corners<P>,
3141}
3142
3143impl<P: Clone + Debug + Default + PartialEq> ContentMask<P> {
3144    /// vue-native fork: a plain rectangular mask.
3145    pub fn rect(bounds: Bounds<P>) -> Self {
3146        ContentMask {
3147            bounds,
3148            corner_radii: Corners::default(),
3149        }
3150    }
3151
3152    /// vue-native fork: whether any corner is rounded.
3153    pub fn is_rounded(&self) -> bool {
3154        self.corner_radii != Corners::default()
3155    }
3156}
3157
3158impl ContentMask<Pixels> {
3159    /// Scale the content mask's pixel units by the given scaling factor.
3160    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
3161        ContentMask {
3162            bounds: self.bounds.scale(factor),
3163            corner_radii: self.corner_radii.scale(factor),
3164        }
3165    }
3166}
3167
3168impl<P> ContentMask<P>
3169where
3170    P: Copy
3171        + Ord
3172        + Debug
3173        + Default
3174        + Add<P, Output = P>
3175        + Sub<P, Output = P>
3176        + Div<f32, Output = P>
3177        + Into<f64>,
3178{
3179    /// Intersect the content mask with the given content mask.
3180    ///
3181    /// vue-native fork, the rounded corners:
3182    /// - Two rectangles intersect exactly, as before.
3183    /// - A corner of the result that is also a corner of one of the masks keeps
3184    ///   that mask's radius. When both masks have a corner there, the larger
3185    ///   radius wins. Two corners at one point nest, so the larger radius is the
3186    ///   smaller region, and that is exact.
3187    /// - Any other corner of the result is square. That is exact when the
3188    ///   rounded mask's curve does not reach it: a rect clip inside the curve's
3189    ///   span, or a scroller inset from its rounded card. Where a rect clip cuts
3190    ///   through a curve, the cut corner comes out square and shows the sliver
3191    ///   the curve would have hidden. That is the one approximation; the common
3192    ///   case, one rounded ancestor around rect clips that fill it or sit
3193    ///   inside it, is exact.
3194    pub fn intersect(&self, other: &Self) -> Self {
3195        let bounds = self.bounds.intersect(&other.bounds);
3196        if !self.is_rounded() && !other.is_rounded() {
3197            return ContentMask::rect(bounds);
3198        }
3199        let at = |mask: &Self, left: bool, top: bool| {
3200            let x = if left { mask.bounds.left() } else { mask.bounds.right() };
3201            let y = if top { mask.bounds.top() } else { mask.bounds.bottom() };
3202            (x, y)
3203        };
3204        let radius = |left: bool, top: bool, mine: P, theirs: P| {
3205            let here = at(&ContentMask::rect(bounds), left, top);
3206            let mine = if at(self, left, top) == here { mine } else { P::default() };
3207            let theirs = if at(other, left, top) == here { theirs } else { P::default() };
3208            mine.max(theirs)
3209        };
3210        let (a, b) = (&self.corner_radii, &other.corner_radii);
3211        let corner_radii = Corners {
3212            top_left: radius(true, true, a.top_left, b.top_left),
3213            top_right: radius(false, true, a.top_right, b.top_right),
3214            bottom_right: radius(false, false, a.bottom_right, b.bottom_right),
3215            bottom_left: radius(true, false, a.bottom_left, b.bottom_left),
3216        }
3217        .clamp_radii_for_quad_size(bounds.size);
3218        ContentMask {
3219            bounds,
3220            corner_radii,
3221        }
3222    }
3223
3224    /// vue-native fork: whether `point` is inside the mask, its rounded
3225    /// corners included. The hit test asks this, so a click outside a rounded
3226    /// clip's curve does not reach what the clip hides.
3227    pub fn contains(&self, point: &Point<P>) -> bool {
3228        if !self.bounds.contains(point) {
3229            return false;
3230        }
3231        if !self.is_rounded() {
3232            return true;
3233        }
3234        let b = &self.bounds;
3235        let r = &self.corner_radii;
3236        for (radius, cx, cy, left, top) in [
3237            (r.top_left, b.left() + r.top_left, b.top() + r.top_left, true, true),
3238            (r.top_right, b.right() - r.top_right, b.top() + r.top_right, false, true),
3239            (r.bottom_right, b.right() - r.bottom_right, b.bottom() - r.bottom_right, false, false),
3240            (r.bottom_left, b.left() + r.bottom_left, b.bottom() - r.bottom_left, true, false),
3241        ] {
3242            let in_x = if left { point.x < cx } else { point.x > cx };
3243            let in_y = if top { point.y < cy } else { point.y > cy };
3244            if radius > P::default() && in_x && in_y {
3245                let (dx, dy): (f64, f64) = ((point.x - cx).into(), (point.y - cy).into());
3246                let radius: f64 = radius.into();
3247                return dx * dx + dy * dy <= radius * radius;
3248            }
3249        }
3250        true
3251    }
3252}
3253
3254impl Window {
3255    fn mark_view_dirty(&mut self, view_id: EntityId) {
3256        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
3257        // should already be dirty.
3258        for view_id in self
3259            .rendered_frame
3260            .dispatch_tree
3261            .view_path_reversed(view_id)
3262        {
3263            if !self.dirty_views.insert(view_id) {
3264                break;
3265            }
3266        }
3267    }
3268
3269    pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
3270        let visibility = self.platform_window.visibility();
3271        if self.visibility != visibility {
3272            self.visibility = visibility;
3273            #[cfg(feature = "profiler")]
3274            profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
3275            self.visibility_observers
3276                .clone()
3277                .retain(|callback| callback(visibility, self, cx));
3278        }
3279        #[cfg(feature = "profiler")]
3280        if self.invalidator.is_dirty() || self.needs_present.get() {
3281            profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
3282        }
3283    }
3284
3285    /// This window's part of [`App::debug_state`].
3286    ///
3287    /// Values GPUI caches are reported next to what the platform reports now,
3288    /// so a stale cache shows up as a mismatch.
3289    pub(crate) fn debug_state(&self) -> serde_json::Value {
3290        let platform_window = &self.platform_window;
3291        serde_json::json!({
3292            "id": self.handle.window_id().as_u64(),
3293            "title": platform_window.get_title(),
3294            "bounds": platform_window.bounds(),
3295            "window_bounds": format!("{:?}", platform_window.window_bounds()),
3296            "content_size": platform_window.content_size(),
3297            "viewport_size": self.viewport_size,
3298            "scale_factor": {
3299                "cached": self.scale_factor,
3300                "platform": platform_window.scale_factor(),
3301            },
3302            "display_id": {
3303                "cached": self.display_id.map(u64::from),
3304                "platform": platform_window.display().map(|display| u64::from(display.id())),
3305            },
3306            "active": {
3307                "cached": self.active.get(),
3308                "platform": platform_window.is_active(),
3309            },
3310            "hovered": {
3311                "cached": self.hovered.get(),
3312                "platform": platform_window.is_hovered(),
3313            },
3314            "visibility": {
3315                "cached": format!("{:?}", self.visibility),
3316                "platform": format!("{:?}", platform_window.visibility()),
3317            },
3318            "appearance": {
3319                "cached": format!("{:?}", self.appearance),
3320                "platform": format!("{:?}", platform_window.appearance()),
3321            },
3322            "is_fullscreen": platform_window.is_fullscreen(),
3323            "is_maximized": platform_window.is_maximized(),
3324            "mouse_position": {
3325                "cached": self.mouse_position,
3326                "platform": platform_window.mouse_position(),
3327            },
3328            "modifiers": {
3329                "cached": self.modifiers,
3330                "platform": platform_window.modifiers(),
3331            },
3332            "cursor_style": self.rendered_frame.cursor_style(self),
3333            "frame": {
3334                "dirty": self.invalidator.is_dirty(),
3335                "needs_present": self.needs_present.get(),
3336                "refreshing": self.refreshing,
3337                "next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
3338            },
3339            "gpu": platform_window.gpu_specs(),
3340            "platform": platform_window.debug_state(),
3341        })
3342    }
3343
3344    /// Whether the platform is presenting this window's frames (see
3345    /// [`WindowVisibility`]).
3346    pub fn visibility(&self) -> WindowVisibility {
3347        self.visibility
3348    }
3349
3350    /// Whether frames drawn for this window will be shown.
3351    ///
3352    /// This is not the window's shown/hidden state: a shown window that is
3353    /// fully behind another window, minimized, or on a sleeping display is not
3354    /// visible here.
3355    pub fn is_visible(&self) -> bool {
3356        self.visibility.is_visible()
3357    }
3358
3359    /// Registers a callback to be invoked when the window's visibility changes.
3360    pub fn observe_window_visibility(
3361        &self,
3362        mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
3363    ) -> Subscription {
3364        self.visibility_observers
3365            .insert(Box::new(move |visibility, window, cx| {
3366                callback(visibility, window, cx);
3367                true
3368            }))
3369    }
3370
3371    /// Registers a callback to be invoked when the window is activated or
3372    /// deactivated, without an entity to update (vue-native fork).
3373    pub fn observe_window_activation(
3374        &self,
3375        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3376    ) -> Subscription {
3377        self.activation_observers
3378            .insert(Box::new(move |window, cx| {
3379                callback(window, cx);
3380                true
3381            }))
3382    }
3383
3384    /// Registers a callback to be invoked when the window appearance changes.
3385    pub fn observe_window_appearance(
3386        &self,
3387        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3388    ) -> Subscription {
3389        self.appearance_observers
3390            .insert(Box::new(move |window, cx| {
3391                callback(window, cx);
3392                true
3393            }))
3394    }
3395
3396    /// Registers a callback to be invoked when the window button layout changes.
3397    pub fn observe_button_layout_changed(
3398        &self,
3399        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3400    ) -> Subscription {
3401        self.button_layout_observers
3402            .insert(Box::new(move |window, cx| {
3403                callback(window, cx);
3404                true
3405            }))
3406    }
3407
3408    /// Replaces the root entity of the window with a new one.
3409    pub fn replace_root<E>(
3410        &mut self,
3411        cx: &mut App,
3412        build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
3413    ) -> Entity<E>
3414    where
3415        E: 'static + Render,
3416    {
3417        let view = cx.new(|cx| build_view(self, cx));
3418        self.root = Some(view.clone().into());
3419        self.refresh();
3420        view
3421    }
3422
3423    /// Returns the root entity of the window, if it has one.
3424    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
3425    where
3426        E: 'static + Render,
3427    {
3428        self.root
3429            .as_ref()
3430            .map(|view| view.clone().downcast::<E>().ok())
3431    }
3432
3433    /// Obtain a handle to the window that belongs to this context.
3434    pub fn window_handle(&self) -> AnyWindowHandle {
3435        self.handle
3436    }
3437
3438    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
3439    pub fn refresh(&mut self) {
3440        if self.invalidator.not_drawing() {
3441            self.refreshing = true;
3442            self.invalidator.set_dirty(true);
3443        }
3444    }
3445
3446    /// Close this window.
3447    pub fn remove_window(&mut self) {
3448        self.removed = true;
3449    }
3450
3451    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
3452    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
3453        self.focus
3454            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
3455    }
3456
3457    /// While focus-lost listeners are being dispatched, returns the closest ancestor of the
3458    /// previously focused element that can still receive focus, making it a suitable target
3459    /// for focus restoration. Returns `None` at all other times, or when no such ancestor exists.
3460    pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
3461        let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
3462        ancestors.iter().rev().find_map(|id| {
3463            self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
3464            FocusHandle::for_id(*id, &cx.focus_handles)
3465        })
3466    }
3467
3468    /// Move focus to the element associated with the given [`FocusHandle`].
3469    pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
3470        if !self.focus_enabled || self.focus == Some(handle.id) {
3471            return;
3472        }
3473
3474        self.focus = Some(handle.id);
3475        self.focus_generation = self.focus_generation.wrapping_add(1);
3476        self.clear_pending_keystrokes(cx);
3477
3478        self.refresh();
3479    }
3480
3481    /// Remove focus from all elements within this context's window.
3482    pub fn blur(&mut self, cx: &mut App) {
3483        self.clear_pending_keystrokes(cx);
3484
3485        if !self.focus_enabled {
3486            return;
3487        }
3488
3489        if self.focus.is_some() {
3490            self.focus_generation = self.focus_generation.wrapping_add(1);
3491        }
3492        self.focus = None;
3493        self.refresh();
3494    }
3495
3496    /// Blur the window and don't allow anything in it to be focused again.
3497    pub fn disable_focus(&mut self, cx: &mut App) {
3498        self.blur(cx);
3499        self.focus_enabled = false;
3500    }
3501
3502    /// Move focus to next tab stop.
3503    pub fn focus_next(&mut self, cx: &mut App) {
3504        if !self.focus_enabled {
3505            return;
3506        }
3507
3508        if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
3509            self.focus(&handle, cx)
3510        }
3511    }
3512
3513    /// Move focus to previous tab stop.
3514    pub fn focus_prev(&mut self, cx: &mut App) {
3515        if !self.focus_enabled {
3516            return;
3517        }
3518
3519        if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
3520            self.focus(&handle, cx)
3521        }
3522    }
3523
3524    /// Accessor for the text system.
3525    pub fn text_system(&self) -> &Rc<WindowTextSystem> {
3526        &self.text_system
3527    }
3528
3529    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
3530    pub fn text_style(&self) -> TextStyle {
3531        let mut style = TextStyle::default();
3532        for refinement in &self.text_style_stack {
3533            style.refine(refinement);
3534        }
3535        style
3536    }
3537
3538    /// Check if the platform window is maximized.
3539    ///
3540    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
3541    pub fn is_maximized(&self) -> bool {
3542        self.platform_window.is_maximized()
3543    }
3544
3545    /// request a certain window decoration (Wayland)
3546    pub fn request_decorations(&self, decorations: WindowDecorations) {
3547        self.platform_window.request_decorations(decorations);
3548    }
3549
3550    /// Set the exclusive zone for a layer-shell surface: how much screen space it
3551    /// reserves so other surfaces avoid occluding it (e.g. a panel reserving space).
3552    /// Positive values reserve that distance from the anchored edge, 0 lets the
3553    /// surface be moved out of others' exclusive zones, and -1 ignores reserved
3554    /// space and may extend under other surfaces. (Wayland layer-shell windows only)
3555    pub fn set_exclusive_zone(&self, zone: Pixels) {
3556        self.platform_window.set_exclusive_zone(zone);
3557    }
3558
3559    /// Set which anchored edge a layer-shell surface's exclusive zone applies to.
3560    /// This is only needed to disambiguate a corner-anchored surface; otherwise the
3561    /// edge is deduced from the anchor. The edge must be a single edge the surface
3562    /// is anchored to, or it is ignored. (Wayland layer-shell windows only)
3563    #[cfg(all(target_os = "linux", feature = "wayland"))]
3564    pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
3565        self.platform_window.set_exclusive_edge(edge);
3566    }
3567
3568    /// Start an interactive window resize operation if this window is resizable.
3569    pub fn start_window_resize(&self, edge: ResizeEdge) {
3570        if self.is_resizable {
3571            self.platform_window.start_window_resize(edge);
3572        }
3573    }
3574
3575    /// Linux (wayland) only: Set the window's input region, the area that receives pointer
3576    /// and touch input. Events outside it pass through to whatever is below the window.
3577    ///
3578    /// - `Some(rects)` restricts input to the union of `rects`, in window coordinates.
3579    /// - `Some(&[])` is an empty region, so the window receives no pointer or touch input.
3580    /// - `None` resets the region to the default, so the whole window receives input again.
3581    pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
3582        self.platform_window.set_input_region(region);
3583    }
3584
3585    /// Return the `WindowBounds` to indicate that how a window should be opened
3586    /// after it has been closed
3587    pub fn window_bounds(&self) -> WindowBounds {
3588        self.platform_window.window_bounds()
3589    }
3590
3591    pub(crate) fn last_window_bounds(&self) -> WindowBounds {
3592        self.last_window_bounds
3593    }
3594
3595    pub(crate) fn display_id(&self) -> Option<DisplayId> {
3596        self.display_id
3597    }
3598
3599    /// Return the `WindowBounds` excluding insets (Wayland and X11)
3600    pub fn inner_window_bounds(&self) -> WindowBounds {
3601        self.platform_window.inner_window_bounds()
3602    }
3603
3604    /// vue-native: Windows' composition device and the container visual drawn
3605    /// UNDER this window's surface (see `PlatformWindow::vn_composition_underlay`):
3606    /// owned COM pointers, released by the caller.
3607    pub fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
3608        self.platform_window.vn_composition_underlay()
3609    }
3610
3611    /// vue-native: maximizes or leaves the maximized state without toggling.
3612    pub fn vn_set_maximized(&self, maximized: bool) {
3613        self.platform_window.vn_set_maximized(maximized)
3614    }
3615
3616    /// vue-native: the platform's own maximized (zoomed) state.
3617    pub fn vn_is_zoomed(&self) -> bool {
3618        self.platform_window.vn_is_zoomed()
3619    }
3620
3621    /// vue-native: minimized, where the platform reports it.
3622    pub fn vn_is_minimized(&self) -> bool {
3623        self.platform_window.vn_is_minimized()
3624    }
3625
3626    /// vue-native: leaves the minimized state.
3627    pub fn vn_unminimize(&self) {
3628        self.platform_window.vn_unminimize()
3629    }
3630
3631    /// vue-native: hides the window without minimizing it; false where unsupported.
3632    pub fn vn_hide(&self) -> bool {
3633        self.platform_window.vn_hide()
3634    }
3635
3636    /// vue-native: false while hidden by [`Self::vn_hide`] or not yet shown.
3637    pub fn vn_is_shown(&self) -> bool {
3638        self.platform_window.vn_is_shown()
3639    }
3640
3641    /// vue-native: moves and/or resizes the outer frame, in the space of [`Self::bounds`];
3642    /// false when the platform refuses part of it.
3643    pub fn vn_set_frame(&self, origin: Option<Point<Pixels>>, size: Option<Size<Pixels>>) -> bool {
3644        self.platform_window.vn_set_frame(origin, size)
3645    }
3646
3647    /// vue-native: keeps the window above normal windows; false where unsupported.
3648    pub fn vn_set_always_on_top(&self, on: bool) -> bool {
3649        self.platform_window.vn_set_always_on_top(on)
3650    }
3651
3652    /// vue-native: whether the platform's own maximize control is enabled.
3653    pub fn vn_set_maximizable(&self, maximizable: bool) {
3654        self.platform_window.vn_set_maximizable(maximizable)
3655    }
3656
3657    /// vue-native: lets pointer input pass through; false where unsupported.
3658    pub fn vn_set_ignore_mouse(&self, ignore: bool) -> bool {
3659        self.platform_window.vn_set_ignore_mouse(ignore)
3660    }
3661
3662    /// vue-native: keeps the contents out of screen capture; false where unsupported.
3663    pub fn vn_set_content_protection(&self, on: bool) -> bool {
3664        self.platform_window.vn_set_content_protection(on)
3665    }
3666
3667    /// vue-native: closes as the platform's close button would; the should-close callback decides.
3668    pub fn vn_request_close(&self) {
3669        self.platform_window.vn_request_close()
3670    }
3671
3672    /// Encode the window's native restorable state into an opaque blob.
3673    /// Returns `None` on platforms without native state restoration or if encoding fails.
3674    pub fn native_window_state(&self) -> Option<Vec<u8>> {
3675        self.platform_window.native_window_state()
3676    }
3677
3678    /// Restore the window's native state from a blob previously produced
3679    /// by [`Window::native_window_state`]. A no-op on platforms without native state restoration.
3680    pub fn restore_native_window_state(&self, state: &[u8]) {
3681        self.platform_window.restore_native_window_state(state);
3682    }
3683
3684    /// Dispatch the given action on the currently focused element.
3685    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
3686        let focus_id = self.focused(cx).map(|handle| handle.id);
3687
3688        let window = self.handle;
3689        cx.defer(move |cx| {
3690            window
3691                .update(cx, |_, window, cx| {
3692                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
3693                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
3694                })
3695                .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
3696                .log_err();
3697        })
3698    }
3699
3700    pub(crate) fn dispatch_keystroke_observers(
3701        &mut self,
3702        keystroke: &Keystroke,
3703        input_preference: InputPreference,
3704        action: Option<&dyn Action>,
3705        context_stack: Vec<KeyContext>,
3706        cx: &mut App,
3707    ) {
3708        cx.keystroke_observers.clone().retain(move |callback| {
3709            (callback)(
3710                &KeystrokeEvent {
3711                    keystroke: keystroke.clone(),
3712                    input_preference,
3713                    action: action.map(|action| action.boxed_clone()),
3714                    context_stack: context_stack.clone(),
3715                },
3716                self,
3717                cx,
3718            )
3719        });
3720    }
3721
3722    pub(crate) fn dispatch_keystroke_interceptors(
3723        &mut self,
3724        keystroke: &Keystroke,
3725        input_preference: InputPreference,
3726        context_stack: Vec<KeyContext>,
3727        cx: &mut App,
3728    ) {
3729        cx.keystroke_interceptors.clone().retain(move |callback| {
3730            (callback)(
3731                &KeystrokeEvent {
3732                    keystroke: keystroke.clone(),
3733                    input_preference,
3734                    action: None,
3735                    context_stack: context_stack.clone(),
3736                },
3737                self,
3738                cx,
3739            )
3740        });
3741    }
3742
3743    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
3744    /// that are currently on the stack to be returned to the app.
3745    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
3746        let handle = self.handle;
3747        cx.defer(move |cx| {
3748            handle.update(cx, |_, window, cx| f(window, cx)).ok();
3749        });
3750    }
3751
3752    /// Subscribe to events emitted by a entity.
3753    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3754    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
3755    pub fn observe<T: 'static>(
3756        &mut self,
3757        observed: &Entity<T>,
3758        cx: &mut App,
3759        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
3760    ) -> Subscription {
3761        let entity_id = observed.entity_id();
3762        let observed = observed.downgrade();
3763        let window_handle = self.handle;
3764        cx.new_observer(
3765            entity_id,
3766            Box::new(move |cx| {
3767                window_handle
3768                    .update(cx, |_, window, cx| {
3769                        if let Some(handle) = observed.upgrade() {
3770                            on_notify(handle, window, cx);
3771                            true
3772                        } else {
3773                            false
3774                        }
3775                    })
3776                    .unwrap_or(false)
3777            }),
3778        )
3779    }
3780
3781    /// Subscribe to events emitted by a entity.
3782    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3783    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
3784    pub fn subscribe<Emitter, Evt>(
3785        &mut self,
3786        entity: &Entity<Emitter>,
3787        cx: &mut App,
3788        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
3789    ) -> Subscription
3790    where
3791        Emitter: EventEmitter<Evt>,
3792        Evt: 'static,
3793    {
3794        let entity_id = entity.entity_id();
3795        let handle = entity.downgrade();
3796        let window_handle = self.handle;
3797        cx.new_subscription(
3798            entity_id,
3799            (
3800                TypeId::of::<Evt>(),
3801                Box::new(move |event, cx| {
3802                    window_handle
3803                        .update(cx, |_, window, cx| {
3804                            if let Some(entity) = handle.upgrade() {
3805                                let event = event.downcast_ref().expect("invalid event type");
3806                                on_event(entity, event, window, cx);
3807                                true
3808                            } else {
3809                                false
3810                            }
3811                        })
3812                        .unwrap_or(false)
3813                }),
3814            ),
3815        )
3816    }
3817
3818    /// Register a callback to be invoked when the given `Entity` is released.
3819    pub fn observe_release<T>(
3820        &self,
3821        entity: &Entity<T>,
3822        cx: &mut App,
3823        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
3824    ) -> Subscription
3825    where
3826        T: 'static,
3827    {
3828        let entity_id = entity.entity_id();
3829        let window_handle = self.handle;
3830        cx.release_listeners.insert(
3831            entity_id,
3832            Box::new(move |entity, cx| {
3833                let entity = entity.downcast_mut().expect("invalid entity type");
3834                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
3835            }),
3836        )
3837    }
3838
3839    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
3840    /// await points in async code.
3841    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
3842        AsyncWindowContext::new_context(cx.to_async(), self.handle)
3843    }
3844
3845    /// Schedule the given closure to be run directly after the current frame is rendered.
3846    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3847        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3848        self.next_frame_wanted.set(true);
3849        self.platform_window.schedule_frame();
3850        // Next-frame callbacks create frame demand without dirtying the
3851        // window, so the platform's frame source must be woken explicitly.
3852        self.invalidator.wake_platform();
3853    }
3854
3855    /// vue-native fork: like [`Self::on_next_frame`], but rides along with the
3856    /// next frame the platform delivers without asking for one. A frame source
3857    /// that paces idle windows can then let a self-rescheduling pump wait for
3858    /// real demand (input, an invalidation, an `on_next_frame`) or its own
3859    /// deadline; one that delivers every refresh runs it on the next.
3860    pub fn on_next_frame_passive(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3861        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3862    }
3863
3864    /// Schedule a frame to be drawn on the next animation frame.
3865    ///
3866    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
3867    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
3868    ///
3869    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
3870    ///
3871    /// Callers driving purely decorative animations (spinners, pulses, and the
3872    /// like) should prefer [`AnimationExt::with_animation`](crate::AnimationExt::with_animation),
3873    /// which automatically respects [`App::reduce_motion`]. When using this
3874    /// method directly for decorative motion, check [`App::reduce_motion`]
3875    /// and skip the frame request when it is set.
3876    pub fn request_animation_frame(&self) {
3877        let entity = self.current_view();
3878        self.on_next_frame(move |_, cx| cx.notify(entity));
3879    }
3880
3881    pub(crate) fn advance_scene_animations(&mut self, cx: &App) {
3882        let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
3883        self.rendered_frame.scene.advance_animations(elapsed);
3884    }
3885
3886    /// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran.
3887    ///
3888    /// Tests have no platform frame loop, so this simulates the delivery of the
3889    /// next frame.
3890    #[cfg(any(test, feature = "test-support"))]
3891    pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
3892        let callbacks = self.next_frame_callbacks.take();
3893        self.next_frame_wanted.set(false);
3894        let count = callbacks.len();
3895        for callback in callbacks {
3896            callback(self, cx);
3897        }
3898        count
3899    }
3900
3901    /// Spawn the future returned by the given closure on the application thread pool.
3902    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
3903    /// use within your future.
3904    #[track_caller]
3905    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
3906    where
3907        R: 'static,
3908        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3909    {
3910        let handle = self.handle;
3911        cx.spawn(async move |app| {
3912            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3913            f(&mut async_window_cx).await
3914        })
3915    }
3916
3917    /// Spawn the future returned by the given closure on the application thread
3918    /// pool, with the given priority. The closure is provided a handle to the
3919    /// current window and an `AsyncWindowContext` for use within your future.
3920    #[track_caller]
3921    pub fn spawn_with_priority<AsyncFn, R>(
3922        &self,
3923        priority: Priority,
3924        cx: &App,
3925        f: AsyncFn,
3926    ) -> Task<R>
3927    where
3928        R: 'static,
3929        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3930    {
3931        let handle = self.handle;
3932        cx.spawn_with_priority(priority, async move |app| {
3933            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3934            f(&mut async_window_cx).await
3935        })
3936    }
3937
3938    /// Notify the window that its bounds have changed.
3939    ///
3940    /// This updates internal state like `viewport_size` and `scale_factor` from
3941    /// the platform window, then notifies observers. Normally called automatically
3942    /// by the platform's resize callback, but exposed publicly for test infrastructure.
3943    pub fn bounds_changed(&mut self, cx: &mut App) {
3944        self.scale_factor = self.platform_window.scale_factor();
3945        self.viewport_size = self.platform_window.content_size();
3946        self.last_window_bounds = self.platform_window.window_bounds();
3947        cx.sync_window_update_entry(self);
3948        self.mouse_position = self.platform_window.mouse_position();
3949
3950        self.refresh();
3951
3952        self.bounds_observers
3953            .clone()
3954            .retain(|callback| callback(self, cx));
3955    }
3956
3957    fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
3958        let moved_to = handle
3959            .update(cx, |_, window, _| {
3960                let display_id = window.platform_window.display().map(|display| display.id());
3961                let moved = display_id != window.display_id;
3962                window.display_id = display_id;
3963                moved.then_some(display_id)
3964            })
3965            .with_context(|| {
3966                format!(
3967                    "handling display change for window {:?}",
3968                    handle.window_id()
3969                )
3970            })
3971            .log_err()
3972            .flatten();
3973        let Some(display_id) = moved_to else {
3974            return;
3975        };
3976        // The platform's notifications about the window and about displays
3977        // arrive in no guaranteed order, so make sure App knows the display
3978        // before the window's observers read its state.
3979        if let Some(display_id) = display_id
3980            && !cx.knows_display(display_id)
3981        {
3982            cx.displays_changed();
3983        }
3984        handle
3985            .update(cx, |_, window, cx| window.notify_display_observers(cx))
3986            .with_context(|| {
3987                format!(
3988                    "notifying display observers for window {:?}",
3989                    handle.window_id()
3990                )
3991            })
3992            .log_err();
3993    }
3994
3995    pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
3996        self.display_observers
3997            .clone()
3998            .retain(|callback| callback(self, cx));
3999    }
4000
4001    /// The time between refreshes of the display the window is on, as of the
4002    /// platform's last display change notification. Variable refresh rate
4003    /// displays report their maximum rate. Returns `None` when the platform
4004    /// doesn't report it.
4005    pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
4006        cx.display_refresh_interval(self.display_id?)
4007    }
4008
4009    /// Registers a callback invoked when the window moves to another display
4010    /// or its display's properties change, for example its refresh
4011    /// interval. [`Self::refresh_interval`] already returns the new value
4012    /// when the callback runs.
4013    pub fn observe_window_display(
4014        &self,
4015        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
4016    ) -> Subscription {
4017        self.display_observers.insert(Box::new(move |window, cx| {
4018            callback(window, cx);
4019            true
4020        }))
4021    }
4022
4023    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
4024    pub fn bounds(&self) -> Bounds<Pixels> {
4025        self.platform_window.bounds()
4026    }
4027
4028    /// Returns the regions of this window obscured by system UI and the keyboard.
4029    pub fn insets(&self) -> WindowInsets {
4030        self.platform_window.insets()
4031    }
4032
4033    /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
4034    /// This does not present the frame to screen - useful for visual testing where we want
4035    /// to capture what would be rendered without displaying it or requiring the window to be visible.
4036    //
4037    // vue-native: upstream gates this on `test`/`test-support`. Our devtools
4038    // screenshot command is a first-class *product* feature that an agent
4039    // drives against a normal (non-test) build, and a headless readback of the
4040    // render target is strictly better than `PrintWindow` for it — it is the
4041    // client area exactly, needs no invisible-border correction, and does not
4042    // depend on DWM holding a live composition. So the gate is dropped rather
4043    // than widened to another feature flag: a feature would have to be plumbed
4044    // through `gpui`, `gpui_windows`, `gpui_macos` and `gpui_apple`, which is
4045    // four more merge surfaces than deleting four attributes.
4046    pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
4047        self.platform_window
4048            .render_to_image(&self.rendered_frame.scene)
4049    }
4050
4051    /// Borrows the most recently rendered frame's scene, so benchmarks can validate their
4052    /// output and report batch counts without cloning it.
4053    #[cfg(feature = "bench-support")]
4054    pub fn rendered_scene(&self) -> &Scene {
4055        &self.rendered_frame.scene
4056    }
4057
4058    /// Returns the quads in the most recently rendered frame's scene, so tests can assert on
4059    /// painted output without rasterizing the frame. Quad bounds are in scaled pixels and are
4060    /// not clipped; each quad carries the content mask it will be clipped to when drawn. Quads
4061    /// whose bounds don't intersect their content mask are culled at paint time and won't appear.
4062    #[cfg(any(test, feature = "test-support"))]
4063    pub fn painted_quads(&self) -> Vec<Quad> {
4064        self.rendered_frame.scene.quads.clone()
4065    }
4066
4067    /// Returns the underlines in the most recently rendered frame's scene.
4068    #[cfg(any(test, feature = "test-support"))]
4069    pub fn painted_underlines(&self) -> Vec<Underline> {
4070        self.rendered_frame.scene.underlines.clone()
4071    }
4072
4073    /// Set the content size of the window.
4074    pub fn resize(&mut self, size: Size<Pixels>) {
4075        self.platform_window.resize(size);
4076    }
4077
4078    /// Returns whether or not the window is currently fullscreen
4079    pub fn is_fullscreen(&self) -> bool {
4080        self.platform_window.is_fullscreen()
4081    }
4082
4083    /// Returns whether the window is currently in simple (borderless) fullscreen,
4084    /// where it covers the entire screen including the menu bar and notch area.
4085    /// Always `false` on platforms other than macOS.
4086    pub fn is_simple_fullscreen(&self) -> bool {
4087        self.platform_window.is_simple_fullscreen()
4088    }
4089
4090    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
4091        self.appearance = self.platform_window.appearance();
4092
4093        self.appearance_observers
4094            .clone()
4095            .retain(|callback| callback(self, cx));
4096    }
4097
4098    pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
4099        self.button_layout_observers
4100            .clone()
4101            .retain(|callback| callback(self, cx));
4102    }
4103
4104    /// Returns the appearance of the current window.
4105    pub fn appearance(&self) -> WindowAppearance {
4106        self.appearance
4107    }
4108
4109    /// Returns the size of the drawable area within the window.
4110    pub fn viewport_size(&self) -> Size<Pixels> {
4111        self.viewport_size
4112    }
4113
4114    /// Returns the platform's visible viewport in window-local logical pixels.
4115    ///
4116    /// Unlike `viewport_size`, this can shrink or move when the keyboard opens.
4117    /// During drawing this is a consistent frame snapshot. Outside drawing it
4118    /// reflects the latest platform sample, not a synchronous geometry query.
4119    pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
4120        self.platform_window.visual_viewport_bounds()
4121    }
4122
4123    /// Returns a conservative rectangle avoiding platform-known obscured content.
4124    ///
4125    /// Intersects the visual viewport with the full layout area inset by system
4126    /// safe areas and keyboard occlusion. Unknown overlays cannot be excluded.
4127    pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
4128        let insets = self.platform_window.insets().effective();
4129        let viewport = self.viewport_size();
4130        let left = insets.left.max(Pixels::ZERO).min(viewport.width);
4131        let top = insets.top.max(Pixels::ZERO).min(viewport.height);
4132        let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
4133        let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
4134        let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
4135        let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
4136        visible.size.width = visible.size.width.max(Pixels::ZERO);
4137        visible.size.height = visible.size.height.max(Pixels::ZERO);
4138        visible
4139    }
4140
4141    /// Requests the virtual keyboard for the currently focused text input.
4142    ///
4143    /// Call from a user gesture on platforms that require one. The platform may
4144    /// decline the request; this does not change focus or the layout viewport.
4145    pub fn request_virtual_keyboard(&self) {
4146        self.platform_window.show_soft_keyboard();
4147    }
4148
4149    /// Requests dismissal of the virtual keyboard without changing GPUI focus.
4150    pub fn dismiss_virtual_keyboard(&self) {
4151        self.platform_window.hide_soft_keyboard();
4152    }
4153
4154    /// Returns whether this window is focused by the operating system (receiving key events).
4155    pub fn is_window_active(&self) -> bool {
4156        self.active.get()
4157    }
4158
4159    /// vue-native fork: while `on`, gpui treats this window as active whatever
4160    /// the operating system says. That covers [`Window::is_window_active`],
4161    /// the focus paths a frame's focus events carry (with no OS activation
4162    /// they are empty, so `on_focus` never fires), and the inactive-window
4163    /// frame throttle. The platform's activation changes are ignored while it
4164    /// is set.
4165    ///
4166    /// Nothing at the OS level changes: the window is not raised, activated
4167    /// or given keyboard focus. vue-native's test hosts open their windows
4168    /// behind everything and never take the foreground, yet must run focus
4169    /// exactly as a window in front does. Turning it off goes back to what
4170    /// the platform reports.
4171    pub fn set_assume_active(&mut self, on: bool) {
4172        self.assume_active = on;
4173        let active = on || self.platform_window.is_active();
4174        if self.active.replace(active) != active {
4175            self.refresh();
4176        }
4177    }
4178
4179    /// Returns whether this window is considered to be the window
4180    /// that currently owns the mouse cursor.
4181    /// On mac, this is equivalent to `is_window_active`.
4182    pub fn is_window_hovered(&self) -> bool {
4183        if cfg!(any(
4184            target_os = "windows",
4185            target_os = "linux",
4186            target_os = "freebsd"
4187        )) {
4188            self.hovered.get()
4189        } else {
4190            self.is_window_active()
4191        }
4192    }
4193
4194    /// Toggle zoom on the window.
4195    pub fn zoom_window(&self) {
4196        self.platform_window.zoom();
4197    }
4198
4199    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
4200    pub fn show_window_menu(&self, position: Point<Pixels>) {
4201        self.platform_window.show_window_menu(position)
4202    }
4203
4204    /// Handle window movement for Linux and macOS.
4205    /// Tells the compositor to take control of window movement (Wayland and X11)
4206    ///
4207    /// Events may not be received during a move operation.
4208    pub fn start_window_move(&self) {
4209        self.platform_window.start_window_move()
4210    }
4211
4212    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
4213    pub fn set_client_inset(&mut self, inset: Pixels) {
4214        self.client_inset = Some(inset);
4215        self.platform_window.set_client_inset(inset);
4216    }
4217
4218    /// Sets the client-drawn corner radii so platform effects can match the window's shape.
4219    pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
4220        self.platform_window.set_client_corner_radii(radii);
4221    }
4222
4223    /// Returns the client_inset value by [`Self::set_client_inset`].
4224    pub fn client_inset(&self) -> Option<Pixels> {
4225        self.client_inset
4226    }
4227
4228    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
4229    pub fn window_decorations(&self) -> Decorations {
4230        self.platform_window.window_decorations()
4231    }
4232
4233    /// Returns whether this window is resizable.
4234    pub fn is_resizable(&self) -> bool {
4235        self.is_resizable
4236    }
4237
4238    /// Returns whether this window is minimizable.
4239    pub fn is_minimizable(&self) -> bool {
4240        self.is_minimizable
4241    }
4242
4243    /// Returns the controls supported by the platform.
4244    pub fn window_controls(&self) -> WindowControls {
4245        self.platform_window.window_controls()
4246    }
4247
4248    /// Updates the window's title at the platform level.
4249    pub fn set_window_title(&mut self, title: &str) {
4250        self.platform_window.set_title(title);
4251        self.a11y.set_window_title(title.to_string());
4252    }
4253
4254    /// Sets the position of the macOS traffic light buttons.
4255    #[cfg(target_os = "macos")]
4256    pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
4257        self.platform_window.set_traffic_light_position(position);
4258    }
4259
4260    /// Shows or hides the native macOS titlebar, including the traffic light buttons.
4261    #[cfg(target_os = "macos")]
4262    pub fn set_native_titlebar_visibility(&self, visible: bool) {
4263        self.platform_window.set_native_titlebar_visibility(visible);
4264    }
4265
4266    /// Sets the application identifier.
4267    pub fn set_app_id(&mut self, app_id: &str) {
4268        self.platform_window.set_app_id(app_id);
4269    }
4270
4271    /// Sets the window background appearance.
4272    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
4273        self.platform_window
4274            .set_background_appearance(background_appearance);
4275    }
4276
4277    /// Whether the window currently draws the appearance last given to
4278    /// [`Self::set_background_appearance`]. `false` only while the platform
4279    /// stands in for it — a blurred macOS window in native fullscreen whose
4280    /// desktop picture could not be shown behind the blur — so an app can
4281    /// paint a background of its own exactly then.
4282    pub fn is_background_appearance_drawn(&self) -> bool {
4283        self.platform_window.is_background_appearance_drawn()
4284    }
4285
4286    /// Mark the window as dirty at the platform level.
4287    pub fn set_window_edited(&mut self, edited: bool) {
4288        self.platform_window.set_edited(edited);
4289    }
4290
4291    /// Set the path of the file this window represents.
4292    /// On macOS, this sets the window's accessibility document property (AXDocument).
4293    pub fn set_document_path(&self, path: Option<&std::path::Path>) {
4294        self.platform_window.set_document_path(path);
4295    }
4296
4297    /// Determine the display on which the window is visible.
4298    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
4299        cx.platform
4300            .displays()
4301            .into_iter()
4302            .find(|display| Some(display.id()) == self.display_id)
4303    }
4304
4305    /// Show the platform character palette.
4306    pub fn show_character_palette(&self) {
4307        self.platform_window.show_character_palette();
4308    }
4309
4310    /// The scale factor of the display associated with the window. For example, it could
4311    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
4312    /// be rendered as two pixels on screen.
4313    pub fn scale_factor(&self) -> f32 {
4314        self.scale_factor
4315    }
4316
4317    /// Overrides the display scale factor for tests.
4318    #[cfg(any(test, feature = "test-support"))]
4319    pub fn set_scale_factor(&mut self, scale_factor: f32) {
4320        self.scale_factor = scale_factor;
4321        self.refresh();
4322    }
4323
4324    /// The size of an em for the base font of the application. Adjusting this value allows the
4325    /// UI to scale, just like zooming a web page.
4326    pub fn rem_size(&self) -> Pixels {
4327        self.rem_size_override_stack
4328            .last()
4329            .copied()
4330            .unwrap_or(self.rem_size)
4331    }
4332
4333    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
4334    /// UI to scale, just like zooming a web page.
4335    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
4336        self.rem_size = rem_size.into();
4337    }
4338
4339    /// Acquire a globally unique identifier for the given ElementId.
4340    /// Only valid for the duration of the provided closure.
4341    pub fn with_global_id<R>(
4342        &mut self,
4343        element_id: ElementId,
4344        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
4345    ) -> R {
4346        self.with_id(element_id, |this| {
4347            let global_id = this.element_id_stack.global_id();
4348
4349            f(&global_id, this)
4350        })
4351    }
4352
4353    /// Calls the provided closure with the element ID pushed on the stack.
4354    #[inline]
4355    pub fn with_id<R>(
4356        &mut self,
4357        element_id: impl Into<ElementId>,
4358        f: impl FnOnce(&mut Self) -> R,
4359    ) -> R {
4360        self.element_id_stack.push(element_id.into());
4361        let result = f(self);
4362        self.element_id_stack.pop();
4363        result
4364    }
4365
4366    /// Executes the provided function with the specified rem size.
4367    ///
4368    /// This method must only be called as part of element drawing.
4369    // This function is called in a highly recursive manner in editor
4370    // prepainting, make sure its inlined to reduce the stack burden
4371    #[inline]
4372    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
4373    where
4374        F: FnOnce(&mut Self) -> R,
4375    {
4376        self.invalidator.debug_assert_paint_or_prepaint();
4377
4378        if let Some(rem_size) = rem_size {
4379            self.rem_size_override_stack.push(rem_size.into());
4380            let result = f(self);
4381            self.rem_size_override_stack.pop();
4382            result
4383        } else {
4384            f(self)
4385        }
4386    }
4387
4388    /// The line height associated with the current text style.
4389    pub fn line_height(&self) -> Pixels {
4390        self.text_style().line_height_in_pixels(self.rem_size())
4391    }
4392
4393    /// Rounds a logical value to the nearest device pixel.
4394    #[inline]
4395    pub fn pixel_snap(&self, value: Pixels) -> Pixels {
4396        px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
4397    }
4398
4399    /// f64 variant of [`Self::pixel_snap`].
4400    #[inline]
4401    pub fn pixel_snap_f64(&self, value: f64) -> f64 {
4402        let scale_factor = f64::from(self.scale_factor());
4403        round_half_toward_zero_f64(value * scale_factor) / scale_factor
4404    }
4405
4406    /// Snaps a bounds' origin and size to the nearest device pixel.
4407    #[inline]
4408    pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
4409        bounds.map(|c| self.pixel_snap(c))
4410    }
4411
4412    /// Snaps a point's coordinates to the nearest device pixel.
4413    #[inline]
4414    pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
4415        position.map(|c| self.pixel_snap(c))
4416    }
4417
4418    /// Returns the snapped device-space bounds used to paint an underline.
4419    pub fn underline_bounds(
4420        &self,
4421        origin: Point<Pixels>,
4422        width: Pixels,
4423        style: &UnderlineStyle,
4424    ) -> Bounds<ScaledPixels> {
4425        let scale_factor = self.scale_factor();
4426        let thickness = self.snap_stroke(style.thickness);
4427        let height = if style.wavy {
4428            ScaledPixels(thickness.0 * 3.)
4429        } else {
4430            thickness
4431        };
4432        Bounds {
4433            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4434            size: size(self.snap_stroke(width), height),
4435        }
4436    }
4437
4438    /// Paints an underline excluding absolute device-space horizontal spans.
4439    pub fn paint_underline_with_exclusions(
4440        &mut self,
4441        origin: Point<Pixels>,
4442        width: Pixels,
4443        style: &UnderlineStyle,
4444        exclusions: &[Range<ScaledPixels>],
4445    ) {
4446        self.invalidator.debug_assert_paint();
4447        let underline = self.underline(origin, width, style);
4448        if exclusions.is_empty() {
4449            self.next_frame.scene.insert_primitive(underline);
4450            return;
4451        }
4452
4453        let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
4454        if bounds.is_empty() {
4455            return;
4456        }
4457
4458        let mut exclusions = exclusions
4459            .iter()
4460            .filter_map(|span| {
4461                let start = span.start.max(bounds.left());
4462                let end = span.end.min(bounds.right());
4463                (start < end).then_some(start..end)
4464            })
4465            .collect::<SmallVec<[_; 4]>>();
4466        if exclusions.is_empty() {
4467            self.next_frame.scene.insert_primitive(underline);
4468            return;
4469        }
4470        exclusions.sort_unstable_by_key(|span| span.start);
4471
4472        let mut paint_span = |start, end| {
4473            // vue-native fork: through `intersect`, so a span that ends at a
4474            // rounded mask's corner keeps the curve.
4475            let span = ContentMask::rect(Bounds::from_corners(
4476                point(start, bounds.top()),
4477                point(end, bounds.bottom()),
4478            ));
4479            self.next_frame.scene.insert_primitive(Underline {
4480                content_mask: underline.content_mask.intersect(&span),
4481                ..underline
4482            });
4483        };
4484        let mut start = bounds.left();
4485        for exclusion in exclusions {
4486            if start < exclusion.start {
4487                paint_span(start, exclusion.start);
4488            }
4489            start = start.max(exclusion.end);
4490        }
4491        if start < bounds.right() {
4492            paint_span(start, bounds.right());
4493        }
4494    }
4495
4496    fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
4497        Underline {
4498            order: 0,
4499            pad: 0,
4500            bounds: self.underline_bounds(origin, width, style),
4501            content_mask: self.snapped_content_mask(),
4502            color: style
4503                .color
4504                .unwrap_or_default()
4505                .opacity(self.element_opacity()),
4506            thickness: self.snap_stroke(style.thickness),
4507            wavy: style.wavy.into(),
4508            // vue-native fork: an underline inside a transformed box turns
4509            // with it, like every other primitive pushed here.
4510            transformation: self.element_transform,
4511        }
4512    }
4513
4514    #[inline]
4515    fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4516        let scale_factor = self.scale_factor();
4517        let left = round_to_device_pixel(bounds.left().0, scale_factor);
4518        let top = round_to_device_pixel(bounds.top().0, scale_factor);
4519        let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
4520        let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4521        Bounds::from_corners(
4522            point(ScaledPixels(left), ScaledPixels(top)),
4523            point(ScaledPixels(right), ScaledPixels(bottom)),
4524        )
4525    }
4526
4527    /// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear.
4528    #[inline]
4529    fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
4530        ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
4531    }
4532
4533    #[inline]
4534    fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
4535        edges.map(|e| self.snap_stroke(*e))
4536    }
4537
4538    /// Floors the near edge and ceils the far edge, producing a strict superset of the raw region.
4539    #[inline]
4540    fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4541        let scale_factor = self.scale_factor();
4542        let left = floor_to_device_pixel(bounds.left().0, scale_factor);
4543        let top = floor_to_device_pixel(bounds.top().0, scale_factor);
4544        let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
4545        let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4546        Bounds::from_corners(
4547            point(ScaledPixels(left), ScaledPixels(top)),
4548            point(ScaledPixels(right), ScaledPixels(bottom)),
4549        )
4550    }
4551
4552    #[inline]
4553    fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
4554        let mask = self.content_mask();
4555        ContentMask {
4556            bounds: self.cover_bounds(mask.bounds),
4557            // vue-native fork: the radii scale as they are. The curve then
4558            // sits on the covered bounds, which are at most one device pixel
4559            // out from the exact ones, as the straight edges already are.
4560            corner_radii: mask.corner_radii.scale(self.scale_factor()),
4561        }
4562    }
4563
4564    /// Call to prevent the default action of an event. Currently only used to prevent
4565    /// parent elements from becoming focused on mouse down.
4566    pub fn prevent_default(&mut self) {
4567        self.default_prevented = true;
4568    }
4569
4570    /// Obtain whether default has been prevented for the event currently being dispatched.
4571    pub fn default_prevented(&self) -> bool {
4572        self.default_prevented
4573    }
4574
4575    /// Determine whether the given action is available along the dispatch path to the currently focused element.
4576    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
4577        let node_id =
4578            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
4579        self.rendered_frame
4580            .dispatch_tree
4581            .is_action_available(action, node_id)
4582    }
4583
4584    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
4585    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
4586        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
4587        self.rendered_frame
4588            .dispatch_tree
4589            .is_action_available(action, node_id)
4590    }
4591
4592    /// The position of the mouse relative to the window.
4593    pub fn mouse_position(&self) -> Point<Pixels> {
4594        self.mouse_position
4595    }
4596
4597    /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
4598    /// events will be routed to listeners that check this hitbox's `is_hovered` status,
4599    /// regardless of actual hit testing. This enables drag operations that continue
4600    /// even when the pointer moves outside the element's bounds.
4601    ///
4602    /// The capture is automatically released on mouse up.
4603    pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
4604        self.captured_hitbox = Some(hitbox_id);
4605    }
4606
4607    /// Releases any active pointer capture.
4608    pub fn release_pointer(&mut self) {
4609        self.captured_hitbox = None;
4610    }
4611
4612    /// Returns the hitbox that has captured the pointer, if any.
4613    pub fn captured_hitbox(&self) -> Option<HitboxId> {
4614        self.captured_hitbox
4615    }
4616
4617    /// Captures the current long press for the given entity.
4618    ///
4619    /// The capture is released when the gesture ends or is cancelled, or when
4620    /// a replacement touch begins. A listener must also call
4621    /// [`Self::prevent_default`] on the started event to claim the gesture.
4622    pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
4623        self.long_press_capture = Some(entity.entity_id());
4624    }
4625
4626    /// Returns whether the given entity has captured the current long press.
4627    pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
4628        self.long_press_capture == Some(entity.entity_id())
4629    }
4630
4631    /// The current state of the keyboard's modifiers
4632    pub fn modifiers(&self) -> Modifiers {
4633        self.modifiers
4634    }
4635
4636    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
4637    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
4638    pub fn last_input_was_keyboard(&self) -> bool {
4639        self.last_input_modality == InputModality::Keyboard
4640    }
4641
4642    /// Returns whether the last input event came from a touch screen.
4643    pub fn last_input_was_touch(&self) -> bool {
4644        self.last_input_modality == InputModality::Touch
4645    }
4646
4647    /// The current state of the keyboard's capslock
4648    pub fn capslock(&self) -> Capslock {
4649        self.capslock
4650    }
4651
4652    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
4653    /// the contents of the new [`Scene`], use [`Self::present`].
4654    #[profiling::function]
4655    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
4656        let _profile_window = crate::native_profiling::window_scope(self.platform_window.as_ref());
4657        let _profile = crate::native_profiling::current_span("native", "GPUI draw");
4658        // Drain every draw in profiler builds so a previous frame's
4659        // first-invalidation timestamp can't be attributed to this one.
4660        #[cfg(feature = "profiler")]
4661        let frame_dirty = self.invalidator.take_frame_dirty();
4662        #[cfg(feature = "profiler")]
4663        self.window_profiler.begin_draw();
4664
4665        // Set up the per-App arena for element allocation during this draw.
4666        // This ensures that multiple test Apps have isolated arenas.
4667        let arena_scope = ElementArenaScope::enter(&cx.element_arena);
4668
4669        if self.platform_window.prepare_frame() {
4670            self.refresh();
4671        }
4672        self.invalidate_entities();
4673        cx.entities.clear_accessed();
4674        debug_assert!(self.rendered_entity_stack.is_empty());
4675        self.invalidator.set_dirty(false);
4676        self.requested_autoscroll = None;
4677
4678        // Restore the previously-used input handler.
4679        // Place it back into a None slot (left by a previous .take()) so that
4680        // cached paint_range indices in reuse_paint find the handler at the
4681        // expected position.
4682        if let Some(input_handler) = self.platform_window.take_input_handler() {
4683            if let Some(slot) = self
4684                .rendered_frame
4685                .input_handlers
4686                .iter_mut()
4687                .rev()
4688                .find(|h| h.is_none())
4689            {
4690                *slot = Some(input_handler);
4691            } else {
4692                self.rendered_frame.input_handlers.push(Some(input_handler));
4693            }
4694        }
4695        if !cx.mode.skip_drawing() {
4696            self.vn_scopes_painted.clear();
4697            self.draw_roots(cx);
4698            let now = crate::effect_clock_seconds();
4699            self.vn_effect_phases
4700                .retain(|_, phase| now - phase.at < VnEffectPhase::KEEP);
4701            #[cfg(feature = "profiler")]
4702            {
4703                let viewport_size = self.viewport_size;
4704                let scale_factor = self.scale_factor();
4705                self.debug_frame_overlay.paint(
4706                    &mut self.next_frame.scene,
4707                    viewport_size,
4708                    scale_factor,
4709                );
4710            }
4711        }
4712        let _finalize = crate::native_profiling::current_span("native", "GPUI finalize frame");
4713        self.dirty_views.clear();
4714        self.next_frame.window_active = self.active.get();
4715
4716        // Register requested input handler with the platform window.
4717        // Use .take() instead of .pop() to preserve Vec length, so that cached
4718        // paint_range indices remain valid for reuse_paint on the next frame.
4719        // Search backwards to find the last Some entry, since reuse_paint may
4720        // have copied None slots from the previous frame. (Fixes #50456)
4721        let focused_text_input = if let Some(mut input_handler) = self
4722            .next_frame
4723            .input_handlers
4724            .iter_mut()
4725            .rev()
4726            .find_map(|h| h.take())
4727        {
4728            let accepts_text_input = input_handler.accepts_text_input(self, cx);
4729            self.platform_window.set_input_handler(input_handler);
4730            self.focus.filter(|_| accepts_text_input)
4731        } else {
4732            None
4733        };
4734        self.apply_text_input_configuration(cx);
4735        let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
4736        if previous.is_some() != focused_text_input.is_some() {
4737            self.platform_window
4738                .text_input_state_changed(if focused_text_input.is_some() {
4739                    TextInputStateChange::FocusGained
4740                } else {
4741                    TextInputStateChange::FocusLost
4742                });
4743        }
4744
4745        {
4746            let _profile = crate::native_profiling::current_span("native", "GPUI finish layout and text");
4747            self.layout_engine.as_mut().unwrap().clear();
4748            self.text_system().finish_frame();
4749        }
4750        {
4751            let _profile = crate::native_profiling::current_span("native", "GPUI finish scene");
4752            self.next_frame.finish(&mut self.rendered_frame);
4753            self.vn_settle_captures();
4754        }
4755
4756        self.invalidator.set_phase(DrawPhase::Focus);
4757        let previous_focus_path = self.rendered_frame.focus_path();
4758        let previous_window_active = self.rendered_frame.window_active;
4759        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
4760        self.scene_animation_interval
4761            .set(self.rendered_frame.scene.animation_frame_interval());
4762        {
4763            let _profile = crate::native_profiling::current_span("native", "GPUI clear previous frame");
4764            self.next_frame.clear();
4765        }
4766        let current_focus_path = self.rendered_frame.focus_path();
4767        let current_window_active = self.rendered_frame.window_active;
4768        let mut focus_before_listeners = self.focus;
4769
4770        if previous_focus_path != current_focus_path
4771            || previous_window_active != current_window_active
4772        {
4773            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
4774                self.focus_lost_path = previous_focus_path.clone();
4775                self.focus_lost_listeners
4776                    .clone()
4777                    .retain(|listener| listener(self, cx));
4778                self.focus_lost_path = SmallVec::new();
4779                // The focus-lost fallback (e.g. a workspace refocusing itself) may target
4780                // an element that isn't part of the element tree, in which case scheduling
4781                // a redraw below would dispatch focus-lost again, looping forever. Only
4782                // track focus movement caused by the focus listeners.
4783                focus_before_listeners = self.focus;
4784            }
4785
4786            let event = WindowFocusEvent {
4787                previous_focus_path: if previous_window_active {
4788                    previous_focus_path
4789                } else {
4790                    Default::default()
4791                },
4792                current_focus_path: if current_window_active {
4793                    current_focus_path
4794                } else {
4795                    Default::default()
4796                },
4797            };
4798            self.focus_listeners
4799                .clone()
4800                .retain(|listener| listener(&event, self, cx));
4801        }
4802
4803        debug_assert!(self.rendered_entity_stack.is_empty());
4804        self.record_entities_accessed(cx);
4805        self.reset_cursor_style(cx);
4806        self.refreshing = false;
4807        self.invalidator.set_phase(DrawPhase::None);
4808        // Focus listeners may move focus (e.g. a dock forwarding focus to its active
4809        // panel). `Window::focus` suppresses `refresh` while a draw is in progress, so
4810        // schedule another frame here to render the new focus state and dispatch the
4811        // resulting focus events.
4812        if self.focus != focus_before_listeners {
4813            self.refresh();
4814        }
4815        self.needs_present.set(true);
4816
4817        #[cfg(feature = "profiler")]
4818        {
4819            self.window_profiler
4820                .set_refresh_interval(self.refresh_interval(cx));
4821            let draw_duration = self
4822                .window_profiler
4823                .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
4824            self.debug_frame_overlay.record_frame(draw_duration);
4825        }
4826
4827        // Exit the scope to obtain the arena-clear token this draw owes; the
4828        // scope's teardown itself happens in `ElementArenaScope::drop`.
4829        arena_scope.exit(&cx.element_arena)
4830    }
4831
4832    fn record_entities_accessed(&mut self, cx: &mut App) {
4833        let entities = cx.entities.take_accessed();
4834        let handle = self.handle;
4835        cx.record_entities_accessed(
4836            handle,
4837            // Try moving window invalidator into the Window
4838            self.invalidator.clone(),
4839            &entities,
4840        );
4841        cx.entities.restore_accessed(entities);
4842    }
4843
4844    fn invalidate_entities(&mut self) {
4845        let mut views = self.invalidator.take_views();
4846        for entity in views.drain() {
4847            self.mark_view_dirty(entity);
4848        }
4849        self.invalidator.replace_views(views);
4850    }
4851
4852    #[profiling::function]
4853    fn present(&mut self) {
4854        #[cfg(feature = "profiler")]
4855        let _foreground_turn = profiler::journal::foreground_turn();
4856        #[cfg(feature = "profiler")]
4857        let present_start = Instant::now();
4858        self.platform_window.draw(&self.rendered_frame.scene);
4859        #[cfg(feature = "profiler")]
4860        self.window_profiler.record_present(
4861            present_start,
4862            Instant::now(),
4863            self.active.get(),
4864            !self.next_frame_callbacks.borrow().is_empty(),
4865        );
4866        self.needs_present.set(false);
4867        profiling::finish_frame!();
4868    }
4869
4870    /// Presents the most recently drawn frame if it hasn't been presented yet.
4871    #[cfg(all(test, feature = "profiler"))]
4872    pub fn present_if_needed(&mut self) {
4873        if self.needs_present.get() {
4874            self.present();
4875        }
4876    }
4877
4878    /// Returns a snapshot of the current input-latency histograms.
4879    #[cfg(feature = "profiler")]
4880    pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
4881        self.window_profiler.input_latency_snapshot()
4882    }
4883
4884    /// Returns a snapshot of the current frame-duration histograms.
4885    #[cfg(feature = "profiler")]
4886    pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
4887        self.window_profiler.frame_duration_snapshot()
4888    }
4889
4890    /// Returns the current mode of the debug frame overlay.
4891    #[cfg(feature = "profiler")]
4892    pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
4893        self.debug_frame_overlay.mode()
4894    }
4895
4896    /// Sets the mode of the debug frame overlay and schedules a redraw.
4897    #[cfg(feature = "profiler")]
4898    pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
4899        self.debug_frame_overlay.set_mode(mode);
4900        self.refresh();
4901    }
4902
4903    /// Advances the debug frame overlay through its hidden, frame-time-only,
4904    /// and detailed modes.
4905    #[cfg(feature = "profiler")]
4906    pub fn cycle_debug_frame_overlay_mode(&mut self) {
4907        self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
4908    }
4909
4910    /// Clears the debug frame overlay's frame-time statistics, except for the
4911    /// total frame count, and schedules a redraw.
4912    #[cfg(feature = "profiler")]
4913    pub fn reset_debug_frame_overlay_stats(&mut self) {
4914        self.debug_frame_overlay.reset_stats();
4915        self.refresh();
4916    }
4917
4918    fn draw_roots(&mut self, cx: &mut App) {
4919        self.invalidator.set_phase(DrawPhase::Prepaint);
4920        self.tooltip_bounds.take();
4921
4922        self.a11y.sync_active_flag();
4923        if self.a11y.is_active() {
4924            self.a11y.begin_frame();
4925        }
4926
4927        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
4928        let root_size = {
4929            #[cfg(any(feature = "inspector", debug_assertions))]
4930            {
4931                if self.inspector.is_some() {
4932                    let mut size = self.viewport_size;
4933                    size.width = (size.width - _inspector_width).max(px(0.0));
4934                    size
4935                } else {
4936                    self.viewport_size
4937                }
4938            }
4939            #[cfg(not(any(feature = "inspector", debug_assertions)))]
4940            {
4941                self.viewport_size
4942            }
4943        };
4944
4945        // Layout all root elements. Like the root element on the web, which
4946        // stretches to fill the viewport unless explicitly sized, window roots
4947        // fill the window when their size is `auto`.
4948        let scale_factor = self.scale_factor();
4949        #[cfg(feature = "profiler")]
4950        let request_layout_start = Instant::now();
4951        let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
4952        let root_layout_id = root_element.request_layout(self, cx);
4953        #[cfg(feature = "profiler")]
4954        let prepaint_start = Instant::now();
4955        self.layout_engine
4956            .as_mut()
4957            .unwrap()
4958            .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
4959        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
4960
4961        #[cfg(any(feature = "inspector", debug_assertions))]
4962        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
4963
4964        let deferred_hitboxes_start = self.next_frame.hitboxes.len();
4965        let deferred_tagged_start = self.next_frame.vn_tagged_hitboxes.len();
4966        self.prepaint_deferred_draws(cx);
4967        let deferred_hitboxes = deferred_hitboxes_start..self.next_frame.hitboxes.len();
4968        self.next_frame.vn_deferred_tagged =
4969            deferred_tagged_start..self.next_frame.vn_tagged_hitboxes.len();
4970
4971        let mut prompt_element = None;
4972        let mut active_drag_element = None;
4973        let mut tooltip_element = None;
4974        if let Some(prompt) = self.prompt.take() {
4975            let mut element = prompt.view.any_view().into_any_element();
4976            let prompt_layout_id = element.request_layout(self, cx);
4977            self.layout_engine
4978                .as_mut()
4979                .unwrap()
4980                .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
4981            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
4982            prompt_element = Some(element);
4983            self.prompt = Some(prompt);
4984        } else if let Some(active_drag) = cx.active_drag.take() {
4985            let mut element = active_drag.view.clone().into_any_element();
4986            let offset = self.mouse_position() - active_drag.cursor_offset;
4987            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
4988            active_drag_element = Some(element);
4989            cx.active_drag = Some(active_drag);
4990        } else {
4991            tooltip_element = self.prepaint_tooltip(cx);
4992        }
4993
4994        self.compute_hit_order(deferred_hitboxes);
4995        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position, self.scale_factor);
4996
4997        // Now actually paint the elements.
4998        #[cfg(feature = "profiler")]
4999        let paint_start = Instant::now();
5000        self.invalidator.set_phase(DrawPhase::Paint);
5001        root_element.paint(self, cx);
5002
5003        #[cfg(any(feature = "inspector", debug_assertions))]
5004        self.paint_inspector(inspector_element, cx);
5005
5006        self.paint_deferred_draws(cx);
5007
5008        if let Some(mut prompt_element) = prompt_element {
5009            prompt_element.paint(self, cx);
5010        } else if let Some(mut drag_element) = active_drag_element {
5011            drag_element.paint(self, cx);
5012        } else if let Some(mut tooltip_element) = tooltip_element {
5013            tooltip_element.paint(self, cx);
5014        }
5015
5016        #[cfg(any(feature = "inspector", debug_assertions))]
5017        self.paint_inspector_hitbox(cx);
5018
5019        #[cfg(feature = "profiler")]
5020        self.window_profiler
5021            .record_draw_phases(profiler::DrawPhases {
5022                request_layout: prepaint_start.duration_since(request_layout_start),
5023                prepaint: paint_start.duration_since(prepaint_start),
5024                paint: Instant::now().duration_since(paint_start),
5025            });
5026
5027        let _profile = crate::native_profiling::current_span("native", "GPUI postpaint accessibility");
5028        // a11y may have been activated/deactivated halfway through the frame
5029        let a11y_active_start_of_frame = self.a11y.is_active();
5030        self.a11y.sync_active_flag();
5031        let a11y_active_end_of_frame = self.a11y.is_active();
5032
5033        let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
5034
5035        if a11y_active_start_of_frame {
5036            // Harvest frame metadata for the debug dump while the live window
5037            // and frame are still in scope.
5038            let frame_info = crate::window::a11y::debug::FrameDebugInfo {
5039                viewport_size: self.viewport_size,
5040                scale_factor: self.scale_factor,
5041                tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
5042            };
5043            // clear the builder state regardless
5044            let tree_update = self.a11y.end_frame(frame_info);
5045
5046            if should_send_a11y_update {
5047                log::debug!(
5048                    "Sending a11y tree update: {} nodes",
5049                    tree_update.nodes.len()
5050                );
5051                self.platform_window.a11y_tree_update(tree_update);
5052            }
5053        }
5054    }
5055
5056    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
5057        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
5058        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
5059            let Some(Some(tooltip_request)) = self
5060                .next_frame
5061                .tooltip_requests
5062                .get(tooltip_request_index)
5063                .cloned()
5064            else {
5065                log::error!("Unexpectedly absent TooltipRequest");
5066                continue;
5067            };
5068            let mut element = tooltip_request.tooltip.view.clone().into_any_element();
5069            let mouse_position = tooltip_request.tooltip.mouse_position;
5070            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
5071
5072            let mut tooltip_bounds =
5073                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
5074            let window_bounds = Bounds {
5075                origin: Point::default(),
5076                size: self.viewport_size(),
5077            };
5078
5079            if tooltip_bounds.right() > window_bounds.right() {
5080                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
5081                if new_x >= Pixels::ZERO {
5082                    tooltip_bounds.origin.x = new_x;
5083                } else {
5084                    tooltip_bounds.origin.x = cmp::max(
5085                        Pixels::ZERO,
5086                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
5087                    );
5088                }
5089            }
5090
5091            if tooltip_bounds.bottom() > window_bounds.bottom() {
5092                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
5093                if new_y >= Pixels::ZERO {
5094                    tooltip_bounds.origin.y = new_y;
5095                } else {
5096                    tooltip_bounds.origin.y = cmp::max(
5097                        Pixels::ZERO,
5098                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
5099                    );
5100                }
5101            }
5102
5103            // It's possible for an element to have an active tooltip while not being painted (e.g.
5104            // via the `visible_on_hover` method). Since mouse listeners are not active in this
5105            // case, instead update the tooltip's visibility here.
5106            let is_visible =
5107                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
5108            if !is_visible {
5109                continue;
5110            }
5111
5112            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
5113                element.prepaint(window, cx)
5114            });
5115
5116            self.tooltip_bounds = Some(TooltipBounds {
5117                id: tooltip_request.id,
5118                bounds: tooltip_bounds,
5119            });
5120            return Some(element);
5121        }
5122        None
5123    }
5124
5125    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
5126        assert_eq!(self.element_id_stack.len(), 0);
5127
5128        // Process deferred draws in multiple rounds to support nesting.
5129        // Each round processes all current deferred draws, which may push new ones.
5130        //
5131        // The draws are processed in place rather than being moved out of
5132        // `next_frame.deferred_draws`: `prepaint_index` snapshots that vector's
5133        // length, so any prepaint range recorded during a round (view caches,
5134        // nested deferred draws) must index the same vector `reuse_prepaint`
5135        // slices on the next frame. Moving the draws out and re-appending them
5136        // shifts the indices of nested draws, causing reused subtrees to graft
5137        // the wrong deferred draws and panic in the dispatch tree.
5138        let mut round_start = 0;
5139        let mut depth = 0;
5140        loop {
5141            let round_end = self.next_frame.deferred_draws.len();
5142            if round_start == round_end {
5143                break;
5144            }
5145            // Limit maximum nesting depth to prevent infinite loops.
5146            //
5147            // vue-native fork: 64, not 10. An embedder that paints CSS
5148            // stacking contexts defers one level per out-of-flow ancestor, and
5149            // a round costs one pass over the draws it adds; the paint order
5150            // does not depend on rounds (`DeferredDraw::order`).
5151            assert!(depth < 64, "Exceeded maximum (64) deferred depth");
5152            depth += 1;
5153
5154            // Sort this round by priority.
5155            let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
5156            {
5157                let draws = &self.next_frame.deferred_draws;
5158                traversal_order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5159            }
5160
5161            for deferred_draw_ix in traversal_order {
5162                let (
5163                    element,
5164                    parent_node,
5165                    current_view,
5166                    rem_size,
5167                    absolute_offset,
5168                    element_transform,
5169                    element_opacity,
5170                    content_mask,
5171                    vn_clip,
5172                    vn_scope,
5173                    prepaint_range,
5174                ) = {
5175                    let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
5176                    self.element_id_stack
5177                        .clone_from(&deferred_draw.element_id_stack);
5178                    self.text_style_stack
5179                        .clone_from(&deferred_draw.text_style_stack);
5180                    (
5181                        deferred_draw.element.take(),
5182                        deferred_draw.parent_node,
5183                        deferred_draw.current_view,
5184                        deferred_draw.rem_size,
5185                        deferred_draw.absolute_offset,
5186                        deferred_draw.element_transform,
5187                        deferred_draw.element_opacity,
5188                        deferred_draw.content_mask,
5189                        deferred_draw.vn_clip.clone(),
5190                        deferred_draw.vn_scope.clone(),
5191                        deferred_draw.prepaint_range.clone(),
5192                    )
5193                };
5194                self.next_frame.dispatch_tree.set_active_node(parent_node);
5195                // vue-native fork: the element's accessibility nodes go under
5196                // the node it was deferred from, not the window root.
5197                let a11y_parent = self.next_frame.deferred_draws[deferred_draw_ix]
5198                    .a11y_parent
5199                    .filter(|&p| p != a11y::ROOT_NODE_ID && self.a11y.is_active());
5200
5201                let prepaint_start = self.prepaint_index();
5202                if let Some(mut element) = element {
5203                    if let Some(parent) = a11y_parent {
5204                        self.a11y.nodes.begin_adopted(parent);
5205                    }
5206                    let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5207                        self.with_rendered_view(current_view, |window| {
5208                            window.with_rem_size(Some(rem_size), |window| {
5209                                // Masks are captured before transforms, in window space.
5210                                window.with_content_mask(content_mask, |window| {
5211                                    window.vn_with_absolute_clip_stack(vn_clip, |window| {
5212                                        window.with_absolute_element_opacity(element_opacity, |window| {
5213                                            window.with_absolute_element_transform(element_transform, |window| {
5214                                                window.with_absolute_element_offset(absolute_offset, |window| {
5215                                                    let outer = mem::replace(&mut window.vn_defer_scope, vn_scope);
5216                                                    element.prepaint(window, cx);
5217                                                    window.vn_defer_scope = outer;
5218                                                });
5219                                            });
5220                                        });
5221                                    });
5222                                });
5223                            });
5224                        });
5225                    });
5226                    if a11y_parent.is_some() {
5227                        self.a11y.nodes.end_adopted();
5228                    }
5229                    self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities = accessed_entities;
5230                    self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
5231                } else {
5232                    cx.entities.extend_accessed(
5233                        self.next_frame.deferred_draws[deferred_draw_ix]
5234                            .accessed_entities
5235                            .iter()
5236                            .copied(),
5237                    );
5238                    self.reuse_prepaint(prepaint_range);
5239                }
5240                let prepaint_end = self.prepaint_index();
5241                self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
5242                    prepaint_start..prepaint_end;
5243            }
5244
5245            self.element_id_stack.clear();
5246            self.text_style_stack.clear();
5247            round_start = round_end;
5248        }
5249    }
5250
5251    fn paint_deferred_draws(&mut self, cx: &mut App) {
5252        let _profile = crate::native_profiling::current_span("paint", "GPUI paint deferred draws");
5253        assert_eq!(self.element_id_stack.len(), 0);
5254
5255        // Paint all deferred draws in priority order.
5256        // Since prepaint has already processed nested deferreds, we just paint them all.
5257        if self.next_frame.deferred_draws.len() == 0 {
5258            return;
5259        }
5260
5261        // vue-native fork: the draws stay in place, since a `VnDeferScope`
5262        // painting among them looks its own draws up.
5263        let traversal_order = self.deferred_draw_traversal_order();
5264        for deferred_draw_ix in traversal_order {
5265            let draw = &self.next_frame.deferred_draws[deferred_draw_ix];
5266            // A replayed one was painted by its scope's replay.
5267            if let Some(scope) = &draw.vn_scope
5268                && (self.vn_scopes_painted.contains(&scope.id) || draw.element.is_none())
5269            {
5270                continue;
5271            }
5272            self.vn_paint_deferred_draw(deferred_draw_ix, None, cx);
5273        }
5274        self.element_id_stack.clear();
5275        self.text_style_stack.clear();
5276    }
5277
5278    /// Paints the deferred draw `ix`. In a scope, `scope` is the absolute
5279    /// opacity the scope's content group took off, and the clip stack it is
5280    /// inside of.
5281    fn vn_paint_deferred_draw(
5282        &mut self,
5283        ix: usize,
5284        scope: Option<(f32, Option<Arc<crate::VnClipNode>>)>,
5285        cx: &mut App,
5286    ) {
5287        let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5288        self.element_id_stack
5289            .clone_from(&deferred_draw.element_id_stack);
5290        // vue-native fork: the text style too, as the prepaint side does.
5291        // Without it a deferred element that reads `Window::text_style` in
5292        // PAINT read the default, not what its ancestors set: an inline
5293        // `<svg>` tinted by the inherited `color` painted black when it was
5294        // `position: absolute` (m26 client sweep #36).
5295        self.text_style_stack
5296            .clone_from(&deferred_draw.text_style_stack);
5297        self.next_frame
5298            .dispatch_tree
5299            .set_active_node(deferred_draw.parent_node);
5300
5301        let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5302        let content_mask = deferred_draw.content_mask;
5303        let element_transform = deferred_draw.element_transform;
5304        let (element_opacity, base) = match &scope {
5305            Some((opacity, base)) => (
5306                (deferred_draw.element_opacity / opacity).min(1.),
5307                base.as_ref(),
5308            ),
5309            None => (deferred_draw.element_opacity, None),
5310        };
5311        let vn_clip = deferred_draw.vn_clip.clone();
5312        let view = deferred_draw.current_view;
5313        let rem_size = deferred_draw.rem_size;
5314        let paint_range = deferred_draw.paint_range.clone();
5315        let mut element = deferred_draw.element.take();
5316
5317        let paint_start = self.paint_index();
5318        if let Some(element) = element.as_mut() {
5319            let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5320                self.with_rendered_view(view, |window| {
5321                    // Reopen inherited clipping and transforms in their original order.
5322                    window.with_content_mask(content_mask, |window| {
5323                        window.vn_reopen_clip_layers(vn_clip, base, cx, |window, cx| {
5324                            window.with_absolute_element_opacity(element_opacity, |window| {
5325                                window.with_absolute_element_transform(element_transform, |window| {
5326                                    window.with_rem_size(Some(rem_size), |window| {
5327                                        element.paint(window, cx);
5328                                    });
5329                                });
5330                            });
5331                        });
5332                    });
5333                });
5334            });
5335            self.next_frame.deferred_draws[ix]
5336                .accessed_entities
5337                .extend(accessed_entities);
5338        } else {
5339            self.reuse_paint(paint_range);
5340        }
5341        let paint_end = self.paint_index();
5342        let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5343        deferred_draw.element = element;
5344        deferred_draw.paint_range = paint_start..paint_end;
5345    }
5346
5347    /// vue-native fork: paints the draws deferred from inside the content
5348    /// effect of element `id` ([`VnDeferScope`]) in their stacking order,
5349    /// into its content group, whose absolute opacity was `opacity`.
5350    fn vn_paint_scope(&mut self, id: u64, opacity: f32, cx: &mut App) {
5351        if id == 0 || !self.vn_scopes_painted.insert(id) {
5352            return;
5353        }
5354        let mut order: SmallVec<[usize; 8]> = self
5355            .next_frame
5356            .deferred_draws
5357            .iter()
5358            .enumerate()
5359            .filter(|(_, draw)| draw.vn_scope.as_ref().is_some_and(|scope| scope.id == id))
5360            .map(|(ix, _)| ix)
5361            .collect();
5362        if order.is_empty() {
5363            return;
5364        }
5365        let draws = &self.next_frame.deferred_draws;
5366        order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5367        let element_id_stack = self.element_id_stack.clone();
5368        let text_style_stack = self.text_style_stack.clone();
5369        let active_node = self.next_frame.dispatch_tree.active_node_id();
5370        for ix in order {
5371            let base = self.next_frame.deferred_draws[ix]
5372                .vn_scope
5373                .as_ref()
5374                .and_then(|scope| scope.clip.clone());
5375            self.vn_paint_deferred_draw(ix, Some((opacity, base)), cx);
5376        }
5377        self.element_id_stack = element_id_stack;
5378        self.text_style_stack = text_style_stack;
5379        if let Some(node) = active_node {
5380            self.next_frame.dispatch_tree.set_active_node(node);
5381        }
5382    }
5383
5384    /// vue-native fork: draws deferred in `f` belong to the content effect of
5385    /// element `id` (0: none), which paints them ([`VnDeferScope`]).
5386    pub fn vn_with_defer_scope<R>(&mut self, id: u64, f: impl FnOnce(&mut Self) -> R) -> R {
5387        if id == 0 {
5388            return f(self);
5389        }
5390        let scope = VnDeferScope {
5391            id,
5392            clip: self.vn_clip_stack.clone(),
5393        };
5394        let previous = self.vn_defer_scope.replace(scope);
5395        let result = f(self);
5396        self.vn_defer_scope = previous;
5397        result
5398    }
5399
5400    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
5401        let deferred_count = self.next_frame.deferred_draws.len();
5402        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
5403        let draws = &self.next_frame.deferred_draws;
5404        sorted_indices.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5405        sorted_indices
5406    }
5407
5408    /// vue-native fork: fills [`Frame::vn_hit_order`] once prepaint is done.
5409    /// `deferred_hitboxes` is the range of hitbox indices the deferred draws'
5410    /// prepaint inserted. Everything before it (the root tree, the inspector)
5411    /// paints first and everything after it (a prompt, a drag, a tooltip)
5412    /// paints last, as inserted; inside it, each draw's hitboxes go where the
5413    /// draw paints. A draw's range never contains a nested draw's, which
5414    /// prepaints in a later round.
5415    fn compute_hit_order(&mut self, deferred_hitboxes: Range<usize>) {
5416        let frame = &mut self.next_frame;
5417        frame.vn_hit_order.clear();
5418        if deferred_hitboxes.is_empty() {
5419            return;
5420        }
5421        let mut order: Vec<u32> = Vec::with_capacity(frame.hitboxes.len());
5422        order.extend(0..deferred_hitboxes.start as u32);
5423        let mut traversal = (0..frame.deferred_draws.len()).collect::<Vec<_>>();
5424        let draws = &frame.deferred_draws;
5425        traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5426        for ix in traversal {
5427            let range = &draws[ix].prepaint_range;
5428            let (start, end) = (range.start.hitboxes_index, range.end.hitboxes_index);
5429            // Draws replayed from a cached view outside this frame's
5430            // deferred pass hold ranges of the frame they were recorded in.
5431            if start >= deferred_hitboxes.start && end <= deferred_hitboxes.end && start < end {
5432                order.extend(start as u32..end as u32);
5433            }
5434        }
5435        order.extend(deferred_hitboxes.end as u32..frame.hitboxes.len() as u32);
5436        // Anything a draw's range did not account for keeps insertion order
5437        // rather than vanishing from the hit test.
5438        if order.len() != frame.hitboxes.len() {
5439            return;
5440        }
5441        frame.vn_hit_order = order;
5442    }
5443
5444    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
5445        PrepaintStateIndex {
5446            hitboxes_index: self.next_frame.hitboxes.len(),
5447            // vue-native fork.
5448            vn_tagged_hitboxes_index: self.next_frame.vn_tagged_hitboxes.len(),
5449            tooltips_index: self.next_frame.tooltip_requests.len(),
5450            deferred_draws_index: self.next_frame.deferred_draws.len(),
5451            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
5452            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5453            line_layout_index: self.text_system.layout_index(),
5454        }
5455    }
5456
5457    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
5458        self.next_frame.hitboxes.extend(
5459            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
5460                .iter()
5461                .cloned(),
5462        );
5463        // vue-native fork: the tags travel with the hitboxes they name. Without
5464        // this line a cached subtree keeps its hitboxes — so it still hovers and
5465        // still takes clicks — while `Window::tagged_hitbox` answers `None` for
5466        // every node inside it, which is what the embedder's element picker,
5467        // highlight overlay and `:hover` reporting are built on.
5468        self.next_frame.vn_tagged_hitboxes.extend(
5469            self.rendered_frame.vn_tagged_hitboxes
5470                [range.start.vn_tagged_hitboxes_index..range.end.vn_tagged_hitboxes_index]
5471                .iter()
5472                .cloned(),
5473        );
5474        self.next_frame.tooltip_requests.extend(
5475            self.rendered_frame.tooltip_requests
5476                [range.start.tooltips_index..range.end.tooltips_index]
5477                .iter_mut()
5478                .map(|request| request.take()),
5479        );
5480        self.next_frame.accessed_element_states.extend(
5481            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5482                ..range.end.accessed_element_states_index]
5483                .iter()
5484                .map(|(id, type_id)| (id.clone(), *type_id)),
5485        );
5486        self.text_system
5487            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5488
5489        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
5490            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
5491            &mut self.rendered_frame.dispatch_tree,
5492            self.focus,
5493        );
5494
5495        if reused_subtree.contains_focus() {
5496            self.next_frame.focus = self.focus;
5497        }
5498
5499        self.next_frame.deferred_draws.extend(
5500            self.rendered_frame.deferred_draws
5501                [range.start.deferred_draws_index..range.end.deferred_draws_index]
5502                .iter()
5503                .map(|deferred_draw| DeferredDraw {
5504                    current_view: deferred_draw.current_view,
5505                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
5506                    element_id_stack: deferred_draw.element_id_stack.clone(),
5507                    text_style_stack: deferred_draw.text_style_stack.clone(),
5508                    content_mask: deferred_draw.content_mask,
5509                    rem_size: deferred_draw.rem_size,
5510                    priority: deferred_draw.priority,
5511                    element: None,
5512                    absolute_offset: deferred_draw.absolute_offset,
5513                    element_transform: deferred_draw.element_transform,
5514                    a11y_parent: deferred_draw.a11y_parent,
5515                    vn_stack: deferred_draw.vn_stack.clone(),
5516                    element_opacity: deferred_draw.element_opacity,
5517                    vn_clip: deferred_draw.vn_clip.clone(),
5518                    vn_scope: deferred_draw.vn_scope.clone(),
5519                    prepaint_range: deferred_draw.prepaint_range.clone(),
5520                    paint_range: deferred_draw.paint_range.clone(),
5521                    accessed_entities: deferred_draw.accessed_entities.clone(),
5522                }),
5523        );
5524    }
5525
5526    pub(crate) fn paint_index(&self) -> PaintIndex {
5527        PaintIndex {
5528            scene_index: self.next_frame.scene.len(),
5529            #[cfg(any(test, feature = "test-support"))]
5530            debug_bounds_index: self.next_frame.debug_bounds_records.len(),
5531            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
5532            input_handlers_index: self.next_frame.input_handlers.len(),
5533            cursor_styles_index: self.next_frame.cursor_styles.len(),
5534            window_control_hitboxes_index: self.next_frame.window_control_hitboxes.len(),
5535            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5536            tab_handle_index: self.next_frame.tab_stops.paint_index(),
5537            line_layout_index: self.text_system.layout_index(),
5538        }
5539    }
5540
5541    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
5542        // Cached elements still exist in the frame even when their paint methods don't run.
5543        #[cfg(any(test, feature = "test-support"))]
5544        for (selector, bounds) in &self.rendered_frame.debug_bounds_records
5545            [range.start.debug_bounds_index..range.end.debug_bounds_index]
5546        {
5547            self.next_frame
5548                .record_debug_bounds(selector.clone(), *bounds);
5549        }
5550        // Caption areas are paint output just like listeners and cursors.
5551        // Dropping this span makes a retained titlebar stop dragging, and
5552        // loses NoDrag cutouts when only an ancestor repaints.
5553        self.next_frame.window_control_hitboxes.extend(
5554            self.rendered_frame.window_control_hitboxes
5555                [range.start.window_control_hitboxes_index..range.end.window_control_hitboxes_index]
5556                .iter()
5557                .cloned(),
5558        );
5559        self.next_frame.cursor_styles.extend(
5560            self.rendered_frame.cursor_styles
5561                [range.start.cursor_styles_index..range.end.cursor_styles_index]
5562                .iter()
5563                .cloned(),
5564        );
5565        self.next_frame.input_handlers.extend(
5566            self.rendered_frame.input_handlers
5567                [range.start.input_handlers_index..range.end.input_handlers_index]
5568                .iter_mut()
5569                .map(|handler| handler.take()),
5570        );
5571        self.next_frame.mouse_listeners.extend(
5572            self.rendered_frame.mouse_listeners
5573                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
5574                .iter_mut()
5575                .map(|listener| listener.take()),
5576        );
5577        self.next_frame.accessed_element_states.extend(
5578            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5579                ..range.end.accessed_element_states_index]
5580                .iter()
5581                .map(|(id, type_id)| (id.clone(), *type_id)),
5582        );
5583        self.next_frame.tab_stops.replay(
5584            &self.rendered_frame.tab_stops.insertion_history
5585                [range.start.tab_handle_index..range.end.tab_handle_index],
5586        );
5587
5588        self.text_system
5589            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5590        self.next_frame.scene.replay(
5591            range.start.scene_index..range.end.scene_index,
5592            &self.rendered_frame.scene,
5593        );
5594    }
5595
5596    /// Push a text style onto the stack, and call a function with that style active.
5597    /// Use [`Window::text_style`] to get the current, combined text style. This method
5598    /// should only be called as part of element drawing.
5599    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
5600    where
5601        F: FnOnce(&mut Self) -> R,
5602    {
5603        self.invalidator.debug_assert_paint_or_prepaint();
5604        if let Some(style) = style {
5605            self.text_style_stack.push(style);
5606            let result = f(self);
5607            self.text_style_stack.pop();
5608            result
5609        } else {
5610            f(self)
5611        }
5612    }
5613
5614    /// Updates the cursor style at the platform level. This method should only be called
5615    /// during the paint phase of element drawing.
5616    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
5617        self.invalidator.debug_assert_paint();
5618        self.next_frame.cursor_styles.push(CursorStyleRequest {
5619            hitbox_id: Some(hitbox.id),
5620            style,
5621        });
5622    }
5623
5624    /// Updates the cursor style for the entire window at the platform level. A cursor
5625    /// style using this method will have precedence over any cursor style set using
5626    /// `set_cursor_style`. This method should only be called during the paint
5627    /// phase of element drawing.
5628    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
5629        self.invalidator.debug_assert_paint();
5630        self.next_frame.cursor_styles.push(CursorStyleRequest {
5631            hitbox_id: None,
5632            style,
5633        })
5634    }
5635
5636    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
5637    /// during the paint phase of element drawing.
5638    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
5639        self.invalidator.debug_assert_prepaint();
5640        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
5641        self.next_frame
5642            .tooltip_requests
5643            .push(Some(TooltipRequest { id, tooltip }));
5644        id
5645    }
5646
5647    /// Invoke the given function with the given content mask after intersecting it
5648    /// with the current mask. This method should only be called during element drawing.
5649    // This function is called in a highly recursive manner in editor
5650    // prepainting, make sure its inlined to reduce the stack burden
5651    #[inline]
5652    pub fn with_content_mask<R>(
5653        &mut self,
5654        mask: Option<ContentMask<Pixels>>,
5655        f: impl FnOnce(&mut Self) -> R,
5656    ) -> R {
5657        self.invalidator.debug_assert_paint_or_prepaint();
5658        if let Some(mask) = mask {
5659            // A clip rect is expressed in the element's OWN frame, and the
5660            // element may be transformed — so the rect has to be mapped into
5661            // window space before it can be intersected with an ancestor's.
5662            // Without this a `transform: translate(-50%, -50%)` element paints
5663            // its subtree half a box away from the region it clips it to, and
5664            // everything that lands outside the old, unmoved rect disappears.
5665            // (reka's dialog is exactly that shape: `fixed top-1/2 left-1/2
5666            // translate-x-[-50%] translate-y-[-50%]` with a scrolling body
5667            // inside, and it came up as a black slab with one stray line of
5668            // text in the corner where the two rects happened to overlap.)
5669            //
5670            // Exact for a translation; a rotation or scale gives the axis-
5671            // aligned bounding box of the mapped rect, which is a superset — a
5672            // clip that shows a little too much rather than one that hides
5673            // content that should be visible. (vue-native fork: the corner
5674            // radii map along; `transform_mask` says when they survive.)
5675            let mask = transform_mask(self.element_transform, mask, self.scale_factor);
5676            let mask = mask.intersect(&self.content_mask());
5677            self.content_mask_stack.push(mask);
5678            let result = f(self);
5679            self.content_mask_stack.pop();
5680            result
5681        } else {
5682            f(self)
5683        }
5684    }
5685
5686    /// vue-native fork: runs `f` under a `clip-path` that is no rounded
5687    /// rectangle ([`crate::Style::vn_clip_outline`]), laid out in the
5688    /// element's own frame. The outline is flattened through the transform in
5689    /// force into window device pixels and pushed on the clip stack, which
5690    /// every hitbox inserted in `f` takes (prepaint). While painting, `f`'s
5691    /// primitives also go into an isolated layer that the renderer composites
5692    /// through the shape ([`crate::Scene::vn_push_isolation`]). The caller
5693    /// pushes the outline's box as a content mask around this, which culls.
5694    pub fn vn_with_clip_shape<R>(
5695        &mut self,
5696        outline: Option<&crate::VnClipOutline>,
5697        f: impl FnOnce(&mut Self) -> R,
5698    ) -> R {
5699        let Some(outline) = outline else {
5700            return f(self);
5701        };
5702        let geometry = Arc::new(crate::VnClipGeometry::new(
5703            outline,
5704            self.scale_factor,
5705            self.element_transform,
5706        ));
5707        let node = Arc::new(crate::VnClipNode {
5708            geometry,
5709            color_matrix: None,
5710            capture: None,
5711            mask: None,
5712            parent: self.vn_clip_stack.clone(),
5713        });
5714        let previous = self.vn_clip_stack.replace(node.clone());
5715        let result = self.vn_with_clip_layer(&node, f);
5716        self.vn_clip_stack = previous;
5717        result
5718    }
5719
5720    /// Applies an SVG color matrix to the entire painted subtree. The same
5721    /// stack node is retained in prepaint so deferred descendants reopen it.
5722    pub fn vn_with_color_matrix<R>(
5723        &mut self,
5724        matrix: Option<crate::VnColorMatrix>,
5725        f: impl FnOnce(&mut Self) -> R,
5726    ) -> R {
5727        let Some(matrix) = matrix else { return f(self) };
5728        let bounds = self.snapped_content_mask().bounds;
5729        let left = bounds.origin.x.0;
5730        let top = bounds.origin.y.0;
5731        let right = left + bounds.size.width.0;
5732        let bottom = top + bounds.size.height.0;
5733        let geometry = Arc::new(crate::VnClipGeometry {
5734            fill_rule: crate::VnFillRule::NonZero,
5735            segments: vec![
5736                [left, top, right, top], [right, top, right, bottom],
5737                [right, bottom, left, bottom], [left, bottom, left, top],
5738            ],
5739            bounds,
5740        });
5741        let node = Arc::new(crate::VnClipNode {
5742            geometry,
5743            color_matrix: Some(matrix),
5744            capture: None,
5745            mask: None,
5746            parent: self.vn_clip_stack.clone(),
5747        });
5748        let previous = self.vn_clip_stack.replace(node.clone());
5749        let result = self.vn_with_clip_layer(&node, f);
5750        self.vn_clip_stack = previous;
5751        result
5752    }
5753
5754    /// Resolve a text brush once at its owner, before descendant overflow masks.
5755    pub fn vn_text_paint(&self, fill: crate::VnTextFill, bounds: Bounds<Pixels>) -> Arc<crate::VnTextPaint> {
5756        let x = bounds.origin.x.0; let y = bounds.origin.y.0;
5757        let right = x + bounds.size.width.0; let bottom = y + bounds.size.height.0;
5758        let outline = crate::VnClipOutline {
5759            fill_rule: crate::VnFillRule::NonZero,
5760            verbs: vec![crate::VnPathVerb::MoveTo([x,y]), crate::VnPathVerb::LineTo([right,y]),
5761                crate::VnPathVerb::LineTo([right,bottom]), crate::VnPathVerb::LineTo([x,bottom]), crate::VnPathVerb::Close],
5762        };
5763        let m = self.element_transform.inverse().unwrap_or_else(TransformationMatrix::unit);
5764        Arc::new(crate::VnTextPaint {
5765            fill, bounds: [x, y, bounds.size.width.0, bounds.size.height.0],
5766            inverse: [m.rotation_scale[0][0], m.rotation_scale[0][1], m.rotation_scale[1][0], m.rotation_scale[1][1], m.translation[0], m.translation[1]],
5767            scale_factor: self.scale_factor,
5768            geometry: Arc::new(crate::VnClipGeometry::new(&outline, self.scale_factor, self.element_transform)),
5769            content_mask: self.snapped_content_mask(),
5770        })
5771    }
5772
5773    /// Paint only glyph alpha into the owner's shared mask. Child overflow
5774    /// masks still apply to their sprites without clipping later sibling glyphs.
5775    pub fn vn_with_text_mask<R>(&mut self, paint: Arc<crate::VnTextPaint>, f: impl FnOnce(&mut Self) -> R) -> R {
5776        self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5777            geometry: paint.geometry.clone(), color_matrix: None,
5778            content_mask: paint.content_mask, text_paint: Some(paint), capture: None,
5779        });
5780        let result = f(self);
5781        self.next_frame.scene.vn_pop_isolation();
5782        result
5783    }
5784
5785    /// vue-native fork: CSS `mask`. While painting, `f` goes into an isolated
5786    /// layer cut to the border box `bounds`, composited multiplied by the alpha
5787    /// (or luminance) of what the mask paints over `bounds`. The mask is on the
5788    /// clip stack meanwhile, in prepaint too, so a deferred descendant paints
5789    /// through it again ([`Window::vn_reopen_clip_layers`]).
5790    pub fn vn_with_mask<R>(
5791        &mut self,
5792        mask: Option<&crate::VnMask>,
5793        bounds: Bounds<Pixels>,
5794        cx: &mut App,
5795        f: impl FnOnce(&mut Self, &mut App) -> R,
5796    ) -> R {
5797        let Some(mask) = mask.filter(|mask| mask.paint.is_some()) else {
5798            return f(self, cx);
5799        };
5800        let node = Arc::new(crate::VnClipNode {
5801            geometry: self.vn_box_geometry(bounds),
5802            color_matrix: None,
5803            capture: None,
5804            mask: Some(crate::VnClipMask {
5805                mask: mask.clone(),
5806                bounds,
5807                transform: self.element_transform,
5808            }),
5809            parent: self.vn_clip_stack.clone(),
5810        });
5811        let previous = self.vn_clip_stack.replace(node.clone());
5812        let result = if self.invalidator.is_painting() {
5813            let content_mask = self.snapped_content_mask();
5814            self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5815                geometry: node.geometry.clone(),
5816                color_matrix: None,
5817                text_paint: None,
5818                content_mask,
5819                capture: None,
5820            });
5821            let result = f(self, cx);
5822            self.vn_paint_mask(&node, cx);
5823            self.next_frame.scene.vn_pop_isolation();
5824            result
5825        } else {
5826            f(self, cx)
5827        };
5828        self.vn_clip_stack = previous;
5829        result
5830    }
5831
5832    /// Ends the content of `node`'s open layer with its mask, if it has one.
5833    fn vn_paint_mask(&mut self, node: &crate::VnClipNode, cx: &mut App) {
5834        let Some(clip) = &node.mask else { return };
5835        let Some(paint) = clip.mask.paint.clone() else { return };
5836        self.next_frame.scene.vn_begin_mask(clip.mask.luminance);
5837        // The content already carries the element's opacity; the mask must not
5838        // apply it a second time.
5839        let opacity = mem::replace(&mut self.element_opacity, 1.);
5840        let tint = mem::replace(&mut self.element_image_tint, Hsla::transparent_black());
5841        let transform = mem::replace(&mut self.element_transform, clip.transform);
5842        paint(clip.bounds, None, self, cx);
5843        self.element_opacity = opacity;
5844        self.element_image_tint = tint;
5845        self.element_transform = transform;
5846    }
5847
5848    /// The border box `bounds` as a clip shape through the element transform.
5849    fn vn_box_geometry(&self, bounds: Bounds<Pixels>) -> Arc<crate::VnClipGeometry> {
5850        let (x, y) = (bounds.origin.x.0, bounds.origin.y.0);
5851        let (right, bottom) = (x + bounds.size.width.0, y + bounds.size.height.0);
5852        let outline = crate::VnClipOutline {
5853            fill_rule: crate::VnFillRule::NonZero,
5854            verbs: vec![
5855                crate::VnPathVerb::MoveTo([x, y]),
5856                crate::VnPathVerb::LineTo([right, y]),
5857                crate::VnPathVerb::LineTo([right, bottom]),
5858                crate::VnPathVerb::LineTo([x, bottom]),
5859                crate::VnPathVerb::Close,
5860            ],
5861        };
5862        Arc::new(crate::VnClipGeometry::new(
5863            &outline,
5864            self.scale_factor,
5865            self.element_transform,
5866        ))
5867    }
5868
5869    /// vue-native fork: `f` inside an isolated layer for `node`'s shape when
5870    /// painting, and as it is otherwise.
5871    fn vn_with_clip_layer<R>(
5872        &mut self,
5873        node: &Arc<crate::VnClipNode>,
5874        f: impl FnOnce(&mut Self) -> R,
5875    ) -> R {
5876        if !self.invalidator.is_painting() {
5877            return f(self);
5878        }
5879        let content_mask = self.snapped_content_mask();
5880        self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5881            geometry: node.geometry.clone(),
5882            color_matrix: node.color_matrix,
5883            text_paint: None,
5884            content_mask,
5885            capture: node.capture,
5886        });
5887        let result = f(self);
5888        self.next_frame.scene.vn_pop_isolation();
5889        result
5890    }
5891
5892    /// vue-native fork: `f` with the clip stack set to `clip`, as a deferred
5893    /// draw's prepaint re-enters the clips it was deferred from inside.
5894    fn vn_with_absolute_clip_stack<R>(
5895        &mut self,
5896        clip: Option<Arc<crate::VnClipNode>>,
5897        f: impl FnOnce(&mut Self) -> R,
5898    ) -> R {
5899        let previous = mem::replace(&mut self.vn_clip_stack, clip);
5900        let result = f(self);
5901        self.vn_clip_stack = previous;
5902        result
5903    }
5904
5905    /// vue-native fork: a deferred draw's paint, inside an isolated layer for
5906    /// each clip shape it was deferred from inside, the outermost first. It
5907    /// paints after the clipped ancestor closed its own layer, so it is
5908    /// composited through the same shapes on its own. Painted inside a
5909    /// [`VnDeferScope`], it reopens only the shapes inside the scope's `base`.
5910    fn vn_reopen_clip_layers<R>(
5911        &mut self,
5912        clip: Option<Arc<crate::VnClipNode>>,
5913        base: Option<&Arc<crate::VnClipNode>>,
5914        cx: &mut App,
5915        f: impl FnOnce(&mut Self, &mut App) -> R,
5916    ) -> R {
5917        let Some(innermost) = clip.clone() else {
5918            return self.vn_with_absolute_clip_stack(None, |window| f(window, cx));
5919        };
5920        let chain = crate::VnClipNode::inside_of(&innermost, base);
5921        self.vn_with_absolute_clip_stack(clip, |window| {
5922            for node in &chain {
5923                let content_mask = window.snapped_content_mask();
5924                window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5925                    geometry: node.geometry.clone(),
5926                    color_matrix: node.color_matrix,
5927                    text_paint: None,
5928                    content_mask,
5929                    capture: node.capture,
5930                });
5931            }
5932            let result = f(window, cx);
5933            for node in chain.iter().rev() {
5934                window.vn_paint_mask(node, cx);
5935                window.next_frame.scene.vn_pop_isolation();
5936            }
5937            result
5938        })
5939    }
5940
5941    /// vue-native fork: `f` paints into the snapshot `id` rather than the
5942    /// page: untransformed, unclipped by its ancestors and at full opacity,
5943    /// in a group the renderer draws first and keeps
5944    /// ([`crate::Scene::vn_captures`]). `bounds` and `own` (the element's
5945    /// transform) are what the capture reports of the element.
5946    pub fn vn_with_capture<R>(
5947        &mut self,
5948        id: Option<u64>,
5949        bounds: Bounds<Pixels>,
5950        own: TransformationMatrix,
5951        f: impl FnOnce(&mut Self) -> R,
5952    ) -> R {
5953        let Some(id) = id else { return f(self) };
5954        let scale_factor = self.scale_factor();
5955        let viewport = Bounds { origin: Point::default(), size: self.viewport_size };
5956        let device = viewport.scale(scale_factor);
5957        let info = crate::VnCaptureInfo {
5958            id,
5959            border_box: bounds.scale(scale_factor),
5960            transform: self.element_transform.compose(own),
5961        };
5962        let node = Arc::new(crate::VnClipNode {
5963            geometry: Arc::new(crate::VnClipGeometry::rect(device)),
5964            color_matrix: None,
5965            capture: Some(info),
5966            mask: None,
5967            parent: None,
5968        });
5969        let previous_clip = self.vn_clip_stack.replace(node.clone());
5970        self.content_mask_stack.push(ContentMask::rect(viewport));
5971        let result = self.with_absolute_element_transform(TransformationMatrix::unit(), |window| {
5972            window.with_absolute_element_opacity(1., |window| {
5973                if !window.invalidator.is_painting() {
5974                    return f(window);
5975                }
5976                window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5977                    geometry: node.geometry.clone(),
5978                    color_matrix: None,
5979                    text_paint: None,
5980                    content_mask: ContentMask { bounds: device, corner_radii: Default::default() },
5981                    capture: Some(info),
5982                });
5983                let result = f(window);
5984                window.next_frame.scene.vn_pop_isolation();
5985                result
5986            })
5987        });
5988        self.content_mask_stack.pop();
5989        self.vn_clip_stack = previous_clip;
5990        result
5991    }
5992
5993    /// vue-native fork: `f` paints into an isolated group composited
5994    /// source-over, so what blends inside it blends with the group only.
5995    pub fn vn_with_isolation<R>(&mut self, isolate: bool, f: impl FnOnce(&mut Self) -> R) -> R {
5996        if !isolate || !self.invalidator.is_painting() {
5997            return f(self);
5998        }
5999        let device = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6000        let content_mask = self.snapped_content_mask();
6001        self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6002            geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6003            color_matrix: None,
6004            text_paint: None,
6005            content_mask,
6006            capture: None,
6007        });
6008        let result = f(self);
6009        self.next_frame.scene.vn_pop_isolation();
6010        result
6011    }
6012
6013    /// vue-native fork: draws the snapshot `id` so that the border box it
6014    /// captured fills `bounds`, through the transform and opacity in force.
6015    /// Ink outside the border box scales along. Nothing is drawn for a
6016    /// snapshot the renderer does not hold.
6017    pub fn vn_paint_snapshot(&mut self, id: u64, bounds: Bounds<Pixels>, plus_lighter: bool) {
6018        self.invalidator.debug_assert_paint();
6019        let scale_factor = self.scale_factor();
6020        let device = bounds.scale(scale_factor);
6021        if device.size.width.0 <= 0. || device.size.height.0 <= 0. {
6022            return;
6023        }
6024        let Some(inverse) = self.element_transform.inverse() else { return };
6025        let (w, h) = (device.size.width.0, device.size.height.0);
6026        let [[a, b], [c, d]] = inverse.rotation_scale;
6027        let [tx, ty] = inverse.translation;
6028        let (x, y) = (device.origin.x.0, device.origin.y.0);
6029        let to_unit = [a / w, b / w, (tx - x) / w, c / h, d / h, (ty - y) / h];
6030        let covered = crate::scene::transformed_bounds(device, self.element_transform);
6031        let covered = Bounds::from_corners(
6032            point(ScaledPixels(covered.origin.x.0.floor()), ScaledPixels(covered.origin.y.0.floor())),
6033            point(
6034                ScaledPixels((covered.origin.x.0 + covered.size.width.0).ceil()),
6035                ScaledPixels((covered.origin.y.0 + covered.size.height.0).ceil()),
6036            ),
6037        );
6038        let opacity = self.element_opacity;
6039        let content_mask = self.snapped_content_mask();
6040        self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6041            id,
6042            to_unit,
6043            bounds: covered,
6044            content_mask,
6045            opacity,
6046            plus_lighter,
6047            in_place: false,
6048        });
6049    }
6050
6051    /// vue-native fork: draws the snapshot `id` where its element was when
6052    /// captured, through the opacity in force.
6053    pub fn vn_paint_snapshot_in_place(&mut self, id: u64) {
6054        self.invalidator.debug_assert_paint();
6055        let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6056        let opacity = self.element_opacity;
6057        let content_mask = self.snapped_content_mask();
6058        self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6059            id,
6060            to_unit: [0.; 6],
6061            bounds: viewport,
6062            content_mask,
6063            opacity,
6064            plus_lighter: false,
6065            in_place: true,
6066        });
6067    }
6068
6069    /// vue-native fork: what the last drawn frame knows of capture `id`:
6070    /// the element's border box and transform in device pixels.
6071    pub fn vn_capture(&self, id: u64) -> Option<crate::VnCaptureInfo> {
6072        self.vn_capture_records.get(&id).map(|(info, _)| *info)
6073    }
6074
6075    /// vue-native fork: forgets captures; their snapshots stop drawing and
6076    /// the renderer frees them once no frame paints them.
6077    pub fn vn_forget_captures(&mut self, ids: &[u64]) {
6078        for id in ids {
6079            self.vn_capture_records.remove(id);
6080        }
6081    }
6082
6083    /// vue-native fork: whether this window's renderer keeps snapshots
6084    /// ([`Window::vn_with_capture`]).
6085    pub fn vn_supports_snapshots(&self) -> bool {
6086        self.platform_window.vn_supports_snapshots()
6087    }
6088
6089    fn vn_settle_captures(&mut self) {
6090        let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6091        let scene = &mut self.next_frame.scene;
6092        for capture in &mut scene.vn_captures {
6093            capture.ink = capture.ink.intersect(&viewport);
6094            self.vn_capture_records.insert(capture.info.id, (capture.info, capture.ink));
6095        }
6096        let records = &self.vn_capture_records;
6097        scene.vn_resolve_snapshots(|id| records.get(&id).copied());
6098    }
6099
6100    /// Updates the global element offset relative to the current offset. This is used to implement
6101    /// scrolling. This method should only be called during the prepaint phase of element drawing.
6102    pub fn with_element_offset<R>(
6103        &mut self,
6104        offset: Point<Pixels>,
6105        f: impl FnOnce(&mut Self) -> R,
6106    ) -> R {
6107        self.invalidator.debug_assert_prepaint();
6108
6109        if offset.is_zero() {
6110            return f(self);
6111        };
6112
6113        let abs_offset = self.element_offset() + offset;
6114        self.with_absolute_element_offset(abs_offset, f)
6115    }
6116
6117    /// Updates the global element offset based on the given offset. This is used to implement
6118    /// drag handles and other manual painting of elements. This method should only be called during
6119    /// the prepaint phase of element drawing.
6120    pub fn with_absolute_element_offset<R>(
6121        &mut self,
6122        offset: Point<Pixels>,
6123        f: impl FnOnce(&mut Self) -> R,
6124    ) -> R {
6125        self.invalidator.debug_assert_prepaint();
6126        self.element_offset_stack.push(offset);
6127        let result = f(self);
6128        self.element_offset_stack.pop();
6129        result
6130    }
6131
6132    pub(crate) fn with_element_opacity<R>(
6133        &mut self,
6134        opacity: Option<f32>,
6135        f: impl FnOnce(&mut Self) -> R,
6136    ) -> R {
6137        self.invalidator.debug_assert_paint_or_prepaint();
6138
6139        let Some(opacity) = opacity else {
6140            return f(self);
6141        };
6142
6143        let previous_opacity = self.element_opacity;
6144        self.element_opacity = previous_opacity * opacity;
6145        let result = f(self);
6146        self.element_opacity = previous_opacity;
6147        result
6148    }
6149
6150    /// vue-native fork: every image [`Window::paint_image`] paints inside `f`
6151    /// is tinted with `tint`: its pixels take the colour by the colour's alpha,
6152    /// keeping their own alpha. In straight alpha that is
6153    /// `rgb = mix(rgb, tint.rgb, tint.a)`, `a = a`, which is a canvas filling
6154    /// the image with `tint` in `source-atop`. A transparent `tint` (the value
6155    /// outside any scope) leaves an image as it is; an opaque one paints the
6156    /// image's alpha in that colour, a monochrome emoji in `currentColor`.
6157    ///
6158    /// The tile is the same one an untinted paint samples: tinting costs no
6159    /// upload, and two tints of one image share it.
6160    pub fn with_image_tint<R>(&mut self, tint: Hsla, f: impl FnOnce(&mut Self) -> R) -> R {
6161        self.invalidator.debug_assert_paint_or_prepaint();
6162        let previous = std::mem::replace(&mut self.element_image_tint, tint);
6163        let result = f(self);
6164        self.element_image_tint = previous;
6165        result
6166    }
6167
6168    /// Paints everything `f` paints — this element's own quads, shadows, text
6169    /// and its whole subtree — through `transformation`, which is composed on
6170    /// top of whatever an ancestor already pushed.
6171    ///
6172    /// This is CSS `transform`'s propagation rule: a transform applies to the
6173    /// element's rendering and to all of its descendants, and to none of the
6174    /// layout. Nothing here touches taffy, `bounds`, or the content mask; the
6175    /// primitives are still emitted in layout coordinates and carry the matrix
6176    /// for the vertex shader to apply.
6177    ///
6178    /// Hitboxes inserted under it record the same matrix, so hit-testing
6179    /// follows the picture (see [`Frame::hit_test`]).
6180    ///
6181    /// The identity is free — it early-returns without touching the field.
6182    /// Installs `transformation` as THE transform, discarding whatever is on the
6183    /// stack, for the duration of `f`.
6184    ///
6185    /// The deferred-draw replay needs this rather than
6186    /// [`Window::with_element_transform`]: it re-enters a subtree that was
6187    /// prepainted somewhere else in the tree, so the transform it has to restore
6188    /// is absolute, not something to compose onto the current one. Same
6189    /// reasoning as [`Window::with_absolute_element_offset`].
6190    pub fn with_absolute_element_transform<R>(
6191        &mut self,
6192        transformation: TransformationMatrix,
6193        f: impl FnOnce(&mut Self) -> R,
6194    ) -> R {
6195        let previous = mem::replace(&mut self.element_transform, transformation);
6196        let result = f(self);
6197        self.element_transform = previous;
6198        result
6199    }
6200
6201    /// vue-native fork: [`Window::with_absolute_element_transform`] for the
6202    /// opacity a deferred draw captured where it was deferred from.
6203    fn with_absolute_element_opacity<R>(
6204        &mut self,
6205        opacity: f32,
6206        f: impl FnOnce(&mut Self) -> R,
6207    ) -> R {
6208        let previous = mem::replace(&mut self.element_opacity, opacity);
6209        let result = f(self);
6210        self.element_opacity = previous;
6211        result
6212    }
6213
6214    /// vue-native fork: composes `transformation` onto the current element
6215    /// transform (the child's own transform applied first) for the duration of
6216    /// `f`. A unit transform is free.
6217    pub fn with_element_transform<R>(
6218        &mut self,
6219        transformation: TransformationMatrix,
6220        f: impl FnOnce(&mut Self) -> R,
6221    ) -> R {
6222        if transformation.is_unit() {
6223            return f(self);
6224        }
6225        let previous = self.element_transform;
6226        // `compose(other)` applies `other` first: the child's own transform
6227        // runs before the ancestors' — which is what nesting means.
6228        self.element_transform = previous.compose(transformation);
6229        let result = f(self);
6230        self.element_transform = previous;
6231        result
6232    }
6233
6234    /// The current content mask, expressed in the frame the CALLER is drawing in
6235    /// — i.e. mapped BACK through the CSS `transform` in force.
6236    ///
6237    /// Painting code computes a primitive's rectangle in the element's own,
6238    /// untransformed space (the shader is what applies the matrix), while
6239    /// [`Window::content_mask`] is a window-space rect. Anything that decides
6240    /// whether to emit a primitive at all by comparing the two has to bring
6241    /// them into one frame first, and this is the cheap end to move.
6242    ///
6243    /// A singular matrix (`scale(0)`) has no inverse; the element is drawn to
6244    /// nothing, so the mask is empty and everything is culled.
6245    pub fn content_mask_in_element_space(&self) -> ContentMask<Pixels> {
6246        let mask = self.content_mask();
6247        if self.element_transform.is_unit() {
6248            return mask;
6249        }
6250        match self.element_transform.inverse() {
6251            Some(inverse) => transform_mask(inverse, mask, self.scale_factor),
6252            None => ContentMask::rect(Bounds::default()),
6253        }
6254    }
6255
6256    /// The composed transform of the element currently being painted. Identity
6257    /// unless an ancestor pushed one with [`Window::with_element_transform`].
6258    #[inline]
6259    pub fn element_transform(&self) -> TransformationMatrix {
6260        self.element_transform
6261    }
6262
6263    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
6264    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
6265    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
6266    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
6267    /// called during the prepaint phase of element drawing.
6268    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
6269        self.invalidator.debug_assert_prepaint();
6270        let index = self.prepaint_index();
6271        let result = f(self);
6272        if result.is_err() {
6273            self.next_frame.hitboxes.truncate(index.hitboxes_index);
6274            // vue-native fork: the tagged boxes (and picks) of the attempt go
6275            // with its hitboxes, or a retried prepaint records them twice.
6276            self.next_frame
6277                .vn_tagged_hitboxes
6278                .truncate(index.vn_tagged_hitboxes_index);
6279            self.next_frame
6280                .tooltip_requests
6281                .truncate(index.tooltips_index);
6282            self.next_frame
6283                .deferred_draws
6284                .truncate(index.deferred_draws_index);
6285            self.next_frame
6286                .dispatch_tree
6287                .truncate(index.dispatch_tree_index);
6288            self.next_frame
6289                .accessed_element_states
6290                .truncate(index.accessed_element_states_index);
6291            self.text_system.truncate_layouts(index.line_layout_index);
6292        }
6293        result
6294    }
6295
6296    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
6297    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
6298    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
6299    /// that supports this method being called on the elements it contains. This method should only be
6300    /// called during the prepaint phase of element drawing.
6301    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
6302        self.invalidator.debug_assert_prepaint();
6303        self.requested_autoscroll = Some(bounds);
6304    }
6305
6306    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
6307    /// described in [`Self::request_autoscroll`].
6308    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
6309        self.invalidator.debug_assert_prepaint();
6310        self.requested_autoscroll.take()
6311    }
6312
6313    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
6314    /// Your view will be re-drawn once the asset has finished loading.
6315    ///
6316    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
6317    /// time.
6318    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6319        cx.asset_entry::<A>(source).use_by(self.current_view())
6320    }
6321
6322    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
6323    /// Your view will not be re-drawn once the asset has finished loading.
6324    ///
6325    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
6326    /// time.
6327    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6328        cx.fetch_asset::<A>(source)
6329    }
6330    /// Obtain the current element offset. This method should only be called during the
6331    /// prepaint phase of element drawing.
6332    pub fn element_offset(&self) -> Point<Pixels> {
6333        self.invalidator.debug_assert_prepaint();
6334        self.element_offset_stack
6335            .last()
6336            .copied()
6337            .unwrap_or_default()
6338    }
6339
6340    /// Obtain the current element opacity. This method should only be called during the
6341    /// prepaint phase of element drawing.
6342    #[inline]
6343    pub(crate) fn element_opacity(&self) -> f32 {
6344        self.invalidator.debug_assert_paint_or_prepaint();
6345        self.element_opacity
6346    }
6347
6348    /// Obtain the current content mask. This method should only be called during element drawing.
6349    pub fn content_mask(&self) -> ContentMask<Pixels> {
6350        self.invalidator.debug_assert_paint_or_prepaint();
6351        self.content_mask_stack
6352            .last()
6353            .cloned()
6354            .unwrap_or_else(|| {
6355                ContentMask::rect(Bounds {
6356                    origin: Point::default(),
6357                    size: self.viewport_size,
6358                })
6359            })
6360    }
6361
6362    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
6363    /// This can be used within a custom element to distinguish multiple sets of child elements.
6364    pub fn with_element_namespace<R>(
6365        &mut self,
6366        element_id: impl Into<ElementId>,
6367        f: impl FnOnce(&mut Self) -> R,
6368    ) -> R {
6369        self.element_id_stack.push(element_id.into());
6370        let result = f(self);
6371        self.element_id_stack.pop();
6372        result
6373    }
6374
6375    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
6376    pub fn use_keyed_state<S: 'static>(
6377        &mut self,
6378        key: impl Into<ElementId>,
6379        cx: &mut App,
6380        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6381    ) -> Entity<S> {
6382        let current_view = self.current_view();
6383        self.with_global_id(key.into(), |global_id, window| {
6384            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
6385                if let Some(state) = state {
6386                    (state.clone(), state)
6387                } else {
6388                    let new_state = cx.new(|cx| init(window, cx));
6389                    Self::observe_keyed_state(&new_state, current_view, cx);
6390                    (new_state.clone(), new_state)
6391                }
6392            })
6393        })
6394    }
6395
6396    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
6397    ///
6398    /// NOTE: This method uses the location of the caller to generate an ID for this state.
6399    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
6400    ///       you can provide a custom ElementID using the `use_keyed_state` method.
6401    #[track_caller]
6402    pub fn use_state<S: 'static>(
6403        &mut self,
6404        cx: &mut App,
6405        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6406    ) -> Entity<S> {
6407        self.use_keyed_state(
6408            ElementId::CodeLocation(*core::panic::Location::caller()),
6409            cx,
6410            init,
6411        )
6412    }
6413
6414    /// Updates or initializes state for an element with the given id that lives across multiple
6415    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
6416    /// to the given closure. The state returned by the closure will be stored so it can be referenced
6417    /// when drawing the next frame. This method should only be called as part of element drawing.
6418    #[inline(always)]
6419    pub fn with_element_state<S, R>(
6420        &mut self,
6421        global_id: &GlobalElementId,
6422        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
6423    ) -> R
6424    where
6425        S: 'static,
6426    {
6427        self.invalidator.debug_assert_paint_or_prepaint();
6428
6429        let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
6430
6431        if let Some(any) = state {
6432            let ElementStateBox {
6433                inner,
6434                #[cfg(debug_assertions)]
6435                type_name,
6436            } = any;
6437            // Using the extra inner option to avoid needing to reallocate a new box.
6438            let mut state_box = inner
6439                .downcast::<Option<S>>()
6440                .map_err(|_| {
6441                    #[cfg(debug_assertions)]
6442                    {
6443                        anyhow::anyhow!(
6444                            "invalid element state type for id, requested {:?}, actual: {:?}",
6445                            std::any::type_name::<S>(),
6446                            type_name
6447                        )
6448                    }
6449
6450                    #[cfg(not(debug_assertions))]
6451                    {
6452                        anyhow::anyhow!(
6453                            "invalid element state type for id, requested {:?}",
6454                            std::any::type_name::<S>(),
6455                        )
6456                    }
6457                })
6458                .unwrap();
6459
6460            let state = state_box.take().expect(
6461                "reentrant call to with_element_state for the same state type and element id",
6462            );
6463            let (result, state) = f(Some(state), self);
6464            state_box.replace(state);
6465            self.insert_element_state(
6466                key,
6467                ElementStateBox {
6468                    inner: state_box,
6469                    #[cfg(debug_assertions)]
6470                    type_name,
6471                },
6472            );
6473            result
6474        } else {
6475            let (result, state) = f(None, self);
6476            self.insert_element_state(
6477                key,
6478                ElementStateBox {
6479                    inner: Box::new(Some(state)),
6480                    #[cfg(debug_assertions)]
6481                    type_name: std::any::type_name::<S>(),
6482                },
6483            );
6484            result
6485        }
6486    }
6487
6488    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
6489    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
6490    /// when the element is guaranteed to have an id.
6491    ///
6492    /// The first option means 'no ID provided'
6493    /// The second option means 'not yet initialized'
6494    pub fn with_optional_element_state<S, R>(
6495        &mut self,
6496        global_id: Option<&GlobalElementId>,
6497        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
6498    ) -> R
6499    where
6500        S: 'static,
6501    {
6502        self.invalidator.debug_assert_paint_or_prepaint();
6503
6504        if let Some(global_id) = global_id {
6505            self.with_element_state(global_id, |state, cx| {
6506                let (result, state) = f(Some(state), cx);
6507                let state =
6508                    state.expect("you must return some state when you pass some element id");
6509                (result, state)
6510            })
6511        } else {
6512            let (result, state) = f(None, self);
6513            debug_assert!(
6514                state.is_none(),
6515                "you must not return an element state when passing None for the global id"
6516            );
6517            result
6518        }
6519    }
6520
6521    /// Executes the given closure within the context of a tab group.
6522    #[inline]
6523    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
6524        if let Some(index) = index {
6525            self.next_frame.tab_stops.begin_group(index);
6526            let result = f(self);
6527            self.next_frame.tab_stops.end_group();
6528            result
6529        } else {
6530            f(self)
6531        }
6532    }
6533
6534    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
6535    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
6536    /// with higher values being drawn on top.
6537    ///
6538    /// When `content_mask` is provided, the deferred element will be clipped to that region during
6539    /// both prepaint and paint. When `None`, no additional clipping is applied.
6540    ///
6541    /// This method should only be called as part of the prepaint phase of element drawing.
6542    pub fn defer_draw(
6543        &mut self,
6544        element: AnyElement,
6545        absolute_offset: Point<Pixels>,
6546        priority: usize,
6547        content_mask: Option<ContentMask<Pixels>>,
6548    ) {
6549        self.defer_draw_with_stack_key(element, absolute_offset, priority, content_mask, None)
6550    }
6551
6552    /// vue-native fork: [`Window::defer_draw`], sorted among draws of equal
6553    /// `priority` by `stack_key` (see [`crate::Deferred::with_stack_key`]).
6554    pub fn defer_draw_with_stack_key(
6555        &mut self,
6556        element: AnyElement,
6557        absolute_offset: Point<Pixels>,
6558        priority: usize,
6559        content_mask: Option<ContentMask<Pixels>>,
6560        stack_key: Option<Rc<[u128]>>,
6561    ) {
6562        self.invalidator.debug_assert_prepaint();
6563        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
6564        self.next_frame.deferred_draws.push(DeferredDraw {
6565            current_view: self.current_view(),
6566            parent_node,
6567            element_id_stack: self.element_id_stack.clone(),
6568            text_style_stack: self.text_style_stack.clone(),
6569            content_mask,
6570            rem_size: self.rem_size(),
6571            priority,
6572            element: Some(element),
6573            absolute_offset,
6574            element_transform: self.element_transform,
6575            a11y_parent: self
6576                .a11y
6577                .is_active()
6578                .then(|| self.a11y.nodes.current_id()),
6579            vn_stack: stack_key,
6580            element_opacity: self.element_opacity,
6581            vn_clip: if content_mask.is_some() {
6582                self.vn_clip_stack.clone()
6583            } else {
6584                crate::VnClipNode::color_filters(&self.vn_clip_stack)
6585            },
6586            vn_scope: self.vn_defer_scope.clone(),
6587            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
6588            paint_range: PaintIndex::default()..PaintIndex::default(),
6589            accessed_entities: FxHashSet::default(),
6590        });
6591    }
6592
6593    /// Creates a new painting layer. A "layer" is a batch of geometry that are
6594    /// non-overlapping and have the same draw order. This is typically used
6595    /// for performance reasons.
6596    ///
6597    /// Layers painted inside `f` are drawn above this layer, including above
6598    /// what `f` paints after them.
6599    ///
6600    /// This method should only be called as part of the paint phase of element drawing.
6601    pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
6602        self.invalidator.debug_assert_paint();
6603
6604        self.next_frame.scene.push_layer();
6605        let result = f(self);
6606        self.next_frame.scene.pop_layer();
6607        result
6608    }
6609
6610    /// Paint the drop (non-inset) shadows from `shadows` into the scene at the current
6611    /// z-index. Inset shadows are skipped; paint those with [`Self::paint_inset_shadows`]
6612    /// after the element's background so they layer on top of the fill.
6613    ///
6614    /// This method should only be called as part of the paint phase of element drawing.
6615    ///
6616    /// vue-native fork: a drop shadow is drawn outside the element's border box
6617    /// only, as CSS clips an outer `box-shadow` (CSS Backgrounds 3 §7.1). So a
6618    /// translucent background shows what is behind the element, not the
6619    /// shadow; a focus ring (`0 0 0 3px`) on a transparent control is a ring.
6620    pub fn paint_drop_shadows(
6621        &mut self,
6622        bounds: Bounds<Pixels>,
6623        corner_radii: Corners<Pixels>,
6624        shadows: &[BoxShadow],
6625    ) {
6626        self.paint_outer_shadows(bounds, corner_radii, shadows, SHADOW_OUTSIDE_BOX);
6627    }
6628
6629    /// vue-native fork: [`Self::paint_drop_shadows`] without the cut-out: the
6630    /// shadow also fills the area under the border box. For a shadow that
6631    /// stands in for the element's own painting ([`Style::vn_shadow_under_box`]).
6632    pub fn paint_drop_shadows_under_box(
6633        &mut self,
6634        bounds: Bounds<Pixels>,
6635        corner_radii: Corners<Pixels>,
6636        shadows: &[BoxShadow],
6637    ) {
6638        self.paint_outer_shadows(bounds, corner_radii, shadows, SHADOW_UNDER_BOX);
6639    }
6640
6641    fn paint_outer_shadows(
6642        &mut self,
6643        bounds: Bounds<Pixels>,
6644        corner_radii: Corners<Pixels>,
6645        shadows: &[BoxShadow],
6646        kind: u32,
6647    ) {
6648        self.invalidator.debug_assert_paint();
6649
6650        let scale_factor = self.scale_factor();
6651        let content_mask = self.snapped_content_mask();
6652        let opacity = self.element_opacity();
6653        let element_bounds = self.cover_bounds(bounds);
6654        let element_corner_radii = corner_radii.scale(scale_factor);
6655        for shadow in shadows {
6656            if shadow.inset {
6657                continue;
6658            }
6659            let shape_bounds =
6660                self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
6661            if shape_bounds.is_empty() {
6662                continue;
6663            }
6664            let blur_radius = shadow.blur_radius.scale(scale_factor);
6665            let spread = shadow.spread_radius;
6666            let shadow_radius = |r: Pixels| spread_shadow_radius(r, spread);
6667            let shadow_corner_radii = Corners {
6668                top_left: shadow_radius(corner_radii.top_left),
6669                top_right: shadow_radius(corner_radii.top_right),
6670                bottom_right: shadow_radius(corner_radii.bottom_right),
6671                bottom_left: shadow_radius(corner_radii.bottom_left),
6672            };
6673            self.next_frame.scene.insert_primitive(Shadow {
6674                order: 0,
6675                blur_radius,
6676                // Leave room for the tail of the blur.
6677                bounds: shape_bounds.dilate(blur_radius * 3.),
6678                content_mask,
6679                corner_radii: element_corner_radii,
6680                color: shadow.color.opacity(opacity),
6681                shape_bounds,
6682                shape_corner_radii: shadow_corner_radii.scale(scale_factor),
6683                inset: kind,
6684                pad: 0,
6685                transformation: self.element_transform,
6686                element_bounds,
6687            });
6688        }
6689    }
6690
6691    /// Paint the inset shadows from `shadows` into the scene at the current z-index. Should
6692    /// be called after the element's background so the shadow layers on top of the fill.
6693    /// Drop shadows are skipped; paint those with [`Self::paint_drop_shadows`] before the background.
6694    pub fn paint_inset_shadows(
6695        &mut self,
6696        bounds: Bounds<Pixels>,
6697        corner_radii: Corners<Pixels>,
6698        shadows: &[BoxShadow],
6699    ) {
6700        self.invalidator.debug_assert_paint();
6701
6702        let scale_factor = self.scale_factor();
6703        let content_mask = self.snapped_content_mask();
6704        let opacity = self.element_opacity();
6705        let element_bounds = self.cover_bounds(bounds);
6706        let element_corner_radii = corner_radii.scale(scale_factor);
6707        for shadow in shadows {
6708            if !shadow.inset {
6709                continue;
6710            }
6711            let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
6712            // Clamp at zero so a large spread can't produce negative radii, which would
6713            // break the SDF in the shader.
6714            let zero = Pixels::ZERO;
6715            let hole_corner_radii = Corners {
6716                top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
6717                top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
6718                bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
6719                bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
6720            };
6721            self.next_frame.scene.insert_primitive(Shadow {
6722                order: 0,
6723                blur_radius: shadow.blur_radius.scale(scale_factor),
6724                bounds: element_bounds,
6725                content_mask,
6726                corner_radii: element_corner_radii,
6727                color: shadow.color.opacity(opacity),
6728                shape_bounds: self.cover_bounds(hole),
6729                shape_corner_radii: hole_corner_radii.scale(scale_factor),
6730                inset: SHADOW_INSET,
6731                pad: 0,
6732                transformation: self.element_transform,
6733                element_bounds,
6734            });
6735        }
6736    }
6737
6738    fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
6739        let size = quad.bounds.size;
6740        let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
6741        if diagonal == 0. {
6742            return Bounds::default();
6743        }
6744        // The interior's corners sit on the corner arcs. Taking the angle along
6745        // the arc whose tangent is the quad's aspect ratio stays within 1% of
6746        // the largest interior.
6747        let cos = size.height.0 / diagonal;
6748        let sin = size.width.0 / diagonal;
6749
6750        // A corner's inner border edge is a quarter ellipse around the
6751        // corner's center, with the border widths taken off its radius.
6752        let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
6753            point(
6754                width_x.max(radius - (radius - width_x) * cos),
6755                width_y.max(radius - (radius - width_y) * sin),
6756            )
6757        };
6758
6759        let radii = &quad.corner_radii;
6760        let widths = &quad.border_widths;
6761        let top_left = corner_inset(radii.top_left, widths.left, widths.top);
6762        let top_right = corner_inset(radii.top_right, widths.right, widths.top);
6763        let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
6764        let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
6765
6766        let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
6767        Bounds::from_corners(
6768            quad.bounds.origin
6769                + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
6770                + antialias_inset,
6771            quad.bounds.bottom_right()
6772                - point(
6773                    top_right.x.max(bottom_right.x),
6774                    bottom_left.y.max(bottom_right.y),
6775                )
6776                - antialias_inset,
6777        )
6778    }
6779
6780    /// Paint one or more quads into the scene for the next frame at the current stacking context.
6781    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
6782    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
6783    ///
6784    /// This method should only be called as part of the paint phase of element drawing.
6785    ///
6786    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
6787    /// where the circular arcs meet. This will not display well when combined with dashed borders.
6788    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
6789    pub fn paint_quad(&mut self, quad: PaintQuad) {
6790        self.invalidator.debug_assert_paint();
6791
6792        let opacity = self.element_opacity();
6793        let snapped_bounds = self.snap_bounds(quad.bounds);
6794        let snapped_border_widths = self.snap_border_widths(quad.border_widths);
6795        let quad = Quad {
6796            order: 0,
6797            bounds: snapped_bounds,
6798            content_mask: self.snapped_content_mask(),
6799            background: quad.background.opacity(opacity),
6800            border_color: quad.border_color.opacity(opacity),
6801            corner_radii: quad.corner_radii.scale(self.scale_factor()),
6802            border_widths: snapped_border_widths,
6803            border_style: quad.border_style,
6804            transformation: self.element_transform,
6805        };
6806        self.insert_quad(quad);
6807    }
6808
6809    fn insert_quad(&mut self, quad: Quad) {
6810        let has_background = !quad.background.is_transparent();
6811        let has_border =
6812            quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
6813        if !has_background && !has_border {
6814            return;
6815        }
6816
6817        let is_rectangle =
6818            quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
6819        if has_background && is_rectangle {
6820            self.next_frame.scene.insert_primitive(quad);
6821            return;
6822        }
6823
6824        // The strip split below carves the quad into AXIS-ALIGNED pieces and
6825        // clips each with an axis-aligned content mask. Under a rotation those
6826        // masks no longer correspond to the pieces they are clipping, so the
6827        // optimisation is skipped rather than made wrong. (vue-native fork:
6828        // under a rounded content mask too: a strip's mask would cut through
6829        // the curve, and `ContentMask::intersect` squares such a corner.)
6830        if !quad.transformation.is_unit() || quad.content_mask.is_rounded() {
6831            self.next_frame.scene.insert_primitive(quad);
6832            return;
6833        }
6834
6835        let plain_border = quad.corner_radii == Corners::default()
6836            && quad.border_style == BorderStyle::Solid
6837            && (!has_background || quad.border_color.is_opaque());
6838
6839        // Splitting off the interior leaves only the strips around it for the
6840        // border and corner shading.
6841        let outer_bounds = quad.bounds;
6842        let inner_bounds = if plain_border {
6843            quad.bounds.extend(quad.border_widths.map(|width| -*width))
6844        } else {
6845            Self::largest_border_interior(&quad)
6846        };
6847
6848        // A plain border's strips can be plain rectangles of the border color.
6849        // Otherwise, each strip is the whole quad masked to the strip, so the
6850        // border, corners and gradients are still shaded relative to the full quad.
6851        let strip_quad = if plain_border {
6852            Quad {
6853                background: quad.border_color.into(),
6854                border_widths: Edges::default(),
6855                ..quad
6856            }
6857        } else {
6858            quad
6859        };
6860
6861        if inner_bounds.is_empty() {
6862            self.next_frame.scene.insert_primitive(strip_quad);
6863            return;
6864        }
6865
6866        // vue-native fork: a ring background paints nothing inside the border.
6867        if has_background && !quad.background.is_ring() {
6868            self.next_frame.scene.insert_primitive(Quad {
6869                content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&inner_bounds)),
6870                border_widths: Edges::default(),
6871                corner_radii: Corners::default(),
6872                ..quad
6873            });
6874        }
6875
6876        let strips = [
6877            // Top
6878            Bounds::from_corners(
6879                outer_bounds.origin,
6880                point(outer_bounds.right(), inner_bounds.top()),
6881            ),
6882            // Bottom
6883            Bounds::from_corners(
6884                point(outer_bounds.left(), inner_bounds.bottom()),
6885                outer_bounds.bottom_right(),
6886            ),
6887            // Left
6888            Bounds::from_corners(
6889                point(outer_bounds.left(), inner_bounds.top()),
6890                inner_bounds.bottom_left(),
6891            ),
6892            // Right
6893            Bounds::from_corners(
6894                inner_bounds.top_right(),
6895                point(outer_bounds.right(), inner_bounds.bottom()),
6896            ),
6897        ];
6898
6899        for strip in strips {
6900            self.next_frame.scene.insert_primitive(Quad {
6901                content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&strip)),
6902                ..strip_quad
6903            });
6904        }
6905    }
6906
6907    /// Paint a backdrop blur rectangle into the scene at the current z-index.
6908    ///
6909    /// This is the primitive behind CSS `backdrop-filter: blur()`: the pixels
6910    /// already painted behind `bounds` are replaced with a blurred copy of
6911    /// themselves, clipped to the rounded rect described by `corner_radii`.
6912    ///
6913    /// The blur samples the render target as it exists at its paint position,
6914    /// so renderers may need to break the current pass when this primitive is
6915    /// encountered. Prefer one blur rect per glass surface rather than many
6916    /// small ones. Renderers without backdrop blur support ignore this
6917    /// primitive entirely, including its tint.
6918    ///
6919    /// This method should only be called as part of the paint phase of element
6920    /// drawing.
6921    pub fn paint_backdrop_blur_rect(
6922        &mut self,
6923        bounds: Bounds<Pixels>,
6924        corner_radii: Corners<Pixels>,
6925        effect: BackdropBlurEffect,
6926    ) {
6927        self.invalidator.debug_assert_paint();
6928
6929        let opacity = self.element_opacity();
6930        if opacity <= 0. {
6931            return;
6932        }
6933
6934        let scale_factor = self.scale_factor();
6935        let blur_radius = effect.radius.scale(scale_factor);
6936        if blur_radius.0 <= 0. {
6937            let tint = effect.tint.opacity(opacity);
6938            if tint.a > 0. {
6939                self.paint_quad(fill(bounds, tint).corner_radii(corner_radii));
6940            }
6941            return;
6942        }
6943
6944        // vue-native fork: the blur has no `transformation` of its own, so the
6945        // element transform is folded into its rect — without this a popper
6946        // positioned by `transform: translate()` blurred a ghost at its
6947        // untransformed place. Under a rotation there is no rect to fold it
6948        // into, and nothing is drawn rather than the ghost.
6949        let Some((bounds, k)) =
6950            crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
6951        else {
6952            return;
6953        };
6954        self.next_frame.scene.insert_primitive(BackdropBlurRect {
6955            order: 0,
6956            pad: 0,
6957            bounds,
6958            content_mask: self.snapped_content_mask(),
6959            corner_radii: corner_radii.scale(scale_factor * k),
6960            blur_radius,
6961            opacity,
6962            tint: effect.tint,
6963        });
6964    }
6965
6966    /// Paint a custom-shaded rounded rect into the scene at the current
6967    /// z-index — the primitive behind the `--shading` CSS property.
6968    ///
6969    /// `spec.id` selects one of the built-in fragment pipelines and `params`
6970    /// are its positional arguments. Parameters the schema marks as lengths
6971    /// arrive in LOGICAL pixels and are scaled here, exactly like every other
6972    /// length in a primitive.
6973    ///
6974    /// An effect that reads the backdrop ([`EFFECT_FLAG_NEEDS_BACKDROP`])
6975    /// samples the render target as it exists at its paint position, so — like
6976    /// [`Self::paint_backdrop_blur_rect`] — renderers break the current pass
6977    /// when they meet one, and the scene forces everything painted afterwards
6978    /// to draw above it. An effect that does not is an ordinary blended quad
6979    /// and costs nothing extra.
6980    ///
6981    /// Renderers without effect support (or on hardware below D3D feature
6982    /// level 11) ignore this primitive entirely.
6983    ///
6984    /// This method should only be called as part of the paint phase of element
6985    /// drawing.
6986    pub fn paint_effect_quad(
6987        &mut self,
6988        bounds: Bounds<Pixels>,
6989        corner_radii: Corners<Pixels>,
6990        spec: EffectSpec,
6991    ) {
6992        self.vn_paint_effect(bounds, corner_radii, spec, 0);
6993    }
6994
6995    /// vue-native fork: [`Self::paint_effect_quad`] for `element`
6996    /// ([`Self::vn_take_effect_element`]), which keys an `[SkHistory]` state.
6997    pub fn vn_paint_effect(
6998        &mut self,
6999        bounds: Bounds<Pixels>,
7000        corner_radii: Corners<Pixels>,
7001        spec: EffectSpec,
7002        element: u64,
7003    ) {
7004        self.vn_paint_effect_with(bounds, corner_radii, spec, element, None);
7005    }
7006
7007    /// vue-native: [`Self::vn_paint_effect`] with the images `spec` samples,
7008    /// resolved through [`crate::set_effect_texture_resolver`].
7009    pub fn vn_paint_textured_effect(
7010        &mut self,
7011        bounds: Bounds<Pixels>,
7012        corner_radii: Corners<Pixels>,
7013        spec: EffectSpec,
7014        element: u64,
7015        cx: &mut App,
7016    ) {
7017        let textures = crate::resolve_effect_textures(&spec, self, cx);
7018        self.vn_paint_effect_with(bounds, corner_radii, spec, element, textures);
7019    }
7020
7021    fn vn_paint_effect_with(
7022        &mut self,
7023        bounds: Bounds<Pixels>,
7024        corner_radii: Corners<Pixels>,
7025        spec: EffectSpec,
7026        element: u64,
7027        textures: Option<Arc<crate::EffectTextureSet>>,
7028    ) {
7029        self.invalidator.debug_assert_paint();
7030        let opacity = self.element_opacity();
7031        let Some(mut quad) =
7032            self.vn_effect_quad(bounds, corner_radii, spec, element, opacity, textures.as_deref())
7033        else {
7034            return;
7035        };
7036        quad.flags &= !crate::EFFECT_FLAG_NEEDS_CONTENT;
7037        let history = vn_history_key(element, &spec);
7038        if history == 0 {
7039            quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7040            self.next_frame
7041                .scene
7042                .insert_primitive(crate::Primitive::EffectQuad(quad, textures));
7043            return;
7044        }
7045        let content_mask = quad.content_mask;
7046        self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7047            draws: vec![crate::VnEffectDraw {
7048                quad,
7049                history,
7050                textures,
7051            }],
7052            content: false,
7053            content_mask,
7054        });
7055        self.next_frame.scene.vn_pop_isolation();
7056    }
7057
7058    /// vue-native fork: names the element whose style paints next
7059    /// ([`Self::vn_take_effect_element`]).
7060    pub fn vn_set_effect_element(&mut self, id: Option<&GlobalElementId>) {
7061        self.vn_effect_element = vn_element_key(id);
7062    }
7063
7064    /// vue-native fork: the element [`Self::vn_set_effect_element`] named, 0
7065    /// for none; taken, so a child without an identity does not inherit it.
7066    pub fn vn_take_effect_element(&mut self) -> u64 {
7067        mem::take(&mut self.vn_effect_element)
7068    }
7069
7070    /// vue-native fork: paints `f` into an isolated group at full opacity, which
7071    /// the `[SkContent]` effects among `effects` composite in its place; the
7072    /// opacity share none of them takes composites the group as it is.
7073    pub fn vn_with_effect_content<R>(
7074        &mut self,
7075        bounds: Bounds<Pixels>,
7076        corner_radii: Corners<Pixels>,
7077        effects: &[(EffectSpec, f32, Option<Arc<crate::EffectTextureSet>>)],
7078        element: u64,
7079        cx: &mut App,
7080        f: impl FnOnce(&mut Self, &mut App) -> R,
7081    ) -> R {
7082        let opacity = self.element_opacity();
7083        if !self.invalidator.is_painting() || opacity <= 0. {
7084            return f(self, cx);
7085        }
7086        let mut draws = Vec::new();
7087        let mut plain = 1.;
7088        for (spec, weight, textures) in effects {
7089            if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0 || *weight <= 0. {
7090                continue;
7091            }
7092            let Some(mut quad) = self.vn_effect_quad(
7093                bounds,
7094                corner_radii,
7095                *spec,
7096                element,
7097                opacity * weight,
7098                textures.as_deref(),
7099            ) else {
7100                continue;
7101            };
7102            let history = vn_history_key(element, spec);
7103            if history == 0 {
7104                quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7105            }
7106            plain -= weight;
7107            draws.push(crate::VnEffectDraw {
7108                quad,
7109                history,
7110                textures: textures.clone(),
7111            });
7112        }
7113        let content_mask = self.snapped_content_mask();
7114        if plain > 1e-3 {
7115            draws.insert(
7116                0,
7117                crate::VnEffectDraw {
7118                    quad: EffectQuad {
7119                        effect_id: crate::effect_id::CONTENT,
7120                        bounds: content_mask.bounds,
7121                        content_mask,
7122                        opacity: opacity * plain.min(1.),
7123                        scale: self.scale_factor(),
7124                        flags: crate::EFFECT_FLAG_NEEDS_CONTENT,
7125                        ..Default::default()
7126                    },
7127                    history: 0,
7128                    textures: None,
7129                },
7130            );
7131        }
7132        self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7133            draws,
7134            content: true,
7135            content_mask,
7136        });
7137        let outer = mem::replace(&mut self.element_opacity, 1.);
7138        let result = f(self, cx);
7139        self.vn_paint_scope(element, opacity, cx);
7140        self.element_opacity = outer;
7141        self.next_frame.scene.vn_pop_isolation();
7142        result
7143    }
7144
7145    /// The quad `spec` draws over `bounds` at `opacity`, None when it draws
7146    /// nothing; asks for the next frame while it animates.
7147    fn vn_effect_quad(
7148        &mut self,
7149        bounds: Bounds<Pixels>,
7150        corner_radii: Corners<Pixels>,
7151        spec: EffectSpec,
7152        element: u64,
7153        opacity: f32,
7154        textures: Option<&crate::EffectTextureSet>,
7155    ) -> Option<EffectQuad> {
7156        if !spec.is_some() || opacity <= 0. {
7157            return None;
7158        }
7159
7160        let scale_factor = self.scale_factor();
7161        let bleed = px(spec.bleed());
7162        // An outer glow needs somewhere to land, so the drawn quad is the
7163        // border box dilated by `bleed` — with the corner radii dilated to
7164        // match, which keeps the dilated shape a true Minkowski offset and
7165        // therefore keeps the SDF relationship the shader relies on exact.
7166        let draw_bounds = bounds.dilate(bleed);
7167        let draw_radii = Corners {
7168            top_left: corner_radii.top_left + bleed,
7169            top_right: corner_radii.top_right + bleed,
7170            bottom_right: corner_radii.bottom_right + bleed,
7171            bottom_left: corner_radii.bottom_left + bleed,
7172        };
7173
7174        let mut params = spec.params;
7175        for (index, param) in params.iter_mut().enumerate() {
7176            if spec.length_mask & (1 << index) != 0 {
7177                *param *= scale_factor;
7178            }
7179        }
7180        crate::write_effect_texture_sizes(&spec, textures, &mut params);
7181
7182        // vue-native fork: as for the backdrop blur — no `transformation`
7183        // field, so the element transform is folded into the rect, and a
7184        // rotated effect is not drawn rather than drawn unrotated elsewhere.
7185        let Some((draw_bounds, k)) = crate::scene::axis_aligned_through(
7186            self.snap_bounds(draw_bounds),
7187            self.element_transform,
7188        ) else {
7189            return None;
7190        };
7191        let bleed = bleed.scale(scale_factor);
7192        let now = crate::effect_clock_seconds();
7193
7194        if let Some(slot) = spec.pointer_param.map(usize::from)
7195            && slot + 2 <= params.len()
7196        {
7197            // The element box as the shader recovers it from the drawn quad.
7198            let origin = draw_bounds.origin.map(|c| c.0 + bleed.0);
7199            let size = draw_bounds.size.map(|c| (c.0 - 2. * bleed.0).max(1.));
7200            let pointer = self.mouse_position.map(|c| c.0 * scale_factor);
7201            params[slot] = (pointer.x - origin.x) / size.width;
7202            params[slot + 1] = (pointer.y - origin.y) / size.height;
7203        }
7204        if let Some(slot) = spec.pointer_times_param.map(usize::from)
7205            && slot + 3 <= params.len()
7206        {
7207            let times = &self.vn_effect_pointer;
7208            params[slot..slot + 3].copy_from_slice(&[times.moved, times.entered, times.left]);
7209        }
7210        if spec.follows_pointer() {
7211            let view = self.current_view();
7212            self.vn_effect_pointer.views.insert(view);
7213        }
7214        if let Some(slot) = spec.animated_param.map(usize::from)
7215            && slot < params.len()
7216            && element != 0
7217        {
7218            let key = vn_phase_key(element, &spec);
7219            let previous = self.vn_effect_phases.get(&key).copied();
7220            let phase = VnEffectPhase::advance(previous, params[slot], now);
7221            self.vn_effect_phases.insert(key, phase);
7222            if let Some(speed) = phase.speed(now) {
7223                params[slot] = speed;
7224            }
7225        }
7226
7227        let mut clocked = spec;
7228        clocked.params = params;
7229        if spec.animated || clocked.clock_running(now) {
7230            // Nothing else in the frame is going to ask for the next one.
7231            self.request_animation_frame();
7232        }
7233
7234        Some(EffectQuad {
7235            order: 0,
7236            effect_id: spec.id,
7237            bounds: draw_bounds,
7238            content_mask: self.snapped_content_mask(),
7239            corner_radii: draw_radii.scale(scale_factor * k),
7240            params,
7241            opacity,
7242            time: now,
7243            bleed,
7244            backdrop_blur_radius: px(spec.backdrop_blur_radius()).scale(scale_factor),
7245            scale: scale_factor,
7246            flags: spec.flags,
7247        })
7248    }
7249
7250    /// vue-native: makes `bounds` (rounded by `corner_radii`) transparent in
7251    /// this window's surface, erasing what was painted there so far; what is
7252    /// painted after it draws over the hole as usual. The window has to
7253    /// present with alpha for anything to show through (on Windows,
7254    /// DirectComposition: `Window::vn_composition_underlay`).
7255    ///
7256    /// This method should only be called as part of the paint phase of element
7257    /// drawing.
7258    pub fn vn_paint_punch(&mut self, bounds: Bounds<Pixels>, corner_radii: Corners<Pixels>) {
7259        self.invalidator.debug_assert_paint();
7260        let opacity = self.element_opacity();
7261        if opacity <= 0. {
7262            return;
7263        }
7264        let scale_factor = self.scale_factor();
7265        // No `transformation` field, as for the effects: a rotated box is not
7266        // punched rather than punched somewhere else.
7267        let Some((draw_bounds, k)) =
7268            crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7269        else {
7270            return;
7271        };
7272        self.next_frame.scene.insert_primitive(EffectQuad {
7273            order: 0,
7274            effect_id: crate::effect_id::PUNCH,
7275            bounds: draw_bounds,
7276            content_mask: self.snapped_content_mask(),
7277            corner_radii: corner_radii.scale(scale_factor * k),
7278            params: [0.; crate::EFFECT_PARAM_SLOTS],
7279            opacity,
7280            time: 0.,
7281            bleed: ScaledPixels(0.),
7282            backdrop_blur_radius: ScaledPixels(0.),
7283            scale: scale_factor,
7284            flags: 0,
7285        });
7286    }
7287
7288    /// Paint the given `Path` into the scene for the next frame at the current z-index.
7289    ///
7290    /// This method should only be called as part of the paint phase of element drawing.
7291    pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
7292        self.invalidator.debug_assert_paint();
7293
7294        let scale_factor = self.scale_factor();
7295        let content_mask = self.content_mask();
7296        let opacity = self.element_opacity();
7297        let color: Background = color.into();
7298        // vue-native fork: every other primitive carries `element_transform`;
7299        // a path painted under one (a `<select>`'s chevron in a dialog centred
7300        // with `translate(-50%, -50%)`) stayed at its layout position, and was
7301        // culled against a content mask that is already in window space.
7302        let path = if self.element_transform.is_unit() {
7303            path
7304        } else {
7305            path.transformed(self.element_transform, scale_factor)
7306        };
7307        self.next_frame.scene.insert_primitive(PaintedPath::new(
7308            path,
7309            scale_factor,
7310            content_mask,
7311            color.opacity(opacity),
7312        ));
7313    }
7314
7315    /// Paint an underline into the scene for the next frame at the current z-index.
7316    ///
7317    /// This method should only be called as part of the paint phase of element drawing.
7318    pub fn paint_underline(
7319        &mut self,
7320        origin: Point<Pixels>,
7321        width: Pixels,
7322        style: &UnderlineStyle,
7323    ) {
7324        self.invalidator.debug_assert_paint();
7325        // vue-native fork: `Self::underline` carries `element_transform`.
7326        let underline = self.underline(origin, width, style);
7327        self.next_frame.scene.insert_primitive(underline);
7328    }
7329
7330    /// Paint a strikethrough into the scene for the next frame at the current z-index.
7331    ///
7332    /// This method should only be called as part of the paint phase of element drawing.
7333    pub fn paint_strikethrough(
7334        &mut self,
7335        origin: Point<Pixels>,
7336        width: Pixels,
7337        style: &StrikethroughStyle,
7338    ) {
7339        self.invalidator.debug_assert_paint();
7340
7341        let scale_factor = self.scale_factor();
7342        let height = style.thickness;
7343        let bounds = Bounds {
7344            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
7345            size: size(self.snap_stroke(width), self.snap_stroke(height)),
7346        };
7347        let opacity = self.element_opacity();
7348
7349        self.next_frame.scene.insert_primitive(Underline {
7350            order: 0,
7351            pad: 0,
7352            bounds,
7353            content_mask: self.snapped_content_mask(),
7354            thickness: self.snap_stroke(style.thickness),
7355            color: style.color.unwrap_or_default().opacity(opacity),
7356            wavy: false.into(),
7357            transformation: self.element_transform,
7358        });
7359    }
7360
7361    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
7362    ///
7363    /// The y component of the origin is the baseline of the glyph.
7364    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
7365    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
7366    /// This method is only useful if you need to paint a single glyph that has already been shaped.
7367    ///
7368    /// This method should only be called as part of the paint phase of element drawing.
7369    pub fn paint_glyph(
7370        &mut self,
7371        origin: Point<Pixels>,
7372        font_id: FontId,
7373        glyph_id: GlyphId,
7374        font_size: Pixels,
7375        color: Hsla,
7376    ) -> Result<()> {
7377        self.invalidator.debug_assert_paint();
7378
7379        let element_opacity = self.element_opacity();
7380        let scale_factor = self.scale_factor();
7381        let glyph_origin = origin.scale(scale_factor);
7382
7383        let quantized_origin = Point::new(
7384            round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7385                / SUBPIXEL_VARIANTS_X as f32,
7386            round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7387                / SUBPIXEL_VARIANTS_Y as f32,
7388        );
7389        let subpixel_variant = Point::new(
7390            (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7391            (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7392        );
7393        let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
7394        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
7395        let dilation = self.text_system().glyph_dilation_for_color(color);
7396        let params = RenderGlyphParams {
7397            font_id,
7398            glyph_id,
7399            font_size,
7400            subpixel_variant,
7401            scale_factor,
7402            is_emoji: false,
7403            subpixel_rendering,
7404            dilation,
7405        };
7406
7407        let raster_bounds = self.text_system().raster_bounds(&params)?;
7408        if !raster_bounds.is_zero() {
7409            let tile = self
7410                .sprite_atlas
7411                .get_or_insert_with(params.clone().into(), &mut || {
7412                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
7413                    Ok(Some((size, Cow::Owned(bytes))))
7414                })?
7415                .expect("Callback above only errors or returns Some");
7416            let bounds = Bounds {
7417                origin: integer_origin + raster_bounds.origin.map(Into::into),
7418                size: tile.bounds.size.map(Into::into),
7419            };
7420            let content_mask = self.snapped_content_mask();
7421
7422            if subpixel_rendering {
7423                self.next_frame.scene.insert_primitive(SubpixelSprite {
7424                    order: 0,
7425                    pad: 0,
7426                    bounds,
7427                    content_mask,
7428                    color: color.opacity(element_opacity),
7429                    tile,
7430                    transformation: self.element_transform,
7431                });
7432            } else {
7433                self.next_frame.scene.insert_primitive(MonochromeSprite {
7434                    order: 0,
7435                    raw_coverage: false.into(),
7436                    animation: SpriteAnimationId::NONE,
7437                    pad: 0,
7438                    bounds,
7439                    content_mask,
7440                    color: color.opacity(element_opacity),
7441                    tile,
7442                    transformation: self.element_transform,
7443                });
7444            }
7445        }
7446        Ok(())
7447    }
7448
7449    /// vue-native fork: paints a glyph's CSS `text-shadow`, its coverage in `color` blurred by
7450    /// `blur_radius`. `origin` is the shadow's baseline origin, offset included.
7451    pub fn paint_glyph_shadow(
7452        &mut self,
7453        origin: Point<Pixels>,
7454        font_id: FontId,
7455        glyph_id: GlyphId,
7456        font_size: Pixels,
7457        is_emoji: bool,
7458        color: Hsla,
7459        blur_radius: Pixels,
7460    ) -> Result<()> {
7461        self.invalidator.debug_assert_paint();
7462        if blur_radius <= px(0.) && !is_emoji {
7463            return self.paint_glyph(origin, font_id, glyph_id, font_size, color);
7464        }
7465
7466        let scale_factor = self.scale_factor();
7467        let glyph_origin = origin.scale(scale_factor);
7468        let (integer_origin, subpixel_variant) = if is_emoji {
7469            (
7470                glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0))),
7471                Point::default(),
7472            )
7473        } else {
7474            let quantized_origin = Point::new(
7475                round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7476                    / SUBPIXEL_VARIANTS_X as f32,
7477                round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7478                    / SUBPIXEL_VARIANTS_Y as f32,
7479            );
7480            (
7481                quantized_origin.map(|c| ScaledPixels(c.trunc())),
7482                Point::new(
7483                    (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7484                    (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7485                ),
7486            )
7487        };
7488        let glyph = RenderGlyphParams {
7489            font_id,
7490            glyph_id,
7491            font_size,
7492            subpixel_variant,
7493            scale_factor,
7494            is_emoji,
7495            subpixel_rendering: false,
7496            dilation: if is_emoji {
7497                0
7498            } else {
7499                self.text_system().glyph_dilation_for_color(color)
7500            },
7501        };
7502        let raster_bounds = self.text_system().raster_bounds(&glyph)?;
7503        if raster_bounds.is_zero() {
7504            return Ok(());
7505        }
7506        let params = GlyphShadowParams {
7507            sigma_quarters: GlyphShadowParams::quantize_sigma(blur_radius.0 / 2. * scale_factor),
7508            glyph,
7509        };
7510        let padding = params.padding();
7511        let sigma = params.sigma();
7512        let Some(tile) = self.sprite_atlas.get_or_insert_with(
7513            AtlasKey::GlyphShadow(params.clone()),
7514            &mut || {
7515                let (size, coverage) = self.text_system().rasterize_glyph(&params.glyph)?;
7516                let (size, blurred) = blur_glyph_coverage(size, &coverage, sigma);
7517                Ok(Some((size, Cow::Owned(blurred))))
7518            },
7519        )?
7520        else {
7521            return Ok(());
7522        };
7523        let bounds = Bounds {
7524            origin: integer_origin
7525                + raster_bounds.origin.map(Into::into)
7526                - point(ScaledPixels(padding as f32), ScaledPixels(padding as f32)),
7527            size: tile.bounds.size.map(Into::into),
7528        };
7529        let content_mask = self.snapped_content_mask();
7530        self.next_frame.scene.insert_primitive(MonochromeSprite {
7531            order: 0,
7532            raw_coverage: true.into(),
7533            animation: SpriteAnimationId::NONE,
7534            pad: 0,
7535            bounds,
7536            content_mask,
7537            color: color.opacity(self.element_opacity()),
7538            tile,
7539            transformation: self.element_transform,
7540        });
7541        Ok(())
7542    }
7543
7544    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
7545        // Checked first because it's cheap, while some platforms lock the window to read its
7546        // background appearance, and this runs for every glyph.
7547        if !self.platform_window.is_subpixel_rendering_supported() {
7548            return false;
7549        }
7550        // vue-native fork: an isolated layer starts transparent, and
7551        // subpixel text has no alpha of its own to composite it with
7552        // (Chromium too draws grayscale text into a layer that is not opaque).
7553        if self.next_frame.scene.vn_is_isolating() {
7554            return false;
7555        }
7556
7557        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
7558            return false;
7559        }
7560
7561        let mode = match self.text_rendering_mode.get() {
7562            TextRenderingMode::PlatformDefault => self
7563                .text_system()
7564                .recommended_rendering_mode(font_id, font_size),
7565            mode => mode,
7566        };
7567
7568        mode == TextRenderingMode::Subpixel
7569    }
7570
7571    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
7572    ///
7573    /// The y component of the origin is the baseline of the glyph.
7574    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
7575    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
7576    /// This method is only useful if you need to paint a single emoji that has already been shaped.
7577    ///
7578    /// This method should only be called as part of the paint phase of element drawing.
7579    pub fn paint_emoji(
7580        &mut self,
7581        origin: Point<Pixels>,
7582        font_id: FontId,
7583        glyph_id: GlyphId,
7584        font_size: Pixels,
7585    ) -> Result<()> {
7586        self.invalidator.debug_assert_paint();
7587
7588        let scale_factor = self.scale_factor();
7589        let glyph_origin = origin.scale(scale_factor);
7590        let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
7591        let params = RenderGlyphParams {
7592            font_id,
7593            glyph_id,
7594            font_size,
7595            subpixel_variant: Default::default(),
7596            scale_factor,
7597            is_emoji: true,
7598            subpixel_rendering: false,
7599            dilation: 0,
7600        };
7601
7602        let raster_bounds = self.text_system().raster_bounds(&params)?;
7603        if !raster_bounds.is_zero() {
7604            let tile = self
7605                .sprite_atlas
7606                .get_or_insert_with(params.clone().into(), &mut || {
7607                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
7608                    Ok(Some((size, Cow::Owned(bytes))))
7609                })?
7610                .expect("Callback above only errors or returns Some");
7611
7612            let bounds = Bounds {
7613                origin: integer_origin + raster_bounds.origin.map(Into::into),
7614                size: tile.bounds.size.map(Into::into),
7615            };
7616            let content_mask = self.snapped_content_mask();
7617            let opacity = self.element_opacity();
7618
7619            self.next_frame.scene.insert_primitive(PolychromeSprite {
7620                order: 0,
7621                pad: 0,
7622                grayscale: false.into(),
7623                bounds,
7624                corner_radii: Default::default(),
7625                content_mask,
7626                tile,
7627                opacity,
7628                transformation: self.element_transform,
7629                tint: Hsla::transparent_black(),
7630            });
7631        }
7632        Ok(())
7633    }
7634
7635    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
7636    ///
7637    /// This method should only be called as part of the paint phase of element drawing.
7638    pub fn paint_svg(
7639        &mut self,
7640        bounds: Bounds<Pixels>,
7641        path: SharedString,
7642        data: Option<&[u8]>,
7643        transformation: TransformationMatrix,
7644        color: Hsla,
7645        cx: &App,
7646    ) -> Result<()> {
7647        self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
7648    }
7649
7650    /// Like [`Self::paint_svg`], with an `animation` the window applies before every
7651    /// present, so the view isn't re-rendered to advance it.
7652    pub(crate) fn paint_animated_svg(
7653        &mut self,
7654        bounds: Bounds<Pixels>,
7655        path: SharedString,
7656        data: Option<&[u8]>,
7657        transformation: TransformationMatrix,
7658        animation: Option<SpriteAnimation>,
7659        color: Hsla,
7660        cx: &App,
7661    ) -> Result<()> {
7662        self.invalidator.debug_assert_paint();
7663
7664        let element_opacity = self.element_opacity();
7665        let bounds = self.snap_bounds(bounds);
7666
7667        let params = RenderSvgParams {
7668            path,
7669            size: bounds.size.map(|pixels| {
7670                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
7671            }),
7672        };
7673
7674        let Some(tile) =
7675            self.sprite_atlas
7676                .get_or_insert_with(params.clone().into(), &mut || {
7677                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
7678                    else {
7679                        return Ok(None);
7680                    };
7681                    Ok(Some((size, Cow::Owned(bytes))))
7682                })?
7683        else {
7684            return Ok(());
7685        };
7686        let content_mask = self.snapped_content_mask();
7687        let svg_bounds = Bounds {
7688            origin: bounds.center()
7689                - Point::new(
7690                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7691                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7692                ),
7693            size: tile
7694                .bounds
7695                .size
7696                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
7697        };
7698        let final_bounds = svg_bounds
7699            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
7700            .map_size(|size| size.ceil());
7701
7702        let sprite = MonochromeSprite {
7703            order: 0,
7704            raw_coverage: false.into(),
7705            animation: SpriteAnimationId::NONE,
7706            pad: 0,
7707            bounds: final_bounds,
7708            content_mask,
7709            color: color.opacity(element_opacity),
7710            tile,
7711            // The caller's own matrix (gpui's `Svg::with_transformation`)
7712            // composed under whatever CSS `transform` an ancestor pushed.
7713            transformation: self.element_transform.compose(transformation),
7714        };
7715        match animation {
7716            Some(animation) => self.next_frame.scene.insert_animated_sprite(
7717                sprite,
7718                animation.under(self.element_transform),
7719            ),
7720            None => self.next_frame.scene.insert_primitive(sprite),
7721        }
7722
7723        Ok(())
7724    }
7725
7726    /// Paint an image into the scene for the next frame at the current z-index.
7727    /// This method will panic if the frame_index is not valid
7728    ///
7729    /// This method should only be called as part of the paint phase of element drawing.
7730    /// Paint an image into `bounds`, positioning and scaling it according to `image_bounds`.
7731    ///
7732    /// vue-native: with an [`ImageResampler`] installed, an image that is not
7733    /// [`RenderImage::dynamic`] may be drawn from the smaller copy it returns.
7734    ///
7735    /// The visible region rendered is `bounds.intersect(&image_bounds)`, with `corner_radii`
7736    /// applied to `bounds`.
7737    pub fn paint_image(
7738        &mut self,
7739        bounds: Bounds<Pixels>,
7740        image_bounds: Bounds<Pixels>,
7741        corner_radii: Corners<Pixels>,
7742        data: Arc<RenderImage>,
7743        frame_index: usize,
7744        grayscale: bool,
7745    ) -> Result<()> {
7746        self.invalidator.debug_assert_paint();
7747
7748        let visible_bounds = bounds.intersect(&image_bounds);
7749        if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
7750            return Ok(());
7751        }
7752        if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
7753            return Ok(());
7754        }
7755
7756        // vue-native: an image drawn well below its own size is drawn from the
7757        // host's smaller copy, when it has one (see `ImageResampler`).
7758        let (data, frame_index) = match IMAGE_RESAMPLER.get() {
7759            Some(resample) if !data.is_dynamic() => {
7760                let scale = self.scale_factor();
7761                let device = size(
7762                    DevicePixels((image_bounds.size.width.0 * scale).round() as i32),
7763                    DevicePixels((image_bounds.size.height.0 * scale).round() as i32),
7764                );
7765                match resample(&data, frame_index, device) {
7766                    Some(smaller) => (smaller, 0),
7767                    None => (data, frame_index),
7768                }
7769            }
7770            _ => (data, frame_index),
7771        };
7772
7773        let params = RenderImageParams {
7774            image_id: data.id,
7775            frame_index,
7776        };
7777
7778        let tile = self.sprite_atlas.get_or_insert_with(params.into(), &mut || {
7779            Ok(data.as_bytes(frame_index).map(|bytes| (data.size(frame_index), Cow::Borrowed(bytes))))
7780        })?;
7781        let Some(tile) = tile else { return Ok(()); };
7782
7783        let visible_bounds_snapped = self.snap_bounds(visible_bounds);
7784
7785        let sub_tile = if visible_bounds == image_bounds {
7786            tile
7787        } else {
7788            let x_offset_ratio =
7789                (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
7790            let y_offset_ratio =
7791                (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
7792            let width_ratio = visible_bounds.size.width / image_bounds.size.width;
7793            let height_ratio = visible_bounds.size.height / image_bounds.size.height;
7794
7795            let tile_origin_x = tile.bounds.origin.x.0;
7796            let tile_origin_y = tile.bounds.origin.y.0;
7797            let tile_width = tile.bounds.size.width.0;
7798            let tile_height = tile.bounds.size.height.0;
7799
7800            let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
7801            let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
7802            let sub_width = (width_ratio * tile_width as f32).round() as i32;
7803            let sub_height = (height_ratio * tile_height as f32).round() as i32;
7804
7805            let max_x = tile_origin_x + tile_width;
7806            let max_y = tile_origin_y + tile_height;
7807
7808            let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
7809            let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
7810            let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
7811            let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
7812
7813            AtlasTile {
7814                bounds: Bounds {
7815                    origin: point(
7816                        DevicePixels(clamped_origin_x),
7817                        DevicePixels(clamped_origin_y),
7818                    ),
7819                    size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
7820                },
7821                ..tile
7822            }
7823        };
7824
7825        let content_mask = self.snapped_content_mask();
7826        let corner_radii = corner_radii
7827            .clamp_radii_for_quad_size(visible_bounds.size)
7828            .scale(self.scale_factor());
7829        let opacity = self.element_opacity();
7830
7831        self.next_frame.scene.insert_primitive(PolychromeSprite {
7832            order: 0,
7833            pad: 0,
7834            grayscale: grayscale.into(),
7835            bounds: visible_bounds_snapped,
7836            content_mask,
7837            corner_radii,
7838            tile: sub_tile,
7839            opacity,
7840            transformation: self.element_transform,
7841            tint: self.element_image_tint,
7842        });
7843        Ok(())
7844    }
7845
7846    /// Paint a surface into the scene for the next frame at the current z-index.
7847    ///
7848    /// This method should only be called as part of the paint phase of element drawing.
7849    #[cfg(any(target_os = "macos", target_os = "ios"))]
7850    pub fn paint_surface(
7851        &mut self,
7852        bounds: Bounds<Pixels>,
7853        image_buffer: CFRetained<CVPixelBuffer>,
7854    ) {
7855        use crate::PaintSurface;
7856
7857        self.invalidator.debug_assert_paint();
7858
7859        let bounds = self.snap_bounds(bounds);
7860        let content_mask = self.snapped_content_mask();
7861        self.next_frame.scene.insert_primitive(PaintSurface {
7862            order: 0,
7863            bounds,
7864            content_mask,
7865            image_buffer,
7866        });
7867    }
7868
7869    /// Fills the sprite-atlas tile that backs `data` from a texture that is
7870    /// already in the renderer's own GPU memory, with no CPU round trip.
7871    ///
7872    /// `data` is used for its **identity and its size only** — its pixel buffer
7873    /// is never read on this path, so a producer that decodes onto the GPU can
7874    /// keep one zero-filled `RenderImage` alive for the life of the element and
7875    /// overwrite its tile every frame. `paint_image` then finds the tile
7876    /// already populated and never runs its `build` closure.
7877    ///
7878    /// Returns `Ok(false)` when the platform has no GPU path or refused the
7879    /// texture (wrong device, wrong format, too small) — the caller is expected
7880    /// to fall back to a `RenderImage` carrying real bytes. This is not a paint
7881    /// method: call it from a frame pump, before the draw that paints the image.
7882    ///
7883    /// # Contract
7884    ///
7885    /// See [`PlatformAtlas::upload_from_gpu`]. On Windows `texture` must be an
7886    /// `ID3D11Texture2D` on the device `gpui_windows::renderer_d3d11_device()`
7887    /// publishes, in `DXGI_FORMAT_B8G8R8A8_UNORM`, at least as large as
7888    /// `data.size(frame_index)`.
7889    pub fn upload_image_from_gpu(
7890        &mut self,
7891        data: &RenderImage,
7892        frame_index: usize,
7893        texture: GpuTextureHandle,
7894    ) -> Result<bool> {
7895        Ok(self.write_image_tile(data, frame_index, TileSource::Gpu(texture))? != TileWrite::Refused)
7896    }
7897
7898    /// vue-native fork: writes a new frame into the sprite-atlas tile that backs
7899    /// `image`, outside any draw, and says whether the frame already drawn will
7900    /// show it.
7901    ///
7902    /// The tile is keyed by `image.id`. A producer that keeps one id for the
7903    /// life of a picture (a zero-copy video placeholder, or
7904    /// [`RenderImage::successor`] for CPU frames) keeps one tile, and the
7905    /// scene that painted it samples whatever was written last. When the write
7906    /// lands [`TileWrite::InPlace`], [`Window::request_present`] shows it with
7907    /// no layout, prepaint or paint. The size is `image.size(frame_index)`.
7908    /// Call it from a frame callback, before the frame's draw, never during one.
7909    ///
7910    /// `TileSource::Bytes` writes `image`'s own pixels (premultiplied BGRA).
7911    /// It always succeeds: a backend with no in-place path re-inserts the key,
7912    /// which reports [`TileWrite::Placed`]. `TileSource::Gpu` has the contract
7913    /// of [`PlatformAtlas::upload_from_gpu`] and reports
7914    /// [`TileWrite::Refused`] where that returns `None`.
7915    pub fn write_image_tile(
7916        &mut self,
7917        image: &RenderImage,
7918        frame_index: usize,
7919        source: TileSource,
7920    ) -> Result<TileWrite> {
7921        let key: AtlasKey = RenderImageParams {
7922            image_id: image.id,
7923            frame_index,
7924        }
7925        .into();
7926        let size = image.size(frame_index);
7927        let before = self.sprite_atlas.tile(&key);
7928        let after = match source {
7929            TileSource::Gpu(texture) => {
7930                match self.sprite_atlas.upload_from_gpu(&key, size, texture)? {
7931                    Some(tile) => tile,
7932                    None => return Ok(TileWrite::Refused),
7933                }
7934            }
7935            TileSource::Bytes => {
7936                let bytes = image
7937                    .as_bytes(frame_index)
7938                    .ok_or_else(|| anyhow!("write_image_tile: no frame {frame_index}"))?;
7939                match self.sprite_atlas.write_bytes(&key, size, bytes)? {
7940                    Some(tile) => tile,
7941                    None => {
7942                        self.sprite_atlas.remove(&key);
7943                        self.sprite_atlas
7944                            .get_or_insert_with(key, &mut || {
7945                                Ok(Some((size, Cow::Borrowed(bytes))))
7946                            })?
7947                            .ok_or_else(|| anyhow!("write_image_tile: the atlas took no tile"))?;
7948                        return Ok(TileWrite::Placed);
7949                    }
7950                }
7951            }
7952        };
7953        Ok(match before {
7954            Some(tile) if tile == after => TileWrite::InPlace,
7955            _ => TileWrite::Placed,
7956        })
7957    }
7958
7959    /// Writes a GPU frame while retaining its producer until the asynchronous
7960    /// atlas copy completes. See [`PlatformAtlas::upload_from_d3d12`].
7961    pub fn write_image_tile_d3d12(
7962        &mut self,
7963        image: &RenderImage,
7964        frame_index: usize,
7965        texture: crate::D3D12TextureHandle,
7966        owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
7967    ) -> Result<TileWrite> {
7968        let key: AtlasKey = RenderImageParams {
7969            image_id: image.id,
7970            frame_index,
7971        }
7972        .into();
7973        let before = self.sprite_atlas.tile(&key);
7974        let Some(after) = self.sprite_atlas.upload_from_d3d12(
7975            &key,
7976            image.size(frame_index),
7977            texture,
7978            owner,
7979        )? else {
7980            return Ok(TileWrite::Refused);
7981        };
7982        Ok(match before {
7983            Some(tile) if tile == after => TileWrite::InPlace,
7984            _ => TileWrite::Placed,
7985        })
7986    }
7987
7988    /// vue-native fork: presents the frame already drawn once more, with no
7989    /// layout, prepaint or paint: the renderer encodes the same scene again, so
7990    /// an atlas tile overwritten in place since ([`Window::write_image_tile`],
7991    /// [`TileWrite::InPlace`]) shows its new pixels. From an `on_next_frame`
7992    /// callback it takes effect in that frame; elsewhere, on the next one. A
7993    /// frame that draws anyway presents what it drew.
7994    pub fn request_present(&self) {
7995        self.needs_present.set(true);
7996        self.invalidator.wake_platform();
7997    }
7998
7999    /// Removes an image from the sprite atlas.
8000    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
8001        for frame_index in 0..data.frame_count() {
8002            let params = RenderImageParams {
8003                image_id: data.id,
8004                frame_index,
8005            };
8006
8007            self.sprite_atlas.remove(&params.into());
8008        }
8009
8010        Ok(())
8011    }
8012
8013    /// vue-native fork: this window's sprite atlas footprint (pages and bytes
8014    /// per texture kind, keys, image tiles), for an embedder's memory report.
8015    /// `None` when the platform's atlas does not keep count.
8016    pub fn sprite_atlas_stats(&self) -> Option<AtlasStats> {
8017        self.sprite_atlas.stats()
8018    }
8019
8020    /// Reports a live atlas tile on backends supporting GPU image imports.
8021    pub fn has_image_atlas_tile(&self, data: &RenderImage, frame_index: usize) -> bool {
8022        self.sprite_atlas.tile(&RenderImageParams {image_id:data.id,frame_index}.into()).is_some()
8023    }
8024
8025    /// Returns whether every frame of an image is present in the sprite atlas.
8026    #[cfg(any(test, feature = "test-support"))]
8027    pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
8028        data.frame_count() > 0
8029            && (0..data.frame_count()).all(|frame_index| {
8030                self.sprite_atlas.contains(
8031                    &RenderImageParams {
8032                        image_id: data.id,
8033                        frame_index,
8034                    }
8035                    .into(),
8036                )
8037            })
8038    }
8039
8040    /// Enable node retention for this window before its first layout request.
8041    /// Generic GPUI windows retain upstream's per-frame layout by default.
8042    pub fn vn_enable_retained_layout(&mut self) {
8043        self.layout_engine.as_mut().unwrap().enable_retention();
8044    }
8045
8046    /// Enable counters only while a profiling capture is active.
8047    pub fn vn_profile_retained_layout(&mut self, enabled: bool) {
8048        self.layout_engine
8049            .as_mut()
8050            .unwrap()
8051            .profile_retention(enabled);
8052    }
8053
8054    /// Drain this window's retention counters, or None while profiling is off.
8055    pub fn vn_take_retained_layout_stats(&mut self) -> Option<crate::VnRetainedLayoutStats> {
8056        self.layout_engine.as_mut().unwrap().take_retention_stats()
8057    }
8058
8059    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
8060    /// layout is being requested, along with the layout ids of any children. This method is called during
8061    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
8062    ///
8063    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
8064    #[must_use]
8065    pub fn request_layout(
8066        &mut self,
8067        style: Style,
8068        children: impl IntoIterator<Item = LayoutId>,
8069        cx: &mut App,
8070    ) -> LayoutId {
8071        self.invalidator.debug_assert_prepaint();
8072
8073        cx.layout_id_buffer.clear();
8074        cx.layout_id_buffer.extend(children);
8075        let rem_size = self.rem_size();
8076        let scale_factor = self.scale_factor();
8077
8078        let scope = self
8079            .layout_engine
8080            .as_ref()
8081            .unwrap()
8082            .retention_enabled()
8083            .then(|| self.element_id_stack.global_id());
8084        let engine = self.layout_engine.as_mut().unwrap();
8085        if let Some(scope) = scope {
8086            engine.request_layout_in_scope(
8087                Some(scope),
8088                style,
8089                rem_size,
8090                scale_factor,
8091                &cx.layout_id_buffer,
8092            )
8093        } else {
8094            engine.request_layout(style, rem_size, scale_factor, &cx.layout_id_buffer)
8095        }
8096    }
8097
8098    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
8099    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
8100    /// determine the element's size. One place this is used internally is when measuring text.
8101    ///
8102    /// The given closure is invoked at layout time with the known dimensions and available space and
8103    /// returns a `Size`.
8104    ///
8105    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
8106    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
8107    where
8108        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
8109            + 'static,
8110    {
8111        self.invalidator.debug_assert_prepaint();
8112
8113        let rem_size = self.rem_size();
8114        let scale_factor = self.scale_factor();
8115        let scope = self
8116            .layout_engine
8117            .as_ref()
8118            .unwrap()
8119            .retention_enabled()
8120            .then(|| self.element_id_stack.global_id());
8121        let engine = self.layout_engine.as_mut().unwrap();
8122        if let Some(scope) = scope {
8123            engine.request_measured_layout_in_scope(
8124                Some(scope),
8125                style,
8126                rem_size,
8127                scale_factor,
8128                measure,
8129            )
8130        } else {
8131            engine.request_measured_layout(style, rem_size, scale_factor, measure)
8132        }
8133    }
8134
8135    /// Compute the layout for the given id within the given available space.
8136    /// This method is called for its side effect, typically by the framework prior to painting.
8137    /// After calling it, you can request the bounds of the given layout node id or any descendant.
8138    ///
8139    /// This method should only be called as part of the prepaint phase of element drawing.
8140    pub fn compute_layout(
8141        &mut self,
8142        layout_id: LayoutId,
8143        available_space: Size<AvailableSpace>,
8144        cx: &mut App,
8145    ) {
8146        self.invalidator.debug_assert_prepaint();
8147
8148        let mut layout_engine = self.layout_engine.take().unwrap();
8149        layout_engine.compute_layout(layout_id, available_space, self, cx);
8150        self.layout_engine = Some(layout_engine);
8151    }
8152
8153    /// vue-native fork: whether the layout node is out of flow (`position:
8154    /// absolute`).
8155    pub fn layout_is_absolute(&self, layout_id: LayoutId) -> bool {
8156        self.layout_engine
8157            .as_ref()
8158            .is_some_and(|engine| engine.is_absolute(layout_id))
8159    }
8160
8161    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
8162    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
8163    ///
8164    /// This method should only be called as part of element drawing.
8165    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
8166        self.invalidator.debug_assert_prepaint();
8167
8168        let scale_factor = self.scale_factor();
8169        let mut bounds = self
8170            .layout_engine
8171            .as_mut()
8172            .unwrap()
8173            .layout_bounds(layout_id, scale_factor)
8174            .map(Into::into);
8175        let snapped_offset = self.pixel_snap_point(self.element_offset());
8176        bounds.origin += snapped_offset;
8177        bounds
8178    }
8179
8180    /// This method should be called during `prepaint`. You can use
8181    /// the returned [Hitbox] during `paint` or in an event handler
8182    /// to determine whether the inserted hitbox was the topmost.
8183    ///
8184    /// This method should only be called as part of the prepaint phase of element drawing.
8185    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
8186        self.invalidator.debug_assert_prepaint();
8187
8188        let content_mask = self.content_mask();
8189        let id = self.next_hitbox_id;
8190        self.next_hitbox_id = self.next_hitbox_id.next();
8191        let hitbox = Hitbox {
8192            id,
8193            bounds,
8194            content_mask,
8195            behavior,
8196            // Whatever CSS `transform` the paint walk is inside. Prepaint
8197            // pushes the same matrix paint does, so a rotated element's hitbox
8198            // knows it is rotated (see `Frame::hit_test`).
8199            transformation: self.element_transform,
8200            vn_clip: self.vn_clip_stack.clone(),
8201        };
8202        self.next_frame.hitboxes.push(hitbox.clone());
8203        // vue-native fork.
8204        if self.vn_hitbox_tag != 0 {
8205            self.next_frame
8206                .vn_tagged_hitboxes
8207                .push((self.vn_hitbox_tag, hitbox.clone()));
8208        }
8209        hitbox
8210    }
8211
8212    /// vue-native fork: tag every hitbox inserted from now until the tag is set
8213    /// back, with an embedder node id. Returns the previous tag, which the
8214    /// caller must restore — the pair brackets one node's prepaint, so a child
8215    /// tags itself and hands the parent's tag back on the way out.
8216    ///
8217    /// `0` disables tagging. See [`Frame::vn_tagged_hitboxes`].
8218    pub fn set_hitbox_tag(&mut self, tag: u32) -> u32 {
8219        mem::replace(&mut self.vn_hitbox_tag, tag)
8220    }
8221
8222    /// vue-native fork: [`Window::set_hitbox_tag`] for the duration of `f`,
8223    /// which prepaints one embedder node, answering also the node's whole CSS
8224    /// `transform` (its ancestors' composed with its own) when it has one of
8225    /// its own. `None` means its picture moved only with its ancestors', by
8226    /// [`Window::element_transform`] as it stood before `f`.
8227    ///
8228    /// "The node's own" is the FIRST element to prepaint inside `f`: the
8229    /// node's element runs before anything inside it, and what it builds
8230    /// internally under the same tag (a `::before` box, a list marker) after,
8231    /// so a transformed pseudo-element does not move its node.
8232    pub fn with_hitbox_tag<R>(
8233        &mut self,
8234        tag: u32,
8235        f: impl FnOnce(&mut Self) -> R,
8236    ) -> (R, Option<TransformationMatrix>) {
8237        let tag = mem::replace(&mut self.vn_hitbox_tag, tag);
8238        let fresh = mem::replace(&mut self.vn_tag_fresh, true);
8239        let noted = self.vn_tag_transform.take();
8240        let result = f(self);
8241        let own = mem::replace(&mut self.vn_tag_transform, noted);
8242        self.vn_tag_fresh = fresh;
8243        self.vn_hitbox_tag = tag;
8244        (result, own)
8245    }
8246
8247    /// vue-native fork: called by every element's prepaint once its own
8248    /// `transform` is pushed. The first one inside a
8249    /// [`Window::with_hitbox_tag`] is the tagged node's.
8250    pub(crate) fn note_tagged_transform(&mut self, own_is_unit: bool) {
8251        if self.vn_tag_fresh {
8252            self.vn_tag_fresh = false;
8253            if !own_is_unit {
8254                self.vn_tag_transform = Some(self.element_transform);
8255            }
8256        }
8257    }
8258
8259    /// vue-native fork: the axis-aligned bounding box of `bounds` (logical
8260    /// pixels) under `matrix` (device space, as [`Window::element_transform`]
8261    /// is) — the rectangle a browser's `getBoundingClientRect()` reports for a
8262    /// transformed box.
8263    pub fn transformed_bounds(
8264        &self,
8265        matrix: TransformationMatrix,
8266        bounds: Bounds<Pixels>,
8267    ) -> Bounds<Pixels> {
8268        transform_bounds(matrix, bounds, self.scale_factor)
8269    }
8270
8271    /// vue-native fork: give EVERY element a hitbox, not only an interactive
8272    /// one, so that [`Window::tagged_hitbox`] can answer for any node. Costs
8273    /// one `Hitbox` per element per frame and the same number of rectangle
8274    /// tests per mouse move, so it is opt-in; a dev host turns it on at boot
8275    /// and a shipped one never does.
8276    pub fn set_tag_every_hitbox(&mut self, on: bool) {
8277        self.vn_tag_every_hitbox = on;
8278    }
8279
8280    /// vue-native fork: is [`Window::set_tag_every_hitbox`] on?
8281    pub fn tags_every_hitbox(&self) -> bool {
8282        self.vn_tag_every_hitbox
8283    }
8284
8285    /// vue-native fork: the hitbox the RENDERED frame made for the element
8286    /// tagged `tag` — the handle [`Hitbox::is_hovered_at`] takes.
8287    ///
8288    /// The first entry wins: an element's own hitbox is inserted before any box
8289    /// its subtree makes, and boxes a node's build produces internally (a
8290    /// pseudo-element, a list marker) carry the same tag. A pick
8291    /// ([`Window::vn_insert_pick`]) is not a hitbox and is passed over.
8292    pub fn tagged_hitbox(&self, tag: u32) -> Option<&Hitbox> {
8293        self.rendered_frame
8294            .vn_tagged_hitboxes
8295            .iter()
8296            .find(|(t, hitbox)| *t == tag && hitbox.id != HitboxId::VN_PICK)
8297            .map(|(_, hitbox)| hitbox)
8298    }
8299
8300    /// vue-native fork: the embedder tags of the hitboxes under `position` in
8301    /// the RENDERED frame, topmost first — the order a press resolves in
8302    /// ([`Frame::hit_test`], so a deferred draw's boxes sort where it paints).
8303    /// A hitbox no node tagged is left out; a node with several boxes there
8304    /// appears once per box.
8305    ///
8306    /// An embedder asks it to learn which of ITS nodes is on top under the
8307    /// pointer, which gpui's own answer (`Hitbox::is_hovered`, true for every
8308    /// box under the pointer) cannot say. One hit test plus one pass over the
8309    /// frame's tagged boxes: meant for a press or a drag, not for every mouse
8310    /// move.
8311    ///
8312    /// The PICK records ([`Window::vn_insert_pick`]) are boxes too, so with
8313    /// [`Window::set_vn_pick_every_box`] on this answers for every element,
8314    /// listening or not. It walks the tagged list in paint order itself rather
8315    /// than asking [`Frame::hit_test`], whose list has no picks; a
8316    /// `BlockMouse` box ends it, as it ends gpui's.
8317    ///
8318    /// A box tagged [`VN_TAG_PASSIVE`] is left out: it is a node's, but it is
8319    /// not where the node is (a scroll container's wheel viewport, which lies
8320    /// over the content it scrolls).
8321    pub fn vn_tags_at(&self, position: Point<Pixels>) -> Vec<u32> {
8322        let frame = &self.rendered_frame;
8323        let tagged = &frame.vn_tagged_hitboxes;
8324        let mut out = Vec::new();
8325        let mut visit = |(tag, hitbox): &(u32, Hitbox)| {
8326            if tag & VN_TAG_PASSIVE != 0 || !Frame::box_contains(hitbox, position, self.scale_factor) {
8327                return true;
8328            }
8329            out.push(*tag);
8330            hitbox.behavior != HitboxBehavior::BlockMouse
8331        };
8332        match frame.vn_tagged_paint_order() {
8333            Some(order) => {
8334                for &ix in order.iter().rev() {
8335                    if !visit(&tagged[ix as usize]) {
8336                        break;
8337                    }
8338                }
8339            }
8340            None => {
8341                for entry in tagged.iter().rev() {
8342                    if !visit(entry) {
8343                        break;
8344                    }
8345                }
8346            }
8347        }
8348        out
8349    }
8350
8351    /// vue-native fork: give an element that needs no hitbox a PICK record
8352    /// instead — its box, content mask, transform and tag, in
8353    /// [`Frame::vn_tagged_hitboxes`] only. gpui's own hit test (the one every
8354    /// mouse move runs) never sees a pick, so it costs a move nothing; it is
8355    /// there for [`Window::vn_tags_at`], which an embedder asks at a press to
8356    /// learn the topmost of ALL its elements, the way a browser targets an
8357    /// event. Replayed with the rest of a cached view's prepaint.
8358    pub fn set_vn_pick_every_box(&mut self, on: bool) {
8359        self.vn_pick_every_box = on;
8360    }
8361
8362    /// vue-native fork: is [`Window::set_vn_pick_every_box`] on?
8363    pub fn vn_picks_every_box(&self) -> bool {
8364        self.vn_pick_every_box
8365    }
8366
8367    /// vue-native fork: records a pick for `bounds` under the current tag
8368    /// (nothing outside a tag). Called where an element would insert its
8369    /// hitbox, so the content mask and transform are the ones a hitbox there
8370    /// would carry.
8371    pub fn vn_insert_pick(&mut self, bounds: Bounds<Pixels>) {
8372        self.invalidator.debug_assert_prepaint();
8373        if self.vn_hitbox_tag == 0 {
8374            return;
8375        }
8376        let hitbox = Hitbox {
8377            id: HitboxId::VN_PICK,
8378            bounds,
8379            content_mask: self.content_mask(),
8380            behavior: HitboxBehavior::Normal,
8381            transformation: self.element_transform,
8382            vn_clip: self.vn_clip_stack.clone(),
8383        };
8384        self.next_frame
8385            .vn_tagged_hitboxes
8386            .push((self.vn_hitbox_tag, hitbox));
8387    }
8388
8389    /// vue-native fork: installs (or removes) the embedder's hit refiner.
8390    ///
8391    /// gpui hands a mouse event to EVERY hitbox under the pointer, so a box
8392    /// that listens takes a press through anything painted over it that does
8393    /// not, and a box that does not listen is never anybody's target. A
8394    /// browser targets the topmost element and bubbles from there. The
8395    /// refiner is run at the start of the dispatch of each press, release and
8396    /// wheel event, before any listener, and may narrow what the event is for
8397    /// with [`Window::vn_restrict_mouse_hit`]. Moves are not refined.
8398    pub fn set_vn_hit_refiner(&mut self, refiner: Option<VnHitRefiner>) {
8399        self.vn_hit_refiner = refiner;
8400    }
8401
8402    /// vue-native fork: is a hit refiner installed?
8403    pub fn has_vn_hit_refiner(&self) -> bool {
8404        self.vn_hit_refiner.is_some()
8405    }
8406
8407    /// vue-native fork: which key event this window is dispatching — one
8408    /// number per key-down, key-up or modifiers change, taken before the
8409    /// keystroke interceptors run, so everything that hears one event (an
8410    /// interceptor, the capture listeners, the bubble listeners) reads the
8411    /// same number and the next event reads another.
8412    ///
8413    /// gpui hands a key event to every listener on the focus path, and an
8414    /// editor's interceptor sees it before any of them. An embedder that turns
8415    /// it into ONE event of its own (a browser's `keydown`, dispatched once at
8416    /// the focused element) records the number it dispatched for and lets the
8417    /// others pass. Interceptor order and listener order do not matter, and a
8418    /// listener whose element the first dispatch removed still reads the same
8419    /// number, because gpui walks the path it computed before any of them ran.
8420    pub fn vn_key_event_seq(&self) -> u64 {
8421        self.vn_key_event_seq
8422    }
8423
8424    /// vue-native fork: is the pointer in this window? `false` once it has
8425    /// left (a `MouseExited`, the end of a file drag over it), `true` again at
8426    /// the next pointer event here. [`Window::mouse_position`] keeps the last
8427    /// position inside either way, so an embedder that decides hover itself
8428    /// (a browser's `:hover` and `mouseenter`, from its own hit test) asks
8429    /// this to know that nothing is hovered, as [`Hitbox::is_hovered`] does.
8430    pub fn vn_pointer_inside(&self) -> bool {
8431        self.pointer_inside
8432    }
8433
8434    /// vue-native fork: a browser's pointer lock. Until [`Window::vn_unlock_pointer`], every
8435    /// mouse event is delivered at the position the pointer had now, and a move's motion is
8436    /// [`Window::vn_mouse_movement`]. Locking again changes the mode.
8437    pub fn vn_lock_pointer(&mut self, how: VnPointerLock) -> Result<(), crate::PointerLockError> {
8438        let anchor = match self.vn_pointer_lock.take() {
8439            Some((previous, anchor)) => {
8440                if matches!(previous, VnPointerLock::System { .. }) {
8441                    self.platform_window.unlock_pointer();
8442                }
8443                anchor
8444            }
8445            None => self.mouse_position,
8446        };
8447        if let VnPointerLock::System { unadjusted } = how {
8448            self.platform_window.lock_pointer(unadjusted)?;
8449        }
8450        self.vn_pointer_lock = Some((how, anchor));
8451        self.vn_raw_mouse_position = None;
8452        Ok(())
8453    }
8454
8455    /// vue-native fork: releases [`Window::vn_lock_pointer`]'s lock, if any.
8456    pub fn vn_unlock_pointer(&mut self) {
8457        if let Some((VnPointerLock::System { .. }, _)) = self.vn_pointer_lock.take() {
8458            self.platform_window.unlock_pointer();
8459        }
8460        self.vn_raw_mouse_position = None;
8461    }
8462
8463    /// vue-native fork: is the pointer still locked? The platform lets go by itself when the
8464    /// window loses activation.
8465    pub fn vn_pointer_locked(&self) -> bool {
8466        match self.vn_pointer_lock {
8467            Some((VnPointerLock::System { .. }, _)) => self.platform_window.is_pointer_locked(),
8468            Some((VnPointerLock::Simulated, _)) => true,
8469            None => false,
8470        }
8471    }
8472
8473    /// vue-native fork: how far the mouse move being dispatched moved the pointer since the
8474    /// previous move, logical pixels: a browser's `movementX`/`movementY`. While the pointer is
8475    /// locked by the system it is the platform's measure (device counts when unadjusted).
8476    pub fn vn_mouse_movement(&self) -> Point<Pixels> {
8477        self.vn_mouse_movement
8478    }
8479
8480    fn vn_pin_to_pointer_lock(&mut self, mut event: PlatformInput) -> PlatformInput {
8481        let system = matches!(
8482            self.vn_pointer_lock,
8483            Some((VnPointerLock::System { .. }, _))
8484        );
8485        if system && !self.platform_window.is_pointer_locked() {
8486            self.vn_pointer_lock = None;
8487            self.vn_raw_mouse_position = None;
8488        }
8489        if let PlatformInput::MouseMove(mouse_move) = &event {
8490            let previous = self.vn_raw_mouse_position.replace(mouse_move.position);
8491            let motion = system.then(|| self.platform_window.take_pointer_motion());
8492            self.vn_mouse_movement = motion.flatten().unwrap_or_else(|| {
8493                previous.map_or_else(Point::default, |previous| mouse_move.position - previous)
8494            });
8495        }
8496        let Some((_, anchor)) = self.vn_pointer_lock else {
8497            return event;
8498        };
8499        match &mut event {
8500            PlatformInput::MouseMove(e) => e.position = anchor,
8501            PlatformInput::MouseDown(e) => e.position = anchor,
8502            PlatformInput::MouseUp(e) => e.position = anchor,
8503            PlatformInput::Scroll(e) => e.position = anchor,
8504            PlatformInput::MouseExited(e) => e.position = anchor,
8505            _ => {}
8506        }
8507        event
8508    }
8509
8510    /// vue-native fork: will this frame draw the window? `true` once anything
8511    /// invalidated it since its last draw (a notify, a `refresh`, a resize).
8512    /// An embedder with work that must follow the frame's layout and precede
8513    /// its paint (a browser's ResizeObserver delivery) draws the window itself
8514    /// from an `on_next_frame` callback when this is set; the frame then finds
8515    /// it clean and presents what that draw produced.
8516    pub fn vn_is_dirty(&self) -> bool {
8517        self.invalidator.is_dirty()
8518    }
8519
8520    /// vue-native fork: for the mouse event being dispatched, keep only the
8521    /// hitboxes whose tag `keep` accepts (an untagged hitbox is not the
8522    /// embedder's and stays). With `add`, the accepted tags' boxes that do
8523    /// NOT contain the pointer join the hovered set as well: a browser's
8524    /// event reaches every ancestor of its target, wherever their boxes are.
8525    ///
8526    /// Only meant from inside a [`VnHitRefiner`]. The next frame or the next
8527    /// mouse event recomputes the hit test from geometry.
8528    pub fn vn_restrict_mouse_hit(&mut self, keep: &dyn Fn(u32) -> bool, add: bool) {
8529        let frame = &self.rendered_frame;
8530        let mut tag_of: FxHashMap<HitboxId, u32> = FxHashMap::default();
8531        // A passive box is judged by the node it belongs to.
8532        for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8533            if hitbox.id != HitboxId::VN_PICK {
8534                tag_of.entry(hitbox.id).or_insert(tag & !VN_TAG_PASSIVE);
8535            }
8536        }
8537        let old = mem::take(&mut self.mouse_hit_test);
8538        let mut ids: SmallVec<[HitboxId; 8]> = SmallVec::new();
8539        let mut hover = 0;
8540        for (ix, id) in old.ids.iter().enumerate() {
8541            if tag_of.get(id).is_none_or(|tag| keep(*tag)) {
8542                ids.push(*id);
8543                if ix < old.hover_hitbox_count {
8544                    hover += 1;
8545                }
8546            }
8547        }
8548        // Nothing was cut from hover by a `BlockMouseExceptScroll` box: the
8549        // added boxes are hovered too.
8550        let all_hovered = old.hover_hitbox_count == old.ids.len();
8551        if add {
8552            for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8553                if hitbox.id != HitboxId::VN_PICK
8554                    && keep(tag & !VN_TAG_PASSIVE)
8555                    && !ids.contains(&hitbox.id)
8556                {
8557                    ids.push(hitbox.id);
8558                }
8559            }
8560        }
8561        if all_hovered {
8562            hover = ids.len();
8563        }
8564        self.mouse_hit_test = HitTest {
8565            ids,
8566            hover_hitbox_count: hover,
8567        };
8568    }
8569
8570    /// Resolves native caption behavior at a point in the current painted frame.
8571    /// This does not reuse or modify the hit set narrowed for a DOM input event.
8572    pub fn window_control_area_at(&self, position: Point<Pixels>) -> Option<WindowControlArea> {
8573        for hitbox in self.rendered_frame.topmost_hitboxes() {
8574            if !Frame::box_contains(hitbox, position, self.scale_factor) {
8575                continue;
8576            }
8577            if let Some((area, _)) = self.rendered_frame.window_control_hitboxes.iter()
8578                .find(|(_, control)| control.id == hitbox.id)
8579            {
8580                return Some(*area);
8581            }
8582            if hitbox.behavior == HitboxBehavior::BlockMouse {
8583                break;
8584            }
8585        }
8586        None
8587    }
8588
8589    /// Set a hitbox which will act as a control area of the platform window.
8590    ///
8591    /// This method should only be called as part of the paint phase of element drawing.
8592    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
8593        self.invalidator.debug_assert_paint();
8594        self.next_frame.window_control_hitboxes.push((area, hitbox));
8595    }
8596
8597    /// Sets the key context for the current element. This context will be used to translate
8598    /// keybindings into actions.
8599    ///
8600    /// This method should only be called as part of the paint phase of element drawing.
8601    pub fn set_key_context(&mut self, context: KeyContext) {
8602        self.invalidator.debug_assert_paint();
8603        self.next_frame.dispatch_tree.set_key_context(context);
8604    }
8605
8606    /// Sets the focus handle for the current element. This handle will be used to manage focus state
8607    /// and keyboard event dispatch for the element.
8608    ///
8609    /// This method should only be called as part of the prepaint phase of element drawing.
8610    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
8611        self.invalidator.debug_assert_prepaint();
8612        if focus_handle.is_focused(self) {
8613            self.next_frame.focus = Some(focus_handle.id);
8614        }
8615        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
8616    }
8617
8618    /// Sets the view id for the current element, which will be used to manage view caching.
8619    ///
8620    /// This method should only be called as part of element prepaint. We plan on removing this
8621    /// method eventually when we solve some issues that require us to construct editor elements
8622    /// directly instead of always using editors via views.
8623    pub fn set_view_id(&mut self, view_id: EntityId) {
8624        self.invalidator.debug_assert_prepaint();
8625        self.next_frame.dispatch_tree.set_view_id(view_id);
8626    }
8627
8628    /// Get the entity ID for the currently rendering view
8629    pub fn current_view(&self) -> EntityId {
8630        self.invalidator.debug_assert_paint_or_prepaint();
8631        self.rendered_entity_stack.last().copied().unwrap()
8632    }
8633
8634    #[inline]
8635    pub(crate) fn with_rendered_view<R>(
8636        &mut self,
8637        id: EntityId,
8638        f: impl FnOnce(&mut Self) -> R,
8639    ) -> R {
8640        self.rendered_entity_stack.push(id);
8641        let result = f(self);
8642        self.rendered_entity_stack.pop();
8643        result
8644    }
8645
8646    /// Executes the provided function with the specified image cache.
8647    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
8648    where
8649        F: FnOnce(&mut Self) -> R,
8650    {
8651        if let Some(image_cache) = image_cache {
8652            self.image_cache_stack.push(image_cache);
8653            let result = f(self);
8654            self.image_cache_stack.pop();
8655            result
8656        } else {
8657            f(self)
8658        }
8659    }
8660
8661    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
8662    /// platform to receive textual input with proper integration with concerns such
8663    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
8664    /// rendered.
8665    ///
8666    /// This method should only be called as part of the paint phase of element drawing.
8667    ///
8668    /// [element_input_handler]: crate::ElementInputHandler
8669    pub fn handle_input(
8670        &mut self,
8671        focus_handle: &FocusHandle,
8672        input_handler: impl InputHandler,
8673        cx: &App,
8674    ) {
8675        self.invalidator.debug_assert_paint();
8676
8677        if focus_handle.is_focused(self) {
8678            let cx = self.to_async(cx);
8679            self.next_frame.input_handlers.push(Some(
8680                PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
8681            ));
8682        }
8683    }
8684
8685    /// Notifies native text services that the focused component's text changed.
8686    ///
8687    /// Text components should call this after application-driven edits, in addition
8688    /// to notifying GPUI to redraw. Unfocused or unregistered components are ignored.
8689    pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
8690        if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8691            self.platform_window
8692                .text_input_state_changed(TextInputStateChange::ContentChanged);
8693        }
8694    }
8695
8696    /// Notifies native text services that the focused component's selection changed.
8697    ///
8698    /// Text components should call this after application-driven selection changes,
8699    /// in addition to notifying GPUI to redraw.
8700    pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
8701        if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8702            self.platform_window
8703                .text_input_state_changed(TextInputStateChange::SelectionChanged);
8704        }
8705    }
8706
8707    /// Forwards the focused input handler's [`TextInputConfiguration`] to the
8708    /// platform window when it differs from the last forwarded value. With no
8709    /// input handler the default configuration applies, so a field's
8710    /// preferences don't outlive its focus.
8711    fn apply_text_input_configuration(&mut self, cx: &mut App) {
8712        let configuration = match self.platform_window.take_input_handler() {
8713            Some(mut input_handler) => {
8714                let configuration = input_handler.text_input_configuration(self, cx);
8715                self.platform_window.set_input_handler(input_handler);
8716                configuration
8717            }
8718            None => TextInputConfiguration::default(),
8719        };
8720        if self.last_text_input_configuration.as_ref() != Some(&configuration) {
8721            self.platform_window
8722                .set_text_input_configuration(configuration.clone());
8723            self.last_text_input_configuration = Some(configuration);
8724        }
8725    }
8726
8727    /// Register a mouse event listener on the window for the next frame. The type of event
8728    /// is determined by the first parameter of the given listener. When the next frame is rendered
8729    /// the listener will be cleared.
8730    ///
8731    /// This method should only be called as part of the paint phase of element drawing.
8732    pub fn on_mouse_event<Event: MouseEvent>(
8733        &mut self,
8734        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8735    ) {
8736        self.invalidator.debug_assert_paint();
8737
8738        self.next_frame.mouse_listeners.push(Some(Box::new(
8739            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
8740                if let Some(event) = event.downcast_ref() {
8741                    listener(event, phase, window, cx)
8742                }
8743            },
8744        )));
8745    }
8746
8747    /// Register a key event listener on this node for the next frame. The type of event
8748    /// is determined by the first parameter of the given listener. When the next frame is rendered
8749    /// the listener will be cleared.
8750    ///
8751    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
8752    /// a specific need to register a listener yourself.
8753    ///
8754    /// This method should only be called as part of the paint phase of element drawing.
8755    pub fn on_key_event<Event: KeyEvent>(
8756        &mut self,
8757        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8758    ) {
8759        self.invalidator.debug_assert_paint();
8760
8761        self.next_frame.dispatch_tree.on_key_event(Rc::new(
8762            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
8763                if let Some(event) = event.downcast_ref::<Event>() {
8764                    listener(event, phase, window, cx)
8765                }
8766            },
8767        ));
8768    }
8769
8770    /// Register a modifiers changed event listener on the window for the next frame.
8771    ///
8772    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
8773    /// a specific need to register a global listener.
8774    ///
8775    /// This method should only be called as part of the paint phase of element drawing.
8776    pub fn on_modifiers_changed(
8777        &mut self,
8778        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
8779    ) {
8780        self.invalidator.debug_assert_paint();
8781
8782        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
8783            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
8784                listener(event, window, cx)
8785            },
8786        ));
8787    }
8788
8789    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
8790    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
8791    /// Returns a subscription and persists until the subscription is dropped.
8792    pub fn on_focus_in(
8793        &mut self,
8794        handle: &FocusHandle,
8795        cx: &mut App,
8796        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
8797    ) -> Subscription {
8798        let focus_id = handle.id;
8799        let (subscription, activate) =
8800            self.new_focus_listener(Box::new(move |event, window, cx| {
8801                if event.is_focus_in(focus_id) {
8802                    listener(window, cx);
8803                }
8804                true
8805            }));
8806        cx.defer(move |_| activate());
8807        subscription
8808    }
8809
8810    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
8811    /// Returns a subscription and persists until the subscription is dropped.
8812    pub fn on_focus_out(
8813        &mut self,
8814        handle: &FocusHandle,
8815        cx: &mut App,
8816        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
8817    ) -> Subscription {
8818        let focus_id = handle.id;
8819        let (subscription, activate) =
8820            self.new_focus_listener(Box::new(move |event, window, cx| {
8821                if let Some(blurred_id) = event.previous_focus_path.last().copied()
8822                    && event.is_focus_out(focus_id)
8823                {
8824                    let event = FocusOutEvent {
8825                        blurred: WeakFocusHandle {
8826                            id: blurred_id,
8827                            handles: Arc::downgrade(&cx.focus_handles),
8828                        },
8829                    };
8830                    listener(event, window, cx)
8831                }
8832                true
8833            }));
8834        cx.defer(move |_| activate());
8835        subscription
8836    }
8837
8838    fn reset_cursor_style(&self, cx: &mut App) {
8839        // Set the cursor only if we're the active window.
8840        if self.is_window_hovered() {
8841            // A drag can start before the next paint records its cursor in the frame.
8842            let style = cx
8843                .active_drag_cursor_style()
8844                .or_else(|| self.rendered_frame.cursor_style(self))
8845                .unwrap_or(CursorStyle::Arrow);
8846            cx.platform.set_cursor_style(style);
8847        }
8848    }
8849
8850    /// Dispatch a given keystroke as though the user had typed it.
8851    /// You can create a keystroke with Keystroke::parse("").
8852    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
8853        let keystroke = keystroke.with_simulated_ime();
8854        let result = self.dispatch_event(
8855            PlatformInput::KeyDown(KeyDownEvent {
8856                keystroke: keystroke.clone(),
8857                is_held: false,
8858                prefer_character_input: false,
8859            }),
8860            cx,
8861        );
8862        if !result.propagate {
8863            return true;
8864        }
8865
8866        if let Some(input) = keystroke.key_char
8867            && let Some(mut input_handler) = self.platform_window.take_input_handler()
8868        {
8869            input_handler.dispatch_input(&input, self, cx);
8870            self.platform_window.set_input_handler(input_handler);
8871            return true;
8872        }
8873
8874        false
8875    }
8876
8877    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
8878    /// binding for the action (last binding added to the keymap).
8879    pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
8880        self.highest_precedence_binding_for_action(action)
8881            .map(|binding| {
8882                binding
8883                    .keystrokes()
8884                    .iter()
8885                    .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
8886                    .collect::<Vec<_>>()
8887                    .join(" ")
8888            })
8889            .unwrap_or_else(|| action.name().to_string())
8890    }
8891
8892    /// Installs a modal input interceptor. Return true to consume the event
8893    /// before normal dispatch. Passing None restores the ordinary input path.
8894    /// The callback may remove itself. No callback runs while it is absent.
8895    pub fn set_input_interceptor(
8896        &mut self,
8897        interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
8898    ) {
8899        self.input_interceptor = interceptor;
8900    }
8901
8902    /// Dispatch a mouse, keyboard, or touch event on the window.
8903    #[profiling::function]
8904    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
8905        // A modal tool consumes the complete gesture before focus, native widgets,
8906        // click tracking and application listeners can observe it. Cloning the
8907        // Rc permits the interceptor to remove itself while handling an event.
8908        if let Some(intercept) = self.input_interceptor.clone() {
8909            if intercept(&event, self, cx) {
8910                return DispatchEventResult { propagate: false, default_prevented: true };
8911            }
8912        }
8913        #[cfg(feature = "profiler")]
8914        self.window_profiler.begin_input(event.kind_name());
8915        let update_count_before = self.invalidator.update_count();
8916        // Track input modality for focus-visible styling and hover suppression.
8917        // Hover is suppressed during keyboard modality so that keyboard navigation
8918        // doesn't show hover highlights on the item under the mouse cursor.
8919        let old_modality = self.last_input_modality;
8920        self.last_input_modality = match &event {
8921            PlatformInput::KeyDown(_) => InputModality::Keyboard,
8922            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
8923            PlatformInput::Touch(_) => InputModality::Touch,
8924            _ => self.last_input_modality,
8925        };
8926        if self.last_input_modality != old_modality {
8927            self.refresh();
8928        }
8929        let was_inside = self.pointer_inside;
8930        let pointer_moved = matches!(event, PlatformInput::MouseMove(_));
8931        // vue-native fork: [`Window::pointer_inside`]. Exhaustive on purpose,
8932        // so a new kind of input has to say which side it is on. A leave
8933        // applies AFTER the event is dispatched, so the listeners that handle
8934        // it (a file drag's exit, say) still see the element the pointer left.
8935        let pointer_leaves = match &event {
8936            PlatformInput::MouseMove(_)
8937            | PlatformInput::MouseDown(_)
8938            | PlatformInput::MouseUp(_)
8939            | PlatformInput::MousePressure(_)
8940            | PlatformInput::Scroll(_)
8941            | PlatformInput::Pinch(_)
8942            | PlatformInput::LongPress(_)
8943            | PlatformInput::TouchDrag(_)
8944            | PlatformInput::BackGesture(_)
8945            | PlatformInput::Touch(_) => {
8946                self.pointer_inside = true;
8947                false
8948            }
8949            PlatformInput::FileDrop(FileDropEvent::Exited) | PlatformInput::MouseExited(_) => true,
8950            PlatformInput::FileDrop(_) => {
8951                self.pointer_inside = true;
8952                false
8953            }
8954            PlatformInput::KeyDown(_)
8955            | PlatformInput::KeyUp(_)
8956            | PlatformInput::ModifiersChanged(_) => false,
8957        };
8958
8959        // Handlers may set this to false by calling `stop_propagation`.
8960        cx.propagate_event = true;
8961        // Handlers may set this to true by calling `prevent_default`.
8962        self.default_prevented = false;
8963
8964        let event = self.vn_pin_to_pointer_lock(event);
8965        let event = match event {
8966            // Track the mouse position with our own state, since accessing the platform
8967            // API for the mouse position can only occur on the main thread.
8968            PlatformInput::MouseMove(mouse_move) => {
8969                self.mouse_position = mouse_move.position;
8970                self.modifiers = mouse_move.modifiers;
8971                PlatformInput::MouseMove(mouse_move)
8972            }
8973            PlatformInput::MouseDown(mouse_down) => {
8974                self.mouse_position = mouse_down.position;
8975                self.modifiers = mouse_down.modifiers;
8976                PlatformInput::MouseDown(mouse_down)
8977            }
8978            PlatformInput::MouseUp(mouse_up) => {
8979                self.mouse_position = mouse_up.position;
8980                self.modifiers = mouse_up.modifiers;
8981                PlatformInput::MouseUp(mouse_up)
8982            }
8983            PlatformInput::MousePressure(mouse_pressure) => {
8984                PlatformInput::MousePressure(mouse_pressure)
8985            }
8986            PlatformInput::MouseExited(mouse_exited) => {
8987                self.modifiers = mouse_exited.modifiers;
8988                PlatformInput::MouseExited(mouse_exited)
8989            }
8990            PlatformInput::ModifiersChanged(modifiers_changed) => {
8991                self.modifiers = modifiers_changed.modifiers;
8992                self.capslock = modifiers_changed.capslock;
8993                PlatformInput::ModifiersChanged(modifiers_changed)
8994            }
8995            PlatformInput::Scroll(scroll_wheel) => {
8996                self.mouse_position = scroll_wheel.position;
8997                self.modifiers = scroll_wheel.modifiers;
8998                PlatformInput::Scroll(scroll_wheel)
8999            }
9000            PlatformInput::Pinch(pinch) => {
9001                self.mouse_position = pinch.position;
9002                self.modifiers = pinch.modifiers;
9003                PlatformInput::Pinch(pinch)
9004            }
9005            // Translate dragging and dropping of external files from the operating system
9006            // to internal drag and drop events.
9007            PlatformInput::FileDrop(file_drop) => match file_drop {
9008                FileDropEvent::Entered { position, paths } => {
9009                    self.mouse_position = position;
9010                    let source_window = self.handle.window_id();
9011                    if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
9012                        cx.active_drag = Some(AnyDrag {
9013                            value: Arc::new(paths.clone()),
9014                            view: cx.new(|_| paths).into(),
9015                            cursor_offset: position,
9016                            cursor_style: None,
9017                            external_payload_source: None,
9018                        });
9019                    }
9020                    PlatformInput::MouseMove(MouseMoveEvent {
9021                        position,
9022                        pressed_button: Some(MouseButton::Left),
9023                        modifiers: Modifiers::default(),
9024                    })
9025                }
9026                FileDropEvent::Pending { position } => {
9027                    self.mouse_position = position;
9028                    PlatformInput::MouseMove(MouseMoveEvent {
9029                        position,
9030                        pressed_button: Some(MouseButton::Left),
9031                        modifiers: Modifiers::default(),
9032                    })
9033                }
9034                FileDropEvent::Submit { position } => {
9035                    cx.activate(true);
9036                    self.mouse_position = position;
9037                    PlatformInput::MouseUp(MouseUpEvent {
9038                        button: MouseButton::Left,
9039                        position,
9040                        modifiers: Modifiers::default(),
9041                        click_count: 1,
9042                    })
9043                }
9044                FileDropEvent::Exited => {
9045                    if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
9046                        cx.active_drag.take();
9047                    }
9048                    self.refresh();
9049                    PlatformInput::FileDrop(FileDropEvent::Exited)
9050                }
9051                FileDropEvent::Ended => {
9052                    cx.end_platform_drag(self.handle.window_id());
9053                    self.refresh();
9054                    PlatformInput::FileDrop(FileDropEvent::Ended)
9055                }
9056            },
9057            PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
9058            PlatformInput::LongPress(long_press) => {
9059                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9060                    long_press.start_position
9061                } else {
9062                    long_press.position
9063                };
9064                if long_press.phase == crate::TouchPhase::Started {
9065                    self.long_press_capture = None;
9066                }
9067                PlatformInput::LongPress(long_press)
9068            }
9069            PlatformInput::TouchDrag(touch_drag) => {
9070                self.mouse_position = touch_drag.start_position;
9071                PlatformInput::TouchDrag(touch_drag)
9072            }
9073            PlatformInput::BackGesture(back) => {
9074                self.mouse_position = back.start_position;
9075                PlatformInput::BackGesture(back)
9076            }
9077            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
9078        };
9079
9080        if let Some(any_mouse_event) = event.mouse_event() {
9081            self.dispatch_mouse_event(any_mouse_event, cx);
9082        } else if let Some(any_key_event) = event.keyboard_event() {
9083            self.dispatch_key_event(any_key_event, cx);
9084        } else if let Some(touch_event) = event.touch_event() {
9085            self.dispatch_touch_event(touch_event, cx);
9086        }
9087        if let PlatformInput::LongPress(long_press) = &event {
9088            match long_press.phase {
9089                crate::TouchPhase::Started if !self.default_prevented => {
9090                    self.long_press_capture = None;
9091                }
9092                crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
9093                    self.long_press_capture = None;
9094                }
9095                crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
9096            }
9097        }
9098
9099        // Must run after the move is dispatched: the platform owns the gesture afterwards, so this
9100        // is the last chance for drag listeners to see the pointer leave and reset their state.
9101        self.promote_external_drag_to_platform(&event, cx);
9102
9103        // vue-native fork: the leave, now that its listeners have run. The
9104        // frame that drops the hover styles is asked for here.
9105        if pointer_leaves && std::mem::replace(&mut self.pointer_inside, false) {
9106            self.refresh();
9107        }
9108        self.vn_effect_pointer
9109            .update(was_inside, self.pointer_inside, pointer_moved, cx);
9110
9111        let caused_invalidation = self.invalidator.update_count() > update_count_before;
9112        if caused_invalidation {
9113            self.input_rate_tracker.borrow_mut().record_input();
9114        }
9115        #[cfg(feature = "profiler")]
9116        self.window_profiler.end_input(caused_invalidation);
9117
9118        DispatchEventResult {
9119            propagate: cx.propagate_event,
9120            default_prevented: self.default_prevented,
9121        }
9122    }
9123
9124    fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
9125        let PlatformInput::MouseMove(mouse_move) = event else {
9126            return;
9127        };
9128        if mouse_move.pressed_button != Some(MouseButton::Left) {
9129            return;
9130        }
9131        if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
9132            return;
9133        }
9134        if !self.platform_window.can_start_external_drag() {
9135            return;
9136        }
9137        let Some(payload_source) = cx
9138            .active_drag
9139            .as_mut()
9140            .and_then(|drag| drag.external_payload_source.take())
9141        else {
9142            return;
9143        };
9144        let Some(payload) = payload_source(self, cx) else {
9145            return;
9146        };
9147        if self.platform_window.start_external_drag(&payload)
9148            && cx.hand_active_drag_to_platform(self.handle.window_id())
9149        {
9150            self.refresh();
9151        }
9152    }
9153
9154    /// Whether recognized touch pans may use the platform's predicted touch
9155    /// positions ([`TouchEvent::predicted_position`]) to compensate for input
9156    /// latency. Defaults to true.
9157    pub fn touch_prediction_enabled(&self) -> bool {
9158        self.touch_prediction_enabled
9159    }
9160
9161    /// Sets whether recognized touch pans may use the platform's predicted
9162    /// touch positions. Disabling drops [`TouchEvent::predicted_position`]
9163    /// before gesture recognition, so pans track only raw touch positions.
9164    pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
9165        self.touch_prediction_enabled = enabled;
9166    }
9167
9168    /// Runs the portable gesture recognizer over a raw touch event and
9169    /// dispatches whatever it resolves (scroll steps, synthesized taps)
9170    /// through the ordinary mouse-event path.
9171    fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
9172        let mut event = event.clone();
9173        if !self.touch_prediction_enabled {
9174            event.predicted_position = None;
9175        }
9176        let recognized_gestures = self.touch_gestures.handle_event(&event);
9177        if event.phase == crate::TouchPhase::Started
9178            && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
9179        {
9180            self.dispatch_recognized_touch_gesture(touch_drag, cx);
9181        }
9182        if event.phase == crate::TouchPhase::Started
9183            && self.touch_gestures.pending_long_press().is_some()
9184        {
9185            self.long_press_capture = None;
9186        }
9187        let mut tapped = false;
9188        for gesture in recognized_gestures {
9189            tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
9190            self.dispatch_recognized_touch_gesture(gesture, cx);
9191        }
9192        if event.phase == crate::TouchPhase::Started {
9193            self.schedule_long_press_timer(cx);
9194        } else if self.touch_gestures.pending_long_press().is_none() {
9195            self.long_press_timer.take();
9196        }
9197        // The platform's touch-release handler may inspect the input handler
9198        // as soon as this dispatch returns (the web platform decides virtual
9199        // keyboard visibility there, inside the user gesture). Input handlers
9200        // are registered during draw, so draw now to make them reflect any
9201        // focus change the tap just caused.
9202        if tapped && self.invalidator.is_dirty() {
9203            self.draw(cx).clear(cx);
9204        }
9205        if self.touch_gestures.has_momentum() {
9206            self.schedule_touch_momentum_tick();
9207        }
9208    }
9209
9210    fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
9211        match gesture {
9212            RecognizedTouchGesture::Scroll(scroll_wheel) => {
9213                self.mouse_position = scroll_wheel.position;
9214                cx.propagate_event = true;
9215                self.dispatch_mouse_event(&scroll_wheel, cx);
9216            }
9217            RecognizedTouchGesture::Tap { down, up } => {
9218                self.mouse_position = up.position;
9219                cx.propagate_event = true;
9220                self.dispatch_mouse_event(&down, cx);
9221                cx.propagate_event = true;
9222                self.dispatch_mouse_event(&up, cx);
9223            }
9224            RecognizedTouchGesture::TouchDrag(touch_drag) => {
9225                self.mouse_position = touch_drag.start_position;
9226                cx.propagate_event = true;
9227                self.default_prevented = false;
9228                let started = touch_drag.phase == crate::TouchPhase::Started;
9229                self.dispatch_mouse_event(&touch_drag, cx);
9230                if started {
9231                    self.touch_gestures
9232                        .resolve_touch_drag(self.default_prevented);
9233                }
9234            }
9235            RecognizedTouchGesture::LongPress(long_press) => {
9236                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9237                    long_press.start_position
9238                } else {
9239                    long_press.position
9240                };
9241                cx.propagate_event = true;
9242                self.default_prevented = false;
9243                let started = long_press.phase == crate::TouchPhase::Started;
9244                let ended = matches!(
9245                    long_press.phase,
9246                    crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
9247                );
9248                self.dispatch_mouse_event(&long_press, cx);
9249                if started {
9250                    let claimed = self.default_prevented;
9251                    self.touch_gestures.resolve_long_press(claimed);
9252                    if !claimed {
9253                        self.long_press_capture = None;
9254                    }
9255                }
9256                if ended {
9257                    self.long_press_capture = None;
9258                }
9259            }
9260        }
9261    }
9262
9263    fn schedule_long_press_timer(&mut self, cx: &mut App) {
9264        self.long_press_timer.take();
9265        let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
9266            return;
9267        };
9268        self.long_press_timer = Some(self.spawn(cx, async move |cx| {
9269            cx.background_executor.timer(duration).await;
9270            cx.update(move |window, cx| {
9271                window.long_press_timer.take();
9272                if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
9273                    window.dispatch_recognized_touch_gesture(gesture, cx);
9274                }
9275            })
9276            .with_context(|| {
9277                format!(
9278                    "handling long-press timer for window {:?}",
9279                    cx.window_handle().window_id()
9280                )
9281            })
9282            .log_err();
9283        }));
9284    }
9285
9286    fn schedule_touch_momentum_tick(&mut self) {
9287        self.on_next_frame(|window, cx| {
9288            if let Some(gesture) = window.touch_gestures.tick_momentum() {
9289                window.dispatch_recognized_touch_gesture(gesture, cx);
9290            }
9291            if window.touch_gestures.has_momentum() {
9292                window.schedule_touch_momentum_tick();
9293            }
9294        });
9295    }
9296
9297    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
9298        self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position(), self.scale_factor);
9299
9300        // vue-native fork: the embedder narrows a press, a release or a wheel
9301        // to the hitboxes it is FOR, before anyone hears it.
9302        if let Some(refiner) = self.vn_hit_refiner.clone() {
9303            let kind = if event.is::<crate::MouseDownEvent>() {
9304                Some(VnHitKind::Down)
9305            } else if event.is::<MouseUpEvent>() {
9306                Some(VnHitKind::Up)
9307            } else if event.is::<crate::ScrollEvent>() {
9308                Some(VnHitKind::Scroll)
9309            } else {
9310                None
9311            };
9312            if let Some(kind) = kind {
9313                let position = self.mouse_position();
9314                refiner(kind, position, self, cx);
9315            }
9316        }
9317
9318        #[cfg(any(feature = "inspector", debug_assertions))]
9319        if self.is_inspector_picking(cx) {
9320            self.reset_cursor_style(cx);
9321            self.handle_inspector_mouse_event(event, cx);
9322            // When inspector is picking, all other mouse handling is skipped.
9323            return;
9324        }
9325
9326        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
9327
9328        // Capture phase, events bubble from back to front. Handlers for this phase are used for
9329        // special purposes, such as detecting events outside of a given Bounds.
9330        for listener in &mut mouse_listeners {
9331            let listener = listener.as_mut().unwrap();
9332            listener(event, DispatchPhase::Capture, self, cx);
9333            if !cx.propagate_event {
9334                break;
9335            }
9336        }
9337
9338        // Bubble phase, where most normal handlers do their work.
9339        if cx.propagate_event {
9340            for listener in mouse_listeners.iter_mut().rev() {
9341                let listener = listener.as_mut().unwrap();
9342                listener(event, DispatchPhase::Bubble, self, cx);
9343                if !cx.propagate_event {
9344                    break;
9345                }
9346            }
9347        }
9348
9349        self.rendered_frame.mouse_listeners = mouse_listeners;
9350
9351        if cx.has_active_drag() {
9352            if event.is::<MouseMoveEvent>() {
9353                // If this was a mouse move event, redraw the window so that the
9354                // active drag can follow the mouse cursor.
9355                self.refresh();
9356            } else if event.is::<MouseUpEvent>() {
9357                // If this was a mouse up event, cancel the active drag and redraw
9358                // the window.
9359                cx.active_drag = None;
9360                self.refresh();
9361            }
9362        }
9363
9364        // Auto-release pointer capture on mouse up
9365        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
9366            self.captured_hitbox = None;
9367        }
9368
9369        // Runs after the listeners so that a drag they start takes effect in this event. Resolving
9370        // the cursor any earlier would briefly select whatever is under the pointer instead.
9371        self.reset_cursor_style(cx);
9372    }
9373
9374    // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
9375    // we prefer the text input over bindings.
9376    fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
9377        let prefer_character_input = event
9378            .downcast_ref::<KeyDownEvent>()
9379            .is_some_and(|key_down_event| key_down_event.prefer_character_input);
9380        if !prefer_character_input {
9381            return InputPreference::KeyBindings;
9382        }
9383        let Some(mut input_handler) = self.platform_window.take_input_handler() else {
9384            return InputPreference::KeyBindings;
9385        };
9386        let accepts_text_input = input_handler.accepts_text_input(self, cx);
9387        self.platform_window.set_input_handler(input_handler);
9388        if accepts_text_input {
9389            InputPreference::CharacterInput
9390        } else {
9391            InputPreference::KeyBindings
9392        }
9393    }
9394
9395    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
9396        if self.invalidator.is_dirty() {
9397            self.draw(cx).clear(cx);
9398        }
9399        // vue-native fork: `Window::vn_key_event_seq`.
9400        self.vn_key_event_seq = self.vn_key_event_seq.wrapping_add(1);
9401
9402        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9403        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9404
9405        let mut keystroke: Option<Keystroke> = None;
9406
9407        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
9408            if event.modifiers.number_of_modifiers() == 0
9409                && self.pending_modifier.modifiers.number_of_modifiers() == 1
9410                && !self.pending_modifier.saw_other_input
9411            {
9412                let key = match self.pending_modifier.modifiers {
9413                    modifiers if modifiers.shift => Some("shift"),
9414                    modifiers if modifiers.control => Some("control"),
9415                    modifiers if modifiers.alt => Some("alt"),
9416                    modifiers if modifiers.platform => Some("platform"),
9417                    modifiers if modifiers.function => Some("function"),
9418                    _ => None,
9419                };
9420                if let Some(key) = key {
9421                    keystroke = Some(Keystroke {
9422                        key: key.to_string(),
9423                        key_char: None,
9424                        modifiers: Modifiers::default(),
9425                    });
9426                }
9427            }
9428
9429            if self.pending_modifier.modifiers.number_of_modifiers() == 0
9430                && event.modifiers.number_of_modifiers() == 1
9431            {
9432                self.pending_modifier.saw_other_input = false
9433            } else if event.modifiers.number_of_modifiers() > 1 {
9434                self.pending_modifier.saw_other_input = true
9435            }
9436            self.pending_modifier.modifiers = event.modifiers
9437        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
9438            self.pending_modifier.saw_other_input = true;
9439            keystroke = Some(key_down_event.keystroke.clone());
9440            if key_down_event.keystroke.key_char.is_some()
9441                && matches!(
9442                    cx.cursor_hide_mode,
9443                    CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
9444                )
9445            {
9446                cx.platform.hide_cursor_until_mouse_moves();
9447            }
9448        }
9449
9450        let Some(keystroke) = keystroke else {
9451            self.finish_dispatch_key_event(
9452                event,
9453                None,
9454                InputPreference::KeyBindings,
9455                dispatch_path,
9456                self.context_stack(),
9457                cx,
9458            );
9459            return;
9460        };
9461
9462        let input_preference = self.input_preference(event, cx);
9463
9464        cx.propagate_event = true;
9465        self.dispatch_keystroke_interceptors(
9466            &keystroke,
9467            input_preference,
9468            self.context_stack(),
9469            cx,
9470        );
9471        if !cx.propagate_event {
9472            self.finish_dispatch_key_event(
9473                event,
9474                Some(&keystroke),
9475                input_preference,
9476                dispatch_path,
9477                self.context_stack(),
9478                cx,
9479            );
9480            return;
9481        }
9482
9483        let mut currently_pending = self.pending_input.take().unwrap_or_default();
9484        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
9485            currently_pending = PendingInput::default();
9486        }
9487
9488        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
9489            currently_pending.keystrokes,
9490            keystroke.clone(),
9491            &dispatch_path,
9492        );
9493
9494        if !match_result.to_replay.is_empty() {
9495            self.replay_pending_input(match_result.to_replay, cx);
9496            cx.propagate_event = true;
9497        }
9498
9499        if !match_result.pending.is_empty() {
9500            let previous_timeout = currently_pending.timeout.take();
9501            currently_pending.keystrokes = match_result.pending;
9502            currently_pending.focus = self.focus;
9503
9504            let text_input_requires_timeout = event
9505                .downcast_ref::<KeyDownEvent>()
9506                .filter(|key_down| key_down.keystroke.key_char.is_some())
9507                .and_then(|_| self.platform_window.take_input_handler())
9508                .map_or(false, |mut input_handler| {
9509                    let accepts = input_handler.accepts_text_input(self, cx);
9510                    self.platform_window.set_input_handler(input_handler);
9511                    accepts
9512                });
9513
9514            let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
9515            let needs_timeout = previous_timeout.is_some()
9516                || match_result.pending_has_binding
9517                || text_input_requires_timeout
9518                || standalone_modifier;
9519            currently_pending.timeout = if needs_timeout {
9520                match previous_timeout {
9521                    Some(mut timeout) if timeout.is_paused() => {
9522                        timeout.reset_duration(PENDING_INPUT_TIMEOUT);
9523                        Some(timeout)
9524                    }
9525                    previous_timeout => {
9526                        drop(previous_timeout);
9527                        Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
9528                    }
9529                }
9530            } else {
9531                None
9532            };
9533            self.pending_input = Some(currently_pending);
9534            self.pending_input_changed(cx);
9535            cx.propagate_event = false;
9536            return;
9537        }
9538
9539        // Interceptors or replayed actions may have changed whether the input handler accepts text.
9540        let input_preference = self.input_preference(event, cx);
9541        if input_preference == InputPreference::KeyBindings {
9542            for binding in match_result.bindings {
9543                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
9544                if !cx.propagate_event {
9545                    self.dispatch_keystroke_observers(
9546                        &keystroke,
9547                        input_preference,
9548                        Some(binding.action.as_ref()),
9549                        match_result.context_stack,
9550                        cx,
9551                    );
9552                    self.pending_input_changed(cx);
9553                    return;
9554                }
9555            }
9556        }
9557
9558        self.finish_dispatch_key_event(
9559            event,
9560            Some(&keystroke),
9561            input_preference,
9562            dispatch_path,
9563            match_result.context_stack,
9564            cx,
9565        );
9566        self.pending_input_changed(cx);
9567    }
9568
9569    fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
9570        let (started_at, task) = self.start_pending_input_timeout(duration, cx);
9571        PendingInputTimeout {
9572            duration,
9573            remaining: duration,
9574            state: PendingInputTimeoutState::Running { started_at, task },
9575        }
9576    }
9577
9578    fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
9579        let started_at = cx.background_executor().now();
9580        let task = self.spawn(cx, async move |cx| {
9581            cx.background_executor.timer(remaining).await;
9582            cx.update(move |window, cx| {
9583                let Some(currently_pending) = window
9584                    .pending_input
9585                    .take()
9586                    .filter(|pending| pending.focus == window.focus)
9587                else {
9588                    return;
9589                };
9590
9591                let node_id = window.focus_node_id_in_rendered_frame(window.focus);
9592                let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
9593
9594                let to_replay = window
9595                    .rendered_frame
9596                    .dispatch_tree
9597                    .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
9598
9599                window.pending_input_changed(cx);
9600                window.replay_pending_input(to_replay, cx)
9601            })
9602            .with_context(|| {
9603                format!(
9604                    "handling pending input timeout for window {:?}",
9605                    cx.window_handle().window_id()
9606                )
9607            })
9608            .log_err();
9609        });
9610        (started_at, task)
9611    }
9612
9613    fn finish_dispatch_key_event(
9614        &mut self,
9615        event: &dyn Any,
9616        recognized_keystroke: Option<&Keystroke>,
9617        input_preference: InputPreference,
9618        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
9619        context_stack: Vec<KeyContext>,
9620        cx: &mut App,
9621    ) {
9622        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
9623        if !cx.propagate_event {
9624            return;
9625        }
9626
9627        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
9628        if !cx.propagate_event {
9629            return;
9630        }
9631
9632        if let Some(keystroke) = recognized_keystroke {
9633            self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
9634        }
9635    }
9636
9637    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
9638        self.pending_input_observers
9639            .clone()
9640            .retain(|callback| callback(self, cx));
9641    }
9642
9643    fn defer_pending_input_changed(&self, cx: &mut App) {
9644        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
9645        // current effect cycle, and only for this window.
9646        let window_handle = self.handle;
9647        cx.defer(move |cx| {
9648            window_handle
9649                .update(cx, |_, window, cx| {
9650                    window.pending_input_changed(cx);
9651                })
9652                .ok();
9653        });
9654    }
9655
9656    fn dispatch_key_down_up_event(
9657        &mut self,
9658        event: &dyn Any,
9659        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9660        cx: &mut App,
9661    ) {
9662        // Capture phase
9663        for node_id in dispatch_path {
9664            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9665
9666            for key_listener in node.key_listeners.clone() {
9667                key_listener(event, DispatchPhase::Capture, self, cx);
9668                if !cx.propagate_event {
9669                    return;
9670                }
9671            }
9672        }
9673
9674        // Bubble phase
9675        for node_id in dispatch_path.iter().rev() {
9676            // Handle low level key events
9677            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9678            for key_listener in node.key_listeners.clone() {
9679                key_listener(event, DispatchPhase::Bubble, self, cx);
9680                if !cx.propagate_event {
9681                    return;
9682                }
9683            }
9684        }
9685    }
9686
9687    fn dispatch_modifiers_changed_event(
9688        &mut self,
9689        event: &dyn Any,
9690        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9691        cx: &mut App,
9692    ) {
9693        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
9694            return;
9695        };
9696        for node_id in dispatch_path.iter().rev() {
9697            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9698            for listener in node.modifiers_changed_listeners.clone() {
9699                listener(event, self, cx);
9700                if !cx.propagate_event {
9701                    return;
9702                }
9703            }
9704        }
9705    }
9706
9707    /// Determine whether a potential multi-stroke key binding is in progress on this window.
9708    pub fn has_pending_keystrokes(&self) -> bool {
9709        self.pending_input().is_some()
9710    }
9711
9712    #[cfg(test)]
9713    pub(crate) fn pending_input_is_none(&self) -> bool {
9714        self.pending_input.is_none()
9715    }
9716
9717    pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
9718        if self.pending_input.take().is_some() {
9719            self.defer_pending_input_changed(cx);
9720        }
9721    }
9722
9723    /// Returns pending input that can still complete a multi-stroke key binding. Input left over
9724    /// from a previous focus can never complete one.
9725    pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
9726        self.pending_input
9727            .as_ref()
9728            .filter(|pending_input| pending_input.focus == self.focus)
9729            .map(|pending_input| PendingInputStatus {
9730                keystrokes: pending_input.keystrokes.as_slice(),
9731                timeout: pending_input
9732                    .timeout
9733                    .as_ref()
9734                    .map(PendingInputTimeout::status),
9735            })
9736    }
9737
9738    /// Pauses or resumes the current pending input timeout on behalf of `owner`.
9739    ///
9740    /// A paused timeout resumes automatically if `owner` is released. Returns whether the timeout
9741    /// state changed. A timeout paused by one owner cannot be resumed by another.
9742    pub fn set_pending_input_timeout_paused<T: 'static>(
9743        &mut self,
9744        owner: &Entity<T>,
9745        paused: bool,
9746        cx: &mut App,
9747    ) -> bool {
9748        let owner_id = owner.entity_id();
9749        if !paused {
9750            return self.resume_pending_input_timeout(owner_id, cx);
9751        }
9752
9753        let timeout = self
9754            .pending_input
9755            .as_ref()
9756            .filter(|pending_input| pending_input.focus == self.focus)
9757            .and_then(|pending_input| pending_input.timeout.as_ref());
9758        let Some(timeout) = timeout else {
9759            return false;
9760        };
9761        if timeout.is_paused() {
9762            return false;
9763        }
9764
9765        let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
9766            window.resume_pending_input_timeout(owner_id, cx);
9767        });
9768        let now = cx.background_executor().now();
9769        let changed = self
9770            .pending_input
9771            .as_mut()
9772            .filter(|pending_input| pending_input.focus == self.focus)
9773            .and_then(|pending_input| pending_input.timeout.as_mut())
9774            .is_some_and(|timeout| {
9775                timeout.pause(
9776                    PendingInputTimeoutPause {
9777                        owner_id,
9778                        _release_subscription: release_subscription,
9779                    },
9780                    now,
9781                )
9782            });
9783
9784        if changed {
9785            self.defer_pending_input_changed(cx);
9786        }
9787        changed
9788    }
9789
9790    fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
9791        let Some(remaining) = self
9792            .pending_input
9793            .as_ref()
9794            .and_then(|pending_input| pending_input.timeout.as_ref())
9795            .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
9796            .map(|timeout| timeout.remaining)
9797        else {
9798            return false;
9799        };
9800
9801        let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
9802        let changed = self
9803            .pending_input
9804            .as_mut()
9805            .and_then(|pending_input| pending_input.timeout.as_mut())
9806            .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
9807
9808        if changed {
9809            self.defer_pending_input_changed(cx);
9810        }
9811        changed
9812    }
9813
9814    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
9815    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
9816        self.pending_input()
9817            .map(|pending_input| pending_input.keystrokes())
9818    }
9819
9820    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
9821        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9822        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9823
9824        'replay: for replay in replays {
9825            let event = KeyDownEvent {
9826                keystroke: replay.keystroke.clone(),
9827                is_held: false,
9828                prefer_character_input: true,
9829            };
9830
9831            cx.propagate_event = true;
9832            for binding in replay.bindings {
9833                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
9834                if !cx.propagate_event {
9835                    self.dispatch_keystroke_observers(
9836                        &replay.keystroke,
9837                        InputPreference::KeyBindings,
9838                        Some(binding.action.as_ref()),
9839                        Vec::default(),
9840                        cx,
9841                    );
9842                    continue 'replay;
9843                }
9844            }
9845
9846            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
9847            if !cx.propagate_event {
9848                continue 'replay;
9849            }
9850            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
9851                && let Some(mut input_handler) = self.platform_window.take_input_handler()
9852            {
9853                input_handler.dispatch_input(&input, self, cx);
9854                self.platform_window.set_input_handler(input_handler)
9855            }
9856        }
9857    }
9858
9859    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
9860        focus_id
9861            .and_then(|focus_id| {
9862                self.rendered_frame
9863                    .dispatch_tree
9864                    .focusable_node_id(focus_id)
9865            })
9866            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
9867    }
9868
9869    fn dispatch_action_on_node(
9870        &mut self,
9871        node_id: DispatchNodeId,
9872        action: &dyn Action,
9873        cx: &mut App,
9874    ) {
9875        self.dispatch_action_on_node_inner(node_id, action, cx);
9876
9877        if !cx.propagate_event
9878            && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
9879            && self.last_input_was_keyboard()
9880        {
9881            cx.platform.hide_cursor_until_mouse_moves();
9882        }
9883    }
9884
9885    fn dispatch_action_on_node_inner(
9886        &mut self,
9887        node_id: DispatchNodeId,
9888        action: &dyn Action,
9889        cx: &mut App,
9890    ) {
9891        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9892
9893        // Capture phase for global actions.
9894        cx.propagate_event = true;
9895        if let Some(mut global_listeners) = cx
9896            .global_action_listeners
9897            .remove(&action.as_any().type_id())
9898        {
9899            for listener in &global_listeners {
9900                #[cfg(feature = "profiler")]
9901                self.window_profiler.begin_action_handler(action, cx);
9902                listener(action.as_any(), DispatchPhase::Capture, cx);
9903                #[cfg(feature = "profiler")]
9904                self.window_profiler.end_action_handler();
9905                if !cx.propagate_event {
9906                    break;
9907                }
9908            }
9909
9910            global_listeners.extend(
9911                cx.global_action_listeners
9912                    .remove(&action.as_any().type_id())
9913                    .unwrap_or_default(),
9914            );
9915
9916            cx.global_action_listeners
9917                .insert(action.as_any().type_id(), global_listeners);
9918        }
9919
9920        if !cx.propagate_event {
9921            return;
9922        }
9923
9924        // Capture phase for window actions.
9925        for node_id in &dispatch_path {
9926            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9927            for DispatchActionListener {
9928                action_type,
9929                listener,
9930            } in node.action_listeners.clone()
9931            {
9932                let any_action = action.as_any();
9933                if action_type == any_action.type_id() {
9934                    #[cfg(feature = "profiler")]
9935                    self.window_profiler.begin_action_handler(action, cx);
9936                    listener(any_action, DispatchPhase::Capture, self, cx);
9937                    #[cfg(feature = "profiler")]
9938                    self.window_profiler.end_action_handler();
9939
9940                    if !cx.propagate_event {
9941                        return;
9942                    }
9943                }
9944            }
9945        }
9946
9947        // Bubble phase for window actions.
9948        for node_id in dispatch_path.iter().rev() {
9949            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9950            for DispatchActionListener {
9951                action_type,
9952                listener,
9953            } in node.action_listeners.clone()
9954            {
9955                let any_action = action.as_any();
9956                if action_type == any_action.type_id() {
9957                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
9958                    #[cfg(feature = "profiler")]
9959                    self.window_profiler.begin_action_handler(action, cx);
9960                    listener(any_action, DispatchPhase::Bubble, self, cx);
9961                    #[cfg(feature = "profiler")]
9962                    self.window_profiler.end_action_handler();
9963
9964                    if !cx.propagate_event {
9965                        return;
9966                    }
9967                }
9968            }
9969        }
9970
9971        // Bubble phase for global actions.
9972        if let Some(mut global_listeners) = cx
9973            .global_action_listeners
9974            .remove(&action.as_any().type_id())
9975        {
9976            for listener in global_listeners.iter().rev() {
9977                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
9978
9979                #[cfg(feature = "profiler")]
9980                self.window_profiler.begin_action_handler(action, cx);
9981                listener(action.as_any(), DispatchPhase::Bubble, cx);
9982                #[cfg(feature = "profiler")]
9983                self.window_profiler.end_action_handler();
9984                if !cx.propagate_event {
9985                    break;
9986                }
9987            }
9988
9989            global_listeners.extend(
9990                cx.global_action_listeners
9991                    .remove(&action.as_any().type_id())
9992                    .unwrap_or_default(),
9993            );
9994
9995            cx.global_action_listeners
9996                .insert(action.as_any().type_id(), global_listeners);
9997        }
9998    }
9999
10000    /// Register the given handler to be invoked whenever the global of the given type
10001    /// is updated.
10002    pub fn observe_global<G: Global>(
10003        &mut self,
10004        cx: &mut App,
10005        f: impl Fn(&mut Window, &mut App) + 'static,
10006    ) -> Subscription {
10007        let window_handle = self.handle;
10008        let (subscription, activate) = cx.global_observers.insert_pending(
10009            TypeId::of::<G>(),
10010            Box::new(move |cx| {
10011                window_handle
10012                    .update(cx, |_, window, cx| f(window, cx))
10013                    .is_ok()
10014            }),
10015        );
10016        cx.defer(move |_| activate());
10017        subscription
10018    }
10019
10020    /// Focus the current window and bring it to the foreground at the platform level.
10021    pub fn activate_window(&self) {
10022        self.platform_window.activate();
10023    }
10024
10025    /// Shows a previously hidden window, optionally requesting focus. Returns
10026    /// false if unsupported; otherwise `completed` reports the native result.
10027    pub fn show_window(
10028        &self,
10029        activate: bool,
10030        should_show: impl FnOnce() -> bool + 'static,
10031        completed: impl FnOnce(bool) + 'static,
10032    ) -> bool {
10033        self.platform_window.show_window(activate, Box::new(should_show), Box::new(completed))
10034    }
10035
10036    /// Requests that the operating system draw attention to this window.
10037    pub fn request_attention(&self) {
10038        self.platform_window.request_attention();
10039    }
10040
10041    /// Minimize the current window at the platform level.
10042    pub fn minimize_window(&self) {
10043        self.platform_window.minimize();
10044    }
10045
10046    /// Toggle full screen status on the current window at the platform level.
10047    pub fn toggle_fullscreen(&self) {
10048        self.platform_window.toggle_fullscreen();
10049    }
10050
10051    /// Toggle simple (borderless) fullscreen, where the window covers the entire
10052    /// screen including the menu bar and, on notched displays, the area around the
10053    /// notch. Unlike [`Window::toggle_fullscreen`], this does not move the window
10054    /// into its own Mission Control space. Only has an effect on macOS.
10055    pub fn toggle_simple_fullscreen(&self) {
10056        self.platform_window.toggle_simple_fullscreen();
10057    }
10058
10059    /// Updates the IME panel position suggestions for languages like japanese, chinese.
10060    pub fn invalidate_character_coordinates(&self) {
10061        self.on_next_frame(|window, cx| {
10062            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
10063                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
10064                    window.platform_window.update_ime_position(bounds);
10065                }
10066                window.platform_window.set_input_handler(input_handler);
10067            }
10068        });
10069    }
10070
10071    /// Present a platform dialog.
10072    /// The provided message will be presented, along with buttons for each answer.
10073    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
10074    pub fn prompt<T>(
10075        &mut self,
10076        level: PromptLevel,
10077        message: &str,
10078        detail: Option<&str>,
10079        answers: &[T],
10080        cx: &mut App,
10081    ) -> oneshot::Receiver<usize>
10082    where
10083        T: Clone + Into<PromptButton>,
10084    {
10085        let prompt_builder = cx.prompt_builder.take();
10086        let Some(prompt_builder) = prompt_builder else {
10087            unreachable!("Re-entrant window prompting is not supported by GPUI");
10088        };
10089
10090        let answers = answers
10091            .iter()
10092            .map(|answer| answer.clone().into())
10093            .collect::<Vec<_>>();
10094
10095        let receiver = match &prompt_builder {
10096            PromptBuilder::Default => self
10097                .platform_window
10098                .prompt(level, message, detail, &answers)
10099                .unwrap_or_else(|| {
10100                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10101                }),
10102            PromptBuilder::Custom(_) => {
10103                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10104            }
10105        };
10106
10107        cx.prompt_builder = Some(prompt_builder);
10108
10109        receiver
10110    }
10111
10112    fn build_custom_prompt(
10113        &mut self,
10114        prompt_builder: &PromptBuilder,
10115        level: PromptLevel,
10116        message: &str,
10117        detail: Option<&str>,
10118        answers: &[PromptButton],
10119        cx: &mut App,
10120    ) -> oneshot::Receiver<usize> {
10121        let (sender, receiver) = oneshot::channel();
10122        let handle = PromptHandle::new(sender);
10123        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
10124        self.prompt = Some(handle);
10125        receiver
10126    }
10127
10128    /// Returns whether a prompt rendered by GPUI is currently active in this window.
10129    ///
10130    /// This is only true for prompts rendered in the window (see
10131    /// [`App::set_prompt_builder`]), not for platform-native prompt dialogs.
10132    pub fn has_active_prompt(&self) -> bool {
10133        self.prompt.is_some()
10134    }
10135
10136    /// Returns the current context stack.
10137    pub fn context_stack(&self) -> Vec<KeyContext> {
10138        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10139        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10140        dispatch_tree
10141            .dispatch_path(node_id)
10142            .iter()
10143            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
10144            .collect()
10145    }
10146
10147    /// Returns all available actions for the focused element.
10148    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
10149        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10150        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
10151        for action_type in cx.global_action_listeners.keys() {
10152            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
10153                let action = cx.actions.build_action_type(action_type).ok();
10154                if let Some(action) = action {
10155                    actions.insert(ix, action);
10156                }
10157            }
10158        }
10159        actions
10160    }
10161
10162    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
10163    /// returned in the order they were added. For display, the last binding should take precedence.
10164    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
10165        self.rendered_frame
10166            .dispatch_tree
10167            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
10168    }
10169
10170    /// Returns the highest precedence key binding that invokes an action on the currently focused
10171    /// element. This is more efficient than getting the last result of `bindings_for_action`.
10172    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
10173        self.rendered_frame
10174            .dispatch_tree
10175            .highest_precedence_binding_for_action(
10176                action,
10177                &self.rendered_frame.dispatch_tree.context_stack,
10178            )
10179    }
10180
10181    /// Returns the key bindings for an action in a context.
10182    pub fn bindings_for_action_in_context(
10183        &self,
10184        action: &dyn Action,
10185        context: KeyContext,
10186    ) -> Vec<KeyBinding> {
10187        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10188        dispatch_tree.bindings_for_action(action, &[context])
10189    }
10190
10191    /// Returns the highest precedence key binding for an action in a context. This is more
10192    /// efficient than getting the last result of `bindings_for_action_in_context`.
10193    pub fn highest_precedence_binding_for_action_in_context(
10194        &self,
10195        action: &dyn Action,
10196        context: KeyContext,
10197    ) -> Option<KeyBinding> {
10198        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10199        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
10200    }
10201
10202    /// Returns any bindings that would invoke an action on the given focus handle if it were
10203    /// focused. Bindings are returned in the order they were added. For display, the last binding
10204    /// should take precedence.
10205    pub fn bindings_for_action_in(
10206        &self,
10207        action: &dyn Action,
10208        focus_handle: &FocusHandle,
10209    ) -> Vec<KeyBinding> {
10210        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10211        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
10212            return vec![];
10213        };
10214        dispatch_tree.bindings_for_action(action, &context_stack)
10215    }
10216
10217    /// Returns the highest precedence key binding that would invoke an action on the given focus
10218    /// handle if it were focused. This is more efficient than getting the last result of
10219    /// `bindings_for_action_in`.
10220    pub fn highest_precedence_binding_for_action_in(
10221        &self,
10222        action: &dyn Action,
10223        focus_handle: &FocusHandle,
10224    ) -> Option<KeyBinding> {
10225        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10226        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
10227        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
10228    }
10229
10230    /// Find the bindings that can follow the current input sequence for the current context stack.
10231    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
10232        self.rendered_frame
10233            .dispatch_tree
10234            .possible_next_bindings_for_input(input, &self.context_stack())
10235    }
10236
10237    fn context_stack_for_focus_handle(
10238        &self,
10239        focus_handle: &FocusHandle,
10240    ) -> Option<Vec<KeyContext>> {
10241        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10242        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
10243        let context_stack: Vec<_> = dispatch_tree
10244            .dispatch_path(node_id)
10245            .into_iter()
10246            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
10247            .collect();
10248        Some(context_stack)
10249    }
10250
10251    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
10252    pub fn listener_for<T: 'static, E>(
10253        &self,
10254        view: &Entity<T>,
10255        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
10256    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
10257        let view = view.downgrade();
10258        move |e: &E, window: &mut Window, cx: &mut App| {
10259            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
10260        }
10261    }
10262
10263    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
10264    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
10265        &self,
10266        entity: &Entity<E>,
10267        f: Callback,
10268    ) -> impl Fn(&mut Window, &mut App) + 'static {
10269        let entity = entity.downgrade();
10270        move |window: &mut Window, cx: &mut App| {
10271            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
10272        }
10273    }
10274
10275    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
10276    /// If the callback returns false, the window won't be closed.
10277    pub fn on_window_should_close(
10278        &self,
10279        cx: &App,
10280        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
10281    ) {
10282        let mut cx = self.to_async(cx);
10283        self.platform_window.on_should_close(Box::new(move || {
10284            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
10285        }))
10286    }
10287
10288    /// Register an action listener on this node for the next frame. The type of action
10289    /// is determined by the first parameter of the given listener. When the next frame is rendered
10290    /// the listener will be cleared.
10291    ///
10292    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
10293    /// a specific need to register a listener yourself.
10294    ///
10295    /// This method should only be called as part of the paint phase of element drawing.
10296    pub fn on_action(
10297        &mut self,
10298        action_type: TypeId,
10299        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10300    ) {
10301        self.invalidator.debug_assert_paint();
10302
10303        self.next_frame
10304            .dispatch_tree
10305            .on_action(action_type, Rc::new(listener));
10306    }
10307
10308    /// Register a capturing action listener on this node for the next frame if the condition is true.
10309    /// The type of action is determined by the first parameter of the given listener. When the next
10310    /// frame is rendered the listener will be cleared.
10311    ///
10312    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
10313    /// a specific need to register a listener yourself.
10314    ///
10315    /// This method should only be called as part of the paint phase of element drawing.
10316    pub fn on_action_when(
10317        &mut self,
10318        condition: bool,
10319        action_type: TypeId,
10320        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10321    ) {
10322        self.invalidator.debug_assert_paint();
10323
10324        if condition {
10325            self.next_frame
10326                .dispatch_tree
10327                .on_action(action_type, Rc::new(listener));
10328        }
10329    }
10330
10331    /// Read information about the GPU backing this window.
10332    /// Currently returns None on Mac and Windows.
10333    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
10334        self.platform_window.gpu_specs()
10335    }
10336
10337    /// Perform titlebar double-click action.
10338    /// This is macOS specific.
10339    pub fn titlebar_double_click(&self) {
10340        self.platform_window
10341            .titlebar_double_click(self.is_resizable, self.is_minimizable);
10342    }
10343
10344    /// Gets the window's title at the platform level.
10345    /// This is macOS specific.
10346    pub fn window_title(&self) -> String {
10347        self.platform_window.get_title()
10348    }
10349
10350    /// Returns a list of all tabbed windows and their titles.
10351    /// This is macOS specific.
10352    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
10353        self.platform_window.tabbed_windows()
10354    }
10355
10356    /// Returns the tab bar visibility.
10357    /// This is macOS specific.
10358    pub fn tab_bar_visible(&self) -> bool {
10359        self.platform_window.tab_bar_visible()
10360    }
10361
10362    /// Merges all open windows into a single tabbed window.
10363    /// This is macOS specific.
10364    pub fn merge_all_windows(&self) {
10365        self.platform_window.merge_all_windows()
10366    }
10367
10368    /// Moves the tab to a new containing window.
10369    /// This is macOS specific.
10370    pub fn move_tab_to_new_window(&self) {
10371        self.platform_window.move_tab_to_new_window()
10372    }
10373
10374    /// Shows or hides the window tab overview.
10375    /// This is macOS specific.
10376    pub fn toggle_window_tab_overview(&self) {
10377        self.platform_window.toggle_window_tab_overview()
10378    }
10379
10380    /// Sets the tabbing identifier for the window.
10381    /// This is macOS specific.
10382    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
10383        self.platform_window
10384            .set_tabbing_identifier(tabbing_identifier)
10385    }
10386
10387    /// Request the OS to play an alert sound. On some platforms this is associated
10388    /// with the window, for others it's just a simple global function call.
10389    pub fn play_system_bell(&self) {
10390        self.platform_window.play_system_bell()
10391    }
10392
10393    /// Returns whether accessibility support is enabled for this window.
10394    ///
10395    /// This is false when the app was created with [`crate::Application::new_inaccessible`].
10396    /// Unlike [`Self::is_a11y_active`], this does not depend on whether assistive
10397    /// technology is currently connected, so it can be used to gate subscriptions
10398    /// that are only needed for accessibility.
10399    pub fn is_a11y_enabled(&self) -> bool {
10400        self.a11y.is_enabled()
10401    }
10402
10403    /// Returns whether accessibility features are active for this frame,
10404    /// i.e. whether assistive technology (such as a screen reader) is
10405    /// connected and an accessibility tree is being built.
10406    ///
10407    /// Use this to skip computing data during rendering that is only
10408    /// observable through the accessibility tree. When accessibility is
10409    /// activated, a redraw is forced, so gated work is recomputed before the
10410    /// next tree update is sent to the platform.
10411    ///
10412    /// See the [accessibility guide](crate::_accessibility) for an overview.
10413    pub fn is_a11y_active(&self) -> bool {
10414        self.a11y.is_active()
10415    }
10416
10417    /// Debug representation of the last frame's accessibility information.
10418    pub fn debug_a11y_tree_json(&self) -> Option<String> {
10419        self.a11y.debug_tree_json()
10420    }
10421
10422    /// Register a listener for an accessibility action on a specific node.
10423    /// The listener will be called when a screen reader requests the given
10424    /// action on the node identified by `node_id`.
10425    ///
10426    /// See the [accessibility guide](crate::_accessibility) for an overview.
10427    pub fn on_a11y_action(
10428        &mut self,
10429        node_id: accesskit::NodeId,
10430        action: accesskit::Action,
10431        listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
10432    ) {
10433        self.a11y
10434            .action_listeners
10435            .entry(node_id)
10436            .or_default()
10437            .push((action, Box::new(listener)));
10438    }
10439
10440    #[cfg(not(target_family = "wasm"))]
10441    pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
10442        // Take listeners out temporarily so the closures can borrow Window
10443        // mutably, then restore them afterward.
10444        if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
10445            let extra_data = request.data.as_ref();
10446            let mut matched = false;
10447            for (action, listener) in &mut listeners {
10448                if *action == request.action {
10449                    listener(extra_data, self, cx);
10450                    matched = true;
10451                }
10452            }
10453            self.a11y
10454                .action_listeners
10455                .insert(request.target_node, listeners);
10456            if matched {
10457                return;
10458            }
10459        }
10460
10461        // Fall back to built-in action handling.
10462        match request.action {
10463            accesskit::Action::Click => {
10464                if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
10465                    let center = bounds.center();
10466                    let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
10467                        button: MouseButton::Left,
10468                        position: center,
10469                        modifiers: Modifiers::default(),
10470                        click_count: 1,
10471                        first_mouse: false,
10472                    });
10473                    let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
10474                        button: MouseButton::Left,
10475                        position: center,
10476                        modifiers: Modifiers::default(),
10477                        click_count: 1,
10478                    });
10479                    self.dispatch_event(mouse_down, cx);
10480                    self.dispatch_event(mouse_up, cx);
10481                }
10482            }
10483            accesskit::Action::Focus => {
10484                if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
10485                    && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
10486                {
10487                    self.focus(&handle, cx);
10488                }
10489            }
10490            accesskit::Action::Blur => {
10491                self.blur(cx);
10492            }
10493            _ => {
10494                log::debug!(
10495                    "Unhandled a11y action: {:?} on {:?}",
10496                    request.action,
10497                    request.target_node
10498                );
10499            }
10500        }
10501    }
10502
10503    /// Toggles the inspector mode on this window.
10504    #[cfg(any(feature = "inspector", debug_assertions))]
10505    pub fn toggle_inspector(&mut self, cx: &mut App) {
10506        self.inspector = match self.inspector {
10507            None => Some(cx.new(|_| Inspector::new())),
10508            Some(_) => {
10509                self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
10510                self.rendered_frame.inspector_hitboxes = FxHashMap::default();
10511                self.next_frame.next_inspector_instance_ids = FxHashMap::default();
10512                self.next_frame.inspector_hitboxes = FxHashMap::default();
10513                None
10514            }
10515        };
10516        self.refresh();
10517    }
10518
10519    /// Returns true if the window is in inspector mode.
10520    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
10521        #[cfg(any(feature = "inspector", debug_assertions))]
10522        {
10523            if let Some(inspector) = &self.inspector {
10524                return inspector.read(_cx).is_picking();
10525            }
10526        }
10527        false
10528    }
10529
10530    /// Executes the provided function with mutable access to an inspector state.
10531    #[cfg(any(feature = "inspector", debug_assertions))]
10532    pub fn with_inspector_state<T: 'static, R>(
10533        &mut self,
10534        inspector_id: Option<&crate::InspectorElementId>,
10535        cx: &mut App,
10536        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
10537    ) -> Option<R> {
10538        let inspector_id = inspector_id?;
10539        let inspector = self.inspector.as_ref()?;
10540        if inspector.read(cx).active_element_id() != Some(inspector_id) {
10541            return None;
10542        }
10543        let inspector = inspector.clone();
10544        Some(inspector.update(cx, |inspector, _cx| {
10545            inspector.with_active_element_state(self, f)
10546        }))
10547    }
10548
10549    #[cfg(any(feature = "inspector", debug_assertions))]
10550    pub(crate) fn inspector_enabled(&self) -> bool {
10551        self.inspector.is_some()
10552    }
10553
10554    #[cfg(any(feature = "inspector", debug_assertions))]
10555    pub(crate) fn build_inspector_element_id(
10556        &mut self,
10557        path: crate::InspectorElementPath,
10558    ) -> crate::InspectorElementId {
10559        self.invalidator.debug_assert_paint_or_prepaint();
10560        let path = Rc::new(path);
10561        let next_instance_id = self
10562            .next_frame
10563            .next_inspector_instance_ids
10564            .entry(path.clone())
10565            .or_insert(0);
10566        let instance_id = *next_instance_id;
10567        *next_instance_id += 1;
10568        crate::InspectorElementId { path, instance_id }
10569    }
10570
10571    #[cfg(any(feature = "inspector", debug_assertions))]
10572    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
10573        if let Some(inspector) = self.inspector.take() {
10574            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
10575            inspector_element.prepaint_as_root(
10576                point(self.viewport_size.width - inspector_width, px(0.0)),
10577                size(inspector_width, self.viewport_size.height).into(),
10578                self,
10579                cx,
10580            );
10581            self.inspector = Some(inspector);
10582            Some(inspector_element)
10583        } else {
10584            None
10585        }
10586    }
10587
10588    #[cfg(any(feature = "inspector", debug_assertions))]
10589    fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
10590        if let Some(mut inspector_element) = inspector_element {
10591            inspector_element.paint(self, cx);
10592        };
10593    }
10594
10595    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
10596    /// inspect UI elements by clicking on them.
10597    #[cfg(any(feature = "inspector", debug_assertions))]
10598    pub fn insert_inspector_hitbox(
10599        &mut self,
10600        hitbox_id: HitboxId,
10601        inspector_id: Option<&crate::InspectorElementId>,
10602        cx: &App,
10603    ) {
10604        self.invalidator.debug_assert_paint_or_prepaint();
10605        if !self.is_inspector_picking(cx) {
10606            return;
10607        }
10608        if let Some(inspector_id) = inspector_id {
10609            self.next_frame
10610                .inspector_hitboxes
10611                .insert(hitbox_id, inspector_id.clone());
10612        }
10613    }
10614
10615    #[cfg(any(feature = "inspector", debug_assertions))]
10616    fn paint_inspector_hitbox(&mut self, cx: &App) {
10617        if let Some(inspector) = self.inspector.as_ref() {
10618            let inspector = inspector.read(cx);
10619            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
10620                && let Some(hitbox) = self
10621                    .next_frame
10622                    .hitboxes
10623                    .iter()
10624                    .find(|hitbox| hitbox.id == hitbox_id)
10625            {
10626                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
10627            }
10628        }
10629    }
10630
10631    #[cfg(any(feature = "inspector", debug_assertions))]
10632    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
10633        let Some(inspector) = self.inspector.clone() else {
10634            return;
10635        };
10636        if event.downcast_ref::<MouseMoveEvent>().is_some() {
10637            inspector.update(cx, |inspector, _cx| {
10638                if let Some((_, inspector_id)) =
10639                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10640                {
10641                    inspector.hover(inspector_id, self);
10642                }
10643            });
10644        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
10645            inspector.update(cx, |inspector, _cx| {
10646                if let Some((_, inspector_id)) =
10647                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10648                {
10649                    inspector.select(inspector_id, self);
10650                }
10651            });
10652        } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
10653            // This should be kept in sync with SCROLL_LINES in x11 platform.
10654            const SCROLL_LINES: f32 = 3.0;
10655            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
10656            let delta_y = event
10657                .delta
10658                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
10659                .y;
10660            if let Some(inspector) = self.inspector.clone() {
10661                inspector.update(cx, |inspector, _cx| {
10662                    if let Some(depth) = inspector.pick_depth.as_mut() {
10663                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
10664                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
10665                        if *depth < 0.0 {
10666                            *depth = 0.0;
10667                        } else if *depth > max_depth {
10668                            *depth = max_depth;
10669                        }
10670                        if let Some((_, inspector_id)) =
10671                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10672                        {
10673                            inspector.set_active_element_id(inspector_id, self);
10674                        }
10675                    }
10676                });
10677            }
10678        }
10679    }
10680
10681    #[cfg(any(feature = "inspector", debug_assertions))]
10682    fn hovered_inspector_hitbox(
10683        &self,
10684        inspector: &Inspector,
10685        frame: &Frame,
10686    ) -> Option<(HitboxId, crate::InspectorElementId)> {
10687        if let Some(pick_depth) = inspector.pick_depth {
10688            let depth = (pick_depth as i64).try_into().unwrap_or(0);
10689            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
10690            let skip_count = (depth as usize).min(max_skipped);
10691            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
10692                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
10693                    return Some((*hitbox_id, inspector_id.clone()));
10694                }
10695            }
10696        }
10697        None
10698    }
10699
10700    /// For testing: set the current modifier keys state.
10701    /// This does not generate any events.
10702    #[cfg(any(test, feature = "test-support"))]
10703    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
10704        self.modifiers = modifiers;
10705    }
10706
10707    /// For testing: simulate a mouse move event to the given position.
10708    /// This dispatches the event through the normal event handling path,
10709    /// which will trigger hover states and tooltips.
10710    #[cfg(any(test, feature = "test-support"))]
10711    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
10712        let event = PlatformInput::MouseMove(MouseMoveEvent {
10713            position,
10714            modifiers: self.modifiers,
10715            pressed_button: None,
10716        });
10717        let _ = self.dispatch_event(event, cx);
10718    }
10719
10720    #[inline(never)]
10721    fn take_element_state(
10722        &mut self,
10723        global_id: &GlobalElementId,
10724        state_type: TypeId,
10725    ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
10726        let key = (global_id.clone(), state_type);
10727        self.next_frame.accessed_element_states.push(key.clone());
10728        let state = self
10729            .next_frame
10730            .element_states
10731            .remove(&key)
10732            .or_else(|| self.rendered_frame.element_states.remove(&key));
10733        (key, state)
10734    }
10735
10736    #[inline(never)]
10737    fn insert_element_state(
10738        &mut self,
10739        key: (GlobalElementId, TypeId),
10740        state: ElementStateBox,
10741    ) -> Option<ElementStateBox> {
10742        self.next_frame.element_states.insert(key, state)
10743    }
10744
10745    #[inline(never)]
10746    fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
10747        cx.observe(state, move |_, cx| {
10748            cx.notify(current_view);
10749        })
10750        .detach();
10751    }
10752}
10753
10754// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
10755slotmap::new_key_type! {
10756    /// A unique identifier for a window.
10757    pub struct WindowId;
10758}
10759
10760impl WindowId {
10761    /// Converts this window ID to a `u64`.
10762    pub fn as_u64(&self) -> u64 {
10763        self.0.as_ffi()
10764    }
10765}
10766
10767impl From<u64> for WindowId {
10768    fn from(value: u64) -> Self {
10769        WindowId(slotmap::KeyData::from_ffi(value))
10770    }
10771}
10772
10773/// A handle to a window with a specific root view type.
10774/// Note that this does not keep the window alive on its own.
10775pub struct WindowHandle<V> {
10776    pub(crate) any_handle: AnyWindowHandle,
10777    state_type: PhantomData<fn(V) -> V>,
10778}
10779
10780impl_deref!([V] WindowHandle<V> => mut any_handle: AnyWindowHandle);
10781
10782impl<V> Debug for WindowHandle<V> {
10783    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10784        f.debug_struct("WindowHandle")
10785            .field("any_handle", &self.any_handle.id.as_u64())
10786            .finish()
10787    }
10788}
10789
10790impl<V: 'static + Render> WindowHandle<V> {
10791    /// Creates a new handle from a window ID.
10792    /// This does not check if the root type of the window is `V`.
10793    pub fn new(id: WindowId) -> Self {
10794        WindowHandle {
10795            any_handle: AnyWindowHandle {
10796                id,
10797                state_type: TypeId::of::<V>(),
10798                root_entity_type_name: std::any::type_name::<V>(),
10799            },
10800            state_type: PhantomData,
10801        }
10802    }
10803
10804    /// Get the root view out of this window.
10805    ///
10806    /// This will fail if the window is closed or if the root view's type does not match `V`.
10807    #[cfg(any(test, feature = "test-support"))]
10808    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
10809    where
10810        C: AppContext,
10811    {
10812        cx.update_window(self.any_handle, |root_view, _, _| {
10813            root_view
10814                .downcast::<V>()
10815                .map_err(|_| anyhow!("the type of the window's root view has changed"))
10816        })?
10817    }
10818
10819    /// Updates the root view of this window.
10820    ///
10821    /// This will fail if the window has been closed or if the root view's type does not match
10822    #[track_caller]
10823    pub fn update<C, R>(
10824        &self,
10825        cx: &mut C,
10826        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
10827    ) -> Result<R>
10828    where
10829        C: AppContext,
10830    {
10831        cx.update_window(self.any_handle, |root_view, window, cx| {
10832            let view = root_view
10833                .downcast::<V>()
10834                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
10835
10836            Ok(view.update(cx, |view, cx| update(view, window, cx)))
10837        })?
10838    }
10839
10840    /// Read the root view out of this window.
10841    ///
10842    /// This will fail if the window is closed or if the root view's type does not match `V`.
10843    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
10844        let x = cx
10845            .windows
10846            .get(self.id)
10847            .and_then(|window| {
10848                window
10849                    .as_deref()
10850                    .and_then(|window| window.root.clone())
10851                    .map(|root_view| root_view.downcast::<V>())
10852            })
10853            .context("window not found")?
10854            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
10855
10856        Ok(x.read(cx))
10857    }
10858
10859    /// Read the root view out of this window, with a callback
10860    ///
10861    /// This will fail if the window is closed or if the root view's type does not match `V`.
10862    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
10863    where
10864        C: AppContext,
10865    {
10866        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
10867    }
10868
10869    /// Read the root view pointer off of this window.
10870    ///
10871    /// This will fail if the window is closed or if the root view's type does not match `V`.
10872    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
10873    where
10874        C: AppContext,
10875    {
10876        cx.read_window(self, |root_view, _cx| root_view)
10877    }
10878
10879    /// Check if this window is 'active'.
10880    ///
10881    /// Will return `None` if the window is closed or currently
10882    /// borrowed.
10883    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
10884        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
10885            .ok()
10886    }
10887}
10888
10889impl<V> Copy for WindowHandle<V> {}
10890
10891impl<V> Clone for WindowHandle<V> {
10892    fn clone(&self) -> Self {
10893        *self
10894    }
10895}
10896
10897impl<V> PartialEq for WindowHandle<V> {
10898    fn eq(&self, other: &Self) -> bool {
10899        self.any_handle == other.any_handle
10900    }
10901}
10902
10903impl<V> Eq for WindowHandle<V> {}
10904
10905impl<V> Hash for WindowHandle<V> {
10906    fn hash<H: Hasher>(&self, state: &mut H) {
10907        self.any_handle.hash(state);
10908    }
10909}
10910
10911impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
10912    fn from(val: WindowHandle<V>) -> Self {
10913        val.any_handle
10914    }
10915}
10916
10917/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
10918#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
10919pub struct AnyWindowHandle {
10920    pub(crate) id: WindowId,
10921    state_type: TypeId,
10922    root_entity_type_name: &'static str,
10923}
10924
10925impl AnyWindowHandle {
10926    /// Get the ID of this window.
10927    pub fn window_id(&self) -> WindowId {
10928        self.id
10929    }
10930
10931    /// Returns the name of the window's declared root entity type.
10932    pub fn root_entity_type_name(&self) -> &'static str {
10933        self.root_entity_type_name
10934    }
10935
10936    /// Attempt to convert this handle to a window handle with a specific root view type.
10937    /// If the types do not match, this will return `None`.
10938    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
10939        if TypeId::of::<T>() == self.state_type {
10940            Some(WindowHandle {
10941                any_handle: *self,
10942                state_type: PhantomData,
10943            })
10944        } else {
10945            None
10946        }
10947    }
10948
10949    /// Updates the state of the root view of this window.
10950    ///
10951    /// This will fail if the window has been closed.
10952    #[track_caller]
10953    pub fn update<C, R>(
10954        self,
10955        cx: &mut C,
10956        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
10957    ) -> Result<R>
10958    where
10959        C: AppContext,
10960    {
10961        cx.update_window(self, update)
10962    }
10963
10964    /// Read the state of the root view of this window.
10965    ///
10966    /// This will fail if the window has been closed.
10967    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
10968    where
10969        C: AppContext,
10970        T: 'static,
10971    {
10972        let view = self
10973            .downcast::<T>()
10974            .context("the type of the window's root view has changed")?;
10975
10976        cx.read_window(&view, read)
10977    }
10978}
10979
10980impl HasWindowHandle for Window {
10981    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
10982        self.platform_window.window_handle()
10983    }
10984}
10985
10986impl HasDisplayHandle for Window {
10987    fn display_handle(
10988        &self,
10989    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
10990        self.platform_window.display_handle()
10991    }
10992}
10993
10994/// An identifier for an [`Element`].
10995///
10996/// Can be constructed with a string, a number, or both, as well
10997/// as other internal representations.
10998#[derive(Clone, Debug, Eq, PartialEq, Hash)]
10999pub enum ElementId {
11000    /// The ID of a View element
11001    View(EntityId),
11002    /// An integer ID.
11003    Integer(u64),
11004    /// A string based ID.
11005    Name(SharedString),
11006    /// A UUID.
11007    Uuid(Uuid),
11008    /// An ID that's equated with a focus handle.
11009    FocusHandle(FocusId),
11010    /// A combination of a name and an integer.
11011    NamedInteger(SharedString, u64),
11012    /// A path.
11013    Path(Arc<std::path::Path>),
11014    /// A code location.
11015    CodeLocation(core::panic::Location<'static>),
11016    /// A labeled child of an element.
11017    NamedChild(Arc<ElementId>, SharedString),
11018    /// A byte array ID (used for text-anchors)
11019    OpaqueId([u8; 20]),
11020}
11021
11022impl ElementId {
11023    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
11024    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
11025        Self::NamedInteger(name.into(), integer as u64)
11026    }
11027}
11028
11029impl Display for ElementId {
11030    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11031        match self {
11032            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
11033            ElementId::Integer(ix) => write!(f, "{}", ix)?,
11034            ElementId::Name(name) => write!(f, "{}", name)?,
11035            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
11036            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
11037            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
11038            ElementId::Path(path) => write!(f, "{}", path.display())?,
11039            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
11040            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
11041            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
11042        }
11043
11044        Ok(())
11045    }
11046}
11047
11048impl TryInto<SharedString> for ElementId {
11049    type Error = anyhow::Error;
11050
11051    fn try_into(self) -> anyhow::Result<SharedString> {
11052        if let ElementId::Name(name) = self {
11053            Ok(name)
11054        } else {
11055            anyhow::bail!("element id is not string")
11056        }
11057    }
11058}
11059
11060impl From<u64> for ElementId {
11061    fn from(id: u64) -> Self {
11062        ElementId::Integer(id)
11063    }
11064}
11065
11066impl From<usize> for ElementId {
11067    fn from(id: usize) -> Self {
11068        ElementId::Integer(id as u64)
11069    }
11070}
11071
11072impl From<i32> for ElementId {
11073    fn from(id: i32) -> Self {
11074        Self::Integer(id as u64)
11075    }
11076}
11077
11078impl From<SharedString> for ElementId {
11079    fn from(name: SharedString) -> Self {
11080        ElementId::Name(name)
11081    }
11082}
11083
11084impl From<String> for ElementId {
11085    fn from(name: String) -> Self {
11086        ElementId::Name(name.into())
11087    }
11088}
11089
11090impl From<Arc<str>> for ElementId {
11091    fn from(name: Arc<str>) -> Self {
11092        ElementId::Name(name.into())
11093    }
11094}
11095
11096impl From<Arc<std::path::Path>> for ElementId {
11097    fn from(path: Arc<std::path::Path>) -> Self {
11098        ElementId::Path(path)
11099    }
11100}
11101
11102impl From<&'static str> for ElementId {
11103    fn from(name: &'static str) -> Self {
11104        ElementId::Name(SharedString::new_static(name))
11105    }
11106}
11107
11108impl<'a> From<&'a FocusHandle> for ElementId {
11109    fn from(handle: &'a FocusHandle) -> Self {
11110        ElementId::FocusHandle(handle.id)
11111    }
11112}
11113
11114impl From<(&'static str, EntityId)> for ElementId {
11115    fn from((name, id): (&'static str, EntityId)) -> Self {
11116        ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
11117    }
11118}
11119
11120impl From<(&'static str, usize)> for ElementId {
11121    fn from((name, id): (&'static str, usize)) -> Self {
11122        ElementId::NamedInteger(SharedString::new_static(name), id as u64)
11123    }
11124}
11125
11126impl From<(SharedString, usize)> for ElementId {
11127    fn from((name, id): (SharedString, usize)) -> Self {
11128        ElementId::NamedInteger(name, id as u64)
11129    }
11130}
11131
11132impl From<(&'static str, u64)> for ElementId {
11133    fn from((name, id): (&'static str, u64)) -> Self {
11134        ElementId::NamedInteger(SharedString::new_static(name), id)
11135    }
11136}
11137
11138impl From<Uuid> for ElementId {
11139    fn from(value: Uuid) -> Self {
11140        Self::Uuid(value)
11141    }
11142}
11143
11144impl From<(&'static str, u32)> for ElementId {
11145    fn from((name, id): (&'static str, u32)) -> Self {
11146        ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
11147    }
11148}
11149
11150impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
11151    fn from((id, name): (ElementId, T)) -> Self {
11152        ElementId::NamedChild(Arc::new(id), name.into())
11153    }
11154}
11155
11156impl From<&'static core::panic::Location<'static>> for ElementId {
11157    fn from(location: &'static core::panic::Location<'static>) -> Self {
11158        ElementId::CodeLocation(*location)
11159    }
11160}
11161
11162impl From<[u8; 20]> for ElementId {
11163    fn from(opaque_id: [u8; 20]) -> Self {
11164        ElementId::OpaqueId(opaque_id)
11165    }
11166}
11167
11168/// A rectangle to be rendered in the window at the given position and size.
11169/// Passed as an argument [`Window::paint_quad`].
11170#[derive(Clone)]
11171pub struct PaintQuad {
11172    /// The bounds of the quad within the window.
11173    pub bounds: Bounds<Pixels>,
11174    /// The radii of the quad's corners.
11175    pub corner_radii: Corners<Pixels>,
11176    /// The background color of the quad.
11177    pub background: Background,
11178    /// The widths of the quad's borders.
11179    pub border_widths: Edges<Pixels>,
11180    /// The color of the quad's borders.
11181    pub border_color: Hsla,
11182    /// The style of the quad's borders.
11183    pub border_style: BorderStyle,
11184}
11185
11186/// Options for [`Window::paint_backdrop_blur_rect`].
11187#[derive(Clone, Copy, Debug)]
11188pub struct BackdropBlurEffect {
11189    /// Approximate uniform backdrop blur radius in logical pixels, matching the
11190    /// CSS `backdrop-filter: blur(<length>)` radius.
11191    ///
11192    /// Non-positive values are treated as zero. Renderers may clamp large radii
11193    /// to a fixed implementation limit.
11194    pub radius: Pixels,
11195    /// Tint color composited over the blurred backdrop.
11196    ///
11197    /// CSS models the element's own `background-color` as a separate paint over
11198    /// the filtered backdrop, so callers implementing `backdrop-filter` should
11199    /// leave this transparent and paint a normal quad instead.
11200    pub tint: Hsla,
11201}
11202
11203impl BackdropBlurEffect {
11204    /// Create a backdrop blur effect with a uniform CSS-like radius.
11205    ///
11206    /// Non-positive values disable blur while still allowing a tint to be painted.
11207    pub fn new(radius: Pixels) -> Self {
11208        Self {
11209            radius,
11210            ..Self::default()
11211        }
11212    }
11213
11214    /// Set a tint color composited over the blurred backdrop.
11215    pub fn tint(mut self, tint: impl Into<Hsla>) -> Self {
11216        self.tint = tint.into();
11217        self
11218    }
11219}
11220
11221impl Default for BackdropBlurEffect {
11222    fn default() -> Self {
11223        Self {
11224            radius: px(20.),
11225            tint: transparent_black(),
11226        }
11227    }
11228}
11229
11230impl PaintQuad {
11231    /// Sets the corner radii of the quad.
11232    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
11233        PaintQuad {
11234            corner_radii: corner_radii.into(),
11235            ..self
11236        }
11237    }
11238
11239    /// Sets the border widths of the quad.
11240    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
11241        PaintQuad {
11242            border_widths: border_widths.into(),
11243            ..self
11244        }
11245    }
11246
11247    /// Sets the border color of the quad.
11248    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
11249        PaintQuad {
11250            border_color: border_color.into(),
11251            ..self
11252        }
11253    }
11254
11255    /// Sets the background color of the quad.
11256    pub fn background(self, background: impl Into<Background>) -> Self {
11257        PaintQuad {
11258            background: background.into(),
11259            ..self
11260        }
11261    }
11262}
11263
11264/// vue-native: a host's smaller copy of an image that is about to be drawn
11265/// well below its own size.
11266///
11267/// The sprite atlas keeps one mip level and samples it LINEARLY, so a 1080 px
11268/// picture drawn at 40 px reads a 2×2 neighbourhood out of every 27×27 block
11269/// and aliases. [`Window::paint_image`] asks this function first, with the
11270/// image, the frame, and the size in device pixels the frame is about to be
11271/// drawn at; `Some` is drawn instead (its frame 0), from its own atlas tile.
11272/// `None` draws the image as it is. Called during paint, so it must be cheap
11273/// whenever it says `None`.
11274pub type ImageResampler =
11275    fn(&Arc<RenderImage>, usize, Size<DevicePixels>) -> Option<Arc<RenderImage>>;
11276
11277static IMAGE_RESAMPLER: std::sync::OnceLock<ImageResampler> = std::sync::OnceLock::new();
11278
11279/// vue-native: installs the process's [`ImageResampler`]. The first one
11280/// installed stays.
11281pub fn set_image_resampler(resampler: ImageResampler) {
11282    let _ = IMAGE_RESAMPLER.set(resampler);
11283}
11284
11285/// Creates a quad with the given parameters.
11286pub fn quad(
11287    bounds: Bounds<Pixels>,
11288    corner_radii: impl Into<Corners<Pixels>>,
11289    background: impl Into<Background>,
11290    border_widths: impl Into<Edges<Pixels>>,
11291    border_color: impl Into<Hsla>,
11292    border_style: BorderStyle,
11293) -> PaintQuad {
11294    PaintQuad {
11295        bounds,
11296        corner_radii: corner_radii.into(),
11297        background: background.into(),
11298        border_widths: border_widths.into(),
11299        border_color: border_color.into(),
11300        border_style,
11301    }
11302}
11303
11304/// Creates a filled quad with the given bounds and background color.
11305pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
11306    PaintQuad {
11307        bounds: bounds.into(),
11308        corner_radii: (0.).into(),
11309        background: background.into(),
11310        border_widths: (0.).into(),
11311        border_color: transparent_black(),
11312        border_style: BorderStyle::default(),
11313    }
11314}
11315
11316/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
11317pub fn outline(
11318    bounds: impl Into<Bounds<Pixels>>,
11319    border_color: impl Into<Hsla>,
11320    border_style: BorderStyle,
11321) -> PaintQuad {
11322    PaintQuad {
11323        bounds: bounds.into(),
11324        corner_radii: (0.).into(),
11325        background: transparent_black().into(),
11326        border_widths: (1.).into(),
11327        border_color: border_color.into(),
11328        border_style,
11329    }
11330}
11331
11332/// vue-native fork: [`Shadow::inset`] for an outer shadow drawn outside the
11333/// element's border box only (CSS). The shaders cut the element out of it.
11334pub(crate) const SHADOW_OUTSIDE_BOX: u32 = 0;
11335/// vue-native fork: [`Shadow::inset`] for an inset shadow.
11336pub(crate) const SHADOW_INSET: u32 = 1;
11337/// vue-native fork: [`Shadow::inset`] for an outer shadow that also fills the
11338/// area under the border box ([`Window::paint_drop_shadows_under_box`]).
11339pub(crate) const SHADOW_UNDER_BOX: u32 = 2;
11340
11341/// vue-native fork: an outer shadow's corner radius for a border-box corner of
11342/// radius `radius` and a spread of `spread` (CSS Backgrounds 3 §7.1.1). A
11343/// positive spread grows a rounded corner by the spread, and a corner rounded
11344/// by less than the spread by less, so a square corner stays square. A
11345/// negative spread shrinks it, down to 0.
11346fn spread_shadow_radius(radius: Pixels, spread: Pixels) -> Pixels {
11347    if spread <= Pixels::ZERO {
11348        return (radius + spread).max(Pixels::ZERO);
11349    }
11350    let ratio = radius / spread;
11351    if ratio >= 1.0 {
11352        radius + spread
11353    } else {
11354        radius + spread * (1.0 + (ratio - 1.0).powi(3))
11355    }
11356}
11357
11358#[inline(never)]
11359fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
11360    if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
11361        // SAFETY: The pointer is valid for the duration of the draw operation
11362        // that set it, and we're being called during that same draw.
11363        let arena_cell = unsafe { &*arena_pointer };
11364        callback(&mut arena_cell.borrow_mut());
11365        Ok(())
11366    } else {
11367        ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
11368    }
11369}
11370
11371#[cfg(test)]
11372mod tests {
11373    use std::{
11374        cell::{Cell, RefCell},
11375        path::PathBuf,
11376        rc::Rc,
11377        time::Duration,
11378    };
11379
11380    use crate::{
11381        AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
11382        Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
11383        ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
11384        InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
11385        MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
11386        Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
11387        TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
11388        UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
11389        size,
11390    };
11391
11392    #[gpui::test]
11393    async fn test_focus_handle_release(cx: &mut TestAppContext) {
11394        let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
11395        let handle_id = handle.id;
11396        let weak_handle = handle.downgrade();
11397        let retained = handle.clone();
11398        drop(handle);
11399
11400        cx.update(|_| {});
11401        cx.read(|cx| {
11402            let handles = cx.focus_handles.read();
11403            assert_eq!(handles.handles.len(), 2);
11404            assert!(handles.dropped_handles.is_empty());
11405        });
11406        assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
11407
11408        cx.background_spawn(async move { drop(retained) }).await;
11409        assert_eq!(weak_handle.upgrade(), None);
11410        cx.read(|cx| {
11411            assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
11412        });
11413        cx.update(|_| {});
11414        cx.read(|cx| {
11415            let handles = cx.focus_handles.read();
11416            assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
11417            assert!(handles.dropped_handles.is_empty());
11418        });
11419
11420        let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
11421        assert_eq!(weak_handle.upgrade(), None);
11422        cx.update(|cx| {
11423            drop(replacements);
11424            cx.defer(move |_| drop(survivor));
11425        });
11426        cx.read(|cx| {
11427            let handles = cx.focus_handles.read();
11428            assert_eq!(handles.handles.len(), 0);
11429            assert!(handles.dropped_handles.is_empty());
11430        });
11431    }
11432
11433    #[gpui::test]
11434    fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
11435        let windows = [
11436            cx.add_window(|_, _| EmptyView),
11437            cx.add_window(|_, _| EmptyView),
11438            cx.add_window(|_, _| EmptyView),
11439            cx.add_window(|_, _| EmptyView),
11440            cx.add_window(|_, _| EmptyView),
11441        ];
11442        let (handle, other_handle, survivor) =
11443            cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
11444        for window in &windows[..2] {
11445            window
11446                .update(cx, |_, window, cx| window.focus(&handle, cx))
11447                .expect("window exists");
11448        }
11449        windows[2]
11450            .update(cx, |_, window, cx| window.focus(&other_handle, cx))
11451            .expect("window exists");
11452        windows[3]
11453            .update(cx, |_, window, cx| window.focus(&survivor, cx))
11454            .expect("window exists");
11455
11456        cx.update(|cx| {
11457            for _ in 0..1_000 {
11458                drop(cx.focus_handle());
11459            }
11460            drop((handle, other_handle));
11461        });
11462        for window in &windows[..3] {
11463            window
11464                .update(cx, |_, window, _| assert_eq!(window.focus, None))
11465                .expect("window exists");
11466        }
11467        windows[3]
11468            .update(cx, |_, window, cx| {
11469                assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
11470                assert_eq!(window.focus_generation, 1);
11471            })
11472            .expect("window exists");
11473        windows[4]
11474            .update(cx, |_, window, _| {
11475                assert_eq!(window.focus, None);
11476                assert_eq!(window.focus_generation, 0);
11477            })
11478            .expect("window exists");
11479    }
11480
11481    #[gpui::test]
11482    fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
11483        let window = cx.add_window(|_, _| EmptyView);
11484        let platform_window = cx.test_window(window.into());
11485        {
11486            let app = cx.app.borrow_mut();
11487            platform_window.simulate_close();
11488            assert!(app.windows.contains_key(window.window_id()));
11489        }
11490        cx.run_until_parked();
11491        assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
11492    }
11493
11494    #[cfg(feature = "profiler")]
11495    #[gpui::test]
11496    fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
11497        use crate::FrameRequestSource;
11498        use crate::profiler::journal::{
11499            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11500        };
11501        use scheduler::Instant;
11502
11503        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11504        let window = cx.add_window(|_, _| EmptyView);
11505        let platform_window = cx.test_window(window.into());
11506        platform_window.simulate_frame_request(RequestFrameOptions::default());
11507        let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
11508        let mut collector = journal.collector();
11509
11510        for (signal_at, source) in [
11511            (Some(Instant::now()), FrameRequestSource::NativeCallback),
11512            (Some(Instant::now()), FrameRequestSource::LocalSchedule),
11513            (None, FrameRequestSource::NativeCallback),
11514        ] {
11515            platform_window.simulate_frame_request(RequestFrameOptions {
11516                signal_at,
11517                signal_source: source,
11518                require_presentation: true,
11519                ..Default::default()
11520            });
11521            let entries = collector.collect_unseen().entries;
11522            let signal_index = entries
11523                .iter()
11524                .position(|entry| {
11525                    matches!(
11526                        entry,
11527                        ForegroundJournalEntry::PlatformSignal(signal)
11528                            if signal.window_id == window.window_id()
11529                                && signal.signal_at == signal_at
11530                                && signal.source == source
11531                                && signal_at.is_none_or(|at| signal.handled_at >= at)
11532                    )
11533                })
11534                .expect("frame request metadata");
11535            let skip_index = entries
11536                .iter()
11537                .position(|entry| {
11538                    matches!(
11539                        entry,
11540                        ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11541                            if skipped.window_id == window.window_id()
11542                                && skipped.reason == FrameSkipReason::NoRenderNeeded
11543                    )
11544                })
11545                .expect("completed no-render boundary");
11546            assert!(signal_index < skip_index);
11547        }
11548    }
11549
11550    #[cfg(feature = "profiler")]
11551    #[gpui::test]
11552    fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
11553        use crate::profiler::journal::{
11554            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11555        };
11556        use scheduler::Instant;
11557
11558        // Test mode draws during effect flushing, bypassing platform frame throttling.
11559        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11560        let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
11561        let mut collector = journal.collector();
11562        for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
11563            // Keep the throttle closed without depending on short wall-clock deadlines.
11564            let window = cx
11565                .app
11566                .borrow_mut()
11567                .open_window(
11568                    WindowOptions {
11569                        inactive_frame_interval: Some(Duration::from_secs(3600)),
11570                        ..Default::default()
11571                    },
11572                    |_, cx| cx.new(|_| EmptyView),
11573                )
11574                .expect("open inactive test window");
11575            let platform_window = cx.test_window(window.into());
11576            platform_window.simulate_active_status_change(false);
11577            platform_window.simulate_frame_request(RequestFrameOptions::default());
11578            let callback_ran = Rc::new(Cell::new(false));
11579            let draws_before = window
11580                .update(cx, |_, window, _| {
11581                    let draws_before = window
11582                        .frame_duration_snapshot()
11583                        .draw_duration_histogram
11584                        .len();
11585                    if initially_dirty {
11586                        window.refresh();
11587                    }
11588                    if schedule_callback {
11589                        window.on_next_frame({
11590                            let callback_ran = callback_ran.clone();
11591                            move |window, _| {
11592                                callback_ran.set(true);
11593                                window.refresh();
11594                            }
11595                        });
11596                    }
11597                    draws_before
11598                })
11599                .expect("schedule throttled frame");
11600            // Skips only seal retained work, so give the throttled skip some.
11601            let input_at = Instant::now();
11602            journal::record_input(journal::InputTiming {
11603                kind: "test",
11604                start: input_at,
11605                end: input_at,
11606                caused_invalidation: false,
11607            });
11608            collector.collect_unseen();
11609            let wakes_before = platform_window.frame_wake_count();
11610            platform_window.simulate_frame_request(RequestFrameOptions {
11611                signal_at: Some(Instant::now()),
11612                ..Default::default()
11613            });
11614            window
11615                .update(cx, |_, window, _| {
11616                    assert_eq!(
11617                        window
11618                            .frame_duration_snapshot()
11619                            .draw_duration_histogram
11620                            .len(),
11621                        draws_before,
11622                    );
11623                })
11624                .expect("inspect deferred frame");
11625            assert!(!callback_ran.get());
11626            assert!(platform_window.frame_scheduled());
11627            assert!(platform_window.frame_wake_count() > wakes_before);
11628            assert!(collector.collect_unseen().entries.iter().any(|entry| {
11629                matches!(
11630                    entry,
11631                    ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11632                        if skipped.window_id == window.window_id()
11633                            && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
11634                )
11635            }));
11636            platform_window.simulate_frame_request(RequestFrameOptions {
11637                signal_at: Some(Instant::now()),
11638                require_presentation: true,
11639                ..Default::default()
11640            });
11641            window
11642                .update(cx, |_, window, _| {
11643                    assert_eq!(
11644                        window
11645                            .frame_duration_snapshot()
11646                            .draw_duration_histogram
11647                            .len(),
11648                        draws_before + 1,
11649                    );
11650                })
11651                .expect("inspect presented frame");
11652            assert_eq!(callback_ran.get(), schedule_callback);
11653        }
11654    }
11655
11656    /// A stale cache is only visible if the snapshot reports GPUI's cached
11657    /// value separately from what the platform reports now.
11658    #[gpui::test]
11659    fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
11660        use crate::WindowVisibility;
11661
11662        let window = cx.add_window(|_, _| EmptyView);
11663        let window_id = window.window_id().as_u64();
11664        let window_state = |cx: &mut TestAppContext| {
11665            let state = cx.update(|cx| cx.debug_state());
11666            state["windows"]
11667                .as_array()
11668                .and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
11669                .cloned()
11670                .expect("the open window is listed")
11671        };
11672
11673        let state = window_state(cx);
11674        assert_eq!(state["visibility"]["cached"], "Visible");
11675        assert_eq!(state["visibility"]["platform"], "Visible");
11676
11677        cx.test_window(window.into())
11678            .simulate_visibility_change(WindowVisibility::Hidden);
11679        let state = window_state(cx);
11680        assert_eq!(state["visibility"]["cached"], "Hidden");
11681        assert_eq!(state["visibility"]["platform"], "Hidden");
11682    }
11683
11684    /// Visibility transitions reach observers exactly once each, with the new
11685    /// state already stored on the window, and never wake the platform for a
11686    /// frame: the platform requests one itself when it resumes presenting.
11687    #[gpui::test]
11688    fn test_window_visibility(cx: &mut TestAppContext) {
11689        use crate::WindowVisibility;
11690
11691        let window = cx.add_window(|_, _| EmptyView);
11692        let observed = Rc::new(RefCell::new(Vec::new()));
11693        let _subscription = window
11694            .update(cx, {
11695                let observed = observed.clone();
11696                move |_, window, _| {
11697                    assert_eq!(window.visibility(), WindowVisibility::Visible);
11698                    assert!(window.is_visible());
11699                    window.observe_window_visibility(move |visibility, window, _| {
11700                        assert_eq!(window.visibility(), visibility);
11701                        observed.borrow_mut().push(visibility);
11702                    })
11703                }
11704            })
11705            .unwrap();
11706        let test_window = cx.test_window(window.into());
11707        let frame_wake_count = test_window.frame_wake_count();
11708
11709        test_window.simulate_visibility_change(WindowVisibility::Hidden);
11710        assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
11711        window
11712            .update(cx, |_, window, _| assert!(!window.is_visible()))
11713            .unwrap();
11714
11715        // Platforms may report the same state again; observers only see changes.
11716        test_window.simulate_visibility_change(WindowVisibility::Hidden);
11717        assert_eq!(observed.borrow().len(), 1);
11718
11719        test_window.simulate_visibility_change(WindowVisibility::Visible);
11720        assert_eq!(
11721            *observed.borrow(),
11722            [WindowVisibility::Hidden, WindowVisibility::Visible]
11723        );
11724        window
11725            .update(cx, |_, window, _| assert!(window.is_visible()))
11726            .unwrap();
11727        assert_eq!(test_window.frame_wake_count(), frame_wake_count);
11728    }
11729
11730    /// App learns display state from the platform's display notifications,
11731    /// and a window from the platform's report of which display it is on.
11732    #[gpui::test]
11733    fn test_display_tracking(cx: &mut TestAppContext) {
11734        use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
11735
11736        let sixty_hertz = Duration::from_secs(1) / 60;
11737        let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
11738        let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
11739
11740        let display_events = Rc::new(RefCell::new(Vec::new()));
11741        let _display_subscription = cx.update({
11742            let display_events = display_events.clone();
11743            move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
11744        });
11745
11746        let window = cx.add_window(|window, cx| DisplayTracker {
11747            refresh_intervals: Vec::new(),
11748            _subscription: cx.observe_window_display(
11749                window,
11750                |tracker: &mut DisplayTracker, window, cx| {
11751                    tracker.refresh_intervals.push(window.refresh_interval(cx));
11752                },
11753            ),
11754        });
11755        let window_notifications = Rc::new(RefCell::new(Vec::new()));
11756        let _window_subscription = window
11757            .update(cx, {
11758                let window_notifications = window_notifications.clone();
11759                move |_, window, cx| {
11760                    assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
11761                    window.observe_window_display(move |window, cx| {
11762                        window_notifications
11763                            .borrow_mut()
11764                            .push((window.display_id, window.refresh_interval(cx)));
11765                    })
11766                }
11767            })
11768            .unwrap();
11769        let test_window = cx.test_window(window.into());
11770
11771        // The window may hear that it moved before App hears the display was
11772        // connected. App learns about the display before the window's
11773        // observers run, and the platform's later notification changes
11774        // nothing.
11775        cx.test_platform()
11776            .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
11777        test_window.simulate_move_to_display(DisplayId(2));
11778        assert_eq!(
11779            window_notifications.take(),
11780            [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
11781        );
11782        assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
11783        cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
11784        assert!(window_notifications.borrow().is_empty());
11785
11786        // Platforms may report a move that isn't one.
11787        test_window.simulate_move_to_display(DisplayId(2));
11788        assert!(window_notifications.borrow().is_empty());
11789
11790        cx.simulate_display_refresh_interval_change(
11791            DisplayId(2),
11792            Some(one_hundred_forty_four_hertz),
11793        );
11794        assert_eq!(
11795            window_notifications.take(),
11796            [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
11797        );
11798
11799        // Changes to a display the window isn't on don't notify it.
11800        cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
11801        cx.simulate_display_removed(DisplayId(1));
11802        assert!(window_notifications.borrow().is_empty());
11803
11804        assert_eq!(
11805            display_events.take(),
11806            [
11807                DisplayEvent::Changed {
11808                    id: DisplayId(2),
11809                    changes: DisplayChanges::REFRESH_INTERVAL,
11810                },
11811                DisplayEvent::Changed {
11812                    id: DisplayId(1),
11813                    changes: DisplayChanges::REFRESH_INTERVAL,
11814                },
11815                DisplayEvent::Removed(DisplayId(1)),
11816            ]
11817        );
11818        window
11819            .update(cx, |tracker, _, _| {
11820                assert_eq!(
11821                    tracker.refresh_intervals,
11822                    [
11823                        Some(one_hundred_twenty_hertz),
11824                        Some(one_hundred_forty_four_hertz)
11825                    ]
11826                );
11827            })
11828            .unwrap();
11829
11830        struct DisplayTracker {
11831            refresh_intervals: Vec<Option<Duration>>,
11832            _subscription: Subscription,
11833        }
11834
11835        impl Render for DisplayTracker {
11836            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11837                Empty
11838            }
11839        }
11840    }
11841
11842    #[gpui::test]
11843    fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
11844        use crate::Subscription;
11845
11846        struct BoundsObserver {
11847            _subscription: Subscription,
11848        }
11849
11850        impl Render for BoundsObserver {
11851            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11852                Empty
11853            }
11854        }
11855
11856        let opened_window = Rc::new(Cell::new(None));
11857        let window = cx.add_window({
11858            let opened_window = opened_window.clone();
11859            move |window, cx| BoundsObserver {
11860                _subscription: cx.observe_window_bounds(window, move |_, _, cx| {
11861                    let handle = cx
11862                        .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
11863                        .unwrap();
11864                    opened_window.set(Some(AnyWindowHandle::from(handle)));
11865                }),
11866            }
11867        });
11868        window
11869            .update(cx, |_, window, _| window.activate_window())
11870            .unwrap();
11871
11872        let new_size = size(px(400.), px(300.));
11873        cx.simulate_window_resize(window.into(), new_size);
11874
11875        let opened_window = opened_window
11876            .take()
11877            .expect("bounds observer should have opened a window");
11878        let opened_size = opened_window
11879            .update(cx, |_, window, _| window.bounds().size)
11880            .unwrap();
11881        assert_eq!(opened_size, new_size);
11882    }
11883
11884    #[gpui::test]
11885    fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
11886        let window = cx.add_window(|_, _| EmptyView);
11887        let mut platform_window = cx.test_window(window.into());
11888        platform_window.simulate_resize(size(px(400.), px(800.)));
11889        window
11890            .update(cx, |_, window, _| {
11891                assert_eq!(
11892                    window.visual_viewport_bounds(),
11893                    Bounds::new(Point::default(), size(px(400.), px(800.)))
11894                );
11895                assert_eq!(
11896                    window.fully_visible_bounds(),
11897                    window.visual_viewport_bounds()
11898                );
11899            })
11900            .unwrap();
11901
11902        platform_window.simulate_frame_request(RequestFrameOptions::default());
11903        let wakes = platform_window.frame_wake_count();
11904        let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
11905        platform_window.simulate_visual_viewport_change(visual_bounds);
11906        assert!(platform_window.frame_wake_count() > wakes);
11907        platform_window.simulate_frame_request(RequestFrameOptions::default());
11908        let wakes = platform_window.frame_wake_count();
11909        let insets = crate::WindowInsets {
11910            safe_area: crate::Edges {
11911                top: px(60.),
11912                right: px(20.),
11913                bottom: px(30.),
11914                left: px(-10.),
11915            },
11916            ime: crate::Edges {
11917                bottom: px(350.),
11918                ..Default::default()
11919            },
11920            ..Default::default()
11921        };
11922        platform_window.simulate_insets_change(insets.clone());
11923        assert!(platform_window.frame_wake_count() > wakes);
11924        window
11925            .update(cx, |_, window, cx| {
11926                let focus = cx.focus_handle();
11927                window.focus(&focus, cx);
11928                assert_eq!(window.insets(), insets);
11929                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
11930                assert_eq!(window.visual_viewport_bounds(), visual_bounds);
11931                assert_eq!(
11932                    window.fully_visible_bounds(),
11933                    Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
11934                );
11935                window.request_virtual_keyboard();
11936                window.dismiss_virtual_keyboard();
11937                assert!(focus.is_focused(window));
11938                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
11939            })
11940            .unwrap();
11941        assert_eq!(platform_window.virtual_keyboard_requests(), 1);
11942        assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
11943
11944        platform_window.simulate_insets_change(crate::WindowInsets {
11945            safe_area: crate::Edges {
11946                top: px(900.),
11947                left: px(500.),
11948                ..Default::default()
11949            },
11950            ..Default::default()
11951        });
11952        window
11953            .update(cx, |_, window, _| {
11954                assert_eq!(
11955                    window.fully_visible_bounds().size,
11956                    size(Pixels::ZERO, Pixels::ZERO)
11957                );
11958            })
11959            .unwrap();
11960
11961        // Some backends update geometry snapshots without delivering inset callbacks.
11962        use crate::PlatformWindow as _;
11963        platform_window.on_insets_changed(Box::new(|_| {}));
11964        platform_window.simulate_insets_change(crate::WindowInsets::default());
11965        window
11966            .update(cx, |_, window, _| {
11967                assert_eq!(window.insets(), crate::WindowInsets::default());
11968            })
11969            .unwrap();
11970    }
11971
11972    #[test]
11973    fn frame_throttle_tracks_display_refreshes() {
11974        let start = super::Instant::now();
11975        for (elapsed, interval) in [
11976            (Duration::from_micros(16_666), Duration::from_micros(16_667)),
11977            (Duration::from_micros(33_332), Duration::from_micros(33_333)),
11978        ] {
11979            let mut pacer = super::FramePacer::default();
11980            assert!(!pacer.should_defer(start, Some(interval)));
11981            assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
11982            assert!(!pacer.should_defer(start + elapsed, Some(interval)));
11983        }
11984    }
11985
11986    #[test]
11987    fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
11988        let start = super::Instant::now();
11989        let interval = Duration::from_micros(33_333);
11990        let mut pacer = super::FramePacer::default();
11991        assert!(!pacer.should_defer(start, Some(interval)));
11992        let delayed_frame = start + interval + Duration::from_millis(5);
11993        assert!(!pacer.should_defer(delayed_frame, Some(interval)));
11994        assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
11995        assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
11996
11997        // Even a stall just short of another full interval must not cause a burst.
11998        let after_stall = start + interval * 4 - Duration::from_millis(1);
11999        assert!(!pacer.should_defer(after_stall, Some(interval)));
12000        assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
12001        assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
12002        // Mandatory presentation bypasses the limit and establishes a fresh cadence.
12003        let mandatory_frame = after_stall + interval + Duration::from_millis(2);
12004        assert!(!pacer.should_defer(mandatory_frame, None));
12005        assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
12006    }
12007
12008    #[test]
12009    fn power_modes_preserve_frame_limits() {
12010        let options = WindowOptions::default();
12011        for (power_mode, active_interval, thermal_interval) in [
12012            (
12013                crate::PowerMode::LowPower,
12014                Some(Duration::from_micros(33_333)),
12015                Duration::from_micros(33_333),
12016            ),
12017            (
12018                crate::PowerMode::Unknown,
12019                None,
12020                Duration::from_micros(16_667),
12021            ),
12022            (
12023                crate::PowerMode::Balanced,
12024                None,
12025                Duration::from_micros(16_667),
12026            ),
12027            (
12028                crate::PowerMode::HighPower,
12029                None,
12030                Duration::from_micros(16_667),
12031            ),
12032        ] {
12033            assert_eq!(
12034                super::minimum_frame_interval(
12035                    true,
12036                    false,
12037                    options.inactive_frame_interval,
12038                    options.low_power_frame_interval,
12039                    options.thermal_frame_interval,
12040                    ThermalState::Nominal,
12041                    power_mode,
12042                ),
12043                active_interval,
12044            );
12045            assert_eq!(
12046                super::minimum_frame_interval(
12047                    true,
12048                    false,
12049                    options.inactive_frame_interval,
12050                    options.low_power_frame_interval,
12051                    options.thermal_frame_interval,
12052                    ThermalState::Serious,
12053                    power_mode,
12054                ),
12055                Some(thermal_interval),
12056            );
12057        }
12058    }
12059
12060    #[test]
12061    fn frame_limits_combine_enabled_intervals() {
12062        let short = Some(Duration::from_millis(10));
12063        let long = Some(Duration::from_millis(100));
12064        for (inactive, low_power, thermal, expected) in [
12065            (long, short, short, long),
12066            (short, long, short, long),
12067            (short, short, long, long),
12068            (long, None, None, long),
12069            (None, long, None, long),
12070            (None, None, long, long),
12071            (None, None, None, None),
12072        ] {
12073            assert_eq!(
12074                super::minimum_frame_interval(
12075                    true,
12076                    true,
12077                    inactive,
12078                    low_power,
12079                    thermal,
12080                    ThermalState::Critical,
12081                    crate::PowerMode::LowPower,
12082                ),
12083                expected,
12084            );
12085        }
12086        assert_eq!(
12087            super::minimum_frame_interval(
12088                false,
12089                true,
12090                long,
12091                long,
12092                long,
12093                ThermalState::Critical,
12094                crate::PowerMode::LowPower,
12095            ),
12096            None,
12097        );
12098    }
12099
12100    struct EmptyView;
12101
12102    impl Render for EmptyView {
12103        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12104            div()
12105        }
12106    }
12107
12108    struct OpensWindowOnPaint {
12109        opened: Rc<Cell<bool>>,
12110    }
12111
12112    impl Render for OpensWindowOnPaint {
12113        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12114            let opened = self.opened.clone();
12115            div()
12116                .size_full()
12117                .child(canvas(
12118                    |_, _, _| {},
12119                    move |_, _, _window, cx| {
12120                        if !opened.replace(true) {
12121                            cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12122                                .unwrap();
12123                        }
12124                    },
12125                ))
12126                // Siblings painted after the canvas: their elements were
12127                // allocated in the arena before the nested draw, so they detect
12128                // a mid-draw arena clear when painted afterwards.
12129                .child(div().child("after"))
12130        }
12131    }
12132
12133    /// Opening a window synchronously draws it and requests an element arena
12134    /// clear. When that happens from within another window's draw (here: from
12135    /// an element's paint), the clear must be deferred until the outer draw
12136    /// finishes, or the outer draw's arena-allocated elements would be freed
12137    /// out from under it.
12138    #[test]
12139    fn test_window_opened_during_draw_defers_arena_clear() {
12140        let mut cx = TestAppContext::single();
12141
12142        let opened = Rc::new(Cell::new(false));
12143        // add_window draws once, which runs the nested open_window mid-draw.
12144        let window = cx.add_window({
12145            let opened = opened.clone();
12146            move |_, _| OpensWindowOnPaint { opened }
12147        });
12148
12149        assert!(opened.get());
12150        assert_eq!(cx.windows().len(), 2);
12151
12152        // The deferred clear must actually run once the outer draw unwinds:
12153        // subsequent draws of both windows work against a fresh arena.
12154        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12155            .unwrap();
12156    }
12157
12158    #[test]
12159    fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
12160        let mut cx = TestAppContext::single();
12161        let window = cx.add_window(|_, _| EmptyView);
12162        let handle: AnyWindowHandle = window.into();
12163        let window_state = |cx: &mut TestAppContext| {
12164            cx.update_window(handle, |_, window, _| {
12165                (
12166                    window.scale_factor(),
12167                    window.bounds(),
12168                    window.viewport_size(),
12169                )
12170            })
12171            .unwrap()
12172        };
12173
12174        let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
12175        assert_eq!(scale_factor, 2.0);
12176
12177        for (scale_factor, resized_size) in [
12178            (1.0, size(px(800.), px(600.))),
12179            (1.25, size(px(640.), px(480.))),
12180            (2.0, size(px(1024.), px(768.))),
12181        ] {
12182            cx.simulate_window_scale_factor_change(handle, scale_factor);
12183            assert_eq!(
12184                window_state(&mut cx),
12185                (scale_factor, expected_bounds, expected_bounds.size)
12186            );
12187
12188            cx.simulate_window_resize(handle, resized_size);
12189            expected_bounds.size = resized_size;
12190            assert_eq!(
12191                window_state(&mut cx),
12192                (scale_factor, expected_bounds, resized_size)
12193            );
12194        }
12195    }
12196
12197    #[gpui::test]
12198    fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
12199        let window = cx.add_window(|_, _| EmptyView);
12200        let handle = AnyWindowHandle::from(window);
12201        let notifications = Rc::new(Cell::new(0));
12202        window
12203            .update(cx, {
12204                let notifications = notifications.clone();
12205                |_, window, cx| {
12206                    cx.observe_window_bounds(window, move |_, _, _| {
12207                        notifications.set(notifications.get() + 1)
12208                    })
12209                    .detach();
12210                }
12211            })
12212            .unwrap();
12213        let window_state = |cx: &mut TestAppContext| {
12214            cx.update_window(handle, |_, window, _| {
12215                (
12216                    window.is_fullscreen(),
12217                    window.bounds().size,
12218                    window.viewport_size(),
12219                )
12220            })
12221            .unwrap()
12222        };
12223        let initial_size = window_state(cx).1;
12224
12225        window
12226            .update(cx, |_, window, _| window.toggle_fullscreen())
12227            .unwrap();
12228        cx.run_until_parked();
12229        assert_eq!(window_state(cx), (true, initial_size, initial_size));
12230        assert_eq!(notifications.get(), 1);
12231
12232        let resized_size = size(px(800.), px(600.));
12233        window
12234            .update(cx, |_, window, _| window.toggle_fullscreen())
12235            .unwrap();
12236        cx.simulate_window_resize(handle, resized_size);
12237        cx.run_until_parked();
12238        assert_eq!(window_state(cx), (false, resized_size, resized_size));
12239    }
12240
12241    /// Platforms that stop requesting frames for idle windows (currently web)
12242    /// rely on the frame waker firing whenever frame demand arises; a demand
12243    /// source that skips the waker shows up there as a window that silently
12244    /// stops repainting until unrelated activity wakes it.
12245    #[gpui::test]
12246    fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
12247        let window = cx.add_window(|_, _| EmptyView);
12248        let test_window = cx.test_window(window.into());
12249        // This test exercises idle wakeups, not the inactive-window frame limit.
12250        test_window.simulate_active_status_change(true);
12251
12252        // Windows start dirty, and that can predate waker installation;
12253        // installing the waker must deliver the pending wake or the first
12254        // frame would never be requested.
12255        assert!(
12256            test_window.frame_wake_count() >= 1,
12257            "opening a window must wake the frame source for the initial frame"
12258        );
12259
12260        // Serve outstanding demand (present the frame drawn by `add_window`).
12261        test_window.simulate_frame_request(RequestFrameOptions::default());
12262
12263        // An idle window must not wake on clean frames or plain updates, or
12264        // the frame source could never stop.
12265        let baseline = test_window.frame_wake_count();
12266        test_window.simulate_frame_request(RequestFrameOptions::default());
12267        window.update(cx, |_, _, _| {}).unwrap();
12268        assert_eq!(
12269            test_window.frame_wake_count(),
12270            baseline,
12271            "clean frames and non-notifying updates must not wake the frame source"
12272        );
12273
12274        // Notifying a view in an idle window is the core demand signal.
12275        window.update(cx, |_, _, cx| cx.notify()).unwrap();
12276        assert!(
12277            test_window.frame_wake_count() > baseline,
12278            "notifying a view in an idle window must wake the frame source"
12279        );
12280
12281        // Serving that demand returns to idle without further wakes.
12282        test_window.simulate_frame_request(RequestFrameOptions::default());
12283        let baseline = test_window.frame_wake_count();
12284        test_window.simulate_frame_request(RequestFrameOptions::default());
12285        assert_eq!(
12286            test_window.frame_wake_count(),
12287            baseline,
12288            "serving demand must return the window to idle"
12289        );
12290
12291        // Next-frame callbacks create demand without dirtying the window.
12292        window
12293            .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
12294            .unwrap();
12295        assert!(
12296            test_window.frame_wake_count() > baseline,
12297            "scheduling a next-frame callback in an idle window must wake the frame source"
12298        );
12299    }
12300
12301    /// A passive next-frame callback rides along with the next delivered frame
12302    /// but never wakes the frame source, even when it re-arms itself.
12303    #[gpui::test]
12304    fn test_passive_next_frame_callbacks_are_not_demand(cx: &mut TestAppContext) {
12305        fn rearm(window: &mut Window, runs: Rc<Cell<usize>>) {
12306            runs.set(runs.get() + 1);
12307            window.on_next_frame_passive(move |window, _| rearm(window, runs));
12308        }
12309        let window = cx.add_window(|_, _| EmptyView);
12310        let test_window = cx.test_window(window.into());
12311        test_window.simulate_frame_request(RequestFrameOptions::default());
12312
12313        let runs = Rc::new(Cell::new(0));
12314        let baseline = test_window.frame_wake_count();
12315        window
12316            .update(cx, {
12317                let runs = runs.clone();
12318                move |_, window, _| window.on_next_frame_passive(move |window, _| rearm(window, runs))
12319            })
12320            .unwrap();
12321        assert_eq!(test_window.frame_wake_count(), baseline, "queueing a passive callback is not demand");
12322
12323        test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12324        test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12325        assert_eq!(runs.get(), 2, "a passive callback runs with every delivered frame");
12326        assert_eq!(test_window.frame_wake_count(), baseline, "a re-arming passive pump never wakes the frame source");
12327
12328        // Real demand next to the passive pump still wakes it.
12329        window.update(cx, |_, window, _| window.on_next_frame(|_, _| {})).unwrap();
12330        assert!(test_window.frame_wake_count() > baseline);
12331    }
12332
12333    /// A frame request that arrives while next-frame callbacks are pending
12334    /// must never strand them: either the frame runs them, or (when the
12335    /// inactive-window frame-rate throttle defers the frame) the waker fires
12336    /// so another request is delivered.
12337    #[gpui::test]
12338    fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
12339        let window = cx.add_window(|_, _| EmptyView);
12340        let test_window = cx.test_window(window.into());
12341        // Establish a recent last-frame time so the inactive-window throttle
12342        // can engage on the next request.
12343        test_window.simulate_frame_request(RequestFrameOptions::default());
12344
12345        let callback_ran = Rc::new(Cell::new(false));
12346        window
12347            .update(cx, {
12348                let callback_ran = callback_ran.clone();
12349                move |_, window, _| {
12350                    window.on_next_frame(move |_, _| callback_ran.set(true));
12351                }
12352            })
12353            .unwrap();
12354
12355        let baseline = test_window.frame_wake_count();
12356        test_window.simulate_frame_request(RequestFrameOptions::default());
12357        // The test window is inactive, so this request throttles to ~30fps
12358        // when it lands within the throttle interval of the previous frame
12359        // (the common case here, but timing-dependent): the callback is
12360        // deferred and the waker must re-arm the frame source. On a slow run
12361        // the request instead lands outside the interval and runs the
12362        // callback directly.
12363        assert!(
12364            test_window.frame_wake_count() > baseline || callback_ran.get(),
12365            "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
12366        );
12367    }
12368
12369    #[gpui::test]
12370    fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
12371        use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
12372
12373        let window = cx.add_window(|_, _| EmptyView);
12374        window
12375            .update(cx, |_, window, _| {
12376                assert!(matches!(
12377                    window.window_handle(),
12378                    Err(HandleError::NotSupported)
12379                ));
12380                assert!(matches!(
12381                    window.display_handle(),
12382                    Err(HandleError::NotSupported)
12383                ));
12384            })
12385            .unwrap();
12386    }
12387
12388    #[gpui::test]
12389    fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
12390        let window = cx.add_window(|_, _| EmptyView);
12391        let observed_appearance = Rc::new(Cell::new(None));
12392        let _subscription = window
12393            .update(cx, {
12394                let observed_appearance = observed_appearance.clone();
12395                move |_, window, _| {
12396                    window.observe_window_appearance(move |window, _| {
12397                        observed_appearance.set(Some(window.appearance()));
12398                    })
12399                }
12400            })
12401            .unwrap();
12402        let test_window = cx.test_window(window.into());
12403
12404        cx.update(|_| {
12405            test_window.simulate_appearance_change(WindowAppearance::Dark);
12406            assert_eq!(observed_appearance.get(), None);
12407        });
12408        cx.run_until_parked();
12409
12410        assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
12411    }
12412
12413    #[gpui::test]
12414    fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12415        let window = cx.add_window(|_, _| Empty);
12416        let test_window = cx.test_window(window.into());
12417
12418        assert!(test_window.simulate_scheduled_frame());
12419        assert!(test_window.simulate_scheduled_frame());
12420        assert!(!test_window.frame_scheduled());
12421
12422        cx.update_window(window.into(), |_, window, _| {
12423            window.active.set(true);
12424            window.on_next_frame(|_, _| {});
12425        })
12426        .unwrap();
12427        assert!(
12428            test_window.frame_scheduled(),
12429            "queuing work on a parked window must wake the render loop"
12430        );
12431
12432        assert!(test_window.simulate_scheduled_frame());
12433        assert!(
12434            test_window.frame_scheduled(),
12435            "presenting the frame must await one compositor callback"
12436        );
12437        assert!(test_window.simulate_scheduled_frame());
12438        assert!(!test_window.frame_scheduled());
12439    }
12440
12441    #[gpui::test]
12442    fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12443        let window = cx.add_window(|_, _| Empty);
12444        let test_window = cx.test_window(window.into());
12445
12446        assert!(test_window.simulate_scheduled_frame());
12447        assert!(test_window.simulate_scheduled_frame());
12448        assert!(!test_window.frame_scheduled());
12449
12450        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12451            .unwrap();
12452
12453        assert!(
12454            test_window.frame_scheduled(),
12455            "a rendered scene awaiting presentation must wake the render loop"
12456        );
12457    }
12458
12459    #[gpui::test]
12460    fn reentrant_frame_request_preserves_pending_callbacks(cx: &mut TestAppContext) {
12461        let window = cx.add_window(|_, _| Empty);
12462        let test_window = cx.test_window(window.into());
12463        let callback_count = Rc::new(Cell::new(0));
12464
12465        cx.update_window(window.into(), |_, window, _| {
12466            window.active.set(true);
12467            let callback_count = callback_count.clone();
12468            window.on_next_frame(move |window, _| {
12469                callback_count.set(callback_count.get() + 1);
12470                window.on_next_frame(move |_, _| {
12471                    callback_count.set(callback_count.get() + 1);
12472                });
12473            });
12474        })
12475        .unwrap();
12476
12477        // Win32 can deliver WM_PAINT from a nested native message loop while
12478        // an input listener or host call still owns the App borrow.
12479        let wake_count = test_window.frame_wake_count();
12480        cx.update(|_| {
12481            test_window.simulate_frame_request(RequestFrameOptions::default());
12482        });
12483        assert_eq!(callback_count.get(), 0);
12484        cx.update_window(window.into(), |_, window, _| {
12485            assert_eq!(window.next_frame_callbacks.borrow().len(), 1);
12486        })
12487        .unwrap();
12488        assert!(
12489            test_window.frame_wake_count() > wake_count,
12490            "a deferred frame callback must wake the frame source for a retry"
12491        );
12492
12493        test_window.simulate_frame_request(RequestFrameOptions::default());
12494        assert_eq!(callback_count.get(), 1);
12495        test_window.simulate_frame_request(RequestFrameOptions::default());
12496        assert_eq!(callback_count.get(), 2);
12497        test_window.simulate_frame_request(RequestFrameOptions::default());
12498        assert_eq!(callback_count.get(), 2);
12499    }
12500
12501    #[gpui::test]
12502    fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
12503        let window = cx.add_window(|_, _| Empty);
12504        let test_window = cx.test_window(window.into());
12505
12506        let callback_ran = Rc::new(Cell::new(false));
12507        cx.update_window(window.into(), |_, window, _| {
12508            // Inactive windows are frame-rate throttled, which would defer the
12509            // ticks this test drives manually.
12510            window.active.set(true);
12511            let callback_ran = callback_ran.clone();
12512            window.on_next_frame(move |window, _| {
12513                window.on_next_frame(move |_, _| callback_ran.set(true));
12514            });
12515        })
12516        .unwrap();
12517
12518        assert!(test_window.simulate_scheduled_frame());
12519        assert!(!callback_ran.get());
12520        assert!(
12521            test_window.frame_scheduled(),
12522            "a callback queued mid-frame must schedule a follow-up before the loop parks"
12523        );
12524
12525        assert!(test_window.simulate_scheduled_frame());
12526        assert!(callback_ran.get());
12527    }
12528
12529    struct RootView {
12530        explicit_size: bool,
12531        child_bounds: Rc<Cell<Bounds<Pixels>>>,
12532    }
12533
12534    impl Render for RootView {
12535        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12536            let child_bounds = self.child_bounds.clone();
12537            let root = div().flex().flex_col().child(
12538                canvas(
12539                    move |bounds, _, _| child_bounds.set(bounds),
12540                    |_, _, _, _| {},
12541                )
12542                .size_full(),
12543            );
12544            if self.explicit_size {
12545                root.w(px(300.)).h(px(200.))
12546            } else {
12547                root
12548            }
12549        }
12550    }
12551
12552    #[test]
12553    fn auto_sized_window_root_fills_the_window() {
12554        let mut cx = TestAppContext::single();
12555        let child_bounds = Rc::new(Cell::new(Bounds::default()));
12556        let window = cx.add_window({
12557            let child_bounds = child_bounds.clone();
12558            move |_, _| RootView {
12559                explicit_size: false,
12560                child_bounds,
12561            }
12562        });
12563
12564        let viewport_size = cx
12565            .update_window(window.into(), |_, window, cx| {
12566                window.draw(cx).clear(cx);
12567                window.viewport_size()
12568            })
12569            .unwrap();
12570
12571        assert_eq!(child_bounds.get().size, viewport_size);
12572    }
12573
12574    #[test]
12575    fn explicitly_sized_window_root_keeps_its_size() {
12576        let mut cx = TestAppContext::single();
12577        let child_bounds = Rc::new(Cell::new(Bounds::default()));
12578        let window = cx.add_window({
12579            let child_bounds = child_bounds.clone();
12580            move |_, _| RootView {
12581                explicit_size: true,
12582                child_bounds,
12583            }
12584        });
12585
12586        cx.update_window(window.into(), |_, window, cx| {
12587            window.draw(cx).clear(cx);
12588        })
12589        .unwrap();
12590
12591        assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
12592    }
12593
12594    struct FileDragView {
12595        path: PathBuf,
12596        observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12597        observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12598    }
12599
12600    struct FileDropExitView(Rc<Cell<usize>>);
12601
12602    impl Render for FileDropExitView {
12603        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12604            div().size_full().on_file_drop_exit({
12605                let observed_file_drop_exit = self.0.clone();
12606                move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
12607            })
12608        }
12609    }
12610
12611    impl Render for FileDragView {
12612        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12613            div()
12614                .id("file-drag")
12615                .size_full()
12616                .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
12617                .external_drag_payload(|path: &PathBuf, _, _| {
12618                    Some(ExternalDragPayload::Files(FileDragPaths::new([(
12619                        path.clone(),
12620                        true,
12621                    )])))
12622                })
12623                .on_drag_move({
12624                    let observed_drag_moves = self.observed_drag_moves.clone();
12625                    move |event: &DragMoveEvent<PathBuf>, _, _| {
12626                        observed_drag_moves.borrow_mut().push(event.event.position);
12627                    }
12628                })
12629                .on_drop({
12630                    let observed_drops = self.observed_drops.clone();
12631                    move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
12632                })
12633        }
12634    }
12635
12636    #[gpui::test]
12637    fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
12638        struct Drag {
12639            window: AnyWindowHandle,
12640            observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12641            observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12642        }
12643
12644        fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
12645            let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
12646            let observed_drops = Rc::new(RefCell::new(Vec::new()));
12647            let window: AnyWindowHandle = cx
12648                .add_window({
12649                    let observed_drag_moves = observed_drag_moves.clone();
12650                    let observed_drops = observed_drops.clone();
12651                    move |_, _| FileDragView {
12652                        path,
12653                        observed_drag_moves,
12654                        observed_drops,
12655                    }
12656                })
12657                .into();
12658            cx.test_window(window)
12659                .set_start_external_drag_result(platform_result);
12660
12661            let update_result = cx.update_window(window, |_, window, cx| {
12662                window.draw(cx).clear(cx);
12663                window.dispatch_event(
12664                    MouseDownEvent {
12665                        position: point(px(10.), px(10.)),
12666                        button: MouseButton::Left,
12667                        modifiers: Default::default(),
12668                        click_count: 1,
12669                        first_mouse: false,
12670                    }
12671                    .to_platform_input(),
12672                    cx,
12673                );
12674                window.dispatch_event(
12675                    MouseMoveEvent {
12676                        position: point(px(20.), px(20.)),
12677                        pressed_button: Some(MouseButton::Left),
12678                        modifiers: Default::default(),
12679                    }
12680                    .to_platform_input(),
12681                    cx,
12682                );
12683                assert!(cx.active_drag.is_some());
12684            });
12685            assert!(
12686                update_result.is_ok(),
12687                "failed to start drag: {update_result:?}"
12688            );
12689
12690            assert!(cx.test_window(window).external_drag_files().is_empty());
12691            Drag {
12692                window,
12693                observed_drag_moves,
12694                observed_drops,
12695            }
12696        }
12697
12698        let successful_path = PathBuf::from("/tmp/successful-drag");
12699        let successful = start_drag(cx, successful_path.clone(), true);
12700        let outside_position = point(px(-1.), px(20.));
12701        let update_result = cx.update_window(successful.window, |_, window, cx| {
12702            window.dispatch_event(
12703                MouseMoveEvent {
12704                    position: outside_position,
12705                    pressed_button: Some(MouseButton::Left),
12706                    modifiers: Default::default(),
12707                }
12708                .to_platform_input(),
12709                cx,
12710            );
12711            assert!(cx.active_drag.is_none());
12712        });
12713        assert!(
12714            update_result.is_ok(),
12715            "failed to promote drag: {update_result:?}"
12716        );
12717        assert_eq!(
12718            cx.test_window(successful.window).external_drag_files(),
12719            [(successful_path.clone(), true)]
12720        );
12721        // Views must still see the move that leaves the window, otherwise they never learn to tear
12722        // down the drag state they built up while the pointer was inside.
12723        assert_eq!(
12724            successful.observed_drag_moves.borrow().last(),
12725            Some(&outside_position)
12726        );
12727
12728        let first_destination_exit_count = Rc::new(Cell::new(0));
12729        let first_destination: AnyWindowHandle = cx
12730            .add_window({
12731                let first_destination_exit_count = first_destination_exit_count.clone();
12732                move |_, _| FileDropExitView(first_destination_exit_count)
12733            })
12734            .into();
12735        let second_destination_exit_count = Rc::new(Cell::new(0));
12736        let second_destination: AnyWindowHandle = cx
12737            .add_window({
12738                let second_destination_exit_count = second_destination_exit_count.clone();
12739                move |_, _| FileDropExitView(second_destination_exit_count)
12740            })
12741            .into();
12742        let reentry_position = point(px(30.), px(30.));
12743        let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
12744        let update_result = cx.update_window(first_destination, |_, window, cx| {
12745            window.draw(cx).clear(cx);
12746            window.dispatch_event(
12747                FileDropEvent::Entered {
12748                    position: reentry_position,
12749                    paths: external_paths(),
12750                }
12751                .to_platform_input(),
12752                cx,
12753            );
12754            assert!(
12755                cx.active_drag
12756                    .as_ref()
12757                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12758            );
12759            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12760            assert!(cx.active_drag.is_none());
12761            assert_eq!(first_destination_exit_count.get(), 1);
12762            assert_eq!(second_destination_exit_count.get(), 0);
12763        });
12764        assert!(
12765            update_result.is_ok(),
12766            "failed to handle drag in first destination window: {update_result:?}"
12767        );
12768
12769        let update_result = cx.update_window(second_destination, |_, window, cx| {
12770            window.draw(cx).clear(cx);
12771            window.dispatch_event(
12772                PlatformInput::KeyDown(KeyDownEvent {
12773                    keystroke: Keystroke::parse("down").expect("valid keystroke"),
12774                    is_held: false,
12775                    prefer_character_input: false,
12776                }),
12777                cx,
12778            );
12779            window.dispatch_event(
12780                FileDropEvent::Entered {
12781                    position: reentry_position,
12782                    paths: external_paths(),
12783                }
12784                .to_platform_input(),
12785                cx,
12786            );
12787            assert!(
12788                cx.active_drag
12789                    .as_ref()
12790                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12791            );
12792            assert_eq!(first_destination_exit_count.get(), 1);
12793            assert_eq!(second_destination_exit_count.get(), 0);
12794
12795            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12796            assert!(cx.active_drag.is_none());
12797            assert_eq!(first_destination_exit_count.get(), 1);
12798            assert_eq!(second_destination_exit_count.get(), 1);
12799        });
12800        assert!(
12801            update_result.is_ok(),
12802            "failed to handle drag in second destination window: {update_result:?}"
12803        );
12804
12805        let update_result = cx.update_window(successful.window, |_, window, cx| {
12806            window.dispatch_event(
12807                FileDropEvent::Entered {
12808                    position: reentry_position,
12809                    paths: external_paths(),
12810                }
12811                .to_platform_input(),
12812                cx,
12813            );
12814            assert!(
12815                cx.active_drag
12816                    .as_ref()
12817                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12818            );
12819            assert_eq!(
12820                successful.observed_drag_moves.borrow().last(),
12821                Some(&reentry_position)
12822            );
12823
12824            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12825            assert!(cx.active_drag.is_none());
12826
12827            window.dispatch_event(
12828                FileDropEvent::Entered {
12829                    position: reentry_position,
12830                    paths: external_paths(),
12831                }
12832                .to_platform_input(),
12833                cx,
12834            );
12835            assert!(
12836                cx.active_drag
12837                    .as_ref()
12838                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12839            );
12840
12841            window.dispatch_event(
12842                FileDropEvent::Submit {
12843                    position: reentry_position,
12844                }
12845                .to_platform_input(),
12846                cx,
12847            );
12848            assert_eq!(
12849                successful.observed_drops.borrow().as_slice(),
12850                std::slice::from_ref(&successful_path)
12851            );
12852            assert!(cx.active_drag.is_none());
12853
12854            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12855            assert!(cx.active_drag.is_none());
12856            window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
12857            assert!(cx.active_drag.is_none());
12858
12859            window.dispatch_event(
12860                FileDropEvent::Entered {
12861                    position: reentry_position,
12862                    paths: external_paths(),
12863                }
12864                .to_platform_input(),
12865                cx,
12866            );
12867            assert!(
12868                cx.active_drag
12869                    .as_ref()
12870                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12871            );
12872            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12873        });
12874        assert!(
12875            update_result.is_ok(),
12876            "failed to restore drag in source window: {update_result:?}"
12877        );
12878
12879        let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
12880        let cancelled = start_drag(cx, cancelled_path.clone(), true);
12881        let update_result = cx.update_window(cancelled.window, |_, window, cx| {
12882            window.dispatch_event(
12883                MouseMoveEvent {
12884                    position: outside_position,
12885                    pressed_button: Some(MouseButton::Left),
12886                    modifiers: Default::default(),
12887                }
12888                .to_platform_input(),
12889                cx,
12890            );
12891            assert!(cx.active_drag.is_none());
12892
12893            window.dispatch_event(
12894                FileDropEvent::Entered {
12895                    position: reentry_position,
12896                    paths: ExternalPaths([cancelled_path].into_iter().collect()),
12897                }
12898                .to_platform_input(),
12899                cx,
12900            );
12901            assert!(
12902                cx.active_drag
12903                    .as_ref()
12904                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12905            );
12906            assert!(cx.stop_active_drag(window));
12907            assert!(cx.active_drag.is_none());
12908        });
12909        assert!(
12910            update_result.is_ok(),
12911            "failed to cancel restored drag: {update_result:?}"
12912        );
12913        assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
12914
12915        let removed_path = PathBuf::from("/tmp/removed-window-drag");
12916        let removed = start_drag(cx, removed_path, true);
12917        let removed_window_id = removed.window.window_id();
12918        let update_result = cx.update_window(removed.window, |_, window, cx| {
12919            window.dispatch_event(
12920                MouseMoveEvent {
12921                    position: outside_position,
12922                    pressed_button: Some(MouseButton::Left),
12923                    modifiers: Default::default(),
12924                }
12925                .to_platform_input(),
12926                cx,
12927            );
12928            assert!(cx.active_drag.is_none());
12929            window.remove_window();
12930        });
12931        assert!(
12932            update_result.is_ok(),
12933            "failed to remove drag source window: {update_result:?}"
12934        );
12935        assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
12936
12937        let failed_path = PathBuf::from("/tmp/failed-drag");
12938        let failed = start_drag(cx, failed_path.clone(), false);
12939        let update_result = cx.update_window(failed.window, |_, window, cx| {
12940            for x_position in [-1., -2.] {
12941                window.dispatch_event(
12942                    MouseMoveEvent {
12943                        position: point(px(x_position), px(20.)),
12944                        pressed_button: Some(MouseButton::Left),
12945                        modifiers: Default::default(),
12946                    }
12947                    .to_platform_input(),
12948                    cx,
12949                );
12950            }
12951            assert!(cx.active_drag.is_some());
12952        });
12953        assert!(
12954            update_result.is_ok(),
12955            "failed to retain drag after platform failure: {update_result:?}"
12956        );
12957        assert_eq!(
12958            cx.test_window(failed.window).external_drag_files(),
12959            [(failed_path, true)]
12960        );
12961    }
12962
12963    struct FocusForwarder {
12964        a: FocusHandle,
12965        b: FocusHandle,
12966    }
12967
12968    impl Render for FocusForwarder {
12969        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12970            div()
12971                .size_full()
12972                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
12973                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
12974        }
12975    }
12976
12977    /// When a focus listener moves focus again (e.g. a dock forwarding focus to its
12978    /// active panel), the resulting focus events must be dispatched without waiting
12979    /// for an unrelated redraw of the window.
12980    #[gpui::test]
12981    fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
12982        let b_focus_count = Rc::new(Cell::new(0));
12983        let window = cx.add_window({
12984            let b_focus_count = b_focus_count.clone();
12985            move |window, cx| {
12986                let a = cx.focus_handle();
12987                let b = cx.focus_handle();
12988                cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
12989                    let b = this.b.clone();
12990                    window.focus(&b, cx);
12991                })
12992                .detach();
12993                cx.on_focus(&b, window, move |_, _, _| {
12994                    b_focus_count.set(b_focus_count.get() + 1);
12995                })
12996                .detach();
12997                FocusForwarder { a, b }
12998            }
12999        });
13000
13001        window
13002            .update(cx, |_, window, _| window.activate_window())
13003            .unwrap();
13004        cx.executor().run_until_parked();
13005
13006        window
13007            .update(cx, |this, window, cx| {
13008                let a = this.a.clone();
13009                window.focus(&a, cx);
13010            })
13011            .unwrap();
13012        cx.executor().run_until_parked();
13013
13014        window
13015            .update(cx, |this, window, _| {
13016                assert!(this.b.is_focused(window));
13017            })
13018            .unwrap();
13019        assert_eq!(b_focus_count.get(), 1);
13020    }
13021
13022    #[gpui::test]
13023    fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
13024        let events = Rc::new(RefCell::new(Vec::new()));
13025        let window = cx.add_window({
13026            let events = events.clone();
13027            move |_, _| TouchDragListener { events }
13028        });
13029        let touch = TouchId(1);
13030
13031        dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
13032        dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
13033        dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
13034
13035        assert_eq!(
13036            events.borrow().as_slice(),
13037            [
13038                (TouchPhase::Started, px(10.)),
13039                (TouchPhase::Moved, px(30.)),
13040                (TouchPhase::Ended, px(40.)),
13041            ]
13042        );
13043    }
13044
13045    #[gpui::test]
13046    fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
13047        let claims = Rc::new(RefCell::new(Vec::new()));
13048        let window = cx.add_window({
13049            let claims = claims.clone();
13050            move |_, _| BackListeners { claims }
13051        });
13052        let dispatch_back = |cx: &mut TestAppContext, x: f32| {
13053            window
13054                .update(cx, |_, window, cx| {
13055                    window
13056                        .dispatch_event(
13057                            BackGestureEvent {
13058                                phase: BackGesturePhase::Started,
13059                                start_position: point(px(x), px(10.)),
13060                                progress: 0.,
13061                            }
13062                            .to_platform_input(),
13063                            cx,
13064                        )
13065                        .default_prevented
13066                })
13067                .unwrap()
13068        };
13069        assert!(dispatch_back(cx, 10.));
13070        assert!(dispatch_back(cx, 80.));
13071        assert!(!dispatch_back(cx, 150.));
13072        assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
13073    }
13074
13075    struct BackListeners {
13076        claims: Rc<RefCell<Vec<&'static str>>>,
13077    }
13078
13079    impl Render for BackListeners {
13080        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13081            let claim = |name: &'static str| {
13082                let claims = self.claims.clone();
13083                move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
13084                    claims.borrow_mut().push(name)
13085                }
13086            };
13087            div().size_full().child(
13088                div()
13089                    .w(px(100.))
13090                    .h_full()
13091                    .on_back_gesture(claim("outer"))
13092                    .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
13093            )
13094        }
13095    }
13096
13097    struct TouchDragListener {
13098        events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
13099    }
13100
13101    impl Render for TouchDragListener {
13102        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13103            let events = self.events.clone();
13104            canvas(
13105                |_, _, _| {},
13106                move |_, _, window, _| {
13107                    window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
13108                        if phase != DispatchPhase::Bubble {
13109                            return;
13110                        }
13111                        events.borrow_mut().push((event.phase, event.position.x));
13112                        if event.phase == TouchPhase::Started {
13113                            window.prevent_default();
13114                        }
13115                    });
13116                },
13117            )
13118        }
13119    }
13120
13121    #[gpui::test]
13122    fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
13123        for response in [
13124            LongPressResponse::PreventDefault,
13125            LongPressResponse::StopPropagation,
13126            LongPressResponse::None,
13127        ] {
13128            let phases = Rc::new(RefCell::new(Vec::new()));
13129            let window = cx.add_window({
13130                let phases = phases.clone();
13131                move |_, _| LongPressListener { phases, response }
13132            });
13133            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13134            cx.executor().advance_clock(Duration::from_millis(501));
13135            cx.executor().run_until_parked();
13136            window
13137                .update(cx, |_, window, _| {
13138                    assert_eq!(
13139                        window.long_press_capture.is_some(),
13140                        response == LongPressResponse::PreventDefault
13141                    );
13142                })
13143                .unwrap();
13144            dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13145            dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
13146            window
13147                .update(cx, |_, window, _| {
13148                    assert!(window.long_press_capture.is_none());
13149                })
13150                .unwrap();
13151
13152            let phases = phases.borrow();
13153            if response == LongPressResponse::PreventDefault {
13154                assert_eq!(
13155                    phases.as_slice(),
13156                    [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
13157                );
13158            } else {
13159                assert_eq!(phases.as_slice(), [TouchPhase::Started]);
13160            }
13161        }
13162    }
13163
13164    #[gpui::test]
13165    fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
13166        let phases = Rc::new(RefCell::new(Vec::new()));
13167        let window = cx.add_window({
13168            let phases = phases.clone();
13169            move |_, _| LongPressListener {
13170                phases,
13171                response: LongPressResponse::None,
13172            }
13173        });
13174        window
13175            .update(cx, |_, window, _| {
13176                window.prevent_default();
13177            })
13178            .unwrap();
13179
13180        dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13181        cx.executor().advance_clock(Duration::from_millis(501));
13182        cx.executor().run_until_parked();
13183        dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13184
13185        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13186    }
13187
13188    #[gpui::test]
13189    fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
13190        for (phase, position) in [
13191            (TouchPhase::Ended, 0.),
13192            (TouchPhase::Cancelled, 0.),
13193            (TouchPhase::Moved, 20.),
13194        ] {
13195            let phases = Rc::new(RefCell::new(Vec::new()));
13196            let window = cx.add_window({
13197                let phases = phases.clone();
13198                move |_, _| LongPressListener {
13199                    phases,
13200                    response: LongPressResponse::PreventDefault,
13201                }
13202            });
13203            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13204            dispatch_touch(window, cx, TouchId(1), phase, position);
13205            cx.executor().advance_clock(Duration::from_millis(501));
13206            cx.executor().run_until_parked();
13207
13208            assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
13209        }
13210    }
13211
13212    #[gpui::test]
13213    fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
13214        let phases = Rc::new(RefCell::new(Vec::new()));
13215        let window = cx.add_window({
13216            let phases = phases.clone();
13217            move |_, _| LongPressListener {
13218                phases,
13219                response: LongPressResponse::PreventDefault,
13220            }
13221        });
13222        let first_touch = TouchId(1);
13223        dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
13224        cx.executor().advance_clock(Duration::from_millis(250));
13225        dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
13226        dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
13227
13228        cx.executor().advance_clock(Duration::from_millis(251));
13229        cx.executor().run_until_parked();
13230        assert!(phases.borrow().is_empty());
13231
13232        cx.executor().advance_clock(Duration::from_millis(250));
13233        cx.executor().run_until_parked();
13234        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13235    }
13236
13237    #[gpui::test]
13238    fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
13239        test_underline_paint_at_scales(cx, |window| {
13240            let (numerator, denominator) = match window.scale_factor() {
13241                1.0 => (1, 1),
13242                1.25 => (5, 4),
13243                1.5 => (3, 2),
13244                2.0 => (2, 1),
13245                3.0 => (3, 1),
13246                scale => panic!("unexpected scale {scale}"),
13247            };
13248            let snap = |quarters: i32| {
13249                let scaled = quarters * numerator;
13250                let divisor = 4 * denominator;
13251                let rounded =
13252                    scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
13253                ScaledPixels((scaled.signum() * rounded) as f32)
13254            };
13255            let stroke = |quarters| {
13256                if quarters == 0 {
13257                    ScaledPixels(0.)
13258                } else {
13259                    snap(quarters).max(ScaledPixels(1.))
13260                }
13261            };
13262
13263            for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
13264                for width in [0, 1, 3, 84] {
13265                    for thickness in [0, 1, 4, 7] {
13266                        for wavy in [false, true] {
13267                            let style = UnderlineStyle {
13268                                thickness: px(thickness as f32 / 4.),
13269                                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13270                                wavy,
13271                                offset: px(0.),
13272                            };
13273                            let bounds = Bounds::new(
13274                                point(snap(origin), snap(-origin)),
13275                                size(
13276                                    stroke(width),
13277                                    stroke(thickness) * if wavy { 3. } else { 1. },
13278                                ),
13279                            );
13280                            let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
13281                            let width = px(width as f32 / 4.);
13282                            assert_eq!(window.underline_bounds(origin, width, &style), bounds);
13283                            let original = paint_test_underlines(window, |window| {
13284                                window.paint_underline(origin, width, &style);
13285                            })
13286                            .to_vec();
13287                            assert_eq!(original.len(), usize::from(!bounds.is_empty()));
13288                            if let Some(underline) = original.first() {
13289                                assert_eq!(underline.bounds, bounds);
13290                                assert_eq!(underline.thickness, stroke(thickness));
13291                                assert_eq!(underline.wavy, wavy.into());
13292                                assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
13293                            }
13294
13295                            let underlines = paint_test_underlines(window, |window| {
13296                                window.paint_underline_with_exclusions(origin, width, &style, &[]);
13297                            });
13298                            assert_eq!(underlines.len(), original.len());
13299                            for (actual, original) in underlines.iter().zip(&original) {
13300                                assert_same_underline_geometry(actual, original);
13301                                assert_eq!(actual.content_mask, original.content_mask);
13302                            }
13303
13304                            let left = bounds.left().0 as i32;
13305                            let right = bounds.right().0 as i32;
13306                            let exclusions = [
13307                                (15, 25),
13308                                (3, 7),
13309                                (5, 10),
13310                                (10, 12),
13311                                (0, 0),
13312                                (4, 2),
13313                                (-50, -1),
13314                                (70, 100),
13315                            ]
13316                            .map(|(start, end)| {
13317                                ScaledPixels((left + start) as f32)
13318                                    ..ScaledPixels((left + end) as f32)
13319                            });
13320                            let underlines = paint_test_underlines(window, |window| {
13321                                window.paint_underline_with_exclusions(
13322                                    origin,
13323                                    width,
13324                                    &style,
13325                                    &exclusions,
13326                                );
13327                            });
13328                            let expected = (left..right)
13329                                .filter(|column| {
13330                                    !bounds.is_empty()
13331                                        && !exclusions.iter().any(|span| {
13332                                            span.contains(&ScaledPixels(*column as f32))
13333                                        })
13334                                })
13335                                .collect::<Vec<_>>();
13336                            assert_eq!(underline_device_columns(underlines), expected);
13337                            for underline in underlines {
13338                                assert_same_underline_geometry(underline, &original[0]);
13339                            }
13340                        }
13341                    }
13342                }
13343            }
13344        });
13345    }
13346
13347    #[gpui::test]
13348    fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
13349        test_underline_paint_at_scales(cx, |window| {
13350            if window.scale_factor() != 2.0 {
13351                return;
13352            }
13353            let style = UnderlineStyle {
13354                thickness: px(1.),
13355                color: None,
13356                wavy: true,
13357                offset: px(0.),
13358            };
13359            let origin = point(px(2.888_183_8), px(15.357_917));
13360            let width = px(23.848_145) - origin.x;
13361            let original = paint_test_underlines(window, |window| {
13362                window.paint_underline(origin, width, &style);
13363            })[0];
13364            assert_eq!(original.bounds.left(), ScaledPixels(6.));
13365            assert_eq!(original.bounds.right(), ScaledPixels(48.));
13366            let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
13367            assert_eq!(point_bounds.left(), ScaledPixels(6.));
13368            assert_eq!(point_bounds.right(), ScaledPixels(28.));
13369
13370            let underlines = paint_test_underlines(window, |window| {
13371                window.paint_underline_with_exclusions(
13372                    origin,
13373                    width,
13374                    &style,
13375                    &[point_bounds.left()..point_bounds.right()],
13376                );
13377            });
13378            assert_eq!(underlines.len(), 1);
13379            assert_same_underline_geometry(&underlines[0], &original);
13380            assert_eq!(
13381                underline_device_columns(underlines),
13382                (28..48).collect::<Vec<_>>()
13383            );
13384        });
13385    }
13386
13387    #[gpui::test]
13388    fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
13389        test_underline_paint_at_scales(cx, |window| {
13390            let scale = window.scale_factor();
13391            let original_mask = window.content_mask();
13392            let original_opacity = window.element_opacity();
13393            let mask = ContentMask {
13394                bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
13395                corner_radii: crate::Corners::default(),
13396            };
13397            let style = UnderlineStyle {
13398                thickness: px(2.),
13399                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13400                wavy: true,
13401                offset: px(0.),
13402            };
13403            let origin = point(px(-1.25), px(9.25));
13404            let width = px(24.);
13405            window.with_content_mask(Some(mask), |window| {
13406                window.with_element_opacity(Some(0.5), |window| {
13407                    window.with_element_opacity(Some(0.5), |window| {
13408                        let original = paint_test_underlines(window, |window| {
13409                            window.paint_underline(origin, width, &style);
13410                        })[0];
13411                        assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
13412                        let underlines = paint_test_underlines(window, |window| {
13413                            window.paint_underline_with_exclusions(
13414                                origin,
13415                                width,
13416                                &style,
13417                                &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
13418                            );
13419                        });
13420                        assert_eq!(underlines.len(), 2);
13421                        let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
13422                            |(left, right)| {
13423                                Bounds::from_corners(
13424                                    point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
13425                                    point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
13426                                )
13427                            },
13428                        );
13429                        assert_eq!(
13430                            underlines
13431                                .iter()
13432                                .map(|underline| underline.content_mask.bounds)
13433                                .collect::<Vec<_>>(),
13434                            expected
13435                        );
13436                        for underline in underlines {
13437                            assert_same_underline_geometry(underline, &original);
13438                        }
13439                    });
13440                });
13441            });
13442            assert_eq!(window.content_mask(), original_mask);
13443            assert_eq!(window.element_opacity(), original_opacity);
13444        });
13445    }
13446
13447    #[gpui::test]
13448    fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
13449        test_underline_paint_at_scales(cx, |window| {
13450            let style = UnderlineStyle {
13451                thickness: px(1.),
13452                color: None,
13453                wavy: true,
13454                offset: px(0.),
13455            };
13456            let origin = point(px(-4.), px(-1.));
13457            let width = px(8.);
13458            let left = (-4. * window.scale_factor()) as i32;
13459            let right = (4. * window.scale_factor()) as i32;
13460            let endpoints = [-16, -8, -1, 0, 1, 8, 16];
13461            for first_start in endpoints {
13462                for first_end in endpoints {
13463                    for second_start in endpoints {
13464                        for second_end in endpoints {
13465                            let exclusions = [first_start..first_end, second_start..second_end];
13466                            let expected = (left..right)
13467                                .filter(|column| {
13468                                    !exclusions.iter().any(|span| span.contains(column))
13469                                })
13470                                .collect::<Vec<_>>();
13471                            let exclusions = exclusions.map(|span| {
13472                                ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
13473                            });
13474                            let underlines = paint_test_underlines(window, |window| {
13475                                window.paint_underline_with_exclusions(
13476                                    origin,
13477                                    width,
13478                                    &style,
13479                                    &exclusions,
13480                                );
13481                            });
13482                            assert_eq!(
13483                                underline_device_columns(underlines),
13484                                expected,
13485                                "{exclusions:?}"
13486                            );
13487                        }
13488                    }
13489                }
13490            }
13491        });
13492    }
13493
13494    #[derive(Clone, Copy, PartialEq)]
13495    enum LongPressResponse {
13496        PreventDefault,
13497        StopPropagation,
13498        None,
13499    }
13500
13501    struct LongPressListener {
13502        phases: Rc<RefCell<Vec<TouchPhase>>>,
13503        response: LongPressResponse,
13504    }
13505
13506    impl Render for LongPressListener {
13507        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13508            let entity = cx.entity();
13509            let phases = self.phases.clone();
13510            let response = self.response;
13511            canvas(
13512                |_, _, _| {},
13513                move |_, _, window, _| {
13514                    window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
13515                        if phase != DispatchPhase::Bubble {
13516                            return;
13517                        }
13518                        phases.borrow_mut().push(event.phase);
13519                        match response {
13520                            LongPressResponse::PreventDefault => {
13521                                window.capture_long_press(&entity);
13522                                window.prevent_default();
13523                            }
13524                            LongPressResponse::StopPropagation => cx.stop_propagation(),
13525                            LongPressResponse::None => {}
13526                        }
13527                    });
13528                },
13529            )
13530        }
13531    }
13532
13533    struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
13534
13535    impl Render for UnderlineTestView {
13536        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13537            let paint = self.0.clone();
13538            canvas(
13539                |_, _, _| {},
13540                move |_, _, window, _| {
13541                    window.content_mask_stack.push(ContentMask::rect(Bounds::from_corners(
13542                        point(px(-1000.), px(-1000.)),
13543                        point(px(1000.), px(1000.)),
13544                    )));
13545                    paint(window);
13546                    window.content_mask_stack.pop();
13547                },
13548            )
13549            .size_full()
13550        }
13551    }
13552
13553    fn test_underline_paint_at_scales(
13554        cx: &mut TestAppContext,
13555        paint: impl Fn(&mut Window) + 'static,
13556    ) {
13557        let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
13558        for scale in [1., 1.25, 1.5, 2., 3.] {
13559            cx.simulate_window_scale_factor_change(window.into(), scale);
13560            cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
13561                .unwrap();
13562        }
13563    }
13564
13565    fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
13566        window.next_frame.scene.clear();
13567        paint(window);
13568        &window.next_frame.scene.underlines
13569    }
13570
13571    fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
13572        assert_eq!(actual.bounds, expected.bounds);
13573        assert_eq!(actual.thickness, expected.thickness);
13574        assert_eq!(actual.wavy, expected.wavy);
13575        assert_eq!(actual.color, expected.color);
13576        assert_eq!(actual.pad, expected.pad);
13577    }
13578
13579    fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
13580        underlines
13581            .iter()
13582            .flat_map(|underline| {
13583                let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
13584                bounds.left().0 as i32..bounds.right().0 as i32
13585            })
13586            .collect()
13587    }
13588
13589    actions!(window_test, [StandaloneModifierAction]);
13590
13591    struct StandaloneModifierView {
13592        focus_handle: FocusHandle,
13593        action_count: usize,
13594    }
13595
13596    impl Render for StandaloneModifierView {
13597        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13598            div()
13599                .key_context("StandaloneModifier")
13600                .track_focus(&self.focus_handle)
13601                .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
13602                    this.action_count += 1;
13603                }))
13604        }
13605    }
13606
13607    #[gpui::test]
13608    fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
13609        use crate::{KeyBinding, Modifiers};
13610
13611        cx.update(|cx| {
13612            cx.bind_keys([KeyBinding::new(
13613                "shift shift",
13614                StandaloneModifierAction,
13615                Some("StandaloneModifier"),
13616            )]);
13617        });
13618        let (view, cx) = cx.add_window_view(|window, cx| {
13619            let focus_handle = cx.focus_handle();
13620            window.focus(&focus_handle, cx);
13621            StandaloneModifierView {
13622                focus_handle,
13623                action_count: 0,
13624            }
13625        });
13626        let shift = Modifiers {
13627            shift: true,
13628            ..Modifiers::default()
13629        };
13630        cx.simulate_modifiers_change(shift);
13631        cx.simulate_modifiers_change(Modifiers::default());
13632        cx.update(|window, _| {
13633            assert_eq!(
13634                window.pending_input_keystrokes(),
13635                Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
13636            );
13637        });
13638        cx.background_executor.advance_clock(Duration::from_secs(2));
13639        cx.run_until_parked();
13640        cx.update(|window, cx| {
13641            assert!(!window.has_pending_keystrokes());
13642            assert_eq!(view.read(cx).action_count, 0);
13643        });
13644
13645        cx.simulate_modifiers_change(shift);
13646        cx.simulate_modifiers_change(Modifiers::default());
13647        cx.update(|window, cx| {
13648            assert!(window.has_pending_keystrokes());
13649            assert_eq!(view.read(cx).action_count, 0);
13650        });
13651
13652        cx.simulate_modifiers_change(shift);
13653        cx.simulate_modifiers_change(Modifiers::default());
13654        cx.update(|window, cx| {
13655            assert!(!window.has_pending_keystrokes());
13656            assert_eq!(view.read(cx).action_count, 1);
13657        });
13658    }
13659
13660    #[gpui::test]
13661    fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
13662        use crate::{KeyBinding, Modifiers};
13663
13664        cx.update(|cx| {
13665            cx.bind_keys([KeyBinding::new(
13666                "shift shift",
13667                StandaloneModifierAction,
13668                Some("StandaloneModifier"),
13669            )]);
13670        });
13671        let (view, cx) = cx.add_window_view(|window, cx| {
13672            let focus_handle = cx.focus_handle();
13673            window.focus(&focus_handle, cx);
13674            StandaloneModifierView {
13675                focus_handle,
13676                action_count: 0,
13677            }
13678        });
13679        let shift = Modifiers {
13680            shift: true,
13681            ..Modifiers::default()
13682        };
13683        cx.simulate_modifiers_change(shift);
13684        cx.simulate_modifiers_change(Modifiers::default());
13685        cx.background_executor
13686            .advance_clock(Duration::from_millis(500));
13687        cx.update(|window, cx| {
13688            assert!(window.has_pending_keystrokes());
13689            assert_eq!(view.read(cx).action_count, 0);
13690        });
13691        cx.simulate_modifiers_change(shift);
13692        cx.simulate_modifiers_change(Modifiers::default());
13693        cx.update(|window, cx| {
13694            assert!(!window.has_pending_keystrokes());
13695            assert_eq!(view.read(cx).action_count, 1);
13696        });
13697        cx.background_executor.advance_clock(Duration::from_secs(2));
13698        cx.run_until_parked();
13699        cx.update(|window, cx| {
13700            assert!(!window.has_pending_keystrokes());
13701            assert_eq!(view.read(cx).action_count, 1);
13702        });
13703    }
13704
13705    fn dispatch_touch<T: 'static>(
13706        window: crate::WindowHandle<T>,
13707        cx: &mut TestAppContext,
13708        id: TouchId,
13709        phase: TouchPhase,
13710        x: f32,
13711    ) {
13712        window
13713            .update(cx, |_, window, cx| {
13714                window.dispatch_event(
13715                    TouchEvent {
13716                        id,
13717                        phase,
13718                        position: point(px(x), px(0.)),
13719                        predicted_position: None,
13720                        force: None,
13721                    }
13722                    .to_platform_input(),
13723                    cx,
13724                );
13725            })
13726            .unwrap();
13727    }
13728
13729    #[gpui::test]
13730    fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
13731        struct Child {
13732            renders: usize,
13733        }
13734
13735        impl Render for Child {
13736            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13737                self.renders += 1;
13738                div().size_full().bg(crate::rgb(0xff0000))
13739            }
13740        }
13741
13742        struct Root {
13743            opacity: f32,
13744            width: Pixels,
13745            child: crate::Entity<Child>,
13746        }
13747
13748        impl Render for Root {
13749            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13750                div()
13751                    .w(self.width)
13752                    .h(px(200.))
13753                    .opacity(self.opacity)
13754                    .hover(|style| style.opacity(1.))
13755                    .child(
13756                        self.child
13757                            .clone()
13758                            .cached(crate::StyleRefinement::default().size(px(100.))),
13759                    )
13760            }
13761        }
13762
13763        /// Updates the root, draws until no more frames are requested, and returns the
13764        /// child's painted alpha and how many times it has rendered.
13765        fn update_and_draw(
13766            window: crate::WindowHandle<Root>,
13767            child: &crate::Entity<Child>,
13768            cx: &mut TestAppContext,
13769            update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
13770        ) -> (f32, usize) {
13771            window
13772                .update(cx, |root, window, cx| {
13773                    update(root, window, cx);
13774                    cx.notify();
13775                })
13776                .expect("update root");
13777            for _ in 0..3 {
13778                let (alpha, renders, requested_frames) = cx
13779                    .update_window(window.into(), |_, window, cx| {
13780                        window.draw(cx).clear(cx);
13781                        let quads = &window.rendered_frame.scene.quads;
13782                        assert_eq!(quads.len(), 1);
13783                        let alpha = quads.first().expect("child quad").background.solid.a;
13784                        (
13785                            alpha,
13786                            child.read(cx).renders,
13787                            window.simulate_next_frame(cx),
13788                        )
13789                    })
13790                    .expect("draw window");
13791                if requested_frames == 0 {
13792                    return (alpha, renders);
13793                }
13794            }
13795            panic!("cached child kept requesting frames");
13796        }
13797
13798        let child = cx.new(|_| Child { renders: 0 });
13799        let window = cx.add_window(|_, _| Root {
13800            opacity: 1.,
13801            width: px(200.),
13802            child: child.clone(),
13803        });
13804        let outside = point(px(500.), px(500.));
13805        let inside = point(px(50.), px(50.));
13806        let beside = point(px(250.), px(50.));
13807
13808        // Changing the wrapper's opacity redraws the child; unchanged opacity reuses it.
13809        let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13810            window.simulate_mouse_move(outside, cx)
13811        };
13812        assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
13813        assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
13814        let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
13815        assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
13816        assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
13817
13818        // Hover opacity applies when the mouse enters and leaves.
13819        let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13820            window.simulate_mouse_move(inside, cx)
13821        };
13822        assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
13823        let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13824            window.simulate_mouse_move(beside, cx)
13825        };
13826        assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
13827
13828        // Widening the wrapper puts it under a still mouse, so only paint's hit test sees
13829        // the hover.
13830        let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
13831        assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
13832    }
13833
13834    #[gpui::test]
13835    fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
13836        struct ResizeHandle;
13837
13838        impl Render for ResizeHandle {
13839            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13840                div().size_full().cursor_text().child(
13841                    div()
13842                        .id("resize-handle")
13843                        .w(px(4.))
13844                        .h_full()
13845                        .cursor_col_resize()
13846                        .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
13847                )
13848            }
13849        }
13850
13851        let window = cx.add_window(|_, _| ResizeHandle);
13852        let handle_position = point(px(1.), px(10.));
13853        let drag_position = point(px(20.), px(10.));
13854        let cursor_observer = cx.clone();
13855
13856        let update_result = cx.update_window(window.into(), |_, window, cx| {
13857            window.hovered.set(true);
13858            window.active.set(true);
13859            window.draw(cx).clear(cx);
13860            window.dispatch_event(
13861                MouseMoveEvent {
13862                    position: handle_position,
13863                    ..Default::default()
13864                }
13865                .to_platform_input(),
13866                cx,
13867            );
13868            window.dispatch_event(
13869                MouseDownEvent {
13870                    position: handle_position,
13871                    button: MouseButton::Left,
13872                    ..Default::default()
13873                }
13874                .to_platform_input(),
13875                cx,
13876            );
13877            window.dispatch_event(
13878                MouseMoveEvent {
13879                    position: drag_position,
13880                    pressed_button: Some(MouseButton::Left),
13881                    ..Default::default()
13882                }
13883                .to_platform_input(),
13884                cx,
13885            );
13886            assert!(cx.has_active_drag());
13887            // Asserted here because leaving this update flushes effects, which paints a frame.
13888            assert_eq!(
13889                cursor_observer.test_platform().cursor_style(),
13890                CursorStyle::ResizeColumn
13891            );
13892
13893            window.draw(cx).clear(cx);
13894            window.dispatch_event(
13895                MouseUpEvent {
13896                    position: drag_position,
13897                    button: MouseButton::Left,
13898                    ..Default::default()
13899                }
13900                .to_platform_input(),
13901                cx,
13902            );
13903            window.draw(cx).clear(cx);
13904        });
13905        assert!(
13906            update_result.is_ok(),
13907            "failed to run drag: {update_result:?}"
13908        );
13909        assert_eq!(
13910            cursor_observer.test_platform().cursor_style(),
13911            CursorStyle::IBeam
13912        );
13913    }
13914}
13915
13916#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
13917mod inspector_tests {
13918    use super::*;
13919    use crate::{
13920        DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
13921    };
13922
13923    #[gpui::test]
13924    fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
13925        let windows = [
13926            cx.add_window(|_, cx| InspectorTestRoot {
13927                child: cx.new(|_| InspectorTestView::default()),
13928            }),
13929            cx.add_window(|_, cx| InspectorTestRoot {
13930                child: cx.new(|_| InspectorTestView::default()),
13931            }),
13932        ];
13933        for window in windows {
13934            assert_closed_inspector(window.into(), cx);
13935        }
13936        for _ in 0..2 {
13937            cx.update_window(windows[0].into(), |root, window, cx| {
13938                let root = root.downcast::<InspectorTestRoot>().expect("test root");
13939                let child_widths = root.read(cx).child.read(cx).child_widths.clone();
13940                window.toggle_inspector(cx);
13941                window.draw(cx).clear(cx);
13942                assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
13943                let path = window
13944                    .rendered_frame
13945                    .next_inspector_instance_ids
13946                    .iter()
13947                    .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
13948                    .expect("anonymous siblings share an inspector path");
13949                let selected_id = InspectorElementId {
13950                    path,
13951                    instance_id: 1,
13952                };
13953                let position = window
13954                    .rendered_frame
13955                    .hitboxes
13956                    .iter()
13957                    .find(|hitbox| {
13958                        window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
13959                            == Some(&selected_id)
13960                    })
13961                    .expect("middle sibling is pickable")
13962                    .bounds
13963                    .center();
13964                window.simulate_mouse_move(position, cx);
13965                window.dispatch_event(
13966                    PlatformInput::MouseDown(MouseDownEvent {
13967                        position,
13968                        button: MouseButton::Left,
13969                        modifiers: Modifiers::default(),
13970                        click_count: 1,
13971                        first_mouse: false,
13972                    }),
13973                    cx,
13974                );
13975                window.dispatch_event(
13976                    PlatformInput::MouseUp(MouseUpEvent {
13977                        position,
13978                        button: MouseButton::Left,
13979                        modifiers: Modifiers::default(),
13980                        click_count: 1,
13981                    }),
13982                    cx,
13983                );
13984                assert!(!window.is_inspector_picking(cx));
13985                assert_eq!(
13986                    window
13987                        .inspector
13988                        .as_ref()
13989                        .expect("open inspector")
13990                        .read(cx)
13991                        .active_element_id(),
13992                    Some(&selected_id)
13993                );
13994                window.draw(cx).clear(cx);
13995                window.with_inspector_state::<DivInspectorState, _>(
13996                    Some(&selected_id),
13997                    cx,
13998                    |state, _| {
13999                        let state = state.as_mut().expect("selected div has style state");
14000                        assert_eq!(
14001                            state.base_style.size.width,
14002                            Some(crate::Length::from(px(10.)))
14003                        );
14004                        state.base_style.size.width = Some(crate::Length::from(px(25.)));
14005                    },
14006                );
14007                window.refresh();
14008                window.draw(cx).clear(cx);
14009                assert_eq!(
14010                    child_widths.borrow().as_slice(),
14011                    &[px(10.), px(25.), px(10.)]
14012                );
14013            })
14014            .expect("pick and edit a cached child");
14015            assert_closed_inspector(windows[1].into(), cx);
14016            windows[0]
14017                .update(cx, |_, window, cx| window.toggle_inspector(cx))
14018                .expect("close inspector");
14019            assert_closed_inspector(windows[0].into(), cx);
14020        }
14021    }
14022
14023    struct InspectorTestRoot {
14024        child: Entity<InspectorTestView>,
14025    }
14026
14027    impl Render for InspectorTestRoot {
14028        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14029            self.child
14030                .clone()
14031                .cached(StyleRefinement::default().size(px(100.)))
14032        }
14033    }
14034
14035    #[derive(Default)]
14036    struct InspectorTestView {
14037        child_widths: Rc<RefCell<Vec<Pixels>>>,
14038    }
14039
14040    impl Render for InspectorTestView {
14041        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14042            let child_widths = self.child_widths.clone();
14043            div()
14044                .on_children_prepainted(move |bounds, _, _| {
14045                    *child_widths.borrow_mut() =
14046                        bounds.iter().map(|bounds| bounds.size.width).collect();
14047                })
14048                .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
14049                .id("inspector-root")
14050                .flex()
14051                .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
14052        }
14053    }
14054
14055    fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
14056        cx.update_window(window, |root, window, cx| {
14057            window.draw(cx).clear(cx);
14058            window.draw(cx).clear(cx);
14059            let root = root.downcast::<InspectorTestRoot>().expect("test root");
14060            assert_eq!(
14061                root.read(cx)
14062                    .child
14063                    .read(cx)
14064                    .child_widths
14065                    .borrow()
14066                    .as_slice(),
14067                &[px(10.); 3]
14068            );
14069            for frame in [&window.rendered_frame, &window.next_frame] {
14070                assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
14071                assert_eq!(frame.inspector_hitboxes.capacity(), 0);
14072            }
14073        })
14074        .expect("closed inspector has no bookkeeping and no style overrides");
14075    }
14076}
14077
14078/// vue-native fork: `Window::set_assume_active`.
14079#[cfg(test)]
14080mod vn_assume_active_tests {
14081    use crate::{
14082        Context, FocusHandle, Render, Subscription, TestAppContext, Window, div, prelude::*, px,
14083        size,
14084    };
14085    use std::{cell::Cell, rc::Rc};
14086
14087    struct Focusable {
14088        handle: FocusHandle,
14089        _on_focus: Subscription,
14090    }
14091
14092    impl Render for Focusable {
14093        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14094            div().size_full().track_focus(&self.handle)
14095        }
14096    }
14097
14098    #[gpui::test]
14099    fn an_assumed_active_window_runs_focus_and_ignores_the_os(cx: &mut TestAppContext) {
14100        let focused = Rc::new(Cell::new(0u32));
14101        let counter = focused.clone();
14102        let window = cx.open_window(size(px(200.), px(200.)), move |window, cx| {
14103            let handle = cx.focus_handle();
14104            let on_focus = cx.on_focus(&handle, window, move |_, _, _| counter.set(counter.get() + 1));
14105            Focusable { handle, _on_focus: on_focus }
14106        });
14107        let platform = cx.test_window(window.into());
14108        platform.simulate_active_status_change(false);
14109        cx.run_until_parked();
14110
14111        // An inactive window's focus events carry no path, so nothing hears
14112        // the focus move.
14113        window
14114            .update(cx, |view, window, cx| window.focus(&view.handle, cx))
14115            .unwrap();
14116        cx.run_until_parked();
14117        assert_eq!(focused.get(), 0, "no focus event without activation");
14118
14119        // Assumed active: the focused element hears it on the next frame.
14120        window
14121            .update(cx, |_, window, _| window.set_assume_active(true))
14122            .unwrap();
14123        cx.run_until_parked();
14124        assert_eq!(focused.get(), 1, "the focus event carries the path");
14125        let active = |cx: &mut TestAppContext| {
14126            window
14127                .update(cx, |_, window, _| window.is_window_active())
14128                .unwrap()
14129        };
14130        assert!(active(cx));
14131
14132        // The OS's activation changes are ignored while it is set.
14133        platform.simulate_active_status_change(false);
14134        cx.run_until_parked();
14135        assert!(active(cx), "still active after the OS says otherwise");
14136
14137        // Off: back to what the platform reports (a test window: inactive).
14138        window
14139            .update(cx, |_, window, _| window.set_assume_active(false))
14140            .unwrap();
14141        assert!(!active(cx));
14142    }
14143}
14144
14145/// vue-native fork: rounded content masks, `ContentMask::intersect`'s corner
14146/// rule, `contains` and `transform_mask`.
14147/// vue-native fork: outer shadows are cut out of the border box
14148/// ([`Window::paint_drop_shadows`]), with CSS's spread radii.
14149#[cfg(test)]
14150mod vn_shadow_tests {
14151    use super::{SHADOW_INSET, SHADOW_OUTSIDE_BOX, SHADOW_UNDER_BOX, spread_shadow_radius};
14152    use crate::{
14153        BoxShadow, Context, Hsla, TestAppContext, Window, div, point, prelude::*, px, size,
14154    };
14155
14156    #[test]
14157    fn a_spread_grows_a_rounded_corner_and_keeps_a_square_one_square() {
14158        // A focus ring: rounded-md (6px) and a 3px spread.
14159        assert_eq!(spread_shadow_radius(px(6.), px(3.)), px(9.));
14160        assert_eq!(spread_shadow_radius(px(0.), px(3.)), px(0.));
14161        // Rounded by less than the spread: 1 + (r/s - 1)^3 of the spread.
14162        assert_eq!(spread_shadow_radius(px(1.5), px(3.)), px(1.5 + 3. * 0.875));
14163        assert_eq!(spread_shadow_radius(px(6.), px(0.)), px(6.));
14164        assert_eq!(spread_shadow_radius(px(6.), px(-2.)), px(4.));
14165        assert_eq!(spread_shadow_radius(px(1.), px(-2.)), px(0.));
14166    }
14167
14168    struct Ring {
14169        under_box: bool,
14170    }
14171
14172    impl Render for Ring {
14173        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14174            let shadow = |inset: bool| BoxShadow {
14175                color: Hsla::white().opacity(0.5),
14176                offset: point(px(0.), px(0.)),
14177                blur_radius: px(0.),
14178                spread_radius: px(3.),
14179                inset,
14180            };
14181            let mut d = div()
14182                .w(px(100.))
14183                .h(px(36.))
14184                .rounded_md()
14185                .shadow(vec![shadow(false), shadow(true)]);
14186            d.style().vn_shadow_under_box = Some(self.under_box);
14187            d
14188        }
14189    }
14190
14191    /// The frame's shadows as (kind, top-left radius, element top-left radius), in device px.
14192    fn paint(under_box: bool, cx: &mut TestAppContext) -> (Vec<(u32, f32, f32)>, f32) {
14193        let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Ring { under_box });
14194        cx.run_until_parked();
14195        window
14196            .update(cx, |_, window, _| {
14197                let shadows = window
14198                    .rendered_frame
14199                    .scene
14200                    .shadows
14201                    .iter()
14202                    .map(|s| (s.inset, s.shape_corner_radii.top_left.0, s.corner_radii.top_left.0))
14203                    .collect();
14204                (shadows, window.scale_factor())
14205            })
14206            .unwrap()
14207    }
14208
14209    #[gpui::test]
14210    fn an_outer_shadow_is_cut_out_of_the_border_box_unless_it_stands_in_for_the_box(
14211        cx: &mut TestAppContext,
14212    ) {
14213        let (shadows, scale) = paint(false, cx);
14214        let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14215        assert_eq!(outer.0, SHADOW_OUTSIDE_BOX, "the shaders cut the border box out of it");
14216        assert_eq!(outer.1, 9. * scale, "6px corner + 3px spread");
14217        assert_eq!(outer.2, 6. * scale, "the cut-out is the border box itself");
14218        assert!(shadows.iter().any(|s| s.0 == SHADOW_INSET), "the inset shadow is unchanged");
14219
14220        let (shadows, _) = paint(true, cx);
14221        let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14222        assert_eq!(outer.0, SHADOW_UNDER_BOX);
14223    }
14224}
14225
14226#[cfg(test)]
14227mod vn_rounded_mask_tests {
14228    use super::transform_mask;
14229    use crate::{Bounds, ContentMask, Corners, TransformationMatrix, point, px, size};
14230
14231    fn mask(x: f32, y: f32, w: f32, h: f32, radius: f32) -> ContentMask<crate::Pixels> {
14232        ContentMask {
14233            bounds: Bounds::new(point(px(x), px(y)), size(px(w), px(h))),
14234            corner_radii: Corners::all(px(radius)),
14235        }
14236    }
14237
14238    #[test]
14239    fn rectangles_intersect_exactly_and_stay_square() {
14240        let a = mask(0., 0., 100., 100., 0.);
14241        let b = mask(50., 20., 100., 30., 0.);
14242        let both = a.intersect(&b);
14243        assert_eq!(both.bounds, Bounds::new(point(px(50.), px(20.)), size(px(50.), px(30.))));
14244        assert!(!both.is_rounded());
14245    }
14246
14247    #[test]
14248    fn a_corner_keeps_the_radius_of_the_mask_it_belongs_to() {
14249        // A rounded card and the square scroller that fills it.
14250        let card = mask(10., 10., 200., 160., 24.);
14251        let scroller = mask(10., 10., 200., 160., 0.);
14252        assert_eq!(scroller.intersect(&card).corner_radii, Corners::all(px(24.)));
14253        assert_eq!(card.intersect(&scroller).corner_radii, Corners::all(px(24.)));
14254
14255        // A rect that shares only the card's top edge: its top corners are
14256        // the card's, its bottom ones are its own.
14257        let header = mask(10., 10., 200., 60., 0.);
14258        let clipped = header.intersect(&card);
14259        assert_eq!(clipped.corner_radii.top_left, px(24.));
14260        assert_eq!(clipped.corner_radii.top_right, px(24.));
14261        assert_eq!(clipped.corner_radii.bottom_left, px(0.));
14262        assert_eq!(clipped.corner_radii.bottom_right, px(0.));
14263
14264        // Two rounded corners at one point nest; the larger radius is the
14265        // smaller region.
14266        let inner = mask(10., 10., 200., 160., 8.);
14267        assert_eq!(inner.intersect(&card).corner_radii, Corners::all(px(24.)));
14268
14269        // A rect inside the card's straight span is square, which is exact.
14270        let row = mask(40., 60., 100., 20., 0.);
14271        assert!(!row.intersect(&card).is_rounded());
14272
14273        // The radii still fit the result.
14274        let sliver = mask(10., 10., 200., 10., 0.);
14275        let clipped = sliver.intersect(&card);
14276        assert_eq!(clipped.corner_radii.top_left, px(5.));
14277    }
14278
14279    #[test]
14280    fn contains_follows_the_curve() {
14281        let avatar = mask(0., 0., 64., 64., 32.);
14282        assert!(avatar.contains(&point(px(32.), px(32.))));
14283        assert!(avatar.contains(&point(px(32.), px(1.))), "the top edge's middle");
14284        assert!(!avatar.contains(&point(px(2.), px(2.))), "outside the curve");
14285        assert!(!avatar.contains(&point(px(62.), px(62.))));
14286        assert!(avatar.contains(&point(px(10.), px(10.))), "inside the curve");
14287        assert!(!avatar.contains(&point(px(70.), px(32.))), "outside the rect");
14288        assert!(mask(0., 0., 64., 64., 0.).contains(&point(px(1.), px(1.))));
14289    }
14290
14291    #[test]
14292    fn a_transform_keeps_the_radii_only_while_corners_stay_round() {
14293        let card = mask(0., 0., 100., 100., 10.);
14294        let moved = TransformationMatrix {
14295            rotation_scale: [[1., 0.], [0., 1.]],
14296            translation: [5., 7.],
14297        };
14298        assert_eq!(transform_mask(moved, card, 1.).corner_radii, Corners::all(px(10.)));
14299
14300        let scaled = TransformationMatrix {
14301            rotation_scale: [[2., 0.], [0., 3.]],
14302            translation: [0., 0.],
14303        };
14304        assert_eq!(
14305            transform_mask(scaled, card, 1.).corner_radii,
14306            Corners::all(px(20.)),
14307            "the smaller factor"
14308        );
14309
14310        let rotated = TransformationMatrix {
14311            rotation_scale: [[0., 1.], [-1., 0.]],
14312            translation: [0., 0.],
14313        };
14314        assert!(!transform_mask(rotated, card, 1.).is_rounded());
14315    }
14316}
14317
14318/// vue-native fork: `Window::pointer_inside`.
14319#[cfg(test)]
14320mod vn_pointer_inside_tests {
14321    use crate::{
14322        Context, Modifiers, MouseExitEvent, MouseMoveEvent, PlatformInput, Render,
14323        TestAppContext, Window, div, point, prelude::*, px, size,
14324    };
14325    use std::{cell::Cell, rc::Rc};
14326
14327    struct Hoverable {
14328        hovered: Rc<Cell<bool>>,
14329    }
14330
14331    impl Render for Hoverable {
14332        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14333            let hovered = self.hovered.clone();
14334            div()
14335                .id("box")
14336                .size_full()
14337                .on_hover(move |is_hovered, _, _| hovered.set(*is_hovered))
14338        }
14339    }
14340
14341    #[gpui::test]
14342    fn a_pointer_outside_the_window_hovers_nothing(cx: &mut TestAppContext) {
14343        let hovered = Rc::new(Cell::new(false));
14344        let state = hovered.clone();
14345        let window = cx.open_window(size(px(200.), px(200.)), move |_, _| Hoverable {
14346            hovered: state,
14347        });
14348        let mut platform = cx.test_window(window.into());
14349        let draw = |cx: &mut TestAppContext| {
14350            window.update(cx, |_, window, _| window.refresh()).unwrap();
14351            cx.run_until_parked();
14352        };
14353        let at = |x: f32, y: f32| point(px(x), px(y));
14354        let moved = |x: f32, y: f32| {
14355            PlatformInput::MouseMove(MouseMoveEvent {
14356                position: at(x, y),
14357                pressed_button: None,
14358                modifiers: Modifiers::default(),
14359            })
14360        };
14361
14362        // The test platform reports the cursor at (0, 0), inside the box, as
14363        // Windows reports wherever the cursor projects. No pointer input has
14364        // reached the window, so nothing is hovered.
14365        draw(cx);
14366        assert!(!hovered.get(), "a cursor that never entered hovers nothing");
14367
14368        platform.simulate_input(moved(50., 50.));
14369        draw(cx);
14370        assert!(hovered.get(), "a move into the box hovers it");
14371
14372        // The platform says the pointer left (`WM_MOUSELEAVE`). The position
14373        // is still inside the box, and the next frame's hit test still finds
14374        // it there.
14375        platform.simulate_hover_status_change(false);
14376        draw(cx);
14377        assert!(!hovered.get(), "a pointer that left hovers nothing");
14378
14379        platform.simulate_input(moved(60., 60.));
14380        draw(cx);
14381        assert!(hovered.get(), "back in");
14382
14383        platform.simulate_input(PlatformInput::MouseExited(MouseExitEvent {
14384            position: at(60., 60.),
14385            pressed_button: None,
14386            modifiers: Modifiers::default(),
14387        }));
14388        draw(cx);
14389        assert!(!hovered.get(), "MouseExited");
14390    }
14391
14392    struct Shaded {
14393        effect: bool,
14394        renders: Rc<Cell<usize>>,
14395    }
14396
14397    impl Render for Shaded {
14398        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14399            self.renders.set(self.renders.get() + 1);
14400            let mut element = div().size_full();
14401            if self.effect {
14402                let mut spec = crate::EffectSpec::NONE;
14403                spec.id = 0;
14404                spec.pointer_param = Some(4);
14405                element.style().vn_effect = Some(spec);
14406            }
14407            element
14408        }
14409    }
14410
14411    #[gpui::test]
14412    fn only_a_pointer_effect_repaints_when_the_pointer_moves(cx: &mut TestAppContext) {
14413        let open = |cx: &mut TestAppContext, effect: bool| {
14414            let renders = Rc::new(Cell::new(0));
14415            let counted = renders.clone();
14416            let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Shaded {
14417                effect,
14418                renders: counted,
14419            });
14420            cx.run_until_parked();
14421            (window, cx.test_window(window.into()), renders)
14422        };
14423        let moved = |x: f32, y: f32| {
14424            PlatformInput::MouseMove(MouseMoveEvent {
14425                position: point(px(x), px(y)),
14426                pressed_button: None,
14427                modifiers: Modifiers::default(),
14428            })
14429        };
14430
14431        let (_, mut platform, renders) = open(cx, false);
14432        platform.simulate_input(moved(10., 10.));
14433        cx.run_until_parked();
14434        let before = renders.get();
14435        platform.simulate_input(moved(20., 20.));
14436        cx.run_until_parked();
14437        assert_eq!(renders.get(), before, "no pointer effect, no repaint");
14438
14439        let (shaded, mut platform, renders) = open(cx, true);
14440        platform.simulate_input(moved(10., 10.));
14441        cx.run_until_parked();
14442        let before = renders.get();
14443        platform.simulate_input(moved(150., 25.));
14444        cx.run_until_parked();
14445        assert!(renders.get() > before, "a pointer effect repaints");
14446        let params = shaded
14447            .update(cx, |_, window, _| {
14448                window.rendered_frame.scene.effect_quads[0].params
14449            })
14450            .unwrap();
14451        assert!((params[4] - 0.75).abs() < 1e-4 && (params[5] - 0.25).abs() < 1e-4);
14452    }
14453
14454    struct Spinning {
14455        speed: Rc<Cell<f32>>,
14456    }
14457
14458    impl Render for Spinning {
14459        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14460            let mut spec = crate::EffectSpec::NONE;
14461            spec.id = 0;
14462            spec.animated_param = Some(0);
14463            spec.params[0] = self.speed.get();
14464            let mut element = div().id("spinning").size_full();
14465            element.style().vn_effect = Some(spec);
14466            element
14467        }
14468    }
14469
14470    #[gpui::test]
14471    fn a_speed_change_continues_the_phase_instead_of_rescaling_the_clock(
14472        cx: &mut TestAppContext,
14473    ) {
14474        let speed = Rc::new(Cell::new(1.));
14475        let shared = speed.clone();
14476        let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Spinning {
14477            speed: shared,
14478        });
14479        cx.run_until_parked();
14480        let repaint = |cx: &mut TestAppContext| {
14481            window.update(cx, |_, window, _| window.refresh()).unwrap();
14482            cx.run_until_parked();
14483            window
14484                .update(cx, |_, window, _| {
14485                    let quad = window.rendered_frame.scene.effect_quads[0];
14486                    (quad.params[0] * quad.time, quad.time)
14487                })
14488                .unwrap()
14489        };
14490        // A rescale is only visible once the clock is away from zero.
14491        std::thread::sleep(std::time::Duration::from_millis(200));
14492        let (before, then) = repaint(cx);
14493        assert!((before - then).abs() < 1e-3, "an unchanged speed is `speed * time`");
14494
14495        speed.set(8.);
14496        let (after, now) = repaint(cx);
14497        let advanced = after - before;
14498        assert!(
14499            advanced >= -1e-3 && advanced <= 8. * (now - then) + 1e-3,
14500            "the phase moved by {advanced} in {}s",
14501            now - then
14502        );
14503    }
14504}
14505
14506#[cfg(test)]
14507mod vn_tagged_transform_tests {
14508    use crate::{
14509        AnyElement, App, Bounds, Context, Element, GlobalElementId, InspectorElementId,
14510        IntoElement, LayoutId, Pixels, Render, TestAppContext, TransformLength, TransformSpec,
14511        Window, div, prelude::*, px, size,
14512    };
14513    use std::{cell::RefCell, rc::Rc};
14514
14515    type Seen = Rc<RefCell<Vec<(u32, Bounds<Pixels>, Bounds<Pixels>)>>>;
14516
14517    /// What an embedder's per-node probe does: tag the subtree, prepaint it,
14518    /// take the node's transform, and map its layout box through it.
14519    struct Probe {
14520        tag: u32,
14521        inner: AnyElement,
14522        seen: Seen,
14523    }
14524
14525    impl Element for Probe {
14526        type RequestLayoutState = ();
14527        type PrepaintState = ();
14528        fn id(&self) -> Option<crate::ElementId> {
14529            None
14530        }
14531        fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
14532            None
14533        }
14534        fn request_layout(
14535            &mut self,
14536            _: Option<&GlobalElementId>,
14537            _: Option<&InspectorElementId>,
14538            window: &mut Window,
14539            cx: &mut App,
14540        ) -> (LayoutId, ()) {
14541            (self.inner.request_layout(window, cx), ())
14542        }
14543        fn prepaint(
14544            &mut self,
14545            _: Option<&GlobalElementId>,
14546            _: Option<&InspectorElementId>,
14547            bounds: Bounds<Pixels>,
14548            _: &mut (),
14549            window: &mut Window,
14550            cx: &mut App,
14551        ) {
14552            let ancestors = window.element_transform();
14553            let (_, own) =
14554                window.with_hitbox_tag(self.tag, |window| self.inner.prepaint(window, cx));
14555            let seen = window.transformed_bounds(own.unwrap_or(ancestors), bounds);
14556            self.seen.borrow_mut().push((self.tag, bounds, seen));
14557        }
14558        fn paint(
14559            &mut self,
14560            _: Option<&GlobalElementId>,
14561            _: Option<&InspectorElementId>,
14562            _: Bounds<Pixels>,
14563            _: &mut (),
14564            _: &mut (),
14565            window: &mut Window,
14566            cx: &mut App,
14567        ) {
14568            self.inner.paint(window, cx);
14569        }
14570    }
14571
14572    fn moved(x: TransformLength, y: TransformLength, scale: f32) -> TransformSpec {
14573        TransformSpec { translate: (x, y), scale: (scale, scale), ..TransformSpec::IDENTITY }
14574    }
14575
14576    /// A popper wrapper laid out at (0, 0) and moved by `translate`, a button
14577    /// inside it, and a third box scaled inside that.
14578    struct Popper {
14579        seen: Seen,
14580    }
14581
14582    impl Render for Popper {
14583        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14584            let probe = |tag, inner: AnyElement| Probe { tag, inner, seen: self.seen.clone() };
14585            let mut wrapper = div().w(px(100.)).h(px(80.));
14586            wrapper.style().vn_transform =
14587                Some(moved(TransformLength::Pixels(300.), TransformLength::Pixels(200.), 1.0));
14588            let mut scaled = div().w(px(20.)).h(px(10.));
14589            scaled.style().vn_transform =
14590                Some(moved(TransformLength::ZERO, TransformLength::ZERO, 2.0));
14591            // Built inside the button under the button's tag, like a
14592            // `::before` box: its own transform is not the button's.
14593            let mut pseudo = div().w(px(4.)).h(px(4.));
14594            pseudo.style().vn_transform =
14595                Some(moved(TransformLength::Pixels(50.), TransformLength::ZERO, 1.0));
14596            let button = div()
14597                .ml(px(10.))
14598                .w(px(30.))
14599                .h(px(20.))
14600                .child(probe(3, scaled.into_any_element()))
14601                .child(pseudo);
14602            div().size_full().child(probe(
14603                1,
14604                wrapper.child(probe(2, button.into_any_element())).into_any_element(),
14605            ))
14606        }
14607    }
14608
14609    #[gpui::test]
14610    fn a_probe_sees_its_node_where_the_transforms_put_it(cx: &mut TestAppContext) {
14611        let seen: Seen = Rc::default();
14612        let state = seen.clone();
14613        let window =
14614            cx.open_window(size(px(800.), px(600.)), move |_, _| Popper { seen: state });
14615        window.update(cx, |_, window, _| window.refresh()).unwrap();
14616        cx.run_until_parked();
14617        let seen = seen.borrow();
14618        let at = |tag: u32| *seen.iter().rev().find(|s| s.0 == tag).expect("probed");
14619        let b = |x: f32, y: f32, w: f32, h: f32| {
14620            Bounds::new(crate::point(px(x), px(y)), size(px(w), px(h)))
14621        };
14622        // Its own translate moves the wrapper; the layout box stays at 0, 0.
14623        assert_eq!(at(1).1, b(0., 0., 100., 80.));
14624        assert_eq!(at(1).2, b(300., 200., 100., 80.));
14625        // A child with no transform of its own moves with its ancestor, and
14626        // not with the one a box built inside it has.
14627        assert_eq!(at(2).1, b(10., 0., 30., 20.));
14628        assert_eq!(at(2).2, b(310., 200., 30., 20.));
14629        // Its own scale (about its centre) composes with the ancestor's move.
14630        assert_eq!(at(3).1, b(10., 0., 20., 10.));
14631        assert_eq!(at(3).2, b(300., 195., 40., 20.));
14632    }
14633}