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, AtlasTextureKind, AtlasTile, AvailableSpace, BackdropBlurRect, Background, BorderStyle,
12    EffectQuad, EffectSpec,
13    Bounds, BoxShadow,
14    Capslock, Context, CornerShape, CornerShapes, 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, HdrOutput,
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            corner_shapes: mask.corner_shapes,
1013        };
1014    }
1015    let [[a, b], [c, d]] = matrix.rotation_scale;
1016    let (corner_radii, corner_shapes) = if b == 0. && c == 0. && a > 0. && d > 0. {
1017        let factor = a.min(d);
1018        let radii = mask.corner_radii
1019            .map(|radius| *radius * factor)
1020            .clamp_radii_for_quad_size(bounds.size);
1021        (radii, mask.corner_shapes.scale(factor))
1022    } else {
1023        (Corners::default(), CornerShapes::default())
1024    };
1025    ContentMask {
1026        bounds,
1027        corner_radii,
1028        corner_shapes,
1029    }
1030}
1031
1032/// A rectangular region that potentially blocks hitboxes inserted prior.
1033/// See [Window::insert_hitbox] for more details.
1034#[derive(Clone, Debug)]
1035pub struct Hitbox {
1036    /// A unique identifier for the hitbox.
1037    pub id: HitboxId,
1038    /// The bounds of the hitbox.
1039    pub bounds: Bounds<Pixels>,
1040    /// The content mask when the hitbox was inserted.
1041    pub content_mask: ContentMask<Pixels>,
1042    /// Flags that specify hitbox behavior.
1043    pub behavior: HitboxBehavior,
1044    /// The composed CSS `transform` in force when the hitbox was inserted, in
1045    /// DEVICE space (the same matrix the primitives carry).
1046    ///
1047    /// `bounds` stays the UNTRANSFORMED rect, because that is the frame the
1048    /// element and everything that reads a hitbox (autoscroll, tooltip
1049    /// placement, `Hitbox::bounds`) thinks in. Hit-testing therefore maps the
1050    /// pointer BACKWARDS through this rather than mapping the rect forwards —
1051    /// see [`Frame::hit_test`].
1052    pub transformation: TransformationMatrix,
1053    /// vue-native fork: the `clip-path` shapes that are no rounded rectangle
1054    /// around the hitbox when it was inserted, in window device pixels. A
1055    /// point outside any of them does not hit it (CSS Masking 1 §5).
1056    pub vn_clip: Option<Arc<crate::VnClipNode>>,
1057}
1058
1059impl_deref!([] Hitbox => bounds: Bounds<Pixels>);
1060
1061impl Hitbox {
1062    /// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality
1063    /// so that keyboard navigation suppresses hover highlights. Except when handling
1064    /// `ScrollEvent`, this is typically what you want when determining whether to handle mouse
1065    /// events or paint hover styles.
1066    ///
1067    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
1068    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
1069    /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`),
1070    /// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]).
1071    ///
1072    /// Handling of `ScrollEvent` should typically use `should_handle_scroll` instead.
1073    /// Concretely, this is due to use-cases like overlays that cause the elements under to be
1074    /// non-interactive while still allowing scrolling. More abstractly, this is because
1075    /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
1076    /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
1077    /// container.
1078    pub fn is_hovered(&self, window: &Window) -> bool {
1079        self.id.is_hovered(window)
1080    }
1081
1082    /// Checks whether this hitbox would be hovered at `position`, regardless of the current input
1083    /// modality or mouse position.
1084    pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
1085        // Our hit test maps the pointer back through each hitbox's transform, so
1086        // it needs the window's scale factor (see `Frame::hit_test`).
1087        let hit_test = window
1088            .rendered_frame
1089            .hit_test(position, window.scale_factor);
1090        hit_test
1091            .ids
1092            .iter()
1093            .take(hit_test.hover_hitbox_count)
1094            .any(|id| self.id == *id)
1095    }
1096
1097    /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
1098    /// should only be used when handling `ScrollEvent`, and otherwise `is_hovered` should be
1099    /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
1100    ///
1101    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
1102    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
1103    pub fn should_handle_scroll(&self, window: &Window) -> bool {
1104        self.id.should_handle_scroll(window)
1105    }
1106}
1107
1108/// vue-native fork: the bit an embedder ORs into a hitbox tag
1109/// ([`Window::set_hitbox_tag`]) for a box that belongs to the node but is not
1110/// where the node is — a scroll container's wheel viewport, inserted after
1111/// the content it covers. [`Window::vn_tags_at`] leaves such boxes out;
1112/// [`Window::vn_restrict_mouse_hit`] judges them by the node.
1113pub const VN_TAG_PASSIVE: u32 = 1 << 31;
1114
1115/// vue-native fork: which mouse event a [`VnHitRefiner`] is refining.
1116#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1117pub enum VnHitKind {
1118    /// A [`MouseDownEvent`](crate::MouseDownEvent).
1119    Down,
1120    /// A [`MouseUpEvent`].
1121    Up,
1122    /// A [`ScrollEvent`](crate::ScrollEvent).
1123    Scroll,
1124}
1125
1126/// vue-native fork: the embedder's say over which hitboxes a mouse event is
1127/// for, run once per press, release and wheel before any listener sees it.
1128/// See [`Window::set_vn_hit_refiner`].
1129pub type VnHitRefiner = Rc<dyn Fn(VnHitKind, Point<Pixels>, &mut Window, &mut App)>;
1130
1131/// vue-native fork: how [`Window::vn_lock_pointer`] holds the pointer.
1132#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1133pub enum VnPointerLock {
1134    /// The platform hides and holds the cursor ([`PlatformWindow::lock_pointer`]).
1135    System {
1136        /// The device's own counts, without pointer acceleration.
1137        unadjusted: bool,
1138    },
1139    /// gpui's half alone, for tests: mouse events hold still at the lock position and moves
1140    /// report how far their own position moved. The cursor is left alone.
1141    Simulated,
1142}
1143
1144/// How the hitbox affects mouse behavior.
1145#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1146pub enum HitboxBehavior {
1147    /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
1148    #[default]
1149    Normal,
1150
1151    /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
1152    /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
1153    /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
1154    /// [`InteractiveElement::occlude`].
1155    ///
1156    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
1157    /// bubble-phase handler for every mouse event type:
1158    ///
1159    /// ```ignore
1160    /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
1161    ///     if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
1162    ///         cx.stop_propagation();
1163    ///     }
1164    /// })
1165    /// ```
1166    ///
1167    /// This has effects beyond event handling - any use of hitbox checking, such as hover
1168    /// styles and tooltips. These other behaviors are the main point of this mechanism. An
1169    /// alternative might be to not affect mouse event handling - but this would allow
1170    /// inconsistent UI where clicks and moves interact with elements that are not considered to
1171    /// be hovered.
1172    BlockMouse,
1173
1174    /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
1175    /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
1176    /// interaction except scroll events to be ignored - see the documentation of
1177    /// [`Hitbox::is_hovered`] for details. This flag is set by
1178    /// [`InteractiveElement::block_mouse_except_scroll`].
1179    ///
1180    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
1181    /// bubble-phase handler for every mouse event type **except** `ScrollEvent`:
1182    ///
1183    /// ```ignore
1184    /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
1185    ///     if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
1186    ///         cx.stop_propagation();
1187    ///     }
1188    /// })
1189    /// ```
1190    ///
1191    /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollEvent` is
1192    /// handled differently than other mouse events. If also blocking these scroll events is
1193    /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
1194    ///
1195    /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
1196    /// hover styles and tooltips. These other behaviors are the main point of this mechanism.
1197    /// An alternative might be to not affect mouse event handling - but this would allow
1198    /// inconsistent UI where clicks and moves interact with elements that are not considered to
1199    /// be hovered.
1200    BlockMouseExceptScroll,
1201}
1202
1203/// An identifier for a tooltip.
1204#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1205pub struct TooltipId(usize);
1206
1207impl TooltipId {
1208    /// Checks if the tooltip is currently hovered.
1209    pub fn is_hovered(&self, window: &Window) -> bool {
1210        window
1211            .tooltip_bounds
1212            .as_ref()
1213            .is_some_and(|tooltip_bounds| {
1214                tooltip_bounds.id == *self
1215                    && tooltip_bounds.bounds.contains(&window.mouse_position())
1216            })
1217    }
1218}
1219
1220pub(crate) struct TooltipBounds {
1221    id: TooltipId,
1222    bounds: Bounds<Pixels>,
1223}
1224
1225#[derive(Clone)]
1226pub(crate) struct TooltipRequest {
1227    id: TooltipId,
1228    tooltip: AnyTooltip,
1229}
1230
1231/// The ids of the elements being drawn, root first, with the hash of every
1232/// prefix alongside: a [`GlobalElementId`] for the current element is then
1233/// the ids cloned out and the hash on top of the stack, without walking the
1234/// path — the ids of every ancestor, string names byte by byte — for each
1235/// element on every frame.
1236#[derive(Clone, Default)]
1237pub(crate) struct ElementIdStack {
1238    ids: SmallVec<[ElementId; 32]>,
1239    hashes: SmallVec<[u64; 32]>,
1240}
1241
1242impl ElementIdStack {
1243    pub(crate) fn push(&mut self, id: ElementId) {
1244        self.hashes.push(crate::extend_path_hash(self.hash(), &id));
1245        self.ids.push(id);
1246    }
1247
1248    pub(crate) fn pop(&mut self) -> Option<ElementId> {
1249        self.hashes.pop();
1250        self.ids.pop()
1251    }
1252
1253    pub(crate) fn clear(&mut self) {
1254        self.ids.clear();
1255        self.hashes.clear();
1256    }
1257
1258    /// The hash of the whole path on the stack.
1259    fn hash(&self) -> u64 {
1260        self.hashes
1261            .last()
1262            .copied()
1263            .unwrap_or(crate::EMPTY_PATH_HASH)
1264    }
1265
1266    pub(crate) fn global_id(&self) -> GlobalElementId {
1267        GlobalElementId::with_hash(&self.ids, self.hash())
1268    }
1269}
1270
1271impl std::ops::Deref for ElementIdStack {
1272    type Target = [ElementId];
1273
1274    fn deref(&self) -> &Self::Target {
1275        &self.ids
1276    }
1277}
1278
1279pub(crate) struct DeferredDraw {
1280    current_view: EntityId,
1281    priority: usize,
1282    parent_node: DispatchNodeId,
1283    element_id_stack: ElementIdStack,
1284    text_style_stack: Vec<TextStyleRefinement>,
1285    content_mask: Option<ContentMask<Pixels>>,
1286    rem_size: Pixels,
1287    element: Option<AnyElement>,
1288    absolute_offset: Point<Pixels>,
1289    /// The CSS `transform` in force where the element was deferred FROM.
1290    ///
1291    /// A deferred draw is replayed at the top of the frame, where the transform
1292    /// stack is empty — so without this, an element that escapes its siblings'
1293    /// paint order (`position: fixed`, `z-index`) also escapes its ancestors'
1294    /// transforms and paints somewhere nobody asked for. A `z-10` sticky header
1295    /// inside a `translate(-50%, -50%)` dialog landed half the window away from
1296    /// the dialog it belongs to.
1297    element_transform: TransformationMatrix,
1298    /// vue-native fork: the accessibility node on top of the stack where the
1299    /// element was deferred FROM, which its nodes belong under
1300    /// (`A11yNodeBuilder::begin_adopted`). `None` when accessibility was off.
1301    a11y_parent: Option<accesskit::NodeId>,
1302    /// vue-native fork: where the draw sorts among draws of equal `priority`,
1303    /// compared lexicographically — see [`crate::Deferred::with_stack_key`].
1304    /// `None` sorts first.
1305    vn_stack: Option<Rc<[u128]>>,
1306    /// vue-native fork: the opacity in force where the element was deferred
1307    /// FROM. Like the transform, it would otherwise be lost at the top of the
1308    /// frame: CSS applies an ancestor's `opacity` to everything inside it,
1309    /// out-of-flow descendants included.
1310    element_opacity: f32,
1311    /// vue-native fork: the `clip-path` shapes in force where the element
1312    /// was deferred FROM, taken with the content mask (none when the draw
1313    /// escapes its ancestors' clips). Its prepaint re-enters them, and its
1314    /// paint re-opens an isolated layer for each ([`Window::vn_with_clip_shape`]).
1315    vn_clip: Option<Arc<crate::VnClipNode>>,
1316    /// vue-native fork: the `[SkContent]` effect the draw was deferred from
1317    /// inside, which paints it into its content ([`VnDeferScope`]).
1318    vn_scope: Option<VnDeferScope>,
1319    prepaint_range: Range<PrepaintStateIndex>,
1320    paint_range: Range<PaintIndex>,
1321    /// The entities the deferred element accessed while it was last drawn, in
1322    /// any phase, restored when its prepaint is reused.
1323    accessed_entities: FxHashSet<EntityId>,
1324}
1325
1326/// vue-native fork: an element whose effect reads its own content. A draw
1327/// deferred from inside it (a positioned descendant) paints into that
1328/// content, after the element's in-flow subtree, rather than after the whole
1329/// tree where the effect never sees it. `id` is the element's
1330/// [`vn_element_key`]; `clip` the clip stack its subtree prepainted in, which
1331/// the content group is already inside of.
1332#[derive(Clone, Debug)]
1333pub(crate) struct VnDeferScope {
1334    id: u64,
1335    clip: Option<Arc<crate::VnClipNode>>,
1336}
1337
1338/// vue-native fork: an element's identity for per-element paint state, 0
1339/// for none. Views are left out: a cached subtree is painted inside its view
1340/// on one frame and replayed without it on the next.
1341pub(crate) fn vn_element_key(id: Option<&GlobalElementId>) -> u64 {
1342    use std::hash::{Hash, Hasher};
1343    id.map_or(0, |id| {
1344        let mut hasher = collections::FxHasher::default();
1345        for id in id.iter() {
1346            if !matches!(id, ElementId::View(_)) {
1347                id.hash(&mut hasher);
1348            }
1349        }
1350        hasher.finish().max(1)
1351    })
1352}
1353
1354impl DeferredDraw {
1355    /// The paint order: `priority`, then the embedder's stack key.
1356    fn order(&self) -> (usize, Option<&[u128]>) {
1357        (self.priority, self.vn_stack.as_deref())
1358    }
1359}
1360
1361pub(crate) struct Frame {
1362    pub(crate) focus: Option<FocusId>,
1363    pub(crate) window_active: bool,
1364    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1365    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1366    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1367    pub(crate) dispatch_tree: DispatchTree,
1368    pub(crate) scene: Scene,
1369    pub(crate) hitboxes: Vec<Hitbox>,
1370    /// vue-native fork: the hitboxes inserted while [`Window::hitbox_tag`] was
1371    /// non-zero, paired with the tag in force.
1372    ///
1373    /// An embedder that mirrors its own retained tree into gpui elements has no
1374    /// other way to get from one of ITS node ids to the hitbox gpui made for it
1375    /// — and without that, `Hitbox::is_hovered_at` (the only public door onto
1376    /// gpui's hit test) cannot be asked about a node. Insertion order is
1377    /// preserved, and an element's own hitbox is inserted before any of its
1378    /// descendants', so the FIRST entry for a tag is that node's own box.
1379    pub(crate) vn_tagged_hitboxes: Vec<(u32, Hitbox)>,
1380    /// vue-native fork: [`Frame::hitboxes`]' indices in PAINT order, which
1381    /// [`Frame::hit_test`] walks topmost-first. Empty means insertion order.
1382    ///
1383    /// Hitboxes are inserted in prepaint order, and deferred draws prepaint in
1384    /// nesting rounds: a draw nested one round deeper is inserted after every
1385    /// draw of the round before, wherever it paints. Hit-testing by insertion
1386    /// let a box that paints UNDER a later overlay take its clicks. The vector
1387    /// itself is not reordered, because cached views replay ranges of it.
1388    pub(crate) vn_hit_order: Vec<u32>,
1389    /// vue-native fork: the slice of [`Frame::vn_tagged_hitboxes`] the
1390    /// deferred draws' prepaint inserted — what
1391    /// [`Frame::vn_tagged_paint_order`] reorders, as `vn_hit_order` does the
1392    /// hitboxes.
1393    pub(crate) vn_deferred_tagged: Range<usize>,
1394    /// vue-native fork: [`Frame::vn_tagged_paint_order`], worked out on the
1395    /// first question about this frame and kept until it is cleared.
1396    vn_tagged_order: std::cell::OnceCell<Option<Vec<u32>>>,
1397    pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1398    pub(crate) deferred_draws: Vec<DeferredDraw>,
1399    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1400    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1401    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1402    #[cfg(any(test, feature = "test-support"))]
1403    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1404    #[cfg(any(test, feature = "test-support"))]
1405    debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1406    #[cfg(any(feature = "inspector", debug_assertions))]
1407    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1408    #[cfg(any(feature = "inspector", debug_assertions))]
1409    pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1410    pub(crate) tab_stops: TabStopMap,
1411}
1412
1413#[derive(Clone, Default)]
1414pub(crate) struct PrepaintStateIndex {
1415    hitboxes_index: usize,
1416    /// vue-native fork: the embedder's tagged-hitbox list is a frame structure
1417    /// like `hitboxes` beside it, so a reused prepaint span has to carry its
1418    /// slice forward too — see [`Window::reuse_prepaint`].
1419    vn_tagged_hitboxes_index: usize,
1420    tooltips_index: usize,
1421    deferred_draws_index: usize,
1422    dispatch_tree_index: usize,
1423    accessed_element_states_index: usize,
1424    line_layout_index: LineLayoutIndex,
1425}
1426
1427#[derive(Clone, Default)]
1428pub(crate) struct PaintIndex {
1429    scene_index: usize,
1430    #[cfg(any(test, feature = "test-support"))]
1431    debug_bounds_index: usize,
1432    mouse_listeners_index: usize,
1433    input_handlers_index: usize,
1434    cursor_styles_index: usize,
1435    window_control_hitboxes_index: usize,
1436    accessed_element_states_index: usize,
1437    tab_handle_index: usize,
1438    line_layout_index: LineLayoutIndex,
1439}
1440
1441impl Frame {
1442    #[cfg(any(test, feature = "test-support"))]
1443    pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1444        self.debug_bounds.insert(selector.clone(), bounds);
1445        self.debug_bounds_records.push((selector, bounds));
1446    }
1447
1448    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1449        Frame {
1450            focus: None,
1451            window_active: false,
1452            element_states: FxHashMap::default(),
1453            accessed_element_states: Vec::new(),
1454            mouse_listeners: Vec::new(),
1455            dispatch_tree,
1456            scene: Scene::default(),
1457            hitboxes: Vec::new(),
1458            vn_tagged_hitboxes: Vec::new(),
1459            vn_hit_order: Vec::new(),
1460            vn_deferred_tagged: 0..0,
1461            vn_tagged_order: std::cell::OnceCell::new(),
1462            window_control_hitboxes: Vec::new(),
1463            deferred_draws: Vec::new(),
1464            input_handlers: Vec::new(),
1465            tooltip_requests: Vec::new(),
1466            cursor_styles: Vec::new(),
1467
1468            #[cfg(any(test, feature = "test-support"))]
1469            debug_bounds: FxHashMap::default(),
1470            #[cfg(any(test, feature = "test-support"))]
1471            debug_bounds_records: Vec::new(),
1472
1473            #[cfg(any(feature = "inspector", debug_assertions))]
1474            next_inspector_instance_ids: FxHashMap::default(),
1475
1476            #[cfg(any(feature = "inspector", debug_assertions))]
1477            inspector_hitboxes: FxHashMap::default(),
1478            tab_stops: TabStopMap::default(),
1479        }
1480    }
1481
1482    pub(crate) fn clear(&mut self) {
1483        self.element_states.clear();
1484        self.accessed_element_states.clear();
1485        self.mouse_listeners.clear();
1486        self.dispatch_tree.clear();
1487        self.scene.clear();
1488        self.input_handlers.clear();
1489        self.tooltip_requests.clear();
1490        self.cursor_styles.clear();
1491        self.hitboxes.clear();
1492        self.vn_tagged_hitboxes.clear();
1493        self.vn_hit_order.clear();
1494        self.vn_deferred_tagged = 0..0;
1495        self.vn_tagged_order = std::cell::OnceCell::new();
1496        self.window_control_hitboxes.clear();
1497        self.deferred_draws.clear();
1498        self.tab_stops.clear();
1499        self.focus = None;
1500
1501        #[cfg(any(test, feature = "test-support"))]
1502        {
1503            self.debug_bounds.clear();
1504            self.debug_bounds_records.clear();
1505        }
1506
1507        #[cfg(any(feature = "inspector", debug_assertions))]
1508        {
1509            self.next_inspector_instance_ids.clear();
1510            self.inspector_hitboxes.clear();
1511        }
1512    }
1513
1514    pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1515        self.cursor_styles
1516            .iter()
1517            .rev()
1518            .fold_while(None, |style, request| match request.hitbox_id {
1519                None => Done(Some(request.style)),
1520                Some(hitbox_id) => Continue(style.or_else(|| {
1521                    hitbox_id
1522                        .is_hovered_ignoring_last_input(window)
1523                        .then_some(request.style)
1524                })),
1525            })
1526            .into_inner()
1527    }
1528
1529    /// Is `position` (window space) inside `hitbox`, as the hit test sees it?
1530    fn box_contains(hitbox: &Hitbox, position: Point<Pixels>, scale_factor: f32) -> bool {
1531        // A transformed element keeps its untransformed `bounds`, so the
1532        // POINTER is mapped back into the element's own frame rather than
1533        // the rect being mapped forward into a polygon. That keeps the test
1534        // a rectangle containment (exact for rotation and scale alike) and
1535        // costs nothing at all when there is no transform.
1536        //
1537        // The matrix is in DEVICE space (it is the same one the primitives
1538        // carry), so the pointer goes there and back; at scale 1 the two
1539        // conversions cancel and this is what it always was.
1540        //
1541        // A singular matrix (`scale(0)`) has no inverse, which is the right
1542        // answer: an element scaled to nothing is not hittable, exactly as
1543        // in a browser.
1544        let local = if hitbox.transformation.is_unit() {
1545            position
1546        } else {
1547            match hitbox.transformation.inverse() {
1548                Some(inverse) => {
1549                    let d = inverse.apply(Point::new(
1550                        px(position.x.0 * scale_factor),
1551                        px(position.y.0 * scale_factor),
1552                    ));
1553                    Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
1554                }
1555                None => return false,
1556            }
1557        };
1558        // The CONTENT MASK is a window-space rect (see
1559        // `Window::with_content_mask`, which maps it through the transform
1560        // in force when it was pushed), so it is tested against the pointer
1561        // as it came in — not against the element-local one. Testing both in
1562        // one intersected rect was only right while transforms did not
1563        // exist: a `translate(-50%, -50%)` dialog painted 500px to the left
1564        // of a clip rect that had not moved, and every clipping element
1565        // inside it hit-tested against a region it no longer covered.
1566        hitbox.content_mask.contains(&position)
1567            && hitbox.bounds.contains(&local)
1568            // vue-native fork: and inside every `clip-path` shape around it,
1569            // which is in window device pixels.
1570            && hitbox.vn_clip.as_ref().is_none_or(|clip| {
1571                clip.contains([position.x.0 * scale_factor, position.y.0 * scale_factor])
1572            })
1573    }
1574
1575    /// vue-native fork: [`Frame::vn_tagged_hitboxes`]' indices in PAINT
1576    /// order — what [`Frame::compute_hit_order`]-style reordering does for
1577    /// the hitboxes, done for the tagged list, which also holds the pick
1578    /// records no hitbox list has. `None` means insertion order is paint
1579    /// order (no deferred draw inserted anything). Worked out once per frame,
1580    /// on the first question.
1581    fn vn_tagged_paint_order(&self) -> Option<&[u32]> {
1582        self.vn_tagged_order
1583            .get_or_init(|| {
1584                let deferred = self.vn_deferred_tagged.clone();
1585                if deferred.is_empty() {
1586                    return None;
1587                }
1588                let len = self.vn_tagged_hitboxes.len();
1589                let mut order: Vec<u32> = Vec::with_capacity(len);
1590                order.extend(0..deferred.start as u32);
1591                let draws = &self.deferred_draws;
1592                let mut traversal = (0..draws.len()).collect::<Vec<_>>();
1593                traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
1594                for ix in traversal {
1595                    let range = &draws[ix].prepaint_range;
1596                    let (start, end) = (
1597                        range.start.vn_tagged_hitboxes_index,
1598                        range.end.vn_tagged_hitboxes_index,
1599                    );
1600                    if start >= deferred.start && end <= deferred.end && start < end {
1601                        order.extend(start as u32..end as u32);
1602                    }
1603                }
1604                order.extend(deferred.end as u32..len as u32);
1605                // Anything a draw's range did not account for keeps insertion
1606                // order rather than vanishing (as `compute_hit_order`).
1607                (order.len() == len).then_some(order)
1608            })
1609            .as_deref()
1610    }
1611
1612    // The iterator is stack-only: native WM_NCHITTEST can precede every mouse
1613    // move, so constructing its paint-order traversal must not allocate.
1614    fn topmost_hitboxes(&self) -> impl Iterator<Item = &Hitbox> {
1615        let in_paint_order = self.vn_hit_order.len() == self.hitboxes.len();
1616        (0..self.hitboxes.len()).rev().map(move |index| {
1617            let index = if in_paint_order { self.vn_hit_order[index] as usize } else { index };
1618            &self.hitboxes[index]
1619        })
1620    }
1621
1622    pub(crate) fn hit_test(&self, position: Point<Pixels>, scale_factor: f32) -> HitTest {
1623        let mut set_hover_hitbox_count = false;
1624        let mut hit_test = HitTest::default();
1625        for hitbox in self.topmost_hitboxes() {
1626            if Self::box_contains(hitbox, position, scale_factor) {
1627                hit_test.ids.push(hitbox.id);
1628                if !set_hover_hitbox_count
1629                    && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1630                {
1631                    hit_test.hover_hitbox_count = hit_test.ids.len();
1632                    set_hover_hitbox_count = true;
1633                }
1634                if hitbox.behavior == HitboxBehavior::BlockMouse {
1635                    break;
1636                }
1637            }
1638        }
1639        if !set_hover_hitbox_count {
1640            hit_test.hover_hitbox_count = hit_test.ids.len();
1641        }
1642        hit_test
1643    }
1644
1645    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1646        self.focus
1647            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1648            .unwrap_or_default()
1649    }
1650
1651    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1652        for element_state_key in &self.accessed_element_states {
1653            if let Some((element_state_key, element_state)) =
1654                prev_frame.element_states.remove_entry(element_state_key)
1655            {
1656                self.element_states.insert(element_state_key, element_state);
1657            }
1658        }
1659
1660        self.scene.finish();
1661    }
1662}
1663
1664#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1665enum InputModality {
1666    Mouse,
1667    Keyboard,
1668    Touch,
1669}
1670
1671/// vue-native fork: what an effect's host-filled pointer parameters read, and
1672/// the views whose effects read them.
1673struct VnEffectPointer {
1674    /// Effect-clock seconds of the last move, entry and exit; the pointer is
1675    /// inside while `entered > left`.
1676    moved: f32,
1677    entered: f32,
1678    left: f32,
1679    /// Notified on the next pointer change, and re-registered when they paint.
1680    views: FxHashSet<EntityId>,
1681}
1682
1683impl VnEffectPointer {
1684    /// Long enough ago for any fade an effect keys off these times to be over.
1685    const NEVER: f32 = -1.0e4;
1686
1687    fn new(inside: bool) -> Self {
1688        let (entered, left) = if inside {
1689            (Self::NEVER, Self::NEVER - 1.)
1690        } else {
1691            (Self::NEVER - 1., Self::NEVER)
1692        };
1693        Self {
1694            moved: Self::NEVER,
1695            entered,
1696            left,
1697            views: FxHashSet::default(),
1698        }
1699    }
1700
1701    fn update(&mut self, was_inside: bool, inside: bool, moved: bool, cx: &mut App) {
1702        if was_inside == inside && !moved {
1703            return;
1704        }
1705        let now = crate::effect_clock_seconds();
1706        if moved {
1707            self.moved = now;
1708        }
1709        if inside && !was_inside {
1710            self.entered = now;
1711        } else if was_inside && !inside {
1712            self.left = now;
1713        }
1714        for view in self.views.drain() {
1715            cx.notify(view);
1716        }
1717    }
1718}
1719
1720/// Holds the state for a specific window.
1721pub struct Window {
1722    pub(crate) handle: AnyWindowHandle,
1723    pub(crate) invalidator: WindowInvalidator,
1724    pub(crate) removed: bool,
1725    pub(crate) platform_window: Box<dyn PlatformWindow>,
1726    pub(crate) display_id: Option<DisplayId>,
1727    pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
1728    is_resizable: bool,
1729    is_minimizable: bool,
1730    last_window_bounds: WindowBounds,
1731    sprite_atlas: Arc<dyn PlatformAtlas>,
1732    text_system: Rc<WindowTextSystem>,
1733    text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1734    rem_size: Pixels,
1735    /// The stack of override values for the window's rem size.
1736    ///
1737    /// This is used by `with_rem_size` to allow rendering an element tree with
1738    /// a given rem size.
1739    rem_size_override_stack: SmallVec<[Pixels; 8]>,
1740    pub(crate) viewport_size: Size<Pixels>,
1741    layout_engine: Option<TaffyLayoutEngine>,
1742    pub(crate) root: Option<AnyView>,
1743    pub(crate) element_id_stack: ElementIdStack,
1744    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1745    pub(crate) rendered_entity_stack: Vec<EntityId>,
1746    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1747    pub(crate) element_opacity: f32,
1748    /// vue-native fork: the colour [`Window::paint_image`] tints with
1749    /// ([`Window::with_image_tint`]); transparent outside a tint scope.
1750    element_image_tint: Hsla,
1751    /// vue-native fork: the brightest value an HDR image tile paints with
1752    /// ([`Window::with_image_headroom`]).
1753    element_image_headroom: f32,
1754    /// The composed CSS `transform` of every ancestor currently being painted,
1755    /// in DEVICE space. Identity outside a `Style::vn_transform`.
1756    ///
1757    /// A field rather than a stack, for the same reason `element_opacity` is:
1758    /// every push already has to compose with what is above it, so the "stack"
1759    /// is one saved value per frame of the paint recursion and lives on the
1760    /// Rust stack instead.
1761    pub(crate) element_transform: TransformationMatrix,
1762    /// vue-native fork: the embedder node id every hitbox inserted from here
1763    /// down is recorded under (0 = record nothing). See
1764    /// [`Frame::vn_tagged_hitboxes`].
1765    vn_hitbox_tag: u32,
1766    /// vue-native fork: no element has prepainted yet under the tag that
1767    /// [`Window::with_hitbox_tag`] set, so the next one is the tagged node's
1768    /// own. See [`Window::note_tagged_transform`].
1769    vn_tag_fresh: bool,
1770    /// vue-native fork: the tagged node's whole `transform` (ancestors' and
1771    /// its own), when it has one of its own.
1772    vn_tag_transform: Option<TransformationMatrix>,
1773    /// vue-native fork: while set, EVERY element gets a hitbox, not only an
1774    /// interactive one — the same thing gpui's own inspector does while it is
1775    /// picking, and for the same reason: a hit test can only answer for a node
1776    /// that has a hitbox.
1777    vn_tag_every_hitbox: bool,
1778    /// vue-native fork: while set, an element that gets no hitbox records a
1779    /// PICK instead ([`Window::vn_insert_pick`]).
1780    vn_pick_every_box: bool,
1781    /// vue-native fork: see [`Window::set_vn_hit_refiner`].
1782    vn_hit_refiner: Option<VnHitRefiner>,
1783    // Optional modal input interception, e.g. an external element inspector.
1784    input_interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
1785    /// vue-native fork: see [`Window::vn_key_event_seq`].
1786    vn_key_event_seq: u64,
1787    /// vue-native fork: [`Window::vn_lock_pointer`]'s mode and the position mouse events hold at.
1788    vn_pointer_lock: Option<(VnPointerLock, Point<Pixels>)>,
1789    /// vue-native fork: the last mouse move's position as delivered, before a lock pinned it.
1790    vn_raw_mouse_position: Option<Point<Pixels>>,
1791    /// vue-native fork: see [`Window::vn_mouse_movement`].
1792    vn_mouse_movement: Point<Pixels>,
1793    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1794    /// vue-native fork: the `clip-path` shapes in force that are no rounded
1795    /// rectangle, innermost first ([`Window::vn_with_clip_shape`]). A hitbox
1796    /// and a deferred draw take it as they take the content mask.
1797    pub(crate) vn_clip_stack: Option<Arc<crate::VnClipNode>>,
1798    /// vue-native fork: every capture drawn and not forgotten, with the
1799    /// pixels its snapshot covers ([Window::vn_with_capture]).
1800    vn_capture_records: FxHashMap<u64, (crate::VnCaptureInfo, Bounds<ScaledPixels>)>,
1801    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1802    /// The [`TextInputConfiguration`] most recently forwarded to the platform
1803    /// window, so that only actual changes are forwarded (reconfiguring a live
1804    /// input session can restart the IME connection).
1805    last_text_input_configuration: Option<TextInputConfiguration>,
1806    focused_text_input: Option<FocusId>,
1807    pub(crate) image_cache_stack: Vec<AnyImageCache>,
1808    pub(crate) rendered_frame: Frame,
1809    pub(crate) next_frame: Frame,
1810    next_hitbox_id: HitboxId,
1811    pub(crate) next_tooltip_id: TooltipId,
1812    pub(crate) tooltip_bounds: Option<TooltipBounds>,
1813    pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1814    /// Whether a queued next-frame callback asked for a frame (passive ones do
1815    /// not; see [`Window::on_next_frame_passive`]).
1816    pub(crate) next_frame_wanted: Rc<Cell<bool>>,
1817    pub(crate) dirty_views: FxHashSet<EntityId>,
1818    focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
1819    pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
1820    focus_lost_path: SmallVec<[FocusId; 8]>,
1821    default_prevented: bool,
1822    mouse_position: Point<Pixels>,
1823    mouse_hit_test: HitTest,
1824    modifiers: Modifiers,
1825    capslock: Capslock,
1826    scale_factor: f32,
1827    pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
1828    appearance: WindowAppearance,
1829    pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
1830    pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
1831    active: Rc<Cell<bool>>,
1832    /// vue-native fork: [`Window::set_assume_active`].
1833    assume_active: bool,
1834    visibility: WindowVisibility,
1835    pub(crate) visibility_observers:
1836        SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1837    hovered: Rc<Cell<bool>>,
1838    /// vue-native fork: is the pointer in this window, as far as the input
1839    /// gpui has seen says? Until it is, `mouse_position` is only where the OS
1840    /// cursor projects onto the client area (`Window::new` and
1841    /// `bounds_changed` read it from the platform). The cursor may be over
1842    /// another window that covers this one, or the position may be stale
1843    /// since the pointer left. No hitbox counts as hovered while this is
1844    /// false ([`HitboxId::is_hovered`]). The hit test itself is kept, because
1845    /// the platform's window-control hit test (`WM_NCHITTEST`) reads it.
1846    ///
1847    /// Any pointer input dispatched to the window sets it, a synthesized
1848    /// one included (a test harness or devtools moving the pointer means it).
1849    /// `MouseExited`, a file drag leaving, and the platform's hover-status
1850    /// change to false clear it. It starts as the platform's `is_hovered()`.
1851    pointer_inside: bool,
1852    vn_effect_pointer: VnEffectPointer,
1853    /// vue-native fork: the identity of the element whose style paints next,
1854    /// which keys an `[SkHistory]` effect's state; 0 when it has none.
1855    vn_effect_element: u64,
1856    /// vue-native fork: per element and effect, how far its `[SkAnimated]`
1857    /// speed has advanced it ([`VnEffectPhase`]).
1858    vn_effect_phases: FxHashMap<u64, VnEffectPhase>,
1859    /// vue-native fork: the scope a draw deferred now goes to, while
1860    /// prepainting.
1861    vn_defer_scope: Option<VnDeferScope>,
1862    /// vue-native fork: the scopes whose content painted their draws this
1863    /// frame.
1864    vn_scopes_painted: FxHashSet<u64>,
1865    pub(crate) needs_present: Rc<Cell<bool>>,
1866    /// The rendered scene's [`Scene::animation_frame_interval`]. While it is
1867    /// `Some`, the scene must keep being presented even when nothing is redrawn.
1868    scene_animation_interval: Rc<Cell<Option<Duration>>>,
1869    /// Tracks recent input event timestamps to determine if input is arriving at a high rate.
1870    /// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
1871    pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1872    #[cfg(feature = "profiler")]
1873    pub(crate) window_profiler: profiler::WindowProfiler,
1874    last_input_modality: InputModality,
1875    touch_gestures: TouchGestureRecognizer,
1876    touch_prediction_enabled: bool,
1877    long_press_timer: Option<Task<()>>,
1878    long_press_capture: Option<EntityId>,
1879    pub(crate) refreshing: bool,
1880    pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
1881    pub(crate) focus: Option<FocusId>,
1882    focus_enabled: bool,
1883    /// Incremented every time focus moves. Used to invalidate a
1884    /// pending keyboard activation state when focus changes.
1885    pub(crate) focus_generation: u64,
1886    pending_input: Option<PendingInput>,
1887    pending_modifier: ModifierState,
1888    pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
1889    prompt: Option<RenderablePromptHandle>,
1890    pub(crate) client_inset: Option<Pixels>,
1891    /// The hitbox that has captured the pointer, if any.
1892    /// While captured, mouse events route to this hitbox regardless of hit testing.
1893    captured_hitbox: Option<HitboxId>,
1894    #[cfg(any(feature = "inspector", debug_assertions))]
1895    inspector: Option<Entity<Inspector>>,
1896    #[cfg(feature = "profiler")]
1897    debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1898    pub(crate) a11y: A11y,
1899}
1900
1901#[derive(Clone, Debug, Default)]
1902struct ModifierState {
1903    modifiers: Modifiers,
1904    saw_other_input: bool,
1905}
1906
1907/// Tracks input event timestamps to determine if input is arriving at a high rate.
1908/// Used for selective VRR (Variable Refresh Rate) optimization.
1909#[derive(Clone, Debug)]
1910pub(crate) struct InputRateTracker {
1911    timestamps: Vec<Instant>,
1912    window: Duration,
1913    inputs_per_second: u32,
1914    sustain_until: Instant,
1915    sustain_duration: Duration,
1916}
1917
1918const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
1919
1920/// Keeps throttled frames on a stable cadence despite callback delivery jitter.
1921#[derive(Default)]
1922struct FramePacer {
1923    last_frame: Option<Instant>,
1924}
1925
1926impl FramePacer {
1927    fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
1928        if let Some(interval) = minimum_interval
1929            && let Some(last_frame) = self.last_frame
1930        {
1931            let deadline = last_frame + interval;
1932            if now + FRAME_INTERVAL_TOLERANCE < deadline {
1933                return true;
1934            }
1935            // Correct small dispatch delays without shifting subsequent deadlines,
1936            // but bound the correction to a quarter interval. Larger delays restart
1937            // the cadence so recovery cannot produce closely spaced catch-up frames.
1938            self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
1939                deadline
1940            } else {
1941                now
1942            });
1943        } else {
1944            self.last_frame = Some(now);
1945        }
1946        false
1947    }
1948}
1949
1950fn minimum_frame_interval(
1951    should_throttle: bool,
1952    inactive_without_high_rate_input: bool,
1953    inactive_frame_interval: Option<Duration>,
1954    low_power_frame_interval: Option<Duration>,
1955    thermal_frame_interval: Option<Duration>,
1956    thermal_state: ThermalState,
1957    power_mode: crate::PowerMode,
1958) -> Option<Duration> {
1959    if !should_throttle {
1960        return None;
1961    }
1962
1963    [
1964        inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
1965        low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
1966        thermal_frame_interval.filter(|_| {
1967            matches!(
1968                thermal_state,
1969                ThermalState::Critical | ThermalState::Serious
1970            )
1971        }),
1972    ]
1973    .into_iter()
1974    .flatten()
1975    .max()
1976}
1977
1978impl Default for InputRateTracker {
1979    fn default() -> Self {
1980        Self {
1981            timestamps: Vec::new(),
1982            window: Duration::from_millis(100),
1983            inputs_per_second: 60,
1984            sustain_until: Instant::now(),
1985            sustain_duration: Duration::from_secs(1),
1986        }
1987    }
1988}
1989
1990impl InputRateTracker {
1991    pub fn record_input(&mut self) {
1992        let now = Instant::now();
1993        self.timestamps.push(now);
1994        self.prune_old_timestamps(now);
1995
1996        let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1997        if self.timestamps.len() as u128 >= min_events {
1998            self.sustain_until = now + self.sustain_duration;
1999        }
2000    }
2001
2002    pub fn is_high_rate(&self) -> bool {
2003        Instant::now() < self.sustain_until
2004    }
2005
2006    fn prune_old_timestamps(&mut self, now: Instant) {
2007        self.timestamps
2008            .retain(|&t| now.duration_since(t) <= self.window);
2009    }
2010}
2011
2012#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2013pub(crate) enum DrawPhase {
2014    None,
2015    Prepaint,
2016    Paint,
2017    Focus,
2018}
2019
2020pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
2021
2022/// Pending input for a potential multi-stroke key binding.
2023pub struct PendingInputStatus<'a> {
2024    keystrokes: &'a [Keystroke],
2025    timeout: Option<PendingInputTimeoutStatus>,
2026}
2027
2028impl<'a> PendingInputStatus<'a> {
2029    /// Returns the keystrokes entered so far.
2030    pub fn keystrokes(&self) -> &'a [Keystroke] {
2031        self.keystrokes
2032    }
2033
2034    /// Returns the timeout state for flushing this input, if it needs a timeout.
2035    pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
2036        self.timeout
2037    }
2038}
2039
2040/// The timeout state for pending input.
2041#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2042pub struct PendingInputTimeoutStatus {
2043    duration: Duration,
2044    remaining: Duration,
2045    started_at: Option<Instant>,
2046    paused: bool,
2047}
2048
2049impl PendingInputTimeoutStatus {
2050    /// Returns the full timeout duration.
2051    pub fn duration(&self) -> Duration {
2052        self.duration
2053    }
2054
2055    /// Returns the duration remaining before pending input is flushed.
2056    pub fn remaining(&self, cx: &App) -> Duration {
2057        self.started_at
2058            .map(|started_at| {
2059                self.remaining
2060                    .saturating_sub(cx.background_executor().now() - started_at)
2061            })
2062            .unwrap_or(self.remaining)
2063    }
2064
2065    /// Returns whether the timeout is paused.
2066    pub fn is_paused(&self) -> bool {
2067        self.paused
2068    }
2069}
2070
2071#[derive(Debug)]
2072struct PendingInputTimeout {
2073    duration: Duration,
2074    remaining: Duration,
2075    state: PendingInputTimeoutState,
2076}
2077
2078#[derive(Debug)]
2079enum PendingInputTimeoutState {
2080    Running { started_at: Instant, task: Task<()> },
2081    Paused { pause: PendingInputTimeoutPause },
2082}
2083
2084#[derive(Debug)]
2085struct PendingInputTimeoutPause {
2086    owner_id: EntityId,
2087    _release_subscription: Subscription,
2088}
2089
2090impl PendingInputTimeout {
2091    fn is_paused(&self) -> bool {
2092        matches!(&self.state, PendingInputTimeoutState::Paused { .. })
2093    }
2094
2095    fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
2096        match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
2097            PendingInputTimeoutState::Running { started_at, task } => {
2098                self.remaining = self.remaining.saturating_sub(now - started_at);
2099                drop(task);
2100                true
2101            }
2102            previous_state @ PendingInputTimeoutState::Paused { .. } => {
2103                self.state = previous_state;
2104                false
2105            }
2106        }
2107    }
2108
2109    fn pause_owner_id(&self) -> Option<EntityId> {
2110        match &self.state {
2111            PendingInputTimeoutState::Running { .. } => None,
2112            PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
2113        }
2114    }
2115
2116    fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
2117        match std::mem::replace(
2118            &mut self.state,
2119            PendingInputTimeoutState::Running { started_at, task },
2120        ) {
2121            PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
2122            previous_state => {
2123                self.state = previous_state;
2124                false
2125            }
2126        }
2127    }
2128
2129    fn reset_duration(&mut self, duration: Duration) {
2130        self.duration = duration;
2131        self.remaining = duration;
2132    }
2133
2134    fn status(&self) -> PendingInputTimeoutStatus {
2135        let (started_at, paused) = match &self.state {
2136            PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
2137            PendingInputTimeoutState::Paused { .. } => (None, true),
2138        };
2139        PendingInputTimeoutStatus {
2140            duration: self.duration,
2141            remaining: self.remaining,
2142            started_at,
2143            paused,
2144        }
2145    }
2146}
2147
2148#[derive(Default, Debug)]
2149struct PendingInput {
2150    keystrokes: SmallVec<[Keystroke; 1]>,
2151    focus: Option<FocusId>,
2152    timeout: Option<PendingInputTimeout>,
2153}
2154
2155pub(crate) struct ElementStateBox {
2156    pub(crate) inner: Box<dyn Any>,
2157    #[cfg(debug_assertions)]
2158    pub(crate) type_name: &'static str,
2159}
2160
2161fn default_bounds(
2162    active_window_bounds: Option<WindowBounds>,
2163    display: Option<&dyn PlatformDisplay>,
2164) -> WindowBounds {
2165    const CASCADE_OFFSET: f32 = 25.0;
2166
2167    let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
2168
2169    // Use visible_bounds to exclude taskbar/dock areas
2170    let display_bounds = display
2171        .map(|d| d.visible_bounds())
2172        .unwrap_or_else(default_placement);
2173
2174    let (
2175        Bounds {
2176            origin: base_origin,
2177            size: base_size,
2178        },
2179        window_bounds_ctor,
2180    ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
2181        Some(bounds) => match bounds {
2182            WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
2183            WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
2184            WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
2185        },
2186        None => (
2187            display
2188                .map(|d| d.default_bounds())
2189                .unwrap_or_else(default_placement),
2190            WindowBounds::Windowed,
2191        ),
2192    };
2193
2194    let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
2195    let proposed_origin = base_origin + cascade_offset;
2196    let proposed_bounds = Bounds::new(proposed_origin, base_size);
2197
2198    let display_right = display_bounds.origin.x + display_bounds.size.width;
2199    let display_bottom = display_bounds.origin.y + display_bounds.size.height;
2200    let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
2201    let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
2202
2203    let fits_horizontally = window_right <= display_right;
2204    let fits_vertically = window_bottom <= display_bottom;
2205
2206    let final_origin = match (fits_horizontally, fits_vertically) {
2207        (true, true) => proposed_origin,
2208        (false, true) => point(display_bounds.origin.x, base_origin.y),
2209        (true, false) => point(base_origin.x, display_bounds.origin.y),
2210        (false, false) => display_bounds.origin,
2211    };
2212    window_bounds_ctor(Bounds::new(final_origin, base_size))
2213}
2214
2215/// Windows sends `WM_SIZE`/`WM_MOVE` synchronously from `SetWindowPos` and the other calls that
2216/// move or size a window, so a report can arrive while App is borrowed by the code that made that
2217/// call. It then runs on the next foreground turn rather than being dropped.
2218fn report_bounds_changed(
2219    handle: AnyWindowHandle,
2220    cx: &mut crate::AsyncApp,
2221    deferred: &Rc<Cell<bool>>,
2222    what: &'static str,
2223) {
2224    let borrowed = cx.app.upgrade().is_some_and(|app| app.is_borrowed());
2225    if !borrowed {
2226        handle
2227            .update(cx, |_, window, cx| window.bounds_changed(cx))
2228            .with_context(|| format!("handling {what} for window {:?}", handle.window_id()))
2229            .log_err();
2230        return;
2231    }
2232    if deferred.replace(true) {
2233        return;
2234    }
2235    let deferred = deferred.clone();
2236    let mut cx = cx.clone();
2237    cx.foreground_executor()
2238        .clone()
2239        .spawn(async move {
2240            deferred.set(false);
2241            // Fails only when the window closed meanwhile; then there is nothing to report.
2242            handle
2243                .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2244                .ok();
2245        })
2246        .detach();
2247}
2248
2249impl Window {
2250    pub(crate) fn new(
2251        handle: AnyWindowHandle,
2252        options: WindowOptions,
2253        cx: &mut App,
2254    ) -> Result<Self> {
2255        let WindowOptions {
2256            window_bounds,
2257            titlebar,
2258            focus,
2259            show,
2260            kind,
2261            is_movable,
2262            app_owns_titlebar_drag,
2263            inactive_frame_interval,
2264            low_power_frame_interval,
2265            thermal_frame_interval,
2266            is_resizable,
2267            is_minimizable,
2268            display_id,
2269            window_background,
2270            app_id,
2271            window_min_size,
2272            window_decorations,
2273            #[cfg_attr(
2274                not(any(target_os = "linux", target_os = "freebsd")),
2275                allow(unused_variables)
2276            )]
2277            icon,
2278            #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2279            tabbing_identifier,
2280            #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2281            use_display_p3,
2282        } = options;
2283
2284        let initial_window_title = titlebar
2285            .as_ref()
2286            .and_then(|titlebar| titlebar.title.clone());
2287
2288        let active_window_placement = cx.active_window_placement();
2289        // Explicit bounds only make sense on the display they were computed for.
2290        let target_display_id = display_id.or_else(|| {
2291            active_window_placement
2292                .filter(|_| window_bounds.is_none())
2293                .and_then(|(display_id, _)| display_id)
2294        });
2295        let display = target_display_id
2296            .and_then(|display_id| cx.find_display(display_id))
2297            .or_else(|| cx.primary_display());
2298        let display_id = display
2299            .as_ref()
2300            .map(|display| display.id())
2301            .or(target_display_id);
2302        let active_window_bounds = active_window_placement
2303            .filter(|(active_display_id, _)| *active_display_id == display_id)
2304            .map(|(_, bounds)| bounds);
2305        let window_bounds = window_bounds
2306            .unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
2307        let mut platform_window = cx.platform.open_window(
2308            handle,
2309            WindowParams {
2310                bounds: window_bounds.get_bounds(),
2311                titlebar,
2312                kind,
2313                is_movable,
2314                app_owns_titlebar_drag,
2315                is_resizable,
2316                is_minimizable,
2317                focus,
2318                show,
2319                display_id,
2320                window_min_size,
2321                app_id: app_id.clone(),
2322                icon,
2323                #[cfg(target_os = "macos")]
2324                tabbing_identifier,
2325                #[cfg(target_os = "macos")]
2326                use_display_p3,
2327            },
2328        )?;
2329
2330        let tab_bar_visible = platform_window.tab_bar_visible();
2331        SystemWindowTabController::init_visible(cx, tab_bar_visible);
2332        if let Some(tabs) = platform_window.tabbed_windows() {
2333            SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
2334        }
2335
2336        let display_id = platform_window.display().map(|display| display.id());
2337        let sprite_atlas = platform_window.sprite_atlas();
2338        let mouse_position = platform_window.mouse_position();
2339        let modifiers = platform_window.modifiers();
2340        let capslock = platform_window.capslock();
2341        let content_size = platform_window.content_size();
2342        let scale_factor = platform_window.scale_factor();
2343        let appearance = platform_window.appearance();
2344        let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
2345        let invalidator = WindowInvalidator::new(handle.window_id());
2346        let active = Rc::new(Cell::new(platform_window.is_active()));
2347        let visibility = platform_window.visibility();
2348        #[cfg(feature = "profiler")]
2349        profiler::journal::record_window_visibility(handle.window_id(), visibility);
2350        let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
2351        let needs_present = Rc::new(Cell::new(false));
2352        let scene_animation_interval = Rc::new(Cell::new(None::<Duration>));
2353        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
2354        let next_frame_wanted: Rc<Cell<bool>> = Default::default();
2355        let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
2356
2357        platform_window
2358            .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
2359        platform_window.set_background_appearance(window_background);
2360
2361        match window_bounds {
2362            WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
2363            WindowBounds::Maximized(_) => platform_window.zoom(),
2364            WindowBounds::Windowed(_) => {}
2365        }
2366
2367        let accessibility_force_disabled = cx.accessibility_force_disabled;
2368        let a11y_active_flag = Arc::new(AtomicBool::new(false));
2369
2370        #[cfg(not(target_family = "wasm"))]
2371        if !accessibility_force_disabled {
2372            let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
2373            if let Some(title) = &initial_window_title {
2374                initial_root_node.set_label(title.to_string());
2375            }
2376            let initial_tree = accesskit::TreeUpdate {
2377                nodes: vec![(ROOT_NODE_ID, initial_root_node)],
2378                tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
2379                tree_id: accesskit::TreeId::ROOT,
2380                focus: ROOT_NODE_ID,
2381            };
2382            let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
2383            let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
2384            let (action_sender, action_receiver) =
2385                async_channel::unbounded::<accesskit::ActionRequest>();
2386
2387            platform_window.a11y_init(crate::A11yCallbacks {
2388                activation: {
2389                    let active_flag = a11y_active_flag.clone();
2390                    Box::new(move || {
2391                        log::info!("Accessibility activated");
2392                        active_flag.store(true, SeqCst);
2393                        activation_sender
2394                            .send_blocking(())
2395                            .with_context(|| {
2396                                format!(
2397                                    "queuing accessibility activation for window {:?}",
2398                                    handle.window_id()
2399                                )
2400                            })
2401                            .log_err();
2402                        Some(initial_tree.clone())
2403                    })
2404                },
2405                action: Box::new(move |request| {
2406                    action_sender
2407                        .send_blocking(request)
2408                        .with_context(|| {
2409                            format!(
2410                                "queuing accessibility action for window {:?}",
2411                                handle.window_id()
2412                            )
2413                        })
2414                        .log_err();
2415                }),
2416                deactivation: {
2417                    let active_flag = a11y_active_flag.clone();
2418                    Box::new(move || {
2419                        log::info!("Accessibility deactivated");
2420                        active_flag.store(false, SeqCst);
2421                        deactivation_sender
2422                            .send_blocking(())
2423                            .with_context(|| {
2424                                format!(
2425                                    "queuing accessibility deactivation for window {:?}",
2426                                    handle.window_id()
2427                                )
2428                            })
2429                            .log_err();
2430                    })
2431                },
2432            });
2433
2434            // A11y can be activated at any time, and so we cannot compute a
2435            // correct `TreeUpdate` on-demand. When this happens, we return a
2436            // default empty `TreeUpdate`.
2437            //
2438            // So we force a new frame, which will then send a correct `TreeUpdate`.
2439            let mut async_cx = cx.to_async();
2440            cx.foreground_executor()
2441                .spawn(async move {
2442                    while activation_receiver.recv().await.is_ok() {
2443                        handle
2444                            .update(&mut async_cx, |_, window, _| window.refresh())
2445                            .with_context(|| {
2446                                format!(
2447                                    "handling accessibility activation for window {:?}",
2448                                    handle.window_id()
2449                                )
2450                            })
2451                            .log_err();
2452                    }
2453                })
2454                .detach();
2455
2456            let mut async_cx = cx.to_async();
2457            cx.foreground_executor()
2458                .spawn(async move {
2459                    while deactivation_receiver.recv().await.is_ok() {
2460                        handle
2461                            .update(&mut async_cx, |_, window, _| window.refresh())
2462                            .with_context(|| {
2463                                format!(
2464                                    "handling accessibility deactivation for window {:?}",
2465                                    handle.window_id()
2466                                )
2467                            })
2468                            .log_err();
2469                    }
2470                })
2471                .detach();
2472
2473            let mut async_cx = cx.to_async();
2474            cx.foreground_executor()
2475                .spawn(async move {
2476                    while let Ok(request) = action_receiver.recv().await {
2477                        handle
2478                            .update(&mut async_cx, |_, window, cx| {
2479                                window.handle_a11y_action(request, cx);
2480                            })
2481                            .with_context(|| {
2482                                format!(
2483                                    "handling accessibility action for window {:?}",
2484                                    handle.window_id()
2485                                )
2486                            })
2487                            .log_err();
2488                    }
2489                })
2490                .detach();
2491        }
2492
2493        platform_window.on_close(Box::new({
2494            let window_id = handle.window_id();
2495            let cx = cx.to_async();
2496            move || {
2497                // Native destruction can re-enter while the app is borrowed.
2498                // Schedule both operations without borrowing the app here.
2499                cx.spawn(async move |cx| {
2500                    cx.update(|cx| {
2501                        // App-driven closure may already have removed the window.
2502                        if cx.windows.contains_key(window_id) {
2503                            handle
2504                                .update(cx, |_, window, _| window.remove_window())
2505                                .with_context(|| format!("handling close for window {window_id:?}"))
2506                                .log_err();
2507                        }
2508                        SystemWindowTabController::remove_tab(cx, window_id);
2509                    });
2510                })
2511                .detach();
2512            }
2513        }));
2514        platform_window.on_request_frame(Box::new({
2515            let mut cx = cx.to_async();
2516            let invalidator = invalidator.clone();
2517            let active = active.clone();
2518            let needs_present = needs_present.clone();
2519            let scene_animation_interval = scene_animation_interval.clone();
2520            let next_frame_callbacks = next_frame_callbacks.clone();
2521            let next_frame_wanted = next_frame_wanted.clone();
2522            let input_rate_tracker = input_rate_tracker.clone();
2523            let mut deferred_force_render = false;
2524            let mut frame_pacer = FramePacer::default();
2525            move |request_frame_options| {
2526                #[cfg(feature = "profiler")]
2527                let (_foreground_turn, window_id) = {
2528                    let foreground_turn = profiler::journal::foreground_turn();
2529                    let window_id = handle.window_id();
2530                    profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
2531                        window_id,
2532                        signal_at: request_frame_options.signal_at,
2533                        handled_at: Instant::now(),
2534                        source: request_frame_options.signal_source,
2535                    });
2536                    (foreground_turn, window_id)
2537                };
2538                // This must be checked before accessing App: if this request
2539                // arrived re-entrantly while a draw is on this thread's stack
2540                // (e.g. via a nested message pump in the Windows window
2541                // procedure), drawing would nest draws, and even touching the
2542                // App would panic on its already-mutable borrow. Skip instead;
2543                // the platform leaves the window invalidated (or re-invalidates
2544                // it), so a fresh request arrives once the in-progress draw
2545                // unwinds. Remember force_render so the deferred frame still
2546                // bypasses the view cache.
2547                //
2548                // Returning here skips `complete_frame`, which on Wayland would
2549                // stall the window's frame callbacks (no `surface.commit()`) —
2550                // but calling it would hit the App borrow panic above, and this
2551                // branch is unreachable there in practice: only Windows pumps
2552                // platform events (and thus requests frames) mid-draw.
2553                if draw_in_progress() {
2554                    log::debug!("deferring re-entrant window draw request");
2555                    deferred_force_render |= request_frame_options.force_render;
2556                    #[cfg(feature = "profiler")]
2557                    profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
2558                    return;
2559                }
2560                // Take the deferred flag first: `||` short-circuits, and leaving
2561                // the flag set when this request already forces a render would
2562                // force a second, redundant render on the next frame.
2563                let force_render =
2564                    mem::take(&mut deferred_force_render) || request_frame_options.force_render;
2565
2566                let power_state = handle
2567                    .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
2568                    .with_context(|| {
2569                        format!(
2570                            "reading power state for frame request for window {:?}",
2571                            handle.window_id()
2572                        )
2573                    })
2574                    .log_err();
2575
2576                // Keep presenting briefly after high-rate input to prevent display
2577                // underclocking, but subject to the same power limits as redraws.
2578                let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
2579                // vue-native: only macOS ProMotion underclocks an idle layer. On
2580                // Windows a present re-renders the whole unchanged scene, so the
2581                // sustain would cost a full GPU frame per refresh for a second.
2582                let present_for_high_rate_input = cfg!(target_os = "macos") && high_rate_input;
2583                let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
2584                // vue-native fork: demand that asks the platform for a frame.
2585                // Passive next-frame callbacks (`Window::on_next_frame_passive`)
2586                // are paced like any other frame work but never wake the frame
2587                // source on their own.
2588                let wants_frame_besides_animation = invalidator.is_dirty()
2589                    || force_render
2590                    || next_frame_wanted.get()
2591                    || request_frame_options.require_presentation
2592                    || needs_present.get()
2593                    || present_for_high_rate_input;
2594                let has_demand_besides_animation =
2595                    wants_frame_besides_animation || has_next_frame_callbacks;
2596                let wants_frame =
2597                    wants_frame_besides_animation || scene_animation_interval.get().is_some();
2598                let has_frame_demand = wants_frame || has_next_frame_callbacks;
2599
2600                let should_throttle = !request_frame_options.require_presentation;
2601                let inactive_without_high_rate_input =
2602                    should_throttle && !active.get() && !high_rate_input;
2603                let (thermal_state, power_mode) =
2604                    power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
2605                let min_frame_interval = minimum_frame_interval(
2606                    should_throttle,
2607                    inactive_without_high_rate_input,
2608                    inactive_frame_interval,
2609                    low_power_frame_interval,
2610                    thermal_frame_interval,
2611                    thermal_state,
2612                    power_mode,
2613                );
2614                let animation_frame_interval = scene_animation_interval
2615                    .get()
2616                    .filter(|interval| !has_demand_besides_animation && !interval.is_zero());
2617                let min_frame_interval = min_frame_interval.max(animation_frame_interval);
2618
2619                let now = Instant::now();
2620                // Idle display-link ticks must neither consume a frame slot nor
2621                // wake a demand-driven frame source.
2622                if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
2623                    // Don't lose a pending forced render to throttling.
2624                    deferred_force_render |= force_render;
2625                    // Passive callbacks alone wait for the next delivered frame.
2626                    if wants_frame {
2627                        // Deferred by throttling: ask demand-driven platforms to retry.
2628                        handle
2629                            .update(&mut cx, |_, window, _| {
2630                                window.platform_window.schedule_frame();
2631                            })
2632                            .with_context(|| {
2633                                format!(
2634                                    "rescheduling throttled frame for window {:?}",
2635                                    handle.window_id()
2636                                )
2637                            })
2638                            .log_err();
2639                        // The demand is still unserved; platforms that stop
2640                        // requesting frames for idle windows need a wakeup to retry.
2641                        invalidator.wake_platform();
2642                    }
2643                    #[cfg(feature = "profiler")]
2644                    profiler::journal::record_frame_skipped(
2645                        window_id,
2646                        Instant::now(),
2647                        if animation_frame_interval.is_some()
2648                            && animation_frame_interval == min_frame_interval
2649                        {
2650                            profiler::journal::FrameSkipReason::AnimationFrameRateLimit
2651                        } else if inactive_without_high_rate_input
2652                            && inactive_frame_interval == min_frame_interval
2653                        {
2654                            profiler::journal::FrameSkipReason::InactiveFrameRateLimit
2655                        } else if power_mode == crate::PowerMode::LowPower
2656                            && low_power_frame_interval == min_frame_interval
2657                        {
2658                            profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
2659                        } else {
2660                            profiler::journal::FrameSkipReason::ThermalFrameRateLimit
2661                        },
2662                    );
2663                    report_frame(handle.window_id(), now, FrameOutcome::Throttled);
2664                    return;
2665                }
2666
2667                if !next_frame_callbacks.borrow().is_empty() {
2668                    handle
2669                        .update(&mut cx, |_, window, cx| {
2670                            // A native frame request can re-enter while App is borrowed.
2671                            // Keep the callbacks queued if updating the window fails,
2672                            // or a self-rescheduling frame pump would be lost forever.
2673                            window.next_frame_wanted.set(false);
2674                            for callback in next_frame_callbacks.take() {
2675                                callback(window, cx);
2676                            }
2677                        })
2678                        .with_context(|| {
2679                            format!(
2680                                "running next-frame callbacks for window {:?}",
2681                                handle.window_id()
2682                            )
2683                        })
2684                        .log_err();
2685                }
2686
2687                let should_draw = invalidator.is_dirty() || force_render;
2688                let needs_present = request_frame_options.require_presentation
2689                    || needs_present.get()
2690                    || scene_animation_interval.get().is_some()
2691                    || present_for_high_rate_input;
2692                if should_draw {
2693                    measure("frame duration", || {
2694                        handle
2695                            .update(&mut cx, |_, window, cx| {
2696                                #[cfg(feature = "profiler")]
2697                                window
2698                                    .window_profiler
2699                                    .record_frame_signal(request_frame_options.signal_at);
2700                                if force_render {
2701                                    // Bypass cached view reuse so we don't replay stale
2702                                    // atlas tile references after a GPU device recovery.
2703                                    window.refresh();
2704                                }
2705                                let arena_clear_needed = window.draw(cx);
2706                                window.advance_scene_animations(cx);
2707                                window.present();
2708                                arena_clear_needed.clear(cx);
2709                            })
2710                            .with_context(|| {
2711                                format!(
2712                                    "drawing and presenting frame for window {:?}",
2713                                    handle.window_id()
2714                                )
2715                            })
2716                            .log_err();
2717                    })
2718                } else if needs_present {
2719                    handle
2720                        .update(&mut cx, |_, window, cx| {
2721                            window.advance_scene_animations(cx);
2722                            window.present();
2723                        })
2724                        .with_context(|| {
2725                            format!("presenting frame for window {:?}", handle.window_id())
2726                        })
2727                        .log_err();
2728                }
2729
2730                handle
2731                    .update(&mut cx, |_, window, _| {
2732                        if window.invalidator.is_dirty()
2733                            || window.next_frame_wanted.get()
2734                            || window.scene_animation_interval.get().is_some()
2735                        {
2736                            window.platform_window.schedule_frame();
2737                        }
2738                    })
2739                    .with_context(|| {
2740                        format!(
2741                            "scheduling follow-up frame for window {:?}",
2742                            handle.window_id()
2743                        )
2744                    })
2745                    .log_err();
2746
2747                // Platforms that stop requesting frames for idle windows only
2748                // deliver another request after a wakeup. If demand remains
2749                // after this frame (the window was re-invalidated mid-draw, or
2750                // animations scheduled next-frame callbacks), re-arm the frame
2751                // source explicitly. Passive callbacks are not demand.
2752                if invalidator.is_dirty()
2753                    || next_frame_wanted.get()
2754                    || scene_animation_interval.get().is_some()
2755                {
2756                    invalidator.wake_platform();
2757                }
2758                #[cfg(feature = "profiler")]
2759                if !should_draw {
2760                    profiler::journal::record_frame_skipped(
2761                        window_id,
2762                        Instant::now(),
2763                        profiler::journal::FrameSkipReason::NoRenderNeeded,
2764                    );
2765                }
2766                if should_draw {
2767                    report_frame(handle.window_id(), now, FrameOutcome::Drew);
2768                } else if has_next_frame_callbacks || needs_present {
2769                    report_frame(handle.window_id(), now, FrameOutcome::NoDraw);
2770                }
2771            }
2772        }));
2773        invalidator.set_platform_waker(platform_window.frame_waker());
2774        platform_window.on_visual_viewport_changed(Box::new({
2775            let mut cx = cx.to_async();
2776            move || {
2777                handle
2778                    .update(&mut cx, |_, window, _| window.refresh())
2779                    .with_context(|| {
2780                        format!(
2781                            "handling visual viewport change for window {:?}",
2782                            handle.window_id()
2783                        )
2784                    })
2785                    .log_err();
2786            }
2787        }));
2788        platform_window.on_insets_changed(Box::new({
2789            let mut cx = cx.to_async();
2790            move |_| {
2791                handle
2792                    .update(&mut cx, |_, window, _| window.refresh())
2793                    .with_context(|| {
2794                        format!("handling insets change for window {:?}", handle.window_id())
2795                    })
2796                    .log_err();
2797            }
2798        }));
2799        // One deferred report covers both: `bounds_changed` reads the bounds when it runs.
2800        let bounds_deferred = Rc::new(Cell::new(false));
2801        platform_window.on_resize(Box::new({
2802            let mut cx = cx.to_async();
2803            let deferred = bounds_deferred.clone();
2804            move |_, _| report_bounds_changed(handle, &mut cx, &deferred, "resize")
2805        }));
2806        platform_window.on_moved(Box::new({
2807            let mut cx = cx.to_async();
2808            let deferred = bounds_deferred;
2809            move || report_bounds_changed(handle, &mut cx, &deferred, "move")
2810        }));
2811        platform_window.on_display_changed(Box::new({
2812            let cx = cx.to_async();
2813            move || cx.update(|cx| Window::display_changed(handle, cx))
2814        }));
2815        platform_window.on_appearance_changed(Box::new({
2816            let cx = cx.to_async();
2817            let foreground_executor = cx.foreground_executor().clone();
2818            move || {
2819                let mut cx = cx.clone();
2820                // Defer the update because changing the AppKit appearance may
2821                // synchronously invoke this callback while App is already borrowed.
2822                foreground_executor
2823                    .spawn(async move {
2824                        handle
2825                            .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2826                            .with_context(|| {
2827                                format!(
2828                                    "handling appearance change for window {:?}",
2829                                    handle.window_id()
2830                                )
2831                            })
2832                            .log_err();
2833                    })
2834                    .detach();
2835            }
2836        }));
2837        platform_window.on_button_layout_changed(Box::new({
2838            let mut cx = cx.to_async();
2839            move || {
2840                handle
2841                    .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2842                    .with_context(|| {
2843                        format!(
2844                            "handling button layout change for window {:?}",
2845                            handle.window_id()
2846                        )
2847                    })
2848                    .log_err();
2849            }
2850        }));
2851        platform_window.on_active_status_change(Box::new({
2852            let mut cx = cx.to_async();
2853            move |active| {
2854                handle
2855                    .update(&mut cx, |_, window, cx| {
2856                        // vue-native fork: an assumed-active window keeps
2857                        // reading as active whatever the OS says
2858                        // (`Window::set_assume_active`).
2859                        if window.assume_active {
2860                            return;
2861                        }
2862                        window.active.set(active);
2863                        window.modifiers = window.platform_window.modifiers();
2864                        window.capslock = window.platform_window.capslock();
2865                        window
2866                            .activation_observers
2867                            .clone()
2868                            .retain(|callback| callback(window, cx));
2869
2870                        window.bounds_changed(cx);
2871                        window.refresh();
2872
2873                        SystemWindowTabController::update_last_active(cx, window.handle.id);
2874                    })
2875                    .with_context(|| {
2876                        format!(
2877                            "handling active status change for window {:?}",
2878                            handle.window_id()
2879                        )
2880                    })
2881                    .log_err();
2882            }
2883        }));
2884        platform_window.on_visibility_change(Box::new({
2885            let mut cx = cx.to_async();
2886            move |_| {
2887                handle
2888                    .update(&mut cx, |_, window, cx| {
2889                        window.refresh_visibility(cx);
2890                    })
2891                    .with_context(|| {
2892                        format!(
2893                            "handling visibility change for window {:?}",
2894                            handle.window_id()
2895                        )
2896                    })
2897                    .log_err();
2898            }
2899        }));
2900        platform_window.on_hover_status_change(Box::new({
2901            let mut cx = cx.to_async();
2902            move |active| {
2903                handle
2904                    .update(&mut cx, |_, window, cx| {
2905                        window.hovered.set(active);
2906                        let was_inside = std::mem::replace(&mut window.pointer_inside, active);
2907                        window
2908                            .vn_effect_pointer
2909                            .update(was_inside, active, false, cx);
2910                        window.refresh();
2911                    })
2912                    .with_context(|| {
2913                        format!(
2914                            "handling hover status change for window {:?}",
2915                            handle.window_id()
2916                        )
2917                    })
2918                    .log_err();
2919            }
2920        }));
2921        platform_window.on_input({
2922            let mut cx = cx.to_async();
2923            Box::new(move |event| {
2924                handle
2925                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2926                    .with_context(|| {
2927                        format!("dispatching input for window {:?}", handle.window_id())
2928                    })
2929                    .log_err()
2930                    .unwrap_or(DispatchEventResult::default())
2931            })
2932        });
2933        platform_window.on_hit_test_window_control_at({
2934            let mut cx = cx.to_async();
2935            Box::new(move |position| {
2936                handle
2937                    .update(&mut cx, |_, window, _cx| {
2938                        // WM_NCHITTEST precedes the next mouse-move and can run
2939                        // after a cached repaint. The previous input's hit set
2940                        // may name another point/frame, or be narrowed to a DOM
2941                        // event path; it is not a native caption hit test.
2942                        let position = position.unwrap_or_else(|| window.platform_window.mouse_position());
2943                        window.window_control_area_at(position)
2944                    })
2945                    .with_context(|| {
2946                        format!(
2947                            "hit-testing window controls for window {:?}",
2948                            handle.window_id()
2949                        )
2950                    })
2951                    .log_err()
2952                    .unwrap_or(None)
2953            })
2954        });
2955        platform_window.on_move_tab_to_new_window({
2956            let mut cx = cx.to_async();
2957            Box::new(move || {
2958                handle
2959                    .update(&mut cx, |_, _window, cx| {
2960                        SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2961                    })
2962                    .with_context(|| {
2963                        format!(
2964                            "moving tab to new window from window {:?}",
2965                            handle.window_id()
2966                        )
2967                    })
2968                    .log_err();
2969            })
2970        });
2971        platform_window.on_merge_all_windows({
2972            let mut cx = cx.to_async();
2973            Box::new(move || {
2974                handle
2975                    .update(&mut cx, |_, _window, cx| {
2976                        SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2977                    })
2978                    .with_context(|| {
2979                        format!("merging all windows into window {:?}", handle.window_id())
2980                    })
2981                    .log_err();
2982            })
2983        });
2984        platform_window.on_select_next_tab({
2985            let mut cx = cx.to_async();
2986            Box::new(move || {
2987                handle
2988                    .update(&mut cx, |_, _window, cx| {
2989                        SystemWindowTabController::select_next_tab(cx, handle.window_id());
2990                    })
2991                    .with_context(|| {
2992                        format!("selecting next tab for window {:?}", handle.window_id())
2993                    })
2994                    .log_err();
2995            })
2996        });
2997        platform_window.on_select_previous_tab({
2998            let mut cx = cx.to_async();
2999            Box::new(move || {
3000                handle
3001                    .update(&mut cx, |_, _window, cx| {
3002                        SystemWindowTabController::select_previous_tab(cx, handle.window_id())
3003                    })
3004                    .with_context(|| {
3005                        format!("selecting previous tab for window {:?}", handle.window_id())
3006                    })
3007                    .log_err();
3008            })
3009        });
3010        platform_window.on_toggle_tab_bar({
3011            let mut cx = cx.to_async();
3012            Box::new(move || {
3013                handle
3014                    .update(&mut cx, |_, window, cx| {
3015                        let tab_bar_visible = window.platform_window.tab_bar_visible();
3016                        SystemWindowTabController::set_visible(cx, tab_bar_visible);
3017                    })
3018                    .with_context(|| {
3019                        format!("toggling tab bar for window {:?}", handle.window_id())
3020                    })
3021                    .log_err();
3022            })
3023        });
3024
3025        if let Some(app_id) = app_id {
3026            platform_window.set_app_id(&app_id);
3027        }
3028
3029        platform_window.map_window().unwrap();
3030
3031        Ok(Window {
3032            handle,
3033            invalidator,
3034            removed: false,
3035            platform_window,
3036            display_id,
3037            display_observers: SingleSubscriberSet::new(),
3038            is_resizable,
3039            is_minimizable,
3040            last_window_bounds: window_bounds,
3041            sprite_atlas,
3042            text_system,
3043            text_rendering_mode: cx.text_rendering_mode.clone(),
3044            rem_size: px(16.),
3045            rem_size_override_stack: SmallVec::new(),
3046            viewport_size: content_size,
3047            layout_engine: Some(TaffyLayoutEngine::new()),
3048            root: None,
3049            element_id_stack: ElementIdStack::default(),
3050            text_style_stack: Vec::new(),
3051            rendered_entity_stack: Vec::new(),
3052            element_offset_stack: Vec::new(),
3053            content_mask_stack: Vec::new(),
3054            vn_clip_stack: None,
3055            vn_capture_records: FxHashMap::default(),
3056            element_opacity: 1.0,
3057            element_image_tint: Hsla::transparent_black(),
3058            element_image_headroom: 1.0,
3059            element_transform: TransformationMatrix::unit(),
3060            vn_hitbox_tag: 0,
3061            vn_tag_fresh: false,
3062            vn_tag_transform: None,
3063            vn_tag_every_hitbox: false,
3064            vn_pick_every_box: false,
3065            vn_hit_refiner: None,
3066            input_interceptor: None,
3067            vn_key_event_seq: 0,
3068            vn_pointer_lock: None,
3069            vn_raw_mouse_position: None,
3070            vn_mouse_movement: Point::default(),
3071            requested_autoscroll: None,
3072            last_text_input_configuration: None,
3073            focused_text_input: None,
3074            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3075            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3076            next_frame_callbacks,
3077            next_frame_wanted,
3078            next_hitbox_id: HitboxId(0),
3079            next_tooltip_id: TooltipId::default(),
3080            tooltip_bounds: None,
3081            dirty_views: FxHashSet::default(),
3082            focus_listeners: SingleSubscriberSet::new(),
3083            focus_lost_listeners: SingleSubscriberSet::new(),
3084            focus_lost_path: SmallVec::new(),
3085            default_prevented: true,
3086            mouse_position,
3087            mouse_hit_test: HitTest::default(),
3088            modifiers,
3089            capslock,
3090            scale_factor,
3091            bounds_observers: SingleSubscriberSet::new(),
3092            appearance,
3093            appearance_observers: SingleSubscriberSet::new(),
3094            button_layout_observers: SingleSubscriberSet::new(),
3095            active,
3096            assume_active: false,
3097            visibility,
3098            visibility_observers: SingleSubscriberSet::new(),
3099            vn_effect_pointer: VnEffectPointer::new(hovered.get()),
3100            vn_effect_element: 0,
3101            vn_effect_phases: FxHashMap::default(),
3102            vn_defer_scope: None,
3103            vn_scopes_painted: FxHashSet::default(),
3104            pointer_inside: hovered.get(),
3105            hovered,
3106            needs_present,
3107            scene_animation_interval,
3108            input_rate_tracker,
3109            #[cfg(feature = "profiler")]
3110            window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
3111            last_input_modality: InputModality::Mouse,
3112            touch_gestures: TouchGestureRecognizer::new(
3113                cx.platform
3114                    .gestures()
3115                    .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
3116            ),
3117            touch_prediction_enabled: true,
3118            long_press_timer: None,
3119            long_press_capture: None,
3120            refreshing: false,
3121            activation_observers: SingleSubscriberSet::new(),
3122            focus: None,
3123            focus_enabled: true,
3124            focus_generation: 0,
3125            pending_input: None,
3126            pending_modifier: ModifierState::default(),
3127            pending_input_observers: SingleSubscriberSet::new(),
3128            prompt: None,
3129            client_inset: None,
3130            image_cache_stack: Vec::new(),
3131            captured_hitbox: None,
3132            #[cfg(any(feature = "inspector", debug_assertions))]
3133            inspector: None,
3134            #[cfg(feature = "profiler")]
3135            debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
3136            a11y: A11y::new(
3137                a11y_active_flag,
3138                accessibility_force_disabled,
3139                initial_window_title,
3140            ),
3141        })
3142    }
3143
3144    pub(crate) fn new_focus_listener(
3145        &self,
3146        value: AnyWindowFocusListener,
3147    ) -> (Subscription, impl FnOnce() + use<>) {
3148        self.focus_listeners.insert_pending(value)
3149    }
3150}
3151
3152#[derive(Clone, Debug, Default, PartialEq, Eq)]
3153#[expect(missing_docs)]
3154pub struct DispatchEventResult {
3155    pub propagate: bool,
3156    pub default_prevented: bool,
3157}
3158
3159/// Indicates which region of the window is visible. Content falling outside of this mask will not be
3160/// rendered.
3161///
3162/// vue-native fork: the mask is a ROUNDED rect. All-zero `corner_radii` is the plain rectangle gpui
3163/// always had, and costs each fragment shader one uniform branch. With radii, every primitive's
3164/// fragment shader multiplies its coverage by the rounded rect's antialiased SDF
3165/// (`content_mask_coverage` in each backend), on top of the hardware clip to `bounds`. CSS
3166/// `overflow` under a `border-radius` is what pushes one ([`crate::Style::overflow_mask`]).
3167/// [`ContentMask::intersect`] says what nesting two masks keeps exact.
3168#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3169#[repr(C)]
3170pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
3171    /// The bounds
3172    pub bounds: Bounds<P>,
3173    /// vue-native fork: each corner's radius, zero for a square corner. Every
3174    /// primitive carries it right after `bounds`, so the shaders' structs do too.
3175    pub corner_radii: Corners<P>,
3176    /// vue-native fork: CSS `corner-shape`, after `corner_radii` in every primitive. A shaped
3177    /// corner's radius is the outer one of the border its insets describe.
3178    pub corner_shapes: CornerShapes,
3179}
3180
3181impl<P: Clone + Debug + Default + PartialEq> ContentMask<P> {
3182    /// vue-native fork: a plain rectangular mask.
3183    pub fn rect(bounds: Bounds<P>) -> Self {
3184        ContentMask {
3185            bounds,
3186            corner_radii: Corners::default(),
3187            corner_shapes: CornerShapes::default(),
3188        }
3189    }
3190
3191    /// vue-native fork: whether any corner is rounded.
3192    pub fn is_rounded(&self) -> bool {
3193        self.corner_radii != Corners::default()
3194    }
3195}
3196
3197impl ContentMask<Pixels> {
3198    /// Scale the content mask's pixel units by the given scaling factor.
3199    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
3200        ContentMask {
3201            bounds: self.bounds.scale(factor),
3202            corner_radii: self.corner_radii.scale(factor),
3203            corner_shapes: self.corner_shapes.scale(factor),
3204        }
3205    }
3206}
3207
3208impl<P> ContentMask<P>
3209where
3210    P: Copy
3211        + Ord
3212        + Debug
3213        + Default
3214        + Add<P, Output = P>
3215        + Sub<P, Output = P>
3216        + Div<f32, Output = P>
3217        + Into<f64>,
3218{
3219    /// Intersect the content mask with the given content mask.
3220    ///
3221    /// vue-native fork, the rounded corners:
3222    /// - Two rectangles intersect exactly, as before.
3223    /// - A corner of the result that is also a corner of one of the masks keeps
3224    ///   that mask's radius. When both masks have a corner there, the larger
3225    ///   radius wins. Two corners at one point nest, so the larger radius is the
3226    ///   smaller region, and that is exact.
3227    /// - Any other corner of the result is square. That is exact when the
3228    ///   rounded mask's curve does not reach it: a rect clip inside the curve's
3229    ///   span, or a scroller inset from its rounded card. Where a rect clip cuts
3230    ///   through a curve, the cut corner comes out square and shows the sliver
3231    ///   the curve would have hidden. That is the one approximation; the common
3232    ///   case, one rounded ancestor around rect clips that fill it or sit
3233    ///   inside it, is exact.
3234    pub fn intersect(&self, other: &Self) -> Self {
3235        let bounds = self.bounds.intersect(&other.bounds);
3236        if !self.is_rounded() && !other.is_rounded() {
3237            return ContentMask::rect(bounds);
3238        }
3239        let at = |mask: &Self, left: bool, top: bool| {
3240            let x = if left { mask.bounds.left() } else { mask.bounds.right() };
3241            let y = if top { mask.bounds.top() } else { mask.bounds.bottom() };
3242            (x, y)
3243        };
3244        let radius = |left: bool, top: bool, mine: (P, u32), theirs: (P, u32)| {
3245            let here = at(&ContentMask::rect(bounds), left, top);
3246            let mine = if at(self, left, top) == here { mine } else { (P::default(), 0) };
3247            let theirs = if at(other, left, top) == here { theirs } else { (P::default(), 0) };
3248            if theirs.0 > mine.0 { theirs } else { mine }
3249        };
3250        let (a, b) = (&self.corner_radii, &other.corner_radii);
3251        let (sa, sb) = (self.corner_shapes.corners(), other.corner_shapes.corners());
3252        let top_left = radius(true, true, (a.top_left, sa.top_left), (b.top_left, sb.top_left));
3253        let top_right = radius(false, true, (a.top_right, sa.top_right), (b.top_right, sb.top_right));
3254        let bottom_right = radius(
3255            false,
3256            false,
3257            (a.bottom_right, sa.bottom_right),
3258            (b.bottom_right, sb.bottom_right),
3259        );
3260        let bottom_left =
3261            radius(true, false, (a.bottom_left, sa.bottom_left), (b.bottom_left, sb.bottom_left));
3262        let corner_radii = Corners {
3263            top_left: top_left.0,
3264            top_right: top_right.0,
3265            bottom_right: bottom_right.0,
3266            bottom_left: bottom_left.0,
3267        }
3268        .clamp_radii_for_quad_size(bounds.size);
3269        ContentMask {
3270            bounds,
3271            corner_radii,
3272            corner_shapes: CornerShapes {
3273                top_left: top_left.1,
3274                top_right: top_right.1,
3275                bottom_right: bottom_right.1,
3276                bottom_left: bottom_left.1,
3277            },
3278        }
3279    }
3280
3281    /// vue-native fork: whether `point` is inside the mask, its rounded
3282    /// corners included. The hit test asks this, so a click outside a rounded
3283    /// clip's curve does not reach what the clip hides.
3284    pub fn contains(&self, point: &Point<P>) -> bool {
3285        if !self.bounds.contains(point) {
3286            return false;
3287        }
3288        if !self.is_rounded() {
3289            return true;
3290        }
3291        if !self.corner_shapes.is_round() {
3292            return crate::corner_shape::shaped_rect_sdf(
3293                *point,
3294                &self.bounds,
3295                &self.corner_radii,
3296                &self.corner_shapes,
3297            ) <= 0.;
3298        }
3299        let b = &self.bounds;
3300        let r = &self.corner_radii;
3301        for (radius, cx, cy, left, top) in [
3302            (r.top_left, b.left() + r.top_left, b.top() + r.top_left, true, true),
3303            (r.top_right, b.right() - r.top_right, b.top() + r.top_right, false, true),
3304            (r.bottom_right, b.right() - r.bottom_right, b.bottom() - r.bottom_right, false, false),
3305            (r.bottom_left, b.left() + r.bottom_left, b.bottom() - r.bottom_left, true, false),
3306        ] {
3307            let in_x = if left { point.x < cx } else { point.x > cx };
3308            let in_y = if top { point.y < cy } else { point.y > cy };
3309            if radius > P::default() && in_x && in_y {
3310                let (dx, dy): (f64, f64) = ((point.x - cx).into(), (point.y - cy).into());
3311                let radius: f64 = radius.into();
3312                return dx * dx + dy * dy <= radius * radius;
3313            }
3314        }
3315        true
3316    }
3317}
3318
3319impl Window {
3320    fn mark_view_dirty(&mut self, view_id: EntityId) {
3321        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
3322        // should already be dirty.
3323        for view_id in self
3324            .rendered_frame
3325            .dispatch_tree
3326            .view_path_reversed(view_id)
3327        {
3328            if !self.dirty_views.insert(view_id) {
3329                break;
3330            }
3331        }
3332    }
3333
3334    pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
3335        let visibility = self.platform_window.visibility();
3336        if self.visibility != visibility {
3337            self.visibility = visibility;
3338            #[cfg(feature = "profiler")]
3339            profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
3340            self.visibility_observers
3341                .clone()
3342                .retain(|callback| callback(visibility, self, cx));
3343        }
3344        #[cfg(feature = "profiler")]
3345        if self.invalidator.is_dirty() || self.needs_present.get() {
3346            profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
3347        }
3348    }
3349
3350    /// This window's part of [`App::debug_state`].
3351    ///
3352    /// Values GPUI caches are reported next to what the platform reports now,
3353    /// so a stale cache shows up as a mismatch.
3354    pub(crate) fn debug_state(&self) -> serde_json::Value {
3355        let platform_window = &self.platform_window;
3356        serde_json::json!({
3357            "id": self.handle.window_id().as_u64(),
3358            "title": platform_window.get_title(),
3359            "bounds": platform_window.bounds(),
3360            "window_bounds": format!("{:?}", platform_window.window_bounds()),
3361            "content_size": platform_window.content_size(),
3362            "viewport_size": self.viewport_size,
3363            "scale_factor": {
3364                "cached": self.scale_factor,
3365                "platform": platform_window.scale_factor(),
3366            },
3367            "display_id": {
3368                "cached": self.display_id.map(u64::from),
3369                "platform": platform_window.display().map(|display| u64::from(display.id())),
3370            },
3371            "active": {
3372                "cached": self.active.get(),
3373                "platform": platform_window.is_active(),
3374            },
3375            "hovered": {
3376                "cached": self.hovered.get(),
3377                "platform": platform_window.is_hovered(),
3378            },
3379            "visibility": {
3380                "cached": format!("{:?}", self.visibility),
3381                "platform": format!("{:?}", platform_window.visibility()),
3382            },
3383            "appearance": {
3384                "cached": format!("{:?}", self.appearance),
3385                "platform": format!("{:?}", platform_window.appearance()),
3386            },
3387            "is_fullscreen": platform_window.is_fullscreen(),
3388            "is_maximized": platform_window.is_maximized(),
3389            "mouse_position": {
3390                "cached": self.mouse_position,
3391                "platform": platform_window.mouse_position(),
3392            },
3393            "modifiers": {
3394                "cached": self.modifiers,
3395                "platform": platform_window.modifiers(),
3396            },
3397            "cursor_style": self.rendered_frame.cursor_style(self),
3398            "frame": {
3399                "dirty": self.invalidator.is_dirty(),
3400                "needs_present": self.needs_present.get(),
3401                "refreshing": self.refreshing,
3402                "next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
3403            },
3404            "gpu": platform_window.gpu_specs(),
3405            "platform": platform_window.debug_state(),
3406        })
3407    }
3408
3409    /// Whether the platform is presenting this window's frames (see
3410    /// [`WindowVisibility`]).
3411    pub fn visibility(&self) -> WindowVisibility {
3412        self.visibility
3413    }
3414
3415    /// Whether frames drawn for this window will be shown.
3416    ///
3417    /// This is not the window's shown/hidden state: a shown window that is
3418    /// fully behind another window, minimized, or on a sleeping display is not
3419    /// visible here.
3420    pub fn is_visible(&self) -> bool {
3421        self.visibility.is_visible()
3422    }
3423
3424    /// Registers a callback to be invoked when the window's visibility changes.
3425    pub fn observe_window_visibility(
3426        &self,
3427        mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
3428    ) -> Subscription {
3429        self.visibility_observers
3430            .insert(Box::new(move |visibility, window, cx| {
3431                callback(visibility, window, cx);
3432                true
3433            }))
3434    }
3435
3436    /// Registers a callback to be invoked when the window is activated or
3437    /// deactivated, without an entity to update (vue-native fork).
3438    pub fn observe_window_activation(
3439        &self,
3440        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3441    ) -> Subscription {
3442        self.activation_observers
3443            .insert(Box::new(move |window, cx| {
3444                callback(window, cx);
3445                true
3446            }))
3447    }
3448
3449    /// Registers a callback to be invoked when the window appearance changes.
3450    pub fn observe_window_appearance(
3451        &self,
3452        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3453    ) -> Subscription {
3454        self.appearance_observers
3455            .insert(Box::new(move |window, cx| {
3456                callback(window, cx);
3457                true
3458            }))
3459    }
3460
3461    /// Registers a callback to be invoked when the window button layout changes.
3462    pub fn observe_button_layout_changed(
3463        &self,
3464        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3465    ) -> Subscription {
3466        self.button_layout_observers
3467            .insert(Box::new(move |window, cx| {
3468                callback(window, cx);
3469                true
3470            }))
3471    }
3472
3473    /// Replaces the root entity of the window with a new one.
3474    pub fn replace_root<E>(
3475        &mut self,
3476        cx: &mut App,
3477        build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
3478    ) -> Entity<E>
3479    where
3480        E: 'static + Render,
3481    {
3482        let view = cx.new(|cx| build_view(self, cx));
3483        self.root = Some(view.clone().into());
3484        self.refresh();
3485        view
3486    }
3487
3488    /// Returns the root entity of the window, if it has one.
3489    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
3490    where
3491        E: 'static + Render,
3492    {
3493        self.root
3494            .as_ref()
3495            .map(|view| view.clone().downcast::<E>().ok())
3496    }
3497
3498    /// Obtain a handle to the window that belongs to this context.
3499    pub fn window_handle(&self) -> AnyWindowHandle {
3500        self.handle
3501    }
3502
3503    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
3504    pub fn refresh(&mut self) {
3505        if self.invalidator.not_drawing() {
3506            self.refreshing = true;
3507            self.invalidator.set_dirty(true);
3508        }
3509    }
3510
3511    /// Close this window.
3512    pub fn remove_window(&mut self) {
3513        self.removed = true;
3514    }
3515
3516    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
3517    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
3518        self.focus
3519            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
3520    }
3521
3522    /// While focus-lost listeners are being dispatched, returns the closest ancestor of the
3523    /// previously focused element that can still receive focus, making it a suitable target
3524    /// for focus restoration. Returns `None` at all other times, or when no such ancestor exists.
3525    pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
3526        let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
3527        ancestors.iter().rev().find_map(|id| {
3528            self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
3529            FocusHandle::for_id(*id, &cx.focus_handles)
3530        })
3531    }
3532
3533    /// Move focus to the element associated with the given [`FocusHandle`].
3534    pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
3535        if !self.focus_enabled || self.focus == Some(handle.id) {
3536            return;
3537        }
3538
3539        self.focus = Some(handle.id);
3540        self.focus_generation = self.focus_generation.wrapping_add(1);
3541        self.clear_pending_keystrokes(cx);
3542
3543        self.refresh();
3544    }
3545
3546    /// Remove focus from all elements within this context's window.
3547    pub fn blur(&mut self, cx: &mut App) {
3548        self.clear_pending_keystrokes(cx);
3549
3550        if !self.focus_enabled {
3551            return;
3552        }
3553
3554        if self.focus.is_some() {
3555            self.focus_generation = self.focus_generation.wrapping_add(1);
3556        }
3557        self.focus = None;
3558        self.refresh();
3559    }
3560
3561    /// Blur the window and don't allow anything in it to be focused again.
3562    pub fn disable_focus(&mut self, cx: &mut App) {
3563        self.blur(cx);
3564        self.focus_enabled = false;
3565    }
3566
3567    /// Move focus to next tab stop.
3568    pub fn focus_next(&mut self, cx: &mut App) {
3569        if !self.focus_enabled {
3570            return;
3571        }
3572
3573        if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
3574            self.focus(&handle, cx)
3575        }
3576    }
3577
3578    /// Move focus to previous tab stop.
3579    pub fn focus_prev(&mut self, cx: &mut App) {
3580        if !self.focus_enabled {
3581            return;
3582        }
3583
3584        if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
3585            self.focus(&handle, cx)
3586        }
3587    }
3588
3589    /// Accessor for the text system.
3590    pub fn text_system(&self) -> &Rc<WindowTextSystem> {
3591        &self.text_system
3592    }
3593
3594    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
3595    pub fn text_style(&self) -> TextStyle {
3596        let mut style = TextStyle::default();
3597        for refinement in &self.text_style_stack {
3598            style.refine(refinement);
3599        }
3600        style
3601    }
3602
3603    /// Check if the platform window is maximized.
3604    ///
3605    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
3606    pub fn is_maximized(&self) -> bool {
3607        self.platform_window.is_maximized()
3608    }
3609
3610    /// request a certain window decoration (Wayland)
3611    pub fn request_decorations(&self, decorations: WindowDecorations) {
3612        self.platform_window.request_decorations(decorations);
3613    }
3614
3615    /// Set the exclusive zone for a layer-shell surface: how much screen space it
3616    /// reserves so other surfaces avoid occluding it (e.g. a panel reserving space).
3617    /// Positive values reserve that distance from the anchored edge, 0 lets the
3618    /// surface be moved out of others' exclusive zones, and -1 ignores reserved
3619    /// space and may extend under other surfaces. (Wayland layer-shell windows only)
3620    pub fn set_exclusive_zone(&self, zone: Pixels) {
3621        self.platform_window.set_exclusive_zone(zone);
3622    }
3623
3624    /// Set which anchored edge a layer-shell surface's exclusive zone applies to.
3625    /// This is only needed to disambiguate a corner-anchored surface; otherwise the
3626    /// edge is deduced from the anchor. The edge must be a single edge the surface
3627    /// is anchored to, or it is ignored. (Wayland layer-shell windows only)
3628    #[cfg(all(target_os = "linux", feature = "wayland"))]
3629    pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
3630        self.platform_window.set_exclusive_edge(edge);
3631    }
3632
3633    /// Start an interactive window resize operation if this window is resizable.
3634    pub fn start_window_resize(&self, edge: ResizeEdge) {
3635        if self.is_resizable {
3636            self.platform_window.start_window_resize(edge);
3637        }
3638    }
3639
3640    /// Linux (wayland) only: Set the window's input region, the area that receives pointer
3641    /// and touch input. Events outside it pass through to whatever is below the window.
3642    ///
3643    /// - `Some(rects)` restricts input to the union of `rects`, in window coordinates.
3644    /// - `Some(&[])` is an empty region, so the window receives no pointer or touch input.
3645    /// - `None` resets the region to the default, so the whole window receives input again.
3646    pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
3647        self.platform_window.set_input_region(region);
3648    }
3649
3650    /// Return the `WindowBounds` to indicate that how a window should be opened
3651    /// after it has been closed
3652    pub fn window_bounds(&self) -> WindowBounds {
3653        self.platform_window.window_bounds()
3654    }
3655
3656    pub(crate) fn last_window_bounds(&self) -> WindowBounds {
3657        self.last_window_bounds
3658    }
3659
3660    pub(crate) fn display_id(&self) -> Option<DisplayId> {
3661        self.display_id
3662    }
3663
3664    /// Return the `WindowBounds` excluding insets (Wayland and X11)
3665    pub fn inner_window_bounds(&self) -> WindowBounds {
3666        self.platform_window.inner_window_bounds()
3667    }
3668
3669    /// vue-native: Windows' composition device and the container visual drawn
3670    /// UNDER this window's surface (see `PlatformWindow::vn_composition_underlay`):
3671    /// owned COM pointers, released by the caller.
3672    pub fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
3673        self.platform_window.vn_composition_underlay()
3674    }
3675
3676    /// vue-native: maximizes or leaves the maximized state without toggling.
3677    pub fn vn_set_maximized(&self, maximized: bool) {
3678        self.platform_window.vn_set_maximized(maximized)
3679    }
3680
3681    /// vue-native: the platform's own maximized (zoomed) state.
3682    pub fn vn_is_zoomed(&self) -> bool {
3683        self.platform_window.vn_is_zoomed()
3684    }
3685
3686    /// vue-native: minimized, where the platform reports it.
3687    pub fn vn_is_minimized(&self) -> bool {
3688        self.platform_window.vn_is_minimized()
3689    }
3690
3691    /// vue-native: leaves the minimized state.
3692    pub fn vn_unminimize(&self) {
3693        self.platform_window.vn_unminimize()
3694    }
3695
3696    /// vue-native: hides the window without minimizing it; false where unsupported.
3697    pub fn vn_hide(&self) -> bool {
3698        self.platform_window.vn_hide()
3699    }
3700
3701    /// vue-native: false while hidden by [`Self::vn_hide`] or not yet shown.
3702    pub fn vn_is_shown(&self) -> bool {
3703        self.platform_window.vn_is_shown()
3704    }
3705
3706    /// vue-native: moves and/or resizes the outer frame, in the space of [`Self::bounds`];
3707    /// false when the platform refuses part of it.
3708    pub fn vn_set_frame(&self, origin: Option<Point<Pixels>>, size: Option<Size<Pixels>>) -> bool {
3709        self.platform_window.vn_set_frame(origin, size)
3710    }
3711
3712    /// vue-native: keeps the window above normal windows; false where unsupported.
3713    pub fn vn_set_always_on_top(&self, on: bool) -> bool {
3714        self.platform_window.vn_set_always_on_top(on)
3715    }
3716
3717    /// vue-native: whether the platform's own maximize control is enabled.
3718    pub fn vn_set_maximizable(&self, maximizable: bool) {
3719        self.platform_window.vn_set_maximizable(maximizable)
3720    }
3721
3722    /// vue-native: lets pointer input pass through; false where unsupported.
3723    pub fn vn_set_ignore_mouse(&self, ignore: bool) -> bool {
3724        self.platform_window.vn_set_ignore_mouse(ignore)
3725    }
3726
3727    /// vue-native: keeps the contents out of screen capture; false where unsupported.
3728    pub fn vn_set_content_protection(&self, on: bool) -> bool {
3729        self.platform_window.vn_set_content_protection(on)
3730    }
3731
3732    /// vue-native: closes as the platform's close button would; the should-close callback decides.
3733    pub fn vn_request_close(&self) {
3734        self.platform_window.vn_request_close()
3735    }
3736
3737    /// Encode the window's native restorable state into an opaque blob.
3738    /// Returns `None` on platforms without native state restoration or if encoding fails.
3739    pub fn native_window_state(&self) -> Option<Vec<u8>> {
3740        self.platform_window.native_window_state()
3741    }
3742
3743    /// Restore the window's native state from a blob previously produced
3744    /// by [`Window::native_window_state`]. A no-op on platforms without native state restoration.
3745    pub fn restore_native_window_state(&self, state: &[u8]) {
3746        self.platform_window.restore_native_window_state(state);
3747    }
3748
3749    /// Dispatch the given action on the currently focused element.
3750    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
3751        let focus_id = self.focused(cx).map(|handle| handle.id);
3752
3753        let window = self.handle;
3754        cx.defer(move |cx| {
3755            window
3756                .update(cx, |_, window, cx| {
3757                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
3758                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
3759                })
3760                .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
3761                .log_err();
3762        })
3763    }
3764
3765    pub(crate) fn dispatch_keystroke_observers(
3766        &mut self,
3767        keystroke: &Keystroke,
3768        input_preference: InputPreference,
3769        action: Option<&dyn Action>,
3770        context_stack: Vec<KeyContext>,
3771        cx: &mut App,
3772    ) {
3773        cx.keystroke_observers.clone().retain(move |callback| {
3774            (callback)(
3775                &KeystrokeEvent {
3776                    keystroke: keystroke.clone(),
3777                    input_preference,
3778                    action: action.map(|action| action.boxed_clone()),
3779                    context_stack: context_stack.clone(),
3780                },
3781                self,
3782                cx,
3783            )
3784        });
3785    }
3786
3787    pub(crate) fn dispatch_keystroke_interceptors(
3788        &mut self,
3789        keystroke: &Keystroke,
3790        input_preference: InputPreference,
3791        context_stack: Vec<KeyContext>,
3792        cx: &mut App,
3793    ) {
3794        cx.keystroke_interceptors.clone().retain(move |callback| {
3795            (callback)(
3796                &KeystrokeEvent {
3797                    keystroke: keystroke.clone(),
3798                    input_preference,
3799                    action: None,
3800                    context_stack: context_stack.clone(),
3801                },
3802                self,
3803                cx,
3804            )
3805        });
3806    }
3807
3808    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
3809    /// that are currently on the stack to be returned to the app.
3810    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
3811        let handle = self.handle;
3812        cx.defer(move |cx| {
3813            handle.update(cx, |_, window, cx| f(window, cx)).ok();
3814        });
3815    }
3816
3817    /// Subscribe to events emitted by a entity.
3818    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3819    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
3820    pub fn observe<T: 'static>(
3821        &mut self,
3822        observed: &Entity<T>,
3823        cx: &mut App,
3824        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
3825    ) -> Subscription {
3826        let entity_id = observed.entity_id();
3827        let observed = observed.downgrade();
3828        let window_handle = self.handle;
3829        cx.new_observer(
3830            entity_id,
3831            Box::new(move |cx| {
3832                window_handle
3833                    .update(cx, |_, window, cx| {
3834                        if let Some(handle) = observed.upgrade() {
3835                            on_notify(handle, window, cx);
3836                            true
3837                        } else {
3838                            false
3839                        }
3840                    })
3841                    .unwrap_or(false)
3842            }),
3843        )
3844    }
3845
3846    /// Subscribe to events emitted by a entity.
3847    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3848    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
3849    pub fn subscribe<Emitter, Evt>(
3850        &mut self,
3851        entity: &Entity<Emitter>,
3852        cx: &mut App,
3853        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
3854    ) -> Subscription
3855    where
3856        Emitter: EventEmitter<Evt>,
3857        Evt: 'static,
3858    {
3859        let entity_id = entity.entity_id();
3860        let handle = entity.downgrade();
3861        let window_handle = self.handle;
3862        cx.new_subscription(
3863            entity_id,
3864            (
3865                TypeId::of::<Evt>(),
3866                Box::new(move |event, cx| {
3867                    window_handle
3868                        .update(cx, |_, window, cx| {
3869                            if let Some(entity) = handle.upgrade() {
3870                                let event = event.downcast_ref().expect("invalid event type");
3871                                on_event(entity, event, window, cx);
3872                                true
3873                            } else {
3874                                false
3875                            }
3876                        })
3877                        .unwrap_or(false)
3878                }),
3879            ),
3880        )
3881    }
3882
3883    /// Register a callback to be invoked when the given `Entity` is released.
3884    pub fn observe_release<T>(
3885        &self,
3886        entity: &Entity<T>,
3887        cx: &mut App,
3888        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
3889    ) -> Subscription
3890    where
3891        T: 'static,
3892    {
3893        let entity_id = entity.entity_id();
3894        let window_handle = self.handle;
3895        cx.release_listeners.insert(
3896            entity_id,
3897            Box::new(move |entity, cx| {
3898                let entity = entity.downcast_mut().expect("invalid entity type");
3899                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
3900            }),
3901        )
3902    }
3903
3904    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
3905    /// await points in async code.
3906    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
3907        AsyncWindowContext::new_context(cx.to_async(), self.handle)
3908    }
3909
3910    /// Schedule the given closure to be run directly after the current frame is rendered.
3911    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3912        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3913        self.next_frame_wanted.set(true);
3914        self.platform_window.schedule_frame();
3915        // Next-frame callbacks create frame demand without dirtying the
3916        // window, so the platform's frame source must be woken explicitly.
3917        self.invalidator.wake_platform();
3918    }
3919
3920    /// vue-native fork: like [`Self::on_next_frame`], but rides along with the
3921    /// next frame the platform delivers without asking for one. A frame source
3922    /// that paces idle windows can then let a self-rescheduling pump wait for
3923    /// real demand (input, an invalidation, an `on_next_frame`) or its own
3924    /// deadline; one that delivers every refresh runs it on the next.
3925    pub fn on_next_frame_passive(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3926        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3927    }
3928
3929    /// Schedule a frame to be drawn on the next animation frame.
3930    ///
3931    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
3932    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
3933    ///
3934    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
3935    ///
3936    /// Callers driving purely decorative animations (spinners, pulses, and the
3937    /// like) should prefer [`AnimationExt::with_animation`](crate::AnimationExt::with_animation),
3938    /// which automatically respects [`App::reduce_motion`]. When using this
3939    /// method directly for decorative motion, check [`App::reduce_motion`]
3940    /// and skip the frame request when it is set.
3941    pub fn request_animation_frame(&self) {
3942        let entity = self.current_view();
3943        self.on_next_frame(move |_, cx| cx.notify(entity));
3944    }
3945
3946    pub(crate) fn advance_scene_animations(&mut self, cx: &App) {
3947        let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
3948        self.rendered_frame.scene.advance_animations(elapsed);
3949    }
3950
3951    /// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran.
3952    ///
3953    /// Tests have no platform frame loop, so this simulates the delivery of the
3954    /// next frame.
3955    #[cfg(any(test, feature = "test-support"))]
3956    pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
3957        let callbacks = self.next_frame_callbacks.take();
3958        self.next_frame_wanted.set(false);
3959        let count = callbacks.len();
3960        for callback in callbacks {
3961            callback(self, cx);
3962        }
3963        count
3964    }
3965
3966    /// Spawn the future returned by the given closure on the application thread pool.
3967    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
3968    /// use within your future.
3969    #[track_caller]
3970    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
3971    where
3972        R: 'static,
3973        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3974    {
3975        let handle = self.handle;
3976        cx.spawn(async move |app| {
3977            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3978            f(&mut async_window_cx).await
3979        })
3980    }
3981
3982    /// Spawn the future returned by the given closure on the application thread
3983    /// pool, with the given priority. The closure is provided a handle to the
3984    /// current window and an `AsyncWindowContext` for use within your future.
3985    #[track_caller]
3986    pub fn spawn_with_priority<AsyncFn, R>(
3987        &self,
3988        priority: Priority,
3989        cx: &App,
3990        f: AsyncFn,
3991    ) -> Task<R>
3992    where
3993        R: 'static,
3994        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3995    {
3996        let handle = self.handle;
3997        cx.spawn_with_priority(priority, async move |app| {
3998            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3999            f(&mut async_window_cx).await
4000        })
4001    }
4002
4003    /// Notify the window that its bounds have changed.
4004    ///
4005    /// This updates internal state like `viewport_size` and `scale_factor` from
4006    /// the platform window, then notifies observers. Normally called automatically
4007    /// by the platform's resize callback, but exposed publicly for test infrastructure.
4008    pub fn bounds_changed(&mut self, cx: &mut App) {
4009        self.scale_factor = self.platform_window.scale_factor();
4010        self.viewport_size = self.platform_window.content_size();
4011        self.last_window_bounds = self.platform_window.window_bounds();
4012        cx.sync_window_update_entry(self);
4013        self.mouse_position = self.platform_window.mouse_position();
4014
4015        self.refresh();
4016
4017        self.bounds_observers
4018            .clone()
4019            .retain(|callback| callback(self, cx));
4020    }
4021
4022    fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
4023        let moved_to = handle
4024            .update(cx, |_, window, _| {
4025                let display_id = window.platform_window.display().map(|display| display.id());
4026                let moved = display_id != window.display_id;
4027                window.display_id = display_id;
4028                moved.then_some(display_id)
4029            })
4030            .with_context(|| {
4031                format!(
4032                    "handling display change for window {:?}",
4033                    handle.window_id()
4034                )
4035            })
4036            .log_err()
4037            .flatten();
4038        let Some(display_id) = moved_to else {
4039            return;
4040        };
4041        // The platform's notifications about the window and about displays
4042        // arrive in no guaranteed order, so make sure App knows the display
4043        // before the window's observers read its state.
4044        if let Some(display_id) = display_id
4045            && !cx.knows_display(display_id)
4046        {
4047            cx.displays_changed();
4048        }
4049        handle
4050            .update(cx, |_, window, cx| window.notify_display_observers(cx))
4051            .with_context(|| {
4052                format!(
4053                    "notifying display observers for window {:?}",
4054                    handle.window_id()
4055                )
4056            })
4057            .log_err();
4058    }
4059
4060    pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
4061        self.display_observers
4062            .clone()
4063            .retain(|callback| callback(self, cx));
4064    }
4065
4066    /// The time between refreshes of the display the window is on, as of the
4067    /// platform's last display change notification. Variable refresh rate
4068    /// displays report their maximum rate. Returns `None` when the platform
4069    /// doesn't report it.
4070    pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
4071        cx.display_refresh_interval(self.display_id?)
4072    }
4073
4074    /// Registers a callback invoked when the window moves to another display
4075    /// or its display's properties change, for example its refresh
4076    /// interval. [`Self::refresh_interval`] already returns the new value
4077    /// when the callback runs.
4078    pub fn observe_window_display(
4079        &self,
4080        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
4081    ) -> Subscription {
4082        self.display_observers.insert(Box::new(move |window, cx| {
4083            callback(window, cx);
4084            true
4085        }))
4086    }
4087
4088    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
4089    pub fn bounds(&self) -> Bounds<Pixels> {
4090        self.platform_window.bounds()
4091    }
4092
4093    /// Returns the regions of this window obscured by system UI and the keyboard.
4094    pub fn insets(&self) -> WindowInsets {
4095        self.platform_window.insets()
4096    }
4097
4098    /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
4099    /// This does not present the frame to screen - useful for visual testing where we want
4100    /// to capture what would be rendered without displaying it or requiring the window to be visible.
4101    //
4102    // vue-native: upstream gates this on `test`/`test-support`. Our devtools
4103    // screenshot command is a first-class *product* feature that an agent
4104    // drives against a normal (non-test) build, and a headless readback of the
4105    // render target is strictly better than `PrintWindow` for it — it is the
4106    // client area exactly, needs no invisible-border correction, and does not
4107    // depend on DWM holding a live composition. So the gate is dropped rather
4108    // than widened to another feature flag: a feature would have to be plumbed
4109    // through `gpui`, `gpui_windows`, `gpui_macos` and `gpui_apple`, which is
4110    // four more merge surfaces than deleting four attributes.
4111    pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
4112        self.platform_window
4113            .render_to_image(&self.rendered_frame.scene)
4114    }
4115
4116    /// Borrows the most recently rendered frame's scene, so benchmarks can validate their
4117    /// output and report batch counts without cloning it.
4118    #[cfg(feature = "bench-support")]
4119    pub fn rendered_scene(&self) -> &Scene {
4120        &self.rendered_frame.scene
4121    }
4122
4123    /// Returns the quads in the most recently rendered frame's scene, so tests can assert on
4124    /// painted output without rasterizing the frame. Quad bounds are in scaled pixels and are
4125    /// not clipped; each quad carries the content mask it will be clipped to when drawn. Quads
4126    /// whose bounds don't intersect their content mask are culled at paint time and won't appear.
4127    #[cfg(any(test, feature = "test-support"))]
4128    pub fn painted_quads(&self) -> Vec<Quad> {
4129        self.rendered_frame.scene.quads.clone()
4130    }
4131
4132    /// Returns the underlines in the most recently rendered frame's scene.
4133    #[cfg(any(test, feature = "test-support"))]
4134    pub fn painted_underlines(&self) -> Vec<Underline> {
4135        self.rendered_frame.scene.underlines.clone()
4136    }
4137
4138    /// Set the content size of the window.
4139    pub fn resize(&mut self, size: Size<Pixels>) {
4140        self.platform_window.resize(size);
4141    }
4142
4143    /// Returns whether or not the window is currently fullscreen
4144    pub fn is_fullscreen(&self) -> bool {
4145        self.platform_window.is_fullscreen()
4146    }
4147
4148    /// Returns whether the window is currently in simple (borderless) fullscreen,
4149    /// where it covers the entire screen including the menu bar and notch area.
4150    /// Always `false` on platforms other than macOS.
4151    pub fn is_simple_fullscreen(&self) -> bool {
4152        self.platform_window.is_simple_fullscreen()
4153    }
4154
4155    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
4156        self.appearance = self.platform_window.appearance();
4157
4158        self.appearance_observers
4159            .clone()
4160            .retain(|callback| callback(self, cx));
4161    }
4162
4163    pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
4164        self.button_layout_observers
4165            .clone()
4166            .retain(|callback| callback(self, cx));
4167    }
4168
4169    /// Returns the appearance of the current window.
4170    pub fn appearance(&self) -> WindowAppearance {
4171        self.appearance
4172    }
4173
4174    /// Returns the size of the drawable area within the window.
4175    pub fn viewport_size(&self) -> Size<Pixels> {
4176        self.viewport_size
4177    }
4178
4179    /// Returns the platform's visible viewport in window-local logical pixels.
4180    ///
4181    /// Unlike `viewport_size`, this can shrink or move when the keyboard opens.
4182    /// During drawing this is a consistent frame snapshot. Outside drawing it
4183    /// reflects the latest platform sample, not a synchronous geometry query.
4184    pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
4185        self.platform_window.visual_viewport_bounds()
4186    }
4187
4188    /// Returns a conservative rectangle avoiding platform-known obscured content.
4189    ///
4190    /// Intersects the visual viewport with the full layout area inset by system
4191    /// safe areas and keyboard occlusion. Unknown overlays cannot be excluded.
4192    pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
4193        let insets = self.platform_window.insets().effective();
4194        let viewport = self.viewport_size();
4195        let left = insets.left.max(Pixels::ZERO).min(viewport.width);
4196        let top = insets.top.max(Pixels::ZERO).min(viewport.height);
4197        let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
4198        let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
4199        let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
4200        let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
4201        visible.size.width = visible.size.width.max(Pixels::ZERO);
4202        visible.size.height = visible.size.height.max(Pixels::ZERO);
4203        visible
4204    }
4205
4206    /// Requests the virtual keyboard for the currently focused text input.
4207    ///
4208    /// Call from a user gesture on platforms that require one. The platform may
4209    /// decline the request; this does not change focus or the layout viewport.
4210    pub fn request_virtual_keyboard(&self) {
4211        self.platform_window.show_soft_keyboard();
4212    }
4213
4214    /// Requests dismissal of the virtual keyboard without changing GPUI focus.
4215    pub fn dismiss_virtual_keyboard(&self) {
4216        self.platform_window.hide_soft_keyboard();
4217    }
4218
4219    /// Returns whether this window is focused by the operating system (receiving key events).
4220    pub fn is_window_active(&self) -> bool {
4221        self.active.get()
4222    }
4223
4224    /// vue-native fork: while `on`, gpui treats this window as active whatever
4225    /// the operating system says. That covers [`Window::is_window_active`],
4226    /// the focus paths a frame's focus events carry (with no OS activation
4227    /// they are empty, so `on_focus` never fires), and the inactive-window
4228    /// frame throttle. The platform's activation changes are ignored while it
4229    /// is set.
4230    ///
4231    /// Nothing at the OS level changes: the window is not raised, activated
4232    /// or given keyboard focus. vue-native's test hosts open their windows
4233    /// behind everything and never take the foreground, yet must run focus
4234    /// exactly as a window in front does. Turning it off goes back to what
4235    /// the platform reports.
4236    pub fn set_assume_active(&mut self, on: bool) {
4237        self.assume_active = on;
4238        let active = on || self.platform_window.is_active();
4239        if self.active.replace(active) != active {
4240            self.refresh();
4241        }
4242    }
4243
4244    /// vue-native fork: a window covered by others keeps drawing and reads as
4245    /// visible (macOS stops it otherwise); minimised or hidden still stops.
4246    pub fn set_draws_while_occluded(&self, on: bool) {
4247        self.platform_window.set_draws_while_occluded(on);
4248    }
4249
4250    /// vue-native fork: draws the window high dynamic range from its next frame, or standard
4251    /// with `None`. False when the renderer cannot; the window then stays standard.
4252    pub fn set_hdr_output(&self, output: Option<HdrOutput>) -> bool {
4253        self.platform_window.set_hdr_output(output)
4254    }
4255
4256    /// Returns whether this window is considered to be the window
4257    /// that currently owns the mouse cursor.
4258    /// On mac, this is equivalent to `is_window_active`.
4259    pub fn is_window_hovered(&self) -> bool {
4260        if cfg!(any(
4261            target_os = "windows",
4262            target_os = "linux",
4263            target_os = "freebsd"
4264        )) {
4265            self.hovered.get()
4266        } else {
4267            self.is_window_active()
4268        }
4269    }
4270
4271    /// Toggle zoom on the window.
4272    pub fn zoom_window(&self) {
4273        self.platform_window.zoom();
4274    }
4275
4276    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
4277    pub fn show_window_menu(&self, position: Point<Pixels>) {
4278        self.platform_window.show_window_menu(position)
4279    }
4280
4281    /// Handle window movement for Linux and macOS.
4282    /// Tells the compositor to take control of window movement (Wayland and X11)
4283    ///
4284    /// Events may not be received during a move operation.
4285    pub fn start_window_move(&self) {
4286        self.platform_window.start_window_move()
4287    }
4288
4289    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
4290    pub fn set_client_inset(&mut self, inset: Pixels) {
4291        self.client_inset = Some(inset);
4292        self.platform_window.set_client_inset(inset);
4293    }
4294
4295    /// Sets the client-drawn corner radii so platform effects can match the window's shape.
4296    pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
4297        self.platform_window.set_client_corner_radii(radii);
4298    }
4299
4300    /// Returns the client_inset value by [`Self::set_client_inset`].
4301    pub fn client_inset(&self) -> Option<Pixels> {
4302        self.client_inset
4303    }
4304
4305    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
4306    pub fn window_decorations(&self) -> Decorations {
4307        self.platform_window.window_decorations()
4308    }
4309
4310    /// Returns whether this window is resizable.
4311    pub fn is_resizable(&self) -> bool {
4312        self.is_resizable
4313    }
4314
4315    /// Returns whether this window is minimizable.
4316    pub fn is_minimizable(&self) -> bool {
4317        self.is_minimizable
4318    }
4319
4320    /// Returns the controls supported by the platform.
4321    pub fn window_controls(&self) -> WindowControls {
4322        self.platform_window.window_controls()
4323    }
4324
4325    /// Updates the window's title at the platform level.
4326    pub fn set_window_title(&mut self, title: &str) {
4327        self.platform_window.set_title(title);
4328        self.a11y.set_window_title(title.to_string());
4329    }
4330
4331    /// Sets the position of the macOS traffic light buttons.
4332    #[cfg(target_os = "macos")]
4333    pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
4334        self.platform_window.set_traffic_light_position(position);
4335    }
4336
4337    /// Shows or hides the native macOS titlebar, including the traffic light buttons.
4338    #[cfg(target_os = "macos")]
4339    pub fn set_native_titlebar_visibility(&self, visible: bool) {
4340        self.platform_window.set_native_titlebar_visibility(visible);
4341    }
4342
4343    /// Sets the application identifier.
4344    pub fn set_app_id(&mut self, app_id: &str) {
4345        self.platform_window.set_app_id(app_id);
4346    }
4347
4348    /// Sets the window background appearance.
4349    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
4350        self.platform_window
4351            .set_background_appearance(background_appearance);
4352    }
4353
4354    /// Whether the window currently draws the appearance last given to
4355    /// [`Self::set_background_appearance`]. `false` only while the platform
4356    /// stands in for it — a blurred macOS window in native fullscreen whose
4357    /// desktop picture could not be shown behind the blur — so an app can
4358    /// paint a background of its own exactly then.
4359    pub fn is_background_appearance_drawn(&self) -> bool {
4360        self.platform_window.is_background_appearance_drawn()
4361    }
4362
4363    /// Mark the window as dirty at the platform level.
4364    pub fn set_window_edited(&mut self, edited: bool) {
4365        self.platform_window.set_edited(edited);
4366    }
4367
4368    /// Set the path of the file this window represents.
4369    /// On macOS, this sets the window's accessibility document property (AXDocument).
4370    pub fn set_document_path(&self, path: Option<&std::path::Path>) {
4371        self.platform_window.set_document_path(path);
4372    }
4373
4374    /// Determine the display on which the window is visible.
4375    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
4376        cx.platform
4377            .displays()
4378            .into_iter()
4379            .find(|display| Some(display.id()) == self.display_id)
4380    }
4381
4382    /// Show the platform character palette.
4383    pub fn show_character_palette(&self) {
4384        self.platform_window.show_character_palette();
4385    }
4386
4387    /// The scale factor of the display associated with the window. For example, it could
4388    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
4389    /// be rendered as two pixels on screen.
4390    pub fn scale_factor(&self) -> f32 {
4391        self.scale_factor
4392    }
4393
4394    /// Overrides the display scale factor for tests.
4395    #[cfg(any(test, feature = "test-support"))]
4396    pub fn set_scale_factor(&mut self, scale_factor: f32) {
4397        self.scale_factor = scale_factor;
4398        self.refresh();
4399    }
4400
4401    /// The size of an em for the base font of the application. Adjusting this value allows the
4402    /// UI to scale, just like zooming a web page.
4403    pub fn rem_size(&self) -> Pixels {
4404        self.rem_size_override_stack
4405            .last()
4406            .copied()
4407            .unwrap_or(self.rem_size)
4408    }
4409
4410    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
4411    /// UI to scale, just like zooming a web page.
4412    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
4413        self.rem_size = rem_size.into();
4414    }
4415
4416    /// Acquire a globally unique identifier for the given ElementId.
4417    /// Only valid for the duration of the provided closure.
4418    pub fn with_global_id<R>(
4419        &mut self,
4420        element_id: ElementId,
4421        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
4422    ) -> R {
4423        self.with_id(element_id, |this| {
4424            let global_id = this.element_id_stack.global_id();
4425
4426            f(&global_id, this)
4427        })
4428    }
4429
4430    /// Calls the provided closure with the element ID pushed on the stack.
4431    #[inline]
4432    pub fn with_id<R>(
4433        &mut self,
4434        element_id: impl Into<ElementId>,
4435        f: impl FnOnce(&mut Self) -> R,
4436    ) -> R {
4437        self.element_id_stack.push(element_id.into());
4438        let result = f(self);
4439        self.element_id_stack.pop();
4440        result
4441    }
4442
4443    /// Executes the provided function with the specified rem size.
4444    ///
4445    /// This method must only be called as part of element drawing.
4446    // This function is called in a highly recursive manner in editor
4447    // prepainting, make sure its inlined to reduce the stack burden
4448    #[inline]
4449    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
4450    where
4451        F: FnOnce(&mut Self) -> R,
4452    {
4453        self.invalidator.debug_assert_paint_or_prepaint();
4454
4455        if let Some(rem_size) = rem_size {
4456            self.rem_size_override_stack.push(rem_size.into());
4457            let result = f(self);
4458            self.rem_size_override_stack.pop();
4459            result
4460        } else {
4461            f(self)
4462        }
4463    }
4464
4465    /// The line height associated with the current text style.
4466    pub fn line_height(&self) -> Pixels {
4467        self.text_style().line_height_in_pixels(self.rem_size())
4468    }
4469
4470    /// Rounds a logical value to the nearest device pixel.
4471    #[inline]
4472    pub fn pixel_snap(&self, value: Pixels) -> Pixels {
4473        px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
4474    }
4475
4476    /// f64 variant of [`Self::pixel_snap`].
4477    #[inline]
4478    pub fn pixel_snap_f64(&self, value: f64) -> f64 {
4479        let scale_factor = f64::from(self.scale_factor());
4480        round_half_toward_zero_f64(value * scale_factor) / scale_factor
4481    }
4482
4483    /// Snaps a bounds' origin and size to the nearest device pixel.
4484    #[inline]
4485    pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
4486        bounds.map(|c| self.pixel_snap(c))
4487    }
4488
4489    /// Snaps a point's coordinates to the nearest device pixel.
4490    #[inline]
4491    pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
4492        position.map(|c| self.pixel_snap(c))
4493    }
4494
4495    /// Returns the snapped device-space bounds used to paint an underline.
4496    pub fn underline_bounds(
4497        &self,
4498        origin: Point<Pixels>,
4499        width: Pixels,
4500        style: &UnderlineStyle,
4501    ) -> Bounds<ScaledPixels> {
4502        let scale_factor = self.scale_factor();
4503        let thickness = self.snap_stroke(style.thickness);
4504        let height = if style.wavy {
4505            ScaledPixels(thickness.0 * 3.)
4506        } else {
4507            thickness
4508        };
4509        Bounds {
4510            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4511            size: size(self.snap_stroke(width), height),
4512        }
4513    }
4514
4515    /// Paints an underline excluding absolute device-space horizontal spans.
4516    pub fn paint_underline_with_exclusions(
4517        &mut self,
4518        origin: Point<Pixels>,
4519        width: Pixels,
4520        style: &UnderlineStyle,
4521        exclusions: &[Range<ScaledPixels>],
4522    ) {
4523        self.invalidator.debug_assert_paint();
4524        let underline = self.underline(origin, width, style);
4525        if exclusions.is_empty() {
4526            self.next_frame.scene.insert_primitive(underline);
4527            return;
4528        }
4529
4530        let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
4531        if bounds.is_empty() {
4532            return;
4533        }
4534
4535        let mut exclusions = exclusions
4536            .iter()
4537            .filter_map(|span| {
4538                let start = span.start.max(bounds.left());
4539                let end = span.end.min(bounds.right());
4540                (start < end).then_some(start..end)
4541            })
4542            .collect::<SmallVec<[_; 4]>>();
4543        if exclusions.is_empty() {
4544            self.next_frame.scene.insert_primitive(underline);
4545            return;
4546        }
4547        exclusions.sort_unstable_by_key(|span| span.start);
4548
4549        let mut paint_span = |start, end| {
4550            // vue-native fork: through `intersect`, so a span that ends at a
4551            // rounded mask's corner keeps the curve.
4552            let span = ContentMask::rect(Bounds::from_corners(
4553                point(start, bounds.top()),
4554                point(end, bounds.bottom()),
4555            ));
4556            self.next_frame.scene.insert_primitive(Underline {
4557                content_mask: underline.content_mask.intersect(&span),
4558                ..underline
4559            });
4560        };
4561        let mut start = bounds.left();
4562        for exclusion in exclusions {
4563            if start < exclusion.start {
4564                paint_span(start, exclusion.start);
4565            }
4566            start = start.max(exclusion.end);
4567        }
4568        if start < bounds.right() {
4569            paint_span(start, bounds.right());
4570        }
4571    }
4572
4573    fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
4574        Underline {
4575            order: 0,
4576            pad: 0,
4577            bounds: self.underline_bounds(origin, width, style),
4578            content_mask: self.snapped_content_mask(),
4579            color: style
4580                .color
4581                .unwrap_or_default()
4582                .opacity(self.element_opacity()),
4583            thickness: self.snap_stroke(style.thickness),
4584            wavy: style.wavy.into(),
4585            // vue-native fork: an underline inside a transformed box turns
4586            // with it, like every other primitive pushed here.
4587            transformation: self.element_transform,
4588        }
4589    }
4590
4591    #[inline]
4592    fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4593        let scale_factor = self.scale_factor();
4594        let left = round_to_device_pixel(bounds.left().0, scale_factor);
4595        let top = round_to_device_pixel(bounds.top().0, scale_factor);
4596        let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
4597        let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4598        Bounds::from_corners(
4599            point(ScaledPixels(left), ScaledPixels(top)),
4600            point(ScaledPixels(right), ScaledPixels(bottom)),
4601        )
4602    }
4603
4604    /// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear.
4605    #[inline]
4606    fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
4607        ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
4608    }
4609
4610    #[inline]
4611    fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
4612        edges.map(|e| self.snap_stroke(*e))
4613    }
4614
4615    /// Floors the near edge and ceils the far edge, producing a strict superset of the raw region.
4616    #[inline]
4617    fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4618        let scale_factor = self.scale_factor();
4619        let left = floor_to_device_pixel(bounds.left().0, scale_factor);
4620        let top = floor_to_device_pixel(bounds.top().0, scale_factor);
4621        let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
4622        let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4623        Bounds::from_corners(
4624            point(ScaledPixels(left), ScaledPixels(top)),
4625            point(ScaledPixels(right), ScaledPixels(bottom)),
4626        )
4627    }
4628
4629    #[inline]
4630    fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
4631        let mask = self.content_mask();
4632        ContentMask {
4633            bounds: self.cover_bounds(mask.bounds),
4634            // vue-native fork: the radii scale as they are. The curve then
4635            // sits on the covered bounds, which are at most one device pixel
4636            // out from the exact ones, as the straight edges already are.
4637            corner_radii: mask.corner_radii.scale(self.scale_factor()),
4638            corner_shapes: mask.corner_shapes.scale(self.scale_factor()),
4639        }
4640    }
4641
4642    /// Call to prevent the default action of an event. Currently only used to prevent
4643    /// parent elements from becoming focused on mouse down.
4644    pub fn prevent_default(&mut self) {
4645        self.default_prevented = true;
4646    }
4647
4648    /// Obtain whether default has been prevented for the event currently being dispatched.
4649    pub fn default_prevented(&self) -> bool {
4650        self.default_prevented
4651    }
4652
4653    /// Determine whether the given action is available along the dispatch path to the currently focused element.
4654    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
4655        let node_id =
4656            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
4657        self.rendered_frame
4658            .dispatch_tree
4659            .is_action_available(action, node_id)
4660    }
4661
4662    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
4663    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
4664        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
4665        self.rendered_frame
4666            .dispatch_tree
4667            .is_action_available(action, node_id)
4668    }
4669
4670    /// The position of the mouse relative to the window.
4671    pub fn mouse_position(&self) -> Point<Pixels> {
4672        self.mouse_position
4673    }
4674
4675    /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
4676    /// events will be routed to listeners that check this hitbox's `is_hovered` status,
4677    /// regardless of actual hit testing. This enables drag operations that continue
4678    /// even when the pointer moves outside the element's bounds.
4679    ///
4680    /// The capture is automatically released on mouse up.
4681    pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
4682        self.captured_hitbox = Some(hitbox_id);
4683    }
4684
4685    /// Releases any active pointer capture.
4686    pub fn release_pointer(&mut self) {
4687        self.captured_hitbox = None;
4688    }
4689
4690    /// Returns the hitbox that has captured the pointer, if any.
4691    pub fn captured_hitbox(&self) -> Option<HitboxId> {
4692        self.captured_hitbox
4693    }
4694
4695    /// Captures the current long press for the given entity.
4696    ///
4697    /// The capture is released when the gesture ends or is cancelled, or when
4698    /// a replacement touch begins. A listener must also call
4699    /// [`Self::prevent_default`] on the started event to claim the gesture.
4700    pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
4701        self.long_press_capture = Some(entity.entity_id());
4702    }
4703
4704    /// Returns whether the given entity has captured the current long press.
4705    pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
4706        self.long_press_capture == Some(entity.entity_id())
4707    }
4708
4709    /// The current state of the keyboard's modifiers
4710    pub fn modifiers(&self) -> Modifiers {
4711        self.modifiers
4712    }
4713
4714    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
4715    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
4716    pub fn last_input_was_keyboard(&self) -> bool {
4717        self.last_input_modality == InputModality::Keyboard
4718    }
4719
4720    /// Returns whether the last input event came from a touch screen.
4721    pub fn last_input_was_touch(&self) -> bool {
4722        self.last_input_modality == InputModality::Touch
4723    }
4724
4725    /// The current state of the keyboard's capslock
4726    pub fn capslock(&self) -> Capslock {
4727        self.capslock
4728    }
4729
4730    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
4731    /// the contents of the new [`Scene`], use [`Self::present`].
4732    #[profiling::function]
4733    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
4734        let _profile_window = crate::native_profiling::window_scope(self.platform_window.as_ref());
4735        let _profile = crate::native_profiling::current_span("native", "GPUI draw");
4736        // Drain every draw in profiler builds so a previous frame's
4737        // first-invalidation timestamp can't be attributed to this one.
4738        #[cfg(feature = "profiler")]
4739        let frame_dirty = self.invalidator.take_frame_dirty();
4740        #[cfg(feature = "profiler")]
4741        self.window_profiler.begin_draw();
4742
4743        // Set up the per-App arena for element allocation during this draw.
4744        // This ensures that multiple test Apps have isolated arenas.
4745        let arena_scope = ElementArenaScope::enter(&cx.element_arena);
4746
4747        if self.platform_window.prepare_frame() {
4748            self.refresh();
4749        }
4750        self.invalidate_entities();
4751        cx.entities.clear_accessed();
4752        debug_assert!(self.rendered_entity_stack.is_empty());
4753        self.invalidator.set_dirty(false);
4754        self.requested_autoscroll = None;
4755
4756        // Restore the previously-used input handler.
4757        // Place it back into a None slot (left by a previous .take()) so that
4758        // cached paint_range indices in reuse_paint find the handler at the
4759        // expected position.
4760        if let Some(input_handler) = self.platform_window.take_input_handler() {
4761            if let Some(slot) = self
4762                .rendered_frame
4763                .input_handlers
4764                .iter_mut()
4765                .rev()
4766                .find(|h| h.is_none())
4767            {
4768                *slot = Some(input_handler);
4769            } else {
4770                self.rendered_frame.input_handlers.push(Some(input_handler));
4771            }
4772        }
4773        if !cx.mode.skip_drawing() {
4774            self.vn_scopes_painted.clear();
4775            self.draw_roots(cx);
4776            let now = crate::effect_clock_seconds();
4777            self.vn_effect_phases
4778                .retain(|_, phase| now - phase.at < VnEffectPhase::KEEP);
4779            #[cfg(feature = "profiler")]
4780            {
4781                let viewport_size = self.viewport_size;
4782                let scale_factor = self.scale_factor();
4783                self.debug_frame_overlay.paint(
4784                    &mut self.next_frame.scene,
4785                    viewport_size,
4786                    scale_factor,
4787                );
4788            }
4789        }
4790        let _finalize = crate::native_profiling::current_span("native", "GPUI finalize frame");
4791        self.dirty_views.clear();
4792        self.next_frame.window_active = self.active.get();
4793
4794        // Register requested input handler with the platform window.
4795        // Use .take() instead of .pop() to preserve Vec length, so that cached
4796        // paint_range indices remain valid for reuse_paint on the next frame.
4797        // Search backwards to find the last Some entry, since reuse_paint may
4798        // have copied None slots from the previous frame. (Fixes #50456)
4799        let focused_text_input = if let Some(mut input_handler) = self
4800            .next_frame
4801            .input_handlers
4802            .iter_mut()
4803            .rev()
4804            .find_map(|h| h.take())
4805        {
4806            let accepts_text_input = input_handler.accepts_text_input(self, cx);
4807            self.platform_window.set_input_handler(input_handler);
4808            self.focus.filter(|_| accepts_text_input)
4809        } else {
4810            None
4811        };
4812        self.apply_text_input_configuration(cx);
4813        let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
4814        if previous.is_some() != focused_text_input.is_some() {
4815            self.platform_window
4816                .text_input_state_changed(if focused_text_input.is_some() {
4817                    TextInputStateChange::FocusGained
4818                } else {
4819                    TextInputStateChange::FocusLost
4820                });
4821        }
4822
4823        {
4824            let _profile = crate::native_profiling::current_span("native", "GPUI finish layout and text");
4825            self.layout_engine.as_mut().unwrap().clear();
4826            self.text_system().finish_frame();
4827        }
4828        {
4829            let _profile = crate::native_profiling::current_span("native", "GPUI finish scene");
4830            self.next_frame.finish(&mut self.rendered_frame);
4831            self.vn_settle_captures();
4832        }
4833
4834        self.invalidator.set_phase(DrawPhase::Focus);
4835        let previous_focus_path = self.rendered_frame.focus_path();
4836        let previous_window_active = self.rendered_frame.window_active;
4837        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
4838        self.scene_animation_interval
4839            .set(self.rendered_frame.scene.animation_frame_interval());
4840        {
4841            let _profile = crate::native_profiling::current_span("native", "GPUI clear previous frame");
4842            self.next_frame.clear();
4843        }
4844        let current_focus_path = self.rendered_frame.focus_path();
4845        let current_window_active = self.rendered_frame.window_active;
4846        let mut focus_before_listeners = self.focus;
4847
4848        if previous_focus_path != current_focus_path
4849            || previous_window_active != current_window_active
4850        {
4851            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
4852                self.focus_lost_path = previous_focus_path.clone();
4853                self.focus_lost_listeners
4854                    .clone()
4855                    .retain(|listener| listener(self, cx));
4856                self.focus_lost_path = SmallVec::new();
4857                // The focus-lost fallback (e.g. a workspace refocusing itself) may target
4858                // an element that isn't part of the element tree, in which case scheduling
4859                // a redraw below would dispatch focus-lost again, looping forever. Only
4860                // track focus movement caused by the focus listeners.
4861                focus_before_listeners = self.focus;
4862            }
4863
4864            let event = WindowFocusEvent {
4865                previous_focus_path: if previous_window_active {
4866                    previous_focus_path
4867                } else {
4868                    Default::default()
4869                },
4870                current_focus_path: if current_window_active {
4871                    current_focus_path
4872                } else {
4873                    Default::default()
4874                },
4875            };
4876            self.focus_listeners
4877                .clone()
4878                .retain(|listener| listener(&event, self, cx));
4879        }
4880
4881        debug_assert!(self.rendered_entity_stack.is_empty());
4882        self.record_entities_accessed(cx);
4883        self.reset_cursor_style(cx);
4884        self.refreshing = false;
4885        self.invalidator.set_phase(DrawPhase::None);
4886        // Focus listeners may move focus (e.g. a dock forwarding focus to its active
4887        // panel). `Window::focus` suppresses `refresh` while a draw is in progress, so
4888        // schedule another frame here to render the new focus state and dispatch the
4889        // resulting focus events.
4890        if self.focus != focus_before_listeners {
4891            self.refresh();
4892        }
4893        self.needs_present.set(true);
4894
4895        #[cfg(feature = "profiler")]
4896        {
4897            self.window_profiler
4898                .set_refresh_interval(self.refresh_interval(cx));
4899            let draw_duration = self
4900                .window_profiler
4901                .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
4902            self.debug_frame_overlay.record_frame(draw_duration);
4903        }
4904
4905        // Exit the scope to obtain the arena-clear token this draw owes; the
4906        // scope's teardown itself happens in `ElementArenaScope::drop`.
4907        arena_scope.exit(&cx.element_arena)
4908    }
4909
4910    fn record_entities_accessed(&mut self, cx: &mut App) {
4911        let entities = cx.entities.take_accessed();
4912        let handle = self.handle;
4913        cx.record_entities_accessed(
4914            handle,
4915            // Try moving window invalidator into the Window
4916            self.invalidator.clone(),
4917            &entities,
4918        );
4919        cx.entities.restore_accessed(entities);
4920    }
4921
4922    fn invalidate_entities(&mut self) {
4923        let mut views = self.invalidator.take_views();
4924        for entity in views.drain() {
4925            self.mark_view_dirty(entity);
4926        }
4927        self.invalidator.replace_views(views);
4928    }
4929
4930    #[profiling::function]
4931    fn present(&mut self) {
4932        #[cfg(feature = "profiler")]
4933        let _foreground_turn = profiler::journal::foreground_turn();
4934        #[cfg(feature = "profiler")]
4935        let present_start = Instant::now();
4936        self.platform_window.draw(&self.rendered_frame.scene);
4937        #[cfg(feature = "profiler")]
4938        self.window_profiler.record_present(
4939            present_start,
4940            Instant::now(),
4941            self.active.get(),
4942            !self.next_frame_callbacks.borrow().is_empty(),
4943        );
4944        self.needs_present.set(false);
4945        profiling::finish_frame!();
4946    }
4947
4948    /// Presents the most recently drawn frame if it hasn't been presented yet.
4949    #[cfg(all(test, feature = "profiler"))]
4950    pub fn present_if_needed(&mut self) {
4951        if self.needs_present.get() {
4952            self.present();
4953        }
4954    }
4955
4956    /// Returns a snapshot of the current input-latency histograms.
4957    #[cfg(feature = "profiler")]
4958    pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
4959        self.window_profiler.input_latency_snapshot()
4960    }
4961
4962    /// Returns a snapshot of the current frame-duration histograms.
4963    #[cfg(feature = "profiler")]
4964    pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
4965        self.window_profiler.frame_duration_snapshot()
4966    }
4967
4968    /// Returns the current mode of the debug frame overlay.
4969    #[cfg(feature = "profiler")]
4970    pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
4971        self.debug_frame_overlay.mode()
4972    }
4973
4974    /// Sets the mode of the debug frame overlay and schedules a redraw.
4975    #[cfg(feature = "profiler")]
4976    pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
4977        self.debug_frame_overlay.set_mode(mode);
4978        self.refresh();
4979    }
4980
4981    /// Advances the debug frame overlay through its hidden, frame-time-only,
4982    /// and detailed modes.
4983    #[cfg(feature = "profiler")]
4984    pub fn cycle_debug_frame_overlay_mode(&mut self) {
4985        self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
4986    }
4987
4988    /// Clears the debug frame overlay's frame-time statistics, except for the
4989    /// total frame count, and schedules a redraw.
4990    #[cfg(feature = "profiler")]
4991    pub fn reset_debug_frame_overlay_stats(&mut self) {
4992        self.debug_frame_overlay.reset_stats();
4993        self.refresh();
4994    }
4995
4996    fn draw_roots(&mut self, cx: &mut App) {
4997        self.invalidator.set_phase(DrawPhase::Prepaint);
4998        self.tooltip_bounds.take();
4999
5000        self.a11y.sync_active_flag();
5001        if self.a11y.is_active() {
5002            self.a11y.begin_frame();
5003        }
5004
5005        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
5006        let root_size = {
5007            #[cfg(any(feature = "inspector", debug_assertions))]
5008            {
5009                if self.inspector.is_some() {
5010                    let mut size = self.viewport_size;
5011                    size.width = (size.width - _inspector_width).max(px(0.0));
5012                    size
5013                } else {
5014                    self.viewport_size
5015                }
5016            }
5017            #[cfg(not(any(feature = "inspector", debug_assertions)))]
5018            {
5019                self.viewport_size
5020            }
5021        };
5022
5023        // Layout all root elements. Like the root element on the web, which
5024        // stretches to fill the viewport unless explicitly sized, window roots
5025        // fill the window when their size is `auto`.
5026        let scale_factor = self.scale_factor();
5027        #[cfg(feature = "profiler")]
5028        let request_layout_start = Instant::now();
5029        let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
5030        let root_layout_id = root_element.request_layout(self, cx);
5031        #[cfg(feature = "profiler")]
5032        let prepaint_start = Instant::now();
5033        self.layout_engine
5034            .as_mut()
5035            .unwrap()
5036            .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
5037        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
5038
5039        #[cfg(any(feature = "inspector", debug_assertions))]
5040        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
5041
5042        let deferred_hitboxes_start = self.next_frame.hitboxes.len();
5043        let deferred_tagged_start = self.next_frame.vn_tagged_hitboxes.len();
5044        self.prepaint_deferred_draws(cx);
5045        let deferred_hitboxes = deferred_hitboxes_start..self.next_frame.hitboxes.len();
5046        self.next_frame.vn_deferred_tagged =
5047            deferred_tagged_start..self.next_frame.vn_tagged_hitboxes.len();
5048
5049        let mut prompt_element = None;
5050        let mut active_drag_element = None;
5051        let mut tooltip_element = None;
5052        if let Some(prompt) = self.prompt.take() {
5053            let mut element = prompt.view.any_view().into_any_element();
5054            let prompt_layout_id = element.request_layout(self, cx);
5055            self.layout_engine
5056                .as_mut()
5057                .unwrap()
5058                .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
5059            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
5060            prompt_element = Some(element);
5061            self.prompt = Some(prompt);
5062        } else if let Some(active_drag) = cx.active_drag.take() {
5063            let mut element = active_drag.view.clone().into_any_element();
5064            let offset = self.mouse_position() - active_drag.cursor_offset;
5065            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
5066            active_drag_element = Some(element);
5067            cx.active_drag = Some(active_drag);
5068        } else {
5069            tooltip_element = self.prepaint_tooltip(cx);
5070        }
5071
5072        self.compute_hit_order(deferred_hitboxes);
5073        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position, self.scale_factor);
5074
5075        // Now actually paint the elements.
5076        #[cfg(feature = "profiler")]
5077        let paint_start = Instant::now();
5078        self.invalidator.set_phase(DrawPhase::Paint);
5079        root_element.paint(self, cx);
5080
5081        #[cfg(any(feature = "inspector", debug_assertions))]
5082        self.paint_inspector(inspector_element, cx);
5083
5084        self.paint_deferred_draws(cx);
5085
5086        if let Some(mut prompt_element) = prompt_element {
5087            prompt_element.paint(self, cx);
5088        } else if let Some(mut drag_element) = active_drag_element {
5089            drag_element.paint(self, cx);
5090        } else if let Some(mut tooltip_element) = tooltip_element {
5091            tooltip_element.paint(self, cx);
5092        }
5093
5094        #[cfg(any(feature = "inspector", debug_assertions))]
5095        self.paint_inspector_hitbox(cx);
5096
5097        #[cfg(feature = "profiler")]
5098        self.window_profiler
5099            .record_draw_phases(profiler::DrawPhases {
5100                request_layout: prepaint_start.duration_since(request_layout_start),
5101                prepaint: paint_start.duration_since(prepaint_start),
5102                paint: Instant::now().duration_since(paint_start),
5103            });
5104
5105        let _profile = crate::native_profiling::current_span("native", "GPUI postpaint accessibility");
5106        // a11y may have been activated/deactivated halfway through the frame
5107        let a11y_active_start_of_frame = self.a11y.is_active();
5108        self.a11y.sync_active_flag();
5109        let a11y_active_end_of_frame = self.a11y.is_active();
5110
5111        let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
5112
5113        if a11y_active_start_of_frame {
5114            // Harvest frame metadata for the debug dump while the live window
5115            // and frame are still in scope.
5116            let frame_info = crate::window::a11y::debug::FrameDebugInfo {
5117                viewport_size: self.viewport_size,
5118                scale_factor: self.scale_factor,
5119                tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
5120            };
5121            // clear the builder state regardless
5122            let tree_update = self.a11y.end_frame(frame_info);
5123
5124            if should_send_a11y_update {
5125                log::debug!(
5126                    "Sending a11y tree update: {} nodes",
5127                    tree_update.nodes.len()
5128                );
5129                self.platform_window.a11y_tree_update(tree_update);
5130            }
5131        }
5132    }
5133
5134    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
5135        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
5136        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
5137            let Some(Some(tooltip_request)) = self
5138                .next_frame
5139                .tooltip_requests
5140                .get(tooltip_request_index)
5141                .cloned()
5142            else {
5143                log::error!("Unexpectedly absent TooltipRequest");
5144                continue;
5145            };
5146            let mut element = tooltip_request.tooltip.view.clone().into_any_element();
5147            let mouse_position = tooltip_request.tooltip.mouse_position;
5148            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
5149
5150            let mut tooltip_bounds =
5151                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
5152            let window_bounds = Bounds {
5153                origin: Point::default(),
5154                size: self.viewport_size(),
5155            };
5156
5157            if tooltip_bounds.right() > window_bounds.right() {
5158                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
5159                if new_x >= Pixels::ZERO {
5160                    tooltip_bounds.origin.x = new_x;
5161                } else {
5162                    tooltip_bounds.origin.x = cmp::max(
5163                        Pixels::ZERO,
5164                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
5165                    );
5166                }
5167            }
5168
5169            if tooltip_bounds.bottom() > window_bounds.bottom() {
5170                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
5171                if new_y >= Pixels::ZERO {
5172                    tooltip_bounds.origin.y = new_y;
5173                } else {
5174                    tooltip_bounds.origin.y = cmp::max(
5175                        Pixels::ZERO,
5176                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
5177                    );
5178                }
5179            }
5180
5181            // It's possible for an element to have an active tooltip while not being painted (e.g.
5182            // via the `visible_on_hover` method). Since mouse listeners are not active in this
5183            // case, instead update the tooltip's visibility here.
5184            let is_visible =
5185                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
5186            if !is_visible {
5187                continue;
5188            }
5189
5190            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
5191                element.prepaint(window, cx)
5192            });
5193
5194            self.tooltip_bounds = Some(TooltipBounds {
5195                id: tooltip_request.id,
5196                bounds: tooltip_bounds,
5197            });
5198            return Some(element);
5199        }
5200        None
5201    }
5202
5203    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
5204        assert_eq!(self.element_id_stack.len(), 0);
5205
5206        // Process deferred draws in multiple rounds to support nesting.
5207        // Each round processes all current deferred draws, which may push new ones.
5208        //
5209        // The draws are processed in place rather than being moved out of
5210        // `next_frame.deferred_draws`: `prepaint_index` snapshots that vector's
5211        // length, so any prepaint range recorded during a round (view caches,
5212        // nested deferred draws) must index the same vector `reuse_prepaint`
5213        // slices on the next frame. Moving the draws out and re-appending them
5214        // shifts the indices of nested draws, causing reused subtrees to graft
5215        // the wrong deferred draws and panic in the dispatch tree.
5216        let mut round_start = 0;
5217        let mut depth = 0;
5218        loop {
5219            let round_end = self.next_frame.deferred_draws.len();
5220            if round_start == round_end {
5221                break;
5222            }
5223            // Limit maximum nesting depth to prevent infinite loops.
5224            //
5225            // vue-native fork: 64, not 10. An embedder that paints CSS
5226            // stacking contexts defers one level per out-of-flow ancestor, and
5227            // a round costs one pass over the draws it adds; the paint order
5228            // does not depend on rounds (`DeferredDraw::order`).
5229            assert!(depth < 64, "Exceeded maximum (64) deferred depth");
5230            depth += 1;
5231
5232            // Sort this round by priority.
5233            let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
5234            {
5235                let draws = &self.next_frame.deferred_draws;
5236                traversal_order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5237            }
5238
5239            for deferred_draw_ix in traversal_order {
5240                let (
5241                    element,
5242                    parent_node,
5243                    current_view,
5244                    rem_size,
5245                    absolute_offset,
5246                    element_transform,
5247                    element_opacity,
5248                    content_mask,
5249                    vn_clip,
5250                    vn_scope,
5251                    prepaint_range,
5252                ) = {
5253                    let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
5254                    self.element_id_stack
5255                        .clone_from(&deferred_draw.element_id_stack);
5256                    self.text_style_stack
5257                        .clone_from(&deferred_draw.text_style_stack);
5258                    (
5259                        deferred_draw.element.take(),
5260                        deferred_draw.parent_node,
5261                        deferred_draw.current_view,
5262                        deferred_draw.rem_size,
5263                        deferred_draw.absolute_offset,
5264                        deferred_draw.element_transform,
5265                        deferred_draw.element_opacity,
5266                        deferred_draw.content_mask,
5267                        deferred_draw.vn_clip.clone(),
5268                        deferred_draw.vn_scope.clone(),
5269                        deferred_draw.prepaint_range.clone(),
5270                    )
5271                };
5272                self.next_frame.dispatch_tree.set_active_node(parent_node);
5273                // vue-native fork: the element's accessibility nodes go under
5274                // the node it was deferred from, not the window root.
5275                let a11y_parent = self.next_frame.deferred_draws[deferred_draw_ix]
5276                    .a11y_parent
5277                    .filter(|&p| p != a11y::ROOT_NODE_ID && self.a11y.is_active());
5278
5279                let prepaint_start = self.prepaint_index();
5280                if let Some(mut element) = element {
5281                    if let Some(parent) = a11y_parent {
5282                        self.a11y.nodes.begin_adopted(parent);
5283                    }
5284                    let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5285                        self.with_rendered_view(current_view, |window| {
5286                            window.with_rem_size(Some(rem_size), |window| {
5287                                // Masks are captured before transforms, in window space.
5288                                window.with_content_mask(content_mask, |window| {
5289                                    window.vn_with_absolute_clip_stack(vn_clip, |window| {
5290                                        window.with_absolute_element_opacity(element_opacity, |window| {
5291                                            window.with_absolute_element_transform(element_transform, |window| {
5292                                                window.with_absolute_element_offset(absolute_offset, |window| {
5293                                                    let outer = mem::replace(&mut window.vn_defer_scope, vn_scope);
5294                                                    element.prepaint(window, cx);
5295                                                    window.vn_defer_scope = outer;
5296                                                });
5297                                            });
5298                                        });
5299                                    });
5300                                });
5301                            });
5302                        });
5303                    });
5304                    if a11y_parent.is_some() {
5305                        self.a11y.nodes.end_adopted();
5306                    }
5307                    self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities = accessed_entities;
5308                    self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
5309                } else {
5310                    cx.entities.extend_accessed(
5311                        self.next_frame.deferred_draws[deferred_draw_ix]
5312                            .accessed_entities
5313                            .iter()
5314                            .copied(),
5315                    );
5316                    self.reuse_prepaint(prepaint_range);
5317                }
5318                let prepaint_end = self.prepaint_index();
5319                self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
5320                    prepaint_start..prepaint_end;
5321            }
5322
5323            self.element_id_stack.clear();
5324            self.text_style_stack.clear();
5325            round_start = round_end;
5326        }
5327    }
5328
5329    fn paint_deferred_draws(&mut self, cx: &mut App) {
5330        let _profile = crate::native_profiling::current_span("paint", "GPUI paint deferred draws");
5331        assert_eq!(self.element_id_stack.len(), 0);
5332
5333        // Paint all deferred draws in priority order.
5334        // Since prepaint has already processed nested deferreds, we just paint them all.
5335        if self.next_frame.deferred_draws.len() == 0 {
5336            return;
5337        }
5338
5339        // vue-native fork: the draws stay in place, since a `VnDeferScope`
5340        // painting among them looks its own draws up.
5341        let traversal_order = self.deferred_draw_traversal_order();
5342        for deferred_draw_ix in traversal_order {
5343            let draw = &self.next_frame.deferred_draws[deferred_draw_ix];
5344            // A replayed one was painted by its scope's replay.
5345            if let Some(scope) = &draw.vn_scope
5346                && (self.vn_scopes_painted.contains(&scope.id) || draw.element.is_none())
5347            {
5348                continue;
5349            }
5350            self.vn_paint_deferred_draw(deferred_draw_ix, None, cx);
5351        }
5352        self.element_id_stack.clear();
5353        self.text_style_stack.clear();
5354    }
5355
5356    /// Paints the deferred draw `ix`. In a scope, `scope` is the absolute
5357    /// opacity the scope's content group took off, and the clip stack it is
5358    /// inside of.
5359    fn vn_paint_deferred_draw(
5360        &mut self,
5361        ix: usize,
5362        scope: Option<(f32, Option<Arc<crate::VnClipNode>>)>,
5363        cx: &mut App,
5364    ) {
5365        let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5366        self.element_id_stack
5367            .clone_from(&deferred_draw.element_id_stack);
5368        // vue-native fork: the text style too, as the prepaint side does.
5369        // Without it a deferred element that reads `Window::text_style` in
5370        // PAINT read the default, not what its ancestors set: an inline
5371        // `<svg>` tinted by the inherited `color` painted black when it was
5372        // `position: absolute` (m26 client sweep #36).
5373        self.text_style_stack
5374            .clone_from(&deferred_draw.text_style_stack);
5375        self.next_frame
5376            .dispatch_tree
5377            .set_active_node(deferred_draw.parent_node);
5378
5379        let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5380        let content_mask = deferred_draw.content_mask;
5381        let element_transform = deferred_draw.element_transform;
5382        let (element_opacity, base) = match &scope {
5383            Some((opacity, base)) => (
5384                (deferred_draw.element_opacity / opacity).min(1.),
5385                base.as_ref(),
5386            ),
5387            None => (deferred_draw.element_opacity, None),
5388        };
5389        let vn_clip = deferred_draw.vn_clip.clone();
5390        let view = deferred_draw.current_view;
5391        let rem_size = deferred_draw.rem_size;
5392        let paint_range = deferred_draw.paint_range.clone();
5393        let mut element = deferred_draw.element.take();
5394
5395        let paint_start = self.paint_index();
5396        if let Some(element) = element.as_mut() {
5397            let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5398                self.with_rendered_view(view, |window| {
5399                    // Reopen inherited clipping and transforms in their original order.
5400                    window.with_content_mask(content_mask, |window| {
5401                        window.vn_reopen_clip_layers(vn_clip, base, cx, |window, cx| {
5402                            window.with_absolute_element_opacity(element_opacity, |window| {
5403                                window.with_absolute_element_transform(element_transform, |window| {
5404                                    window.with_rem_size(Some(rem_size), |window| {
5405                                        element.paint(window, cx);
5406                                    });
5407                                });
5408                            });
5409                        });
5410                    });
5411                });
5412            });
5413            self.next_frame.deferred_draws[ix]
5414                .accessed_entities
5415                .extend(accessed_entities);
5416        } else {
5417            self.reuse_paint(paint_range);
5418        }
5419        let paint_end = self.paint_index();
5420        let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5421        deferred_draw.element = element;
5422        deferred_draw.paint_range = paint_start..paint_end;
5423    }
5424
5425    /// vue-native fork: paints the draws deferred from inside the content
5426    /// effect of element `id` ([`VnDeferScope`]) in their stacking order,
5427    /// into its content group, whose absolute opacity was `opacity`.
5428    fn vn_paint_scope(&mut self, id: u64, opacity: f32, cx: &mut App) {
5429        if id == 0 || !self.vn_scopes_painted.insert(id) {
5430            return;
5431        }
5432        let mut order: SmallVec<[usize; 8]> = self
5433            .next_frame
5434            .deferred_draws
5435            .iter()
5436            .enumerate()
5437            .filter(|(_, draw)| draw.vn_scope.as_ref().is_some_and(|scope| scope.id == id))
5438            .map(|(ix, _)| ix)
5439            .collect();
5440        if order.is_empty() {
5441            return;
5442        }
5443        let draws = &self.next_frame.deferred_draws;
5444        order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5445        let element_id_stack = self.element_id_stack.clone();
5446        let text_style_stack = self.text_style_stack.clone();
5447        let active_node = self.next_frame.dispatch_tree.active_node_id();
5448        for ix in order {
5449            let base = self.next_frame.deferred_draws[ix]
5450                .vn_scope
5451                .as_ref()
5452                .and_then(|scope| scope.clip.clone());
5453            self.vn_paint_deferred_draw(ix, Some((opacity, base)), cx);
5454        }
5455        self.element_id_stack = element_id_stack;
5456        self.text_style_stack = text_style_stack;
5457        if let Some(node) = active_node {
5458            self.next_frame.dispatch_tree.set_active_node(node);
5459        }
5460    }
5461
5462    /// vue-native fork: draws deferred in `f` belong to the content effect of
5463    /// element `id` (0: none), which paints them ([`VnDeferScope`]).
5464    pub fn vn_with_defer_scope<R>(&mut self, id: u64, f: impl FnOnce(&mut Self) -> R) -> R {
5465        if id == 0 {
5466            return f(self);
5467        }
5468        let scope = VnDeferScope {
5469            id,
5470            clip: self.vn_clip_stack.clone(),
5471        };
5472        let previous = self.vn_defer_scope.replace(scope);
5473        let result = f(self);
5474        self.vn_defer_scope = previous;
5475        result
5476    }
5477
5478    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
5479        let deferred_count = self.next_frame.deferred_draws.len();
5480        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
5481        let draws = &self.next_frame.deferred_draws;
5482        sorted_indices.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5483        sorted_indices
5484    }
5485
5486    /// vue-native fork: fills [`Frame::vn_hit_order`] once prepaint is done.
5487    /// `deferred_hitboxes` is the range of hitbox indices the deferred draws'
5488    /// prepaint inserted. Everything before it (the root tree, the inspector)
5489    /// paints first and everything after it (a prompt, a drag, a tooltip)
5490    /// paints last, as inserted; inside it, each draw's hitboxes go where the
5491    /// draw paints. A draw's range never contains a nested draw's, which
5492    /// prepaints in a later round.
5493    fn compute_hit_order(&mut self, deferred_hitboxes: Range<usize>) {
5494        let frame = &mut self.next_frame;
5495        frame.vn_hit_order.clear();
5496        if deferred_hitboxes.is_empty() {
5497            return;
5498        }
5499        let mut order: Vec<u32> = Vec::with_capacity(frame.hitboxes.len());
5500        order.extend(0..deferred_hitboxes.start as u32);
5501        let mut traversal = (0..frame.deferred_draws.len()).collect::<Vec<_>>();
5502        let draws = &frame.deferred_draws;
5503        traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5504        for ix in traversal {
5505            let range = &draws[ix].prepaint_range;
5506            let (start, end) = (range.start.hitboxes_index, range.end.hitboxes_index);
5507            // Draws replayed from a cached view outside this frame's
5508            // deferred pass hold ranges of the frame they were recorded in.
5509            if start >= deferred_hitboxes.start && end <= deferred_hitboxes.end && start < end {
5510                order.extend(start as u32..end as u32);
5511            }
5512        }
5513        order.extend(deferred_hitboxes.end as u32..frame.hitboxes.len() as u32);
5514        // Anything a draw's range did not account for keeps insertion order
5515        // rather than vanishing from the hit test.
5516        if order.len() != frame.hitboxes.len() {
5517            return;
5518        }
5519        frame.vn_hit_order = order;
5520    }
5521
5522    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
5523        PrepaintStateIndex {
5524            hitboxes_index: self.next_frame.hitboxes.len(),
5525            // vue-native fork.
5526            vn_tagged_hitboxes_index: self.next_frame.vn_tagged_hitboxes.len(),
5527            tooltips_index: self.next_frame.tooltip_requests.len(),
5528            deferred_draws_index: self.next_frame.deferred_draws.len(),
5529            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
5530            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5531            line_layout_index: self.text_system.layout_index(),
5532        }
5533    }
5534
5535    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
5536        self.next_frame.hitboxes.extend(
5537            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
5538                .iter()
5539                .cloned(),
5540        );
5541        // vue-native fork: the tags travel with the hitboxes they name. Without
5542        // this line a cached subtree keeps its hitboxes — so it still hovers and
5543        // still takes clicks — while `Window::tagged_hitbox` answers `None` for
5544        // every node inside it, which is what the embedder's element picker,
5545        // highlight overlay and `:hover` reporting are built on.
5546        self.next_frame.vn_tagged_hitboxes.extend(
5547            self.rendered_frame.vn_tagged_hitboxes
5548                [range.start.vn_tagged_hitboxes_index..range.end.vn_tagged_hitboxes_index]
5549                .iter()
5550                .cloned(),
5551        );
5552        self.next_frame.tooltip_requests.extend(
5553            self.rendered_frame.tooltip_requests
5554                [range.start.tooltips_index..range.end.tooltips_index]
5555                .iter_mut()
5556                .map(|request| request.take()),
5557        );
5558        self.next_frame.accessed_element_states.extend(
5559            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5560                ..range.end.accessed_element_states_index]
5561                .iter()
5562                .map(|(id, type_id)| (id.clone(), *type_id)),
5563        );
5564        self.text_system
5565            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5566
5567        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
5568            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
5569            &mut self.rendered_frame.dispatch_tree,
5570            self.focus,
5571        );
5572
5573        if reused_subtree.contains_focus() {
5574            self.next_frame.focus = self.focus;
5575        }
5576
5577        self.next_frame.deferred_draws.extend(
5578            self.rendered_frame.deferred_draws
5579                [range.start.deferred_draws_index..range.end.deferred_draws_index]
5580                .iter()
5581                .map(|deferred_draw| DeferredDraw {
5582                    current_view: deferred_draw.current_view,
5583                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
5584                    element_id_stack: deferred_draw.element_id_stack.clone(),
5585                    text_style_stack: deferred_draw.text_style_stack.clone(),
5586                    content_mask: deferred_draw.content_mask,
5587                    rem_size: deferred_draw.rem_size,
5588                    priority: deferred_draw.priority,
5589                    element: None,
5590                    absolute_offset: deferred_draw.absolute_offset,
5591                    element_transform: deferred_draw.element_transform,
5592                    a11y_parent: deferred_draw.a11y_parent,
5593                    vn_stack: deferred_draw.vn_stack.clone(),
5594                    element_opacity: deferred_draw.element_opacity,
5595                    vn_clip: deferred_draw.vn_clip.clone(),
5596                    vn_scope: deferred_draw.vn_scope.clone(),
5597                    prepaint_range: deferred_draw.prepaint_range.clone(),
5598                    paint_range: deferred_draw.paint_range.clone(),
5599                    accessed_entities: deferred_draw.accessed_entities.clone(),
5600                }),
5601        );
5602    }
5603
5604    pub(crate) fn paint_index(&self) -> PaintIndex {
5605        PaintIndex {
5606            scene_index: self.next_frame.scene.len(),
5607            #[cfg(any(test, feature = "test-support"))]
5608            debug_bounds_index: self.next_frame.debug_bounds_records.len(),
5609            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
5610            input_handlers_index: self.next_frame.input_handlers.len(),
5611            cursor_styles_index: self.next_frame.cursor_styles.len(),
5612            window_control_hitboxes_index: self.next_frame.window_control_hitboxes.len(),
5613            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5614            tab_handle_index: self.next_frame.tab_stops.paint_index(),
5615            line_layout_index: self.text_system.layout_index(),
5616        }
5617    }
5618
5619    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
5620        // Cached elements still exist in the frame even when their paint methods don't run.
5621        #[cfg(any(test, feature = "test-support"))]
5622        for (selector, bounds) in &self.rendered_frame.debug_bounds_records
5623            [range.start.debug_bounds_index..range.end.debug_bounds_index]
5624        {
5625            self.next_frame
5626                .record_debug_bounds(selector.clone(), *bounds);
5627        }
5628        // Caption areas are paint output just like listeners and cursors.
5629        // Dropping this span makes a retained titlebar stop dragging, and
5630        // loses NoDrag cutouts when only an ancestor repaints.
5631        self.next_frame.window_control_hitboxes.extend(
5632            self.rendered_frame.window_control_hitboxes
5633                [range.start.window_control_hitboxes_index..range.end.window_control_hitboxes_index]
5634                .iter()
5635                .cloned(),
5636        );
5637        self.next_frame.cursor_styles.extend(
5638            self.rendered_frame.cursor_styles
5639                [range.start.cursor_styles_index..range.end.cursor_styles_index]
5640                .iter()
5641                .cloned(),
5642        );
5643        self.next_frame.input_handlers.extend(
5644            self.rendered_frame.input_handlers
5645                [range.start.input_handlers_index..range.end.input_handlers_index]
5646                .iter_mut()
5647                .map(|handler| handler.take()),
5648        );
5649        self.next_frame.mouse_listeners.extend(
5650            self.rendered_frame.mouse_listeners
5651                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
5652                .iter_mut()
5653                .map(|listener| listener.take()),
5654        );
5655        self.next_frame.accessed_element_states.extend(
5656            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5657                ..range.end.accessed_element_states_index]
5658                .iter()
5659                .map(|(id, type_id)| (id.clone(), *type_id)),
5660        );
5661        self.next_frame.tab_stops.replay(
5662            &self.rendered_frame.tab_stops.insertion_history
5663                [range.start.tab_handle_index..range.end.tab_handle_index],
5664        );
5665
5666        self.text_system
5667            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5668        self.next_frame.scene.replay(
5669            range.start.scene_index..range.end.scene_index,
5670            &self.rendered_frame.scene,
5671        );
5672    }
5673
5674    /// Push a text style onto the stack, and call a function with that style active.
5675    /// Use [`Window::text_style`] to get the current, combined text style. This method
5676    /// should only be called as part of element drawing.
5677    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
5678    where
5679        F: FnOnce(&mut Self) -> R,
5680    {
5681        self.invalidator.debug_assert_paint_or_prepaint();
5682        if let Some(style) = style {
5683            self.text_style_stack.push(style);
5684            let result = f(self);
5685            self.text_style_stack.pop();
5686            result
5687        } else {
5688            f(self)
5689        }
5690    }
5691
5692    /// Updates the cursor style at the platform level. This method should only be called
5693    /// during the paint phase of element drawing.
5694    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
5695        self.invalidator.debug_assert_paint();
5696        self.next_frame.cursor_styles.push(CursorStyleRequest {
5697            hitbox_id: Some(hitbox.id),
5698            style,
5699        });
5700    }
5701
5702    /// Updates the cursor style for the entire window at the platform level. A cursor
5703    /// style using this method will have precedence over any cursor style set using
5704    /// `set_cursor_style`. This method should only be called during the paint
5705    /// phase of element drawing.
5706    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
5707        self.invalidator.debug_assert_paint();
5708        self.next_frame.cursor_styles.push(CursorStyleRequest {
5709            hitbox_id: None,
5710            style,
5711        })
5712    }
5713
5714    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
5715    /// during the paint phase of element drawing.
5716    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
5717        self.invalidator.debug_assert_prepaint();
5718        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
5719        self.next_frame
5720            .tooltip_requests
5721            .push(Some(TooltipRequest { id, tooltip }));
5722        id
5723    }
5724
5725    /// Invoke the given function with the given content mask after intersecting it
5726    /// with the current mask. This method should only be called during element drawing.
5727    // This function is called in a highly recursive manner in editor
5728    // prepainting, make sure its inlined to reduce the stack burden
5729    #[inline]
5730    pub fn with_content_mask<R>(
5731        &mut self,
5732        mask: Option<ContentMask<Pixels>>,
5733        f: impl FnOnce(&mut Self) -> R,
5734    ) -> R {
5735        self.invalidator.debug_assert_paint_or_prepaint();
5736        if let Some(mask) = mask {
5737            // A clip rect is expressed in the element's OWN frame, and the
5738            // element may be transformed — so the rect has to be mapped into
5739            // window space before it can be intersected with an ancestor's.
5740            // Without this a `transform: translate(-50%, -50%)` element paints
5741            // its subtree half a box away from the region it clips it to, and
5742            // everything that lands outside the old, unmoved rect disappears.
5743            // (reka's dialog is exactly that shape: `fixed top-1/2 left-1/2
5744            // translate-x-[-50%] translate-y-[-50%]` with a scrolling body
5745            // inside, and it came up as a black slab with one stray line of
5746            // text in the corner where the two rects happened to overlap.)
5747            //
5748            // Exact for a translation; a rotation or scale gives the axis-
5749            // aligned bounding box of the mapped rect, which is a superset — a
5750            // clip that shows a little too much rather than one that hides
5751            // content that should be visible. (vue-native fork: the corner
5752            // radii map along; `transform_mask` says when they survive.)
5753            let mask = transform_mask(self.element_transform, mask, self.scale_factor);
5754            let mask = mask.intersect(&self.content_mask());
5755            self.content_mask_stack.push(mask);
5756            let result = f(self);
5757            self.content_mask_stack.pop();
5758            result
5759        } else {
5760            f(self)
5761        }
5762    }
5763
5764    /// vue-native fork: runs `f` under a `clip-path` that is no rounded
5765    /// rectangle ([`crate::Style::vn_clip_outline`]), laid out in the
5766    /// element's own frame. The outline is flattened through the transform in
5767    /// force into window device pixels and pushed on the clip stack, which
5768    /// every hitbox inserted in `f` takes (prepaint). While painting, `f`'s
5769    /// primitives also go into an isolated layer that the renderer composites
5770    /// through the shape ([`crate::Scene::vn_push_isolation`]). The caller
5771    /// pushes the outline's box as a content mask around this, which culls.
5772    pub fn vn_with_clip_shape<R>(
5773        &mut self,
5774        outline: Option<&crate::VnClipOutline>,
5775        f: impl FnOnce(&mut Self) -> R,
5776    ) -> R {
5777        let Some(outline) = outline else {
5778            return f(self);
5779        };
5780        let geometry = Arc::new(crate::VnClipGeometry::new(
5781            outline,
5782            self.scale_factor,
5783            self.element_transform,
5784        ));
5785        let node = Arc::new(crate::VnClipNode {
5786            geometry,
5787            color_matrix: None,
5788            capture: None,
5789            mask: None,
5790            parent: self.vn_clip_stack.clone(),
5791        });
5792        let previous = self.vn_clip_stack.replace(node.clone());
5793        let result = self.vn_with_clip_layer(&node, f);
5794        self.vn_clip_stack = previous;
5795        result
5796    }
5797
5798    /// Applies an SVG color matrix to the entire painted subtree. The same
5799    /// stack node is retained in prepaint so deferred descendants reopen it.
5800    pub fn vn_with_color_matrix<R>(
5801        &mut self,
5802        matrix: Option<crate::VnColorMatrix>,
5803        f: impl FnOnce(&mut Self) -> R,
5804    ) -> R {
5805        let Some(matrix) = matrix else { return f(self) };
5806        let bounds = self.snapped_content_mask().bounds;
5807        let left = bounds.origin.x.0;
5808        let top = bounds.origin.y.0;
5809        let right = left + bounds.size.width.0;
5810        let bottom = top + bounds.size.height.0;
5811        let geometry = Arc::new(crate::VnClipGeometry {
5812            fill_rule: crate::VnFillRule::NonZero,
5813            segments: vec![
5814                [left, top, right, top], [right, top, right, bottom],
5815                [right, bottom, left, bottom], [left, bottom, left, top],
5816            ],
5817            bounds,
5818        });
5819        let node = Arc::new(crate::VnClipNode {
5820            geometry,
5821            color_matrix: Some(matrix),
5822            capture: None,
5823            mask: None,
5824            parent: self.vn_clip_stack.clone(),
5825        });
5826        let previous = self.vn_clip_stack.replace(node.clone());
5827        let result = self.vn_with_clip_layer(&node, f);
5828        self.vn_clip_stack = previous;
5829        result
5830    }
5831
5832    /// Resolve a text brush once at its owner, before descendant overflow masks.
5833    pub fn vn_text_paint(&self, fill: crate::VnTextFill, bounds: Bounds<Pixels>) -> Arc<crate::VnTextPaint> {
5834        let x = bounds.origin.x.0; let y = bounds.origin.y.0;
5835        let right = x + bounds.size.width.0; let bottom = y + bounds.size.height.0;
5836        let outline = crate::VnClipOutline {
5837            fill_rule: crate::VnFillRule::NonZero,
5838            verbs: vec![crate::VnPathVerb::MoveTo([x,y]), crate::VnPathVerb::LineTo([right,y]),
5839                crate::VnPathVerb::LineTo([right,bottom]), crate::VnPathVerb::LineTo([x,bottom]), crate::VnPathVerb::Close],
5840        };
5841        let m = self.element_transform.inverse().unwrap_or_else(TransformationMatrix::unit);
5842        Arc::new(crate::VnTextPaint {
5843            fill, bounds: [x, y, bounds.size.width.0, bounds.size.height.0],
5844            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]],
5845            scale_factor: self.scale_factor,
5846            geometry: Arc::new(crate::VnClipGeometry::new(&outline, self.scale_factor, self.element_transform)),
5847            content_mask: self.snapped_content_mask(),
5848        })
5849    }
5850
5851    /// Paint only glyph alpha into the owner's shared mask. Child overflow
5852    /// masks still apply to their sprites without clipping later sibling glyphs.
5853    pub fn vn_with_text_mask<R>(&mut self, paint: Arc<crate::VnTextPaint>, f: impl FnOnce(&mut Self) -> R) -> R {
5854        self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5855            geometry: paint.geometry.clone(), color_matrix: None,
5856            content_mask: paint.content_mask, text_paint: Some(paint), capture: None,
5857        });
5858        let result = f(self);
5859        self.next_frame.scene.vn_pop_isolation();
5860        result
5861    }
5862
5863    /// vue-native fork: CSS `mask`. While painting, `f` goes into an isolated
5864    /// layer cut to the border box `bounds`, composited multiplied by the alpha
5865    /// (or luminance) of what the mask paints over `bounds`. The mask is on the
5866    /// clip stack meanwhile, in prepaint too, so a deferred descendant paints
5867    /// through it again ([`Window::vn_reopen_clip_layers`]).
5868    pub fn vn_with_mask<R>(
5869        &mut self,
5870        mask: Option<&crate::VnMask>,
5871        bounds: Bounds<Pixels>,
5872        cx: &mut App,
5873        f: impl FnOnce(&mut Self, &mut App) -> R,
5874    ) -> R {
5875        let Some(mask) = mask.filter(|mask| mask.paint.is_some()) else {
5876            return f(self, cx);
5877        };
5878        let node = Arc::new(crate::VnClipNode {
5879            geometry: self.vn_box_geometry(bounds),
5880            color_matrix: None,
5881            capture: None,
5882            mask: Some(crate::VnClipMask {
5883                mask: mask.clone(),
5884                bounds,
5885                transform: self.element_transform,
5886            }),
5887            parent: self.vn_clip_stack.clone(),
5888        });
5889        let previous = self.vn_clip_stack.replace(node.clone());
5890        let result = if self.invalidator.is_painting() {
5891            let content_mask = self.snapped_content_mask();
5892            self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5893                geometry: node.geometry.clone(),
5894                color_matrix: None,
5895                text_paint: None,
5896                content_mask,
5897                capture: None,
5898            });
5899            let result = f(self, cx);
5900            self.vn_paint_mask(&node, cx);
5901            self.next_frame.scene.vn_pop_isolation();
5902            result
5903        } else {
5904            f(self, cx)
5905        };
5906        self.vn_clip_stack = previous;
5907        result
5908    }
5909
5910    /// Ends the content of `node`'s open layer with its mask, if it has one.
5911    fn vn_paint_mask(&mut self, node: &crate::VnClipNode, cx: &mut App) {
5912        let Some(clip) = &node.mask else { return };
5913        let Some(paint) = clip.mask.paint.clone() else { return };
5914        self.next_frame.scene.vn_begin_mask(clip.mask.luminance);
5915        // The content already carries the element's opacity; the mask must not
5916        // apply it a second time.
5917        let opacity = mem::replace(&mut self.element_opacity, 1.);
5918        let tint = mem::replace(&mut self.element_image_tint, Hsla::transparent_black());
5919        let transform = mem::replace(&mut self.element_transform, clip.transform);
5920        paint(clip.bounds, None, self, cx);
5921        self.element_opacity = opacity;
5922        self.element_image_tint = tint;
5923        self.element_transform = transform;
5924    }
5925
5926    /// The border box `bounds` as a clip shape through the element transform.
5927    fn vn_box_geometry(&self, bounds: Bounds<Pixels>) -> Arc<crate::VnClipGeometry> {
5928        let (x, y) = (bounds.origin.x.0, bounds.origin.y.0);
5929        let (right, bottom) = (x + bounds.size.width.0, y + bounds.size.height.0);
5930        let outline = crate::VnClipOutline {
5931            fill_rule: crate::VnFillRule::NonZero,
5932            verbs: vec![
5933                crate::VnPathVerb::MoveTo([x, y]),
5934                crate::VnPathVerb::LineTo([right, y]),
5935                crate::VnPathVerb::LineTo([right, bottom]),
5936                crate::VnPathVerb::LineTo([x, bottom]),
5937                crate::VnPathVerb::Close,
5938            ],
5939        };
5940        Arc::new(crate::VnClipGeometry::new(
5941            &outline,
5942            self.scale_factor,
5943            self.element_transform,
5944        ))
5945    }
5946
5947    /// vue-native fork: `f` inside an isolated layer for `node`'s shape when
5948    /// painting, and as it is otherwise.
5949    fn vn_with_clip_layer<R>(
5950        &mut self,
5951        node: &Arc<crate::VnClipNode>,
5952        f: impl FnOnce(&mut Self) -> R,
5953    ) -> R {
5954        if !self.invalidator.is_painting() {
5955            return f(self);
5956        }
5957        let content_mask = self.snapped_content_mask();
5958        self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5959            geometry: node.geometry.clone(),
5960            color_matrix: node.color_matrix,
5961            text_paint: None,
5962            content_mask,
5963            capture: node.capture,
5964        });
5965        let result = f(self);
5966        self.next_frame.scene.vn_pop_isolation();
5967        result
5968    }
5969
5970    /// vue-native fork: `f` with the clip stack set to `clip`, as a deferred
5971    /// draw's prepaint re-enters the clips it was deferred from inside.
5972    fn vn_with_absolute_clip_stack<R>(
5973        &mut self,
5974        clip: Option<Arc<crate::VnClipNode>>,
5975        f: impl FnOnce(&mut Self) -> R,
5976    ) -> R {
5977        let previous = mem::replace(&mut self.vn_clip_stack, clip);
5978        let result = f(self);
5979        self.vn_clip_stack = previous;
5980        result
5981    }
5982
5983    /// vue-native fork: a deferred draw's paint, inside an isolated layer for
5984    /// each clip shape it was deferred from inside, the outermost first. It
5985    /// paints after the clipped ancestor closed its own layer, so it is
5986    /// composited through the same shapes on its own. Painted inside a
5987    /// [`VnDeferScope`], it reopens only the shapes inside the scope's `base`.
5988    fn vn_reopen_clip_layers<R>(
5989        &mut self,
5990        clip: Option<Arc<crate::VnClipNode>>,
5991        base: Option<&Arc<crate::VnClipNode>>,
5992        cx: &mut App,
5993        f: impl FnOnce(&mut Self, &mut App) -> R,
5994    ) -> R {
5995        let Some(innermost) = clip.clone() else {
5996            return self.vn_with_absolute_clip_stack(None, |window| f(window, cx));
5997        };
5998        let chain = crate::VnClipNode::inside_of(&innermost, base);
5999        self.vn_with_absolute_clip_stack(clip, |window| {
6000            for node in &chain {
6001                let content_mask = window.snapped_content_mask();
6002                window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6003                    geometry: node.geometry.clone(),
6004                    color_matrix: node.color_matrix,
6005                    text_paint: None,
6006                    content_mask,
6007                    capture: node.capture,
6008                });
6009            }
6010            let result = f(window, cx);
6011            for node in chain.iter().rev() {
6012                window.vn_paint_mask(node, cx);
6013                window.next_frame.scene.vn_pop_isolation();
6014            }
6015            result
6016        })
6017    }
6018
6019    /// vue-native fork: `f` paints into the snapshot `id` rather than the
6020    /// page: untransformed, unclipped by its ancestors and at full opacity,
6021    /// in a group the renderer draws first and keeps
6022    /// ([`crate::Scene::vn_captures`]). `bounds` and `own` (the element's
6023    /// transform) are what the capture reports of the element.
6024    pub fn vn_with_capture<R>(
6025        &mut self,
6026        id: Option<u64>,
6027        bounds: Bounds<Pixels>,
6028        own: TransformationMatrix,
6029        f: impl FnOnce(&mut Self) -> R,
6030    ) -> R {
6031        let Some(id) = id else { return f(self) };
6032        let scale_factor = self.scale_factor();
6033        let viewport = Bounds { origin: Point::default(), size: self.viewport_size };
6034        let device = viewport.scale(scale_factor);
6035        let info = crate::VnCaptureInfo {
6036            id,
6037            border_box: bounds.scale(scale_factor),
6038            transform: self.element_transform.compose(own),
6039        };
6040        let node = Arc::new(crate::VnClipNode {
6041            geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6042            color_matrix: None,
6043            capture: Some(info),
6044            mask: None,
6045            parent: None,
6046        });
6047        let previous_clip = self.vn_clip_stack.replace(node.clone());
6048        self.content_mask_stack.push(ContentMask::rect(viewport));
6049        let result = self.with_absolute_element_transform(TransformationMatrix::unit(), |window| {
6050            window.with_absolute_element_opacity(1., |window| {
6051                if !window.invalidator.is_painting() {
6052                    return f(window);
6053                }
6054                window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6055                    geometry: node.geometry.clone(),
6056                    color_matrix: None,
6057                    text_paint: None,
6058                    content_mask: ContentMask::rect(device),
6059                    capture: Some(info),
6060                });
6061                let result = f(window);
6062                window.next_frame.scene.vn_pop_isolation();
6063                result
6064            })
6065        });
6066        self.content_mask_stack.pop();
6067        self.vn_clip_stack = previous_clip;
6068        result
6069    }
6070
6071    /// vue-native fork: `f` paints into an isolated group composited
6072    /// source-over, so what blends inside it blends with the group only.
6073    pub fn vn_with_isolation<R>(&mut self, isolate: bool, f: impl FnOnce(&mut Self) -> R) -> R {
6074        if !isolate || !self.invalidator.is_painting() {
6075            return f(self);
6076        }
6077        let device = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6078        let content_mask = self.snapped_content_mask();
6079        self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6080            geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6081            color_matrix: None,
6082            text_paint: None,
6083            content_mask,
6084            capture: None,
6085        });
6086        let result = f(self);
6087        self.next_frame.scene.vn_pop_isolation();
6088        result
6089    }
6090
6091    /// vue-native fork: draws the snapshot `id` so that the border box it
6092    /// captured fills `bounds`, through the transform and opacity in force.
6093    /// Ink outside the border box scales along. Nothing is drawn for a
6094    /// snapshot the renderer does not hold.
6095    pub fn vn_paint_snapshot(&mut self, id: u64, bounds: Bounds<Pixels>, plus_lighter: bool) {
6096        self.invalidator.debug_assert_paint();
6097        let scale_factor = self.scale_factor();
6098        let device = bounds.scale(scale_factor);
6099        if device.size.width.0 <= 0. || device.size.height.0 <= 0. {
6100            return;
6101        }
6102        let Some(inverse) = self.element_transform.inverse() else { return };
6103        let (w, h) = (device.size.width.0, device.size.height.0);
6104        let [[a, b], [c, d]] = inverse.rotation_scale;
6105        let [tx, ty] = inverse.translation;
6106        let (x, y) = (device.origin.x.0, device.origin.y.0);
6107        let to_unit = [a / w, b / w, (tx - x) / w, c / h, d / h, (ty - y) / h];
6108        let covered = crate::scene::transformed_bounds(device, self.element_transform);
6109        let covered = Bounds::from_corners(
6110            point(ScaledPixels(covered.origin.x.0.floor()), ScaledPixels(covered.origin.y.0.floor())),
6111            point(
6112                ScaledPixels((covered.origin.x.0 + covered.size.width.0).ceil()),
6113                ScaledPixels((covered.origin.y.0 + covered.size.height.0).ceil()),
6114            ),
6115        );
6116        let opacity = self.element_opacity;
6117        let content_mask = self.snapped_content_mask();
6118        self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6119            id,
6120            to_unit,
6121            bounds: covered,
6122            content_mask,
6123            opacity,
6124            plus_lighter,
6125            in_place: false,
6126        });
6127    }
6128
6129    /// vue-native fork: draws the snapshot `id` where its element was when
6130    /// captured, through the opacity in force.
6131    pub fn vn_paint_snapshot_in_place(&mut self, id: u64) {
6132        self.invalidator.debug_assert_paint();
6133        let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6134        let opacity = self.element_opacity;
6135        let content_mask = self.snapped_content_mask();
6136        self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6137            id,
6138            to_unit: [0.; 6],
6139            bounds: viewport,
6140            content_mask,
6141            opacity,
6142            plus_lighter: false,
6143            in_place: true,
6144        });
6145    }
6146
6147    /// vue-native fork: what the last drawn frame knows of capture `id`:
6148    /// the element's border box and transform in device pixels.
6149    pub fn vn_capture(&self, id: u64) -> Option<crate::VnCaptureInfo> {
6150        self.vn_capture_records.get(&id).map(|(info, _)| *info)
6151    }
6152
6153    /// vue-native fork: forgets captures; their snapshots stop drawing and
6154    /// the renderer frees them once no frame paints them.
6155    pub fn vn_forget_captures(&mut self, ids: &[u64]) {
6156        for id in ids {
6157            self.vn_capture_records.remove(id);
6158        }
6159    }
6160
6161    /// vue-native fork: whether this window's renderer keeps snapshots
6162    /// ([`Window::vn_with_capture`]).
6163    pub fn vn_supports_snapshots(&self) -> bool {
6164        self.platform_window.vn_supports_snapshots()
6165    }
6166
6167    fn vn_settle_captures(&mut self) {
6168        let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6169        let scene = &mut self.next_frame.scene;
6170        for capture in &mut scene.vn_captures {
6171            capture.ink = capture.ink.intersect(&viewport);
6172            self.vn_capture_records.insert(capture.info.id, (capture.info, capture.ink));
6173        }
6174        let records = &self.vn_capture_records;
6175        scene.vn_resolve_snapshots(|id| records.get(&id).copied());
6176    }
6177
6178    /// Updates the global element offset relative to the current offset. This is used to implement
6179    /// scrolling. This method should only be called during the prepaint phase of element drawing.
6180    pub fn with_element_offset<R>(
6181        &mut self,
6182        offset: Point<Pixels>,
6183        f: impl FnOnce(&mut Self) -> R,
6184    ) -> R {
6185        self.invalidator.debug_assert_prepaint();
6186
6187        if offset.is_zero() {
6188            return f(self);
6189        };
6190
6191        let abs_offset = self.element_offset() + offset;
6192        self.with_absolute_element_offset(abs_offset, f)
6193    }
6194
6195    /// Updates the global element offset based on the given offset. This is used to implement
6196    /// drag handles and other manual painting of elements. This method should only be called during
6197    /// the prepaint phase of element drawing.
6198    pub fn with_absolute_element_offset<R>(
6199        &mut self,
6200        offset: Point<Pixels>,
6201        f: impl FnOnce(&mut Self) -> R,
6202    ) -> R {
6203        self.invalidator.debug_assert_prepaint();
6204        self.element_offset_stack.push(offset);
6205        let result = f(self);
6206        self.element_offset_stack.pop();
6207        result
6208    }
6209
6210    pub(crate) fn with_element_opacity<R>(
6211        &mut self,
6212        opacity: Option<f32>,
6213        f: impl FnOnce(&mut Self) -> R,
6214    ) -> R {
6215        self.invalidator.debug_assert_paint_or_prepaint();
6216
6217        let Some(opacity) = opacity else {
6218            return f(self);
6219        };
6220
6221        let previous_opacity = self.element_opacity;
6222        self.element_opacity = previous_opacity * opacity;
6223        let result = f(self);
6224        self.element_opacity = previous_opacity;
6225        result
6226    }
6227
6228    /// vue-native fork: every image [`Window::paint_image`] paints inside `f`
6229    /// is tinted with `tint`: its pixels take the colour by the colour's alpha,
6230    /// keeping their own alpha. In straight alpha that is
6231    /// `rgb = mix(rgb, tint.rgb, tint.a)`, `a = a`, which is a canvas filling
6232    /// the image with `tint` in `source-atop`. A transparent `tint` (the value
6233    /// outside any scope) leaves an image as it is; an opaque one paints the
6234    /// image's alpha in that colour, a monochrome emoji in `currentColor`.
6235    ///
6236    /// The tile is the same one an untinted paint samples: tinting costs no
6237    /// upload, and two tints of one image share it.
6238    pub fn with_image_tint<R>(&mut self, tint: Hsla, f: impl FnOnce(&mut Self) -> R) -> R {
6239        self.invalidator.debug_assert_paint_or_prepaint();
6240        let previous = std::mem::replace(&mut self.element_image_tint, tint);
6241        let result = f(self);
6242        self.element_image_tint = previous;
6243        result
6244    }
6245
6246    /// vue-native fork: the brightest value, in SDR-white units, that an
6247    /// [`AtlasTextureKind::PolychromeHdr`] image painted inside `f` reaches; 1.0 outside any
6248    /// scope. CSS `dynamic-range-limit` applied to the display's headroom.
6249    pub fn with_image_headroom<R>(&mut self, headroom: f32, f: impl FnOnce(&mut Self) -> R) -> R {
6250        self.invalidator.debug_assert_paint_or_prepaint();
6251        let headroom = if headroom.is_finite() {
6252            headroom.max(1.0)
6253        } else {
6254            1.0
6255        };
6256        let previous = std::mem::replace(&mut self.element_image_headroom, headroom);
6257        let result = f(self);
6258        self.element_image_headroom = previous;
6259        result
6260    }
6261
6262    /// Paints everything `f` paints — this element's own quads, shadows, text
6263    /// and its whole subtree — through `transformation`, which is composed on
6264    /// top of whatever an ancestor already pushed.
6265    ///
6266    /// This is CSS `transform`'s propagation rule: a transform applies to the
6267    /// element's rendering and to all of its descendants, and to none of the
6268    /// layout. Nothing here touches taffy, `bounds`, or the content mask; the
6269    /// primitives are still emitted in layout coordinates and carry the matrix
6270    /// for the vertex shader to apply.
6271    ///
6272    /// Hitboxes inserted under it record the same matrix, so hit-testing
6273    /// follows the picture (see [`Frame::hit_test`]).
6274    ///
6275    /// The identity is free — it early-returns without touching the field.
6276    /// Installs `transformation` as THE transform, discarding whatever is on the
6277    /// stack, for the duration of `f`.
6278    ///
6279    /// The deferred-draw replay needs this rather than
6280    /// [`Window::with_element_transform`]: it re-enters a subtree that was
6281    /// prepainted somewhere else in the tree, so the transform it has to restore
6282    /// is absolute, not something to compose onto the current one. Same
6283    /// reasoning as [`Window::with_absolute_element_offset`].
6284    pub fn with_absolute_element_transform<R>(
6285        &mut self,
6286        transformation: TransformationMatrix,
6287        f: impl FnOnce(&mut Self) -> R,
6288    ) -> R {
6289        let previous = mem::replace(&mut self.element_transform, transformation);
6290        let result = f(self);
6291        self.element_transform = previous;
6292        result
6293    }
6294
6295    /// vue-native fork: [`Window::with_absolute_element_transform`] for the
6296    /// opacity a deferred draw captured where it was deferred from.
6297    fn with_absolute_element_opacity<R>(
6298        &mut self,
6299        opacity: f32,
6300        f: impl FnOnce(&mut Self) -> R,
6301    ) -> R {
6302        let previous = mem::replace(&mut self.element_opacity, opacity);
6303        let result = f(self);
6304        self.element_opacity = previous;
6305        result
6306    }
6307
6308    /// vue-native fork: composes `transformation` onto the current element
6309    /// transform (the child's own transform applied first) for the duration of
6310    /// `f`. A unit transform is free.
6311    pub fn with_element_transform<R>(
6312        &mut self,
6313        transformation: TransformationMatrix,
6314        f: impl FnOnce(&mut Self) -> R,
6315    ) -> R {
6316        if transformation.is_unit() {
6317            return f(self);
6318        }
6319        let previous = self.element_transform;
6320        // `compose(other)` applies `other` first: the child's own transform
6321        // runs before the ancestors' — which is what nesting means.
6322        self.element_transform = previous.compose(transformation);
6323        let result = f(self);
6324        self.element_transform = previous;
6325        result
6326    }
6327
6328    /// The current content mask, expressed in the frame the CALLER is drawing in
6329    /// — i.e. mapped BACK through the CSS `transform` in force.
6330    ///
6331    /// Painting code computes a primitive's rectangle in the element's own,
6332    /// untransformed space (the shader is what applies the matrix), while
6333    /// [`Window::content_mask`] is a window-space rect. Anything that decides
6334    /// whether to emit a primitive at all by comparing the two has to bring
6335    /// them into one frame first, and this is the cheap end to move.
6336    ///
6337    /// A singular matrix (`scale(0)`) has no inverse; the element is drawn to
6338    /// nothing, so the mask is empty and everything is culled.
6339    pub fn content_mask_in_element_space(&self) -> ContentMask<Pixels> {
6340        let mask = self.content_mask();
6341        if self.element_transform.is_unit() {
6342            return mask;
6343        }
6344        match self.element_transform.inverse() {
6345            Some(inverse) => transform_mask(inverse, mask, self.scale_factor),
6346            None => ContentMask::rect(Bounds::default()),
6347        }
6348    }
6349
6350    /// The composed transform of the element currently being painted. Identity
6351    /// unless an ancestor pushed one with [`Window::with_element_transform`].
6352    #[inline]
6353    pub fn element_transform(&self) -> TransformationMatrix {
6354        self.element_transform
6355    }
6356
6357    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
6358    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
6359    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
6360    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
6361    /// called during the prepaint phase of element drawing.
6362    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
6363        self.invalidator.debug_assert_prepaint();
6364        let index = self.prepaint_index();
6365        let result = f(self);
6366        if result.is_err() {
6367            self.next_frame.hitboxes.truncate(index.hitboxes_index);
6368            // vue-native fork: the tagged boxes (and picks) of the attempt go
6369            // with its hitboxes, or a retried prepaint records them twice.
6370            self.next_frame
6371                .vn_tagged_hitboxes
6372                .truncate(index.vn_tagged_hitboxes_index);
6373            self.next_frame
6374                .tooltip_requests
6375                .truncate(index.tooltips_index);
6376            self.next_frame
6377                .deferred_draws
6378                .truncate(index.deferred_draws_index);
6379            self.next_frame
6380                .dispatch_tree
6381                .truncate(index.dispatch_tree_index);
6382            self.next_frame
6383                .accessed_element_states
6384                .truncate(index.accessed_element_states_index);
6385            self.text_system.truncate_layouts(index.line_layout_index);
6386        }
6387        result
6388    }
6389
6390    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
6391    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
6392    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
6393    /// that supports this method being called on the elements it contains. This method should only be
6394    /// called during the prepaint phase of element drawing.
6395    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
6396        self.invalidator.debug_assert_prepaint();
6397        self.requested_autoscroll = Some(bounds);
6398    }
6399
6400    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
6401    /// described in [`Self::request_autoscroll`].
6402    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
6403        self.invalidator.debug_assert_prepaint();
6404        self.requested_autoscroll.take()
6405    }
6406
6407    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
6408    /// Your view will be re-drawn once the asset has finished loading.
6409    ///
6410    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
6411    /// time.
6412    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6413        cx.asset_entry::<A>(source).use_by(self.current_view())
6414    }
6415
6416    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
6417    /// Your view will not be re-drawn once the asset has finished loading.
6418    ///
6419    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
6420    /// time.
6421    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6422        cx.fetch_asset::<A>(source)
6423    }
6424    /// Obtain the current element offset. This method should only be called during the
6425    /// prepaint phase of element drawing.
6426    pub fn element_offset(&self) -> Point<Pixels> {
6427        self.invalidator.debug_assert_prepaint();
6428        self.element_offset_stack
6429            .last()
6430            .copied()
6431            .unwrap_or_default()
6432    }
6433
6434    /// Obtain the current element opacity. This method should only be called during the
6435    /// prepaint phase of element drawing.
6436    #[inline]
6437    pub(crate) fn element_opacity(&self) -> f32 {
6438        self.invalidator.debug_assert_paint_or_prepaint();
6439        self.element_opacity
6440    }
6441
6442    /// Obtain the current content mask. This method should only be called during element drawing.
6443    pub fn content_mask(&self) -> ContentMask<Pixels> {
6444        self.invalidator.debug_assert_paint_or_prepaint();
6445        self.content_mask_stack
6446            .last()
6447            .cloned()
6448            .unwrap_or_else(|| {
6449                ContentMask::rect(Bounds {
6450                    origin: Point::default(),
6451                    size: self.viewport_size,
6452                })
6453            })
6454    }
6455
6456    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
6457    /// This can be used within a custom element to distinguish multiple sets of child elements.
6458    pub fn with_element_namespace<R>(
6459        &mut self,
6460        element_id: impl Into<ElementId>,
6461        f: impl FnOnce(&mut Self) -> R,
6462    ) -> R {
6463        self.element_id_stack.push(element_id.into());
6464        let result = f(self);
6465        self.element_id_stack.pop();
6466        result
6467    }
6468
6469    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
6470    pub fn use_keyed_state<S: 'static>(
6471        &mut self,
6472        key: impl Into<ElementId>,
6473        cx: &mut App,
6474        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6475    ) -> Entity<S> {
6476        let current_view = self.current_view();
6477        self.with_global_id(key.into(), |global_id, window| {
6478            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
6479                if let Some(state) = state {
6480                    (state.clone(), state)
6481                } else {
6482                    let new_state = cx.new(|cx| init(window, cx));
6483                    Self::observe_keyed_state(&new_state, current_view, cx);
6484                    (new_state.clone(), new_state)
6485                }
6486            })
6487        })
6488    }
6489
6490    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
6491    ///
6492    /// NOTE: This method uses the location of the caller to generate an ID for this state.
6493    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
6494    ///       you can provide a custom ElementID using the `use_keyed_state` method.
6495    #[track_caller]
6496    pub fn use_state<S: 'static>(
6497        &mut self,
6498        cx: &mut App,
6499        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6500    ) -> Entity<S> {
6501        self.use_keyed_state(
6502            ElementId::CodeLocation(*core::panic::Location::caller()),
6503            cx,
6504            init,
6505        )
6506    }
6507
6508    /// Updates or initializes state for an element with the given id that lives across multiple
6509    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
6510    /// to the given closure. The state returned by the closure will be stored so it can be referenced
6511    /// when drawing the next frame. This method should only be called as part of element drawing.
6512    #[inline(always)]
6513    pub fn with_element_state<S, R>(
6514        &mut self,
6515        global_id: &GlobalElementId,
6516        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
6517    ) -> R
6518    where
6519        S: 'static,
6520    {
6521        self.invalidator.debug_assert_paint_or_prepaint();
6522
6523        let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
6524
6525        if let Some(any) = state {
6526            let ElementStateBox {
6527                inner,
6528                #[cfg(debug_assertions)]
6529                type_name,
6530            } = any;
6531            // Using the extra inner option to avoid needing to reallocate a new box.
6532            let mut state_box = inner
6533                .downcast::<Option<S>>()
6534                .map_err(|_| {
6535                    #[cfg(debug_assertions)]
6536                    {
6537                        anyhow::anyhow!(
6538                            "invalid element state type for id, requested {:?}, actual: {:?}",
6539                            std::any::type_name::<S>(),
6540                            type_name
6541                        )
6542                    }
6543
6544                    #[cfg(not(debug_assertions))]
6545                    {
6546                        anyhow::anyhow!(
6547                            "invalid element state type for id, requested {:?}",
6548                            std::any::type_name::<S>(),
6549                        )
6550                    }
6551                })
6552                .unwrap();
6553
6554            let state = state_box.take().expect(
6555                "reentrant call to with_element_state for the same state type and element id",
6556            );
6557            let (result, state) = f(Some(state), self);
6558            state_box.replace(state);
6559            self.insert_element_state(
6560                key,
6561                ElementStateBox {
6562                    inner: state_box,
6563                    #[cfg(debug_assertions)]
6564                    type_name,
6565                },
6566            );
6567            result
6568        } else {
6569            let (result, state) = f(None, self);
6570            self.insert_element_state(
6571                key,
6572                ElementStateBox {
6573                    inner: Box::new(Some(state)),
6574                    #[cfg(debug_assertions)]
6575                    type_name: std::any::type_name::<S>(),
6576                },
6577            );
6578            result
6579        }
6580    }
6581
6582    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
6583    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
6584    /// when the element is guaranteed to have an id.
6585    ///
6586    /// The first option means 'no ID provided'
6587    /// The second option means 'not yet initialized'
6588    pub fn with_optional_element_state<S, R>(
6589        &mut self,
6590        global_id: Option<&GlobalElementId>,
6591        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
6592    ) -> R
6593    where
6594        S: 'static,
6595    {
6596        self.invalidator.debug_assert_paint_or_prepaint();
6597
6598        if let Some(global_id) = global_id {
6599            self.with_element_state(global_id, |state, cx| {
6600                let (result, state) = f(Some(state), cx);
6601                let state =
6602                    state.expect("you must return some state when you pass some element id");
6603                (result, state)
6604            })
6605        } else {
6606            let (result, state) = f(None, self);
6607            debug_assert!(
6608                state.is_none(),
6609                "you must not return an element state when passing None for the global id"
6610            );
6611            result
6612        }
6613    }
6614
6615    /// Executes the given closure within the context of a tab group.
6616    #[inline]
6617    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
6618        if let Some(index) = index {
6619            self.next_frame.tab_stops.begin_group(index);
6620            let result = f(self);
6621            self.next_frame.tab_stops.end_group();
6622            result
6623        } else {
6624            f(self)
6625        }
6626    }
6627
6628    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
6629    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
6630    /// with higher values being drawn on top.
6631    ///
6632    /// When `content_mask` is provided, the deferred element will be clipped to that region during
6633    /// both prepaint and paint. When `None`, no additional clipping is applied.
6634    ///
6635    /// This method should only be called as part of the prepaint phase of element drawing.
6636    pub fn defer_draw(
6637        &mut self,
6638        element: AnyElement,
6639        absolute_offset: Point<Pixels>,
6640        priority: usize,
6641        content_mask: Option<ContentMask<Pixels>>,
6642    ) {
6643        self.defer_draw_with_stack_key(element, absolute_offset, priority, content_mask, None)
6644    }
6645
6646    /// vue-native fork: [`Window::defer_draw`], sorted among draws of equal
6647    /// `priority` by `stack_key` (see [`crate::Deferred::with_stack_key`]).
6648    pub fn defer_draw_with_stack_key(
6649        &mut self,
6650        element: AnyElement,
6651        absolute_offset: Point<Pixels>,
6652        priority: usize,
6653        content_mask: Option<ContentMask<Pixels>>,
6654        stack_key: Option<Rc<[u128]>>,
6655    ) {
6656        self.invalidator.debug_assert_prepaint();
6657        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
6658        self.next_frame.deferred_draws.push(DeferredDraw {
6659            current_view: self.current_view(),
6660            parent_node,
6661            element_id_stack: self.element_id_stack.clone(),
6662            text_style_stack: self.text_style_stack.clone(),
6663            content_mask,
6664            rem_size: self.rem_size(),
6665            priority,
6666            element: Some(element),
6667            absolute_offset,
6668            element_transform: self.element_transform,
6669            a11y_parent: self
6670                .a11y
6671                .is_active()
6672                .then(|| self.a11y.nodes.current_id()),
6673            vn_stack: stack_key,
6674            element_opacity: self.element_opacity,
6675            vn_clip: if content_mask.is_some() {
6676                self.vn_clip_stack.clone()
6677            } else {
6678                crate::VnClipNode::color_filters(&self.vn_clip_stack)
6679            },
6680            vn_scope: self.vn_defer_scope.clone(),
6681            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
6682            paint_range: PaintIndex::default()..PaintIndex::default(),
6683            accessed_entities: FxHashSet::default(),
6684        });
6685    }
6686
6687    /// Creates a new painting layer. A "layer" is a batch of geometry that are
6688    /// non-overlapping and have the same draw order. This is typically used
6689    /// for performance reasons.
6690    ///
6691    /// Layers painted inside `f` are drawn above this layer, including above
6692    /// what `f` paints after them.
6693    ///
6694    /// This method should only be called as part of the paint phase of element drawing.
6695    pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
6696        self.invalidator.debug_assert_paint();
6697
6698        self.next_frame.scene.push_layer();
6699        let result = f(self);
6700        self.next_frame.scene.pop_layer();
6701        result
6702    }
6703
6704    /// Paint the drop (non-inset) shadows from `shadows` into the scene at the current
6705    /// z-index. Inset shadows are skipped; paint those with [`Self::paint_inset_shadows`]
6706    /// after the element's background so they layer on top of the fill.
6707    ///
6708    /// This method should only be called as part of the paint phase of element drawing.
6709    ///
6710    /// vue-native fork: a drop shadow is drawn outside the element's border box
6711    /// only, as CSS clips an outer `box-shadow` (CSS Backgrounds 3 §7.1). So a
6712    /// translucent background shows what is behind the element, not the
6713    /// shadow; a focus ring (`0 0 0 3px`) on a transparent control is a ring.
6714    pub fn paint_drop_shadows(
6715        &mut self,
6716        bounds: Bounds<Pixels>,
6717        corner_radii: Corners<Pixels>,
6718        shadows: &[BoxShadow],
6719    ) {
6720        self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_OUTSIDE_BOX);
6721    }
6722
6723    /// vue-native fork: [`Self::paint_drop_shadows`] without the cut-out: the
6724    /// shadow also fills the area under the border box. For a shadow that
6725    /// stands in for the element's own painting ([`Style::vn_shadow_under_box`]).
6726    pub fn paint_drop_shadows_under_box(
6727        &mut self,
6728        bounds: Bounds<Pixels>,
6729        corner_radii: Corners<Pixels>,
6730        shadows: &[BoxShadow],
6731    ) {
6732        self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_UNDER_BOX);
6733    }
6734
6735    /// vue-native fork: [`Self::paint_drop_shadows`] (or, with `under_box`,
6736    /// [`Self::paint_drop_shadows_under_box`]) for a box with CSS `corner-shape`.
6737    pub fn vn_paint_drop_shadows(
6738        &mut self,
6739        bounds: Bounds<Pixels>,
6740        corner_radii: Corners<Pixels>,
6741        corner_shapes: Corners<CornerShape>,
6742        shadows: &[BoxShadow],
6743        under_box: bool,
6744    ) {
6745        let kind = if under_box { SHADOW_UNDER_BOX } else { SHADOW_OUTSIDE_BOX };
6746        self.paint_outer_shadows(bounds, corner_radii, corner_shapes, shadows, kind);
6747    }
6748
6749    fn paint_outer_shadows(
6750        &mut self,
6751        bounds: Bounds<Pixels>,
6752        corner_radii: Corners<Pixels>,
6753        corner_shapes: Corners<CornerShape>,
6754        shadows: &[BoxShadow],
6755        kind: u32,
6756    ) {
6757        self.invalidator.debug_assert_paint();
6758
6759        let scale_factor = self.scale_factor();
6760        let content_mask = self.snapped_content_mask();
6761        let opacity = self.element_opacity();
6762        let element_bounds = self.cover_bounds(bounds);
6763        let element_corner_radii = corner_radii.scale(scale_factor);
6764        for shadow in shadows {
6765            if shadow.inset {
6766                continue;
6767            }
6768            let shape_bounds =
6769                self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
6770            if shape_bounds.is_empty() {
6771                continue;
6772            }
6773            let blur_radius = shadow.blur_radius.scale(scale_factor);
6774            let spread = shadow.spread_radius;
6775            let shadow_radius = |r: Pixels| spread_shadow_radius(r, spread);
6776            let shadow_corner_radii = Corners {
6777                top_left: shadow_radius(corner_radii.top_left),
6778                top_right: shadow_radius(corner_radii.top_right),
6779                bottom_right: shadow_radius(corner_radii.bottom_right),
6780                bottom_left: shadow_radius(corner_radii.bottom_left),
6781            };
6782            self.next_frame.scene.insert_primitive(Shadow {
6783                order: 0,
6784                blur_radius,
6785                // Leave room for the tail of the blur.
6786                bounds: shape_bounds.dilate(blur_radius * 3.),
6787                content_mask,
6788                corner_radii: element_corner_radii,
6789                color: shadow.color.opacity(opacity),
6790                shape_bounds,
6791                shape_corner_radii: shadow_corner_radii.scale(scale_factor),
6792                inset: kind,
6793                pad: 0,
6794                transformation: self.element_transform,
6795                element_bounds,
6796                corner_shapes: CornerShapes::new(&corner_shapes),
6797            });
6798        }
6799    }
6800
6801    /// Paint the inset shadows from `shadows` into the scene at the current z-index. Should
6802    /// be called after the element's background so the shadow layers on top of the fill.
6803    /// Drop shadows are skipped; paint those with [`Self::paint_drop_shadows`] before the background.
6804    pub fn paint_inset_shadows(
6805        &mut self,
6806        bounds: Bounds<Pixels>,
6807        corner_radii: Corners<Pixels>,
6808        shadows: &[BoxShadow],
6809    ) {
6810        self.vn_paint_inset_shadows(bounds, corner_radii, Corners::default(), shadows);
6811    }
6812
6813    /// vue-native fork: [`Self::paint_inset_shadows`] for a box with CSS `corner-shape`. A
6814    /// shaped corner's hole is the inner edge of a border as wide as the spread (css-borders-4
6815    /// §3.9.4), not the corner shrunk by it.
6816    pub fn vn_paint_inset_shadows(
6817        &mut self,
6818        bounds: Bounds<Pixels>,
6819        corner_radii: Corners<Pixels>,
6820        corner_shapes: Corners<CornerShape>,
6821        shadows: &[BoxShadow],
6822    ) {
6823        self.invalidator.debug_assert_paint();
6824
6825        let scale_factor = self.scale_factor();
6826        let content_mask = self.snapped_content_mask();
6827        let opacity = self.element_opacity();
6828        let element_bounds = self.cover_bounds(bounds);
6829        let element_corner_radii = corner_radii.scale(scale_factor);
6830        for shadow in shadows {
6831            if !shadow.inset {
6832                continue;
6833            }
6834            let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
6835            // Clamp at zero so a large spread can't produce negative radii, which would
6836            // break the SDF in the shader.
6837            let zero = Pixels::ZERO;
6838            let spread = shadow.spread_radius;
6839            let hole_radius = |radius: Pixels, shape: CornerShape| {
6840                if shape.is_round() || spread <= zero { (radius - spread).max(zero) } else { radius }
6841            };
6842            let hole_corner_radii = Corners {
6843                top_left: hole_radius(corner_radii.top_left, corner_shapes.top_left),
6844                top_right: hole_radius(corner_radii.top_right, corner_shapes.top_right),
6845                bottom_right: hole_radius(corner_radii.bottom_right, corner_shapes.bottom_right),
6846                bottom_left: hole_radius(corner_radii.bottom_left, corner_shapes.bottom_left),
6847            };
6848            let inset = f32::from(spread.max(zero)) * scale_factor;
6849            self.next_frame.scene.insert_primitive(Shadow {
6850                order: 0,
6851                blur_radius: shadow.blur_radius.scale(scale_factor),
6852                bounds: element_bounds,
6853                content_mask,
6854                corner_radii: element_corner_radii,
6855                color: shadow.color.opacity(opacity),
6856                shape_bounds: self.cover_bounds(hole),
6857                shape_corner_radii: hole_corner_radii.scale(scale_factor),
6858                inset: SHADOW_INSET,
6859                pad: 0,
6860                transformation: self.element_transform,
6861                element_bounds,
6862                corner_shapes: CornerShapes::new(&corner_shapes)
6863                    .with_insets(Corners {
6864                        top_left: (inset, inset),
6865                        top_right: (inset, inset),
6866                        bottom_right: (inset, inset),
6867                        bottom_left: (inset, inset),
6868                    }),
6869            });
6870        }
6871    }
6872
6873    fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
6874        let size = quad.bounds.size;
6875        let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
6876        if diagonal == 0. {
6877            return Bounds::default();
6878        }
6879        // The interior's corners sit on the corner arcs. Taking the angle along
6880        // the arc whose tangent is the quad's aspect ratio stays within 1% of
6881        // the largest interior.
6882        let cos = size.height.0 / diagonal;
6883        let sin = size.width.0 / diagonal;
6884
6885        // A corner's inner border edge is a quarter ellipse around the
6886        // corner's center, with the border widths taken off its radius.
6887        let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
6888            point(
6889                width_x.max(radius - (radius - width_x) * cos),
6890                width_y.max(radius - (radius - width_y) * sin),
6891            )
6892        };
6893
6894        let radii = &quad.corner_radii;
6895        let widths = &quad.border_widths;
6896        let top_left = corner_inset(radii.top_left, widths.left, widths.top);
6897        let top_right = corner_inset(radii.top_right, widths.right, widths.top);
6898        let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
6899        let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
6900
6901        let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
6902        Bounds::from_corners(
6903            quad.bounds.origin
6904                + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
6905                + antialias_inset,
6906            quad.bounds.bottom_right()
6907                - point(
6908                    top_right.x.max(bottom_right.x),
6909                    bottom_left.y.max(bottom_right.y),
6910                )
6911                - antialias_inset,
6912        )
6913    }
6914
6915    /// Paint one or more quads into the scene for the next frame at the current stacking context.
6916    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
6917    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
6918    ///
6919    /// This method should only be called as part of the paint phase of element drawing.
6920    ///
6921    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
6922    /// where the circular arcs meet. This will not display well when combined with dashed borders.
6923    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
6924    pub fn paint_quad(&mut self, quad: PaintQuad) {
6925        self.invalidator.debug_assert_paint();
6926
6927        let opacity = self.element_opacity();
6928        let snapped_bounds = self.snap_bounds(quad.bounds);
6929        let snapped_border_widths = self.snap_border_widths(quad.border_widths);
6930        let quad = Quad {
6931            order: 0,
6932            bounds: snapped_bounds,
6933            content_mask: self.snapped_content_mask(),
6934            background: quad.background.opacity(opacity),
6935            border_color: quad.border_color.opacity(opacity),
6936            corner_radii: quad.corner_radii.scale(self.scale_factor()),
6937            border_widths: snapped_border_widths,
6938            border_style: quad.border_style,
6939            transformation: self.element_transform,
6940            corner_shapes: CornerShapes::new(&quad.corner_shapes),
6941        };
6942        self.insert_quad(quad);
6943    }
6944
6945    fn insert_quad(&mut self, quad: Quad) {
6946        let has_background = !quad.background.is_transparent();
6947        let has_border =
6948            quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
6949        if !has_background && !has_border {
6950            return;
6951        }
6952
6953        let is_rectangle =
6954            quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
6955        if has_background && is_rectangle {
6956            self.next_frame.scene.insert_primitive(quad);
6957            return;
6958        }
6959
6960        // The strip split below carves the quad into AXIS-ALIGNED pieces and
6961        // clips each with an axis-aligned content mask. Under a rotation those
6962        // masks no longer correspond to the pieces they are clipping, so the
6963        // optimisation is skipped rather than made wrong. (vue-native fork:
6964        // under a rounded content mask too: a strip's mask would cut through
6965        // the curve, and `ContentMask::intersect` squares such a corner.)
6966        // A shaped corner reaches past the rounded interior the split assumes.
6967        if !quad.transformation.is_unit()
6968            || quad.content_mask.is_rounded()
6969            || !quad.corner_shapes.is_round()
6970        {
6971            self.next_frame.scene.insert_primitive(quad);
6972            return;
6973        }
6974
6975        let plain_border = quad.corner_radii == Corners::default()
6976            && quad.border_style == BorderStyle::Solid
6977            && (!has_background || quad.border_color.is_opaque());
6978
6979        // Splitting off the interior leaves only the strips around it for the
6980        // border and corner shading.
6981        let outer_bounds = quad.bounds;
6982        let inner_bounds = if plain_border {
6983            quad.bounds.extend(quad.border_widths.map(|width| -*width))
6984        } else {
6985            Self::largest_border_interior(&quad)
6986        };
6987
6988        // A plain border's strips can be plain rectangles of the border color.
6989        // Otherwise, each strip is the whole quad masked to the strip, so the
6990        // border, corners and gradients are still shaded relative to the full quad.
6991        let strip_quad = if plain_border {
6992            Quad {
6993                background: quad.border_color.into(),
6994                border_widths: Edges::default(),
6995                ..quad
6996            }
6997        } else {
6998            quad
6999        };
7000
7001        if inner_bounds.is_empty() {
7002            self.next_frame.scene.insert_primitive(strip_quad);
7003            return;
7004        }
7005
7006        // vue-native fork: a ring background paints nothing inside the border.
7007        if has_background && !quad.background.is_ring() {
7008            self.next_frame.scene.insert_primitive(Quad {
7009                content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&inner_bounds)),
7010                border_widths: Edges::default(),
7011                corner_radii: Corners::default(),
7012                ..quad
7013            });
7014        }
7015
7016        let strips = [
7017            // Top
7018            Bounds::from_corners(
7019                outer_bounds.origin,
7020                point(outer_bounds.right(), inner_bounds.top()),
7021            ),
7022            // Bottom
7023            Bounds::from_corners(
7024                point(outer_bounds.left(), inner_bounds.bottom()),
7025                outer_bounds.bottom_right(),
7026            ),
7027            // Left
7028            Bounds::from_corners(
7029                point(outer_bounds.left(), inner_bounds.top()),
7030                inner_bounds.bottom_left(),
7031            ),
7032            // Right
7033            Bounds::from_corners(
7034                inner_bounds.top_right(),
7035                point(outer_bounds.right(), inner_bounds.bottom()),
7036            ),
7037        ];
7038
7039        for strip in strips {
7040            self.next_frame.scene.insert_primitive(Quad {
7041                content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&strip)),
7042                ..strip_quad
7043            });
7044        }
7045    }
7046
7047    /// Paint a backdrop blur rectangle into the scene at the current z-index.
7048    ///
7049    /// This is the primitive behind CSS `backdrop-filter: blur()`: the pixels
7050    /// already painted behind `bounds` are replaced with a blurred copy of
7051    /// themselves, clipped to the rounded rect described by `corner_radii`.
7052    ///
7053    /// The blur samples the render target as it exists at its paint position,
7054    /// so renderers may need to break the current pass when this primitive is
7055    /// encountered. Prefer one blur rect per glass surface rather than many
7056    /// small ones. Renderers without backdrop blur support ignore this
7057    /// primitive entirely, including its tint.
7058    ///
7059    /// This method should only be called as part of the paint phase of element
7060    /// drawing.
7061    pub fn paint_backdrop_blur_rect(
7062        &mut self,
7063        bounds: Bounds<Pixels>,
7064        corner_radii: Corners<Pixels>,
7065        effect: BackdropBlurEffect,
7066    ) {
7067        self.vn_paint_backdrop_blur_rect(bounds, corner_radii, Corners::default(), effect);
7068    }
7069
7070    /// vue-native fork: [`Self::paint_backdrop_blur_rect`] with CSS `corner-shape`.
7071    pub fn vn_paint_backdrop_blur_rect(
7072        &mut self,
7073        bounds: Bounds<Pixels>,
7074        corner_radii: Corners<Pixels>,
7075        corner_shapes: Corners<CornerShape>,
7076        effect: BackdropBlurEffect,
7077    ) {
7078        self.invalidator.debug_assert_paint();
7079
7080        let opacity = self.element_opacity();
7081        if opacity <= 0. {
7082            return;
7083        }
7084
7085        let scale_factor = self.scale_factor();
7086        let blur_radius = effect.radius.scale(scale_factor);
7087        if blur_radius.0 <= 0. {
7088            let tint = effect.tint.opacity(opacity);
7089            if tint.a > 0. {
7090                self.paint_quad(
7091                    fill(bounds, tint).corner_radii(corner_radii).corner_shapes(corner_shapes),
7092                );
7093            }
7094            return;
7095        }
7096
7097        // vue-native fork: the blur has no `transformation` of its own, so the
7098        // element transform is folded into its rect — without this a popper
7099        // positioned by `transform: translate()` blurred a ghost at its
7100        // untransformed place. Under a rotation there is no rect to fold it
7101        // into, and nothing is drawn rather than the ghost.
7102        let Some((bounds, k)) =
7103            crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7104        else {
7105            return;
7106        };
7107        self.next_frame.scene.insert_primitive(BackdropBlurRect {
7108            order: 0,
7109            pad: 0,
7110            bounds,
7111            content_mask: self.snapped_content_mask(),
7112            corner_radii: corner_radii.scale(scale_factor * k),
7113            blur_radius,
7114            opacity,
7115            tint: effect.tint,
7116            corner_shapes: CornerShapes::new(&corner_shapes),
7117        });
7118    }
7119
7120    /// Paint a custom-shaded rounded rect into the scene at the current
7121    /// z-index — the primitive behind the `--shading` CSS property.
7122    ///
7123    /// `spec.id` selects one of the built-in fragment pipelines and `params`
7124    /// are its positional arguments. Parameters the schema marks as lengths
7125    /// arrive in LOGICAL pixels and are scaled here, exactly like every other
7126    /// length in a primitive.
7127    ///
7128    /// An effect that reads the backdrop ([`EFFECT_FLAG_NEEDS_BACKDROP`])
7129    /// samples the render target as it exists at its paint position, so — like
7130    /// [`Self::paint_backdrop_blur_rect`] — renderers break the current pass
7131    /// when they meet one, and the scene forces everything painted afterwards
7132    /// to draw above it. An effect that does not is an ordinary blended quad
7133    /// and costs nothing extra.
7134    ///
7135    /// Renderers without effect support (or on hardware below D3D feature
7136    /// level 11) ignore this primitive entirely.
7137    ///
7138    /// This method should only be called as part of the paint phase of element
7139    /// drawing.
7140    pub fn paint_effect_quad(
7141        &mut self,
7142        bounds: Bounds<Pixels>,
7143        corner_radii: Corners<Pixels>,
7144        spec: EffectSpec,
7145    ) {
7146        self.vn_paint_effect(bounds, corner_radii, spec, 0);
7147    }
7148
7149    /// vue-native fork: [`Self::paint_effect_quad`] for `element`
7150    /// ([`Self::vn_take_effect_element`]), which keys an `[SkHistory]` state.
7151    pub fn vn_paint_effect(
7152        &mut self,
7153        bounds: Bounds<Pixels>,
7154        corner_radii: Corners<Pixels>,
7155        spec: EffectSpec,
7156        element: u64,
7157    ) {
7158        self.vn_paint_effect_with(bounds, corner_radii, Corners::default(), spec, element, None);
7159    }
7160
7161    /// vue-native: [`Self::vn_paint_effect`] with the images `spec` samples,
7162    /// resolved through [`crate::set_effect_texture_resolver`].
7163    pub fn vn_paint_textured_effect(
7164        &mut self,
7165        bounds: Bounds<Pixels>,
7166        corner_radii: Corners<Pixels>,
7167        corner_shapes: Corners<CornerShape>,
7168        spec: EffectSpec,
7169        element: u64,
7170        cx: &mut App,
7171    ) {
7172        let textures = crate::resolve_effect_textures(&spec, self, cx);
7173        self.vn_paint_effect_with(bounds, corner_radii, corner_shapes, spec, element, textures);
7174    }
7175
7176    fn vn_paint_effect_with(
7177        &mut self,
7178        bounds: Bounds<Pixels>,
7179        corner_radii: Corners<Pixels>,
7180        corner_shapes: Corners<CornerShape>,
7181        spec: EffectSpec,
7182        element: u64,
7183        textures: Option<Arc<crate::EffectTextureSet>>,
7184    ) {
7185        self.invalidator.debug_assert_paint();
7186        let opacity = self.element_opacity();
7187        let Some(mut quad) =
7188            self.vn_effect_quad(bounds, corner_radii, corner_shapes, spec, element, opacity, textures.as_deref())
7189        else {
7190            return;
7191        };
7192        quad.flags &= !crate::EFFECT_FLAG_NEEDS_CONTENT;
7193        let history = vn_history_key(element, &spec);
7194        if history == 0 {
7195            quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7196            self.next_frame
7197                .scene
7198                .insert_primitive(crate::Primitive::EffectQuad(quad, textures));
7199            return;
7200        }
7201        let content_mask = quad.content_mask;
7202        self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7203            draws: vec![crate::VnEffectDraw {
7204                quad,
7205                history,
7206                textures,
7207            }],
7208            content: false,
7209            content_mask,
7210        });
7211        self.next_frame.scene.vn_pop_isolation();
7212    }
7213
7214    /// vue-native fork: names the element whose style paints next
7215    /// ([`Self::vn_take_effect_element`]).
7216    pub fn vn_set_effect_element(&mut self, id: Option<&GlobalElementId>) {
7217        self.vn_effect_element = vn_element_key(id);
7218    }
7219
7220    /// vue-native fork: the element [`Self::vn_set_effect_element`] named, 0
7221    /// for none; taken, so a child without an identity does not inherit it.
7222    pub fn vn_take_effect_element(&mut self) -> u64 {
7223        mem::take(&mut self.vn_effect_element)
7224    }
7225
7226    /// vue-native fork: paints `f` into an isolated group at full opacity, which
7227    /// the `[SkContent]` effects among `effects` composite in its place; the
7228    /// opacity share none of them takes composites the group as it is.
7229    #[allow(clippy::too_many_arguments)]
7230    pub fn vn_with_effect_content<R>(
7231        &mut self,
7232        bounds: Bounds<Pixels>,
7233        corner_radii: Corners<Pixels>,
7234        corner_shapes: Corners<CornerShape>,
7235        effects: &[(EffectSpec, f32, Option<Arc<crate::EffectTextureSet>>)],
7236        element: u64,
7237        cx: &mut App,
7238        f: impl FnOnce(&mut Self, &mut App) -> R,
7239    ) -> R {
7240        let opacity = self.element_opacity();
7241        if !self.invalidator.is_painting() || opacity <= 0. {
7242            return f(self, cx);
7243        }
7244        let mut draws = Vec::new();
7245        let mut plain = 1.;
7246        for (spec, weight, textures) in effects {
7247            if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0 || *weight <= 0. {
7248                continue;
7249            }
7250            let Some(mut quad) = self.vn_effect_quad(
7251                bounds,
7252                corner_radii,
7253                corner_shapes,
7254                *spec,
7255                element,
7256                opacity * weight,
7257                textures.as_deref(),
7258            ) else {
7259                continue;
7260            };
7261            let history = vn_history_key(element, spec);
7262            if history == 0 {
7263                quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7264            }
7265            plain -= weight;
7266            draws.push(crate::VnEffectDraw {
7267                quad,
7268                history,
7269                textures: textures.clone(),
7270            });
7271        }
7272        let content_mask = self.snapped_content_mask();
7273        if plain > 1e-3 {
7274            draws.insert(
7275                0,
7276                crate::VnEffectDraw {
7277                    quad: EffectQuad {
7278                        effect_id: crate::effect_id::CONTENT,
7279                        bounds: content_mask.bounds,
7280                        content_mask,
7281                        opacity: opacity * plain.min(1.),
7282                        scale: self.scale_factor(),
7283                        flags: crate::EFFECT_FLAG_NEEDS_CONTENT,
7284                        ..Default::default()
7285                    },
7286                    history: 0,
7287                    textures: None,
7288                },
7289            );
7290        }
7291        self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7292            draws,
7293            content: true,
7294            content_mask,
7295        });
7296        let outer = mem::replace(&mut self.element_opacity, 1.);
7297        let result = f(self, cx);
7298        self.vn_paint_scope(element, opacity, cx);
7299        self.element_opacity = outer;
7300        self.next_frame.scene.vn_pop_isolation();
7301        result
7302    }
7303
7304    /// The quad `spec` draws over `bounds` at `opacity`, None when it draws
7305    /// nothing; asks for the next frame while it animates.
7306    #[allow(clippy::too_many_arguments)]
7307    fn vn_effect_quad(
7308        &mut self,
7309        bounds: Bounds<Pixels>,
7310        corner_radii: Corners<Pixels>,
7311        corner_shapes: Corners<CornerShape>,
7312        spec: EffectSpec,
7313        element: u64,
7314        opacity: f32,
7315        textures: Option<&crate::EffectTextureSet>,
7316    ) -> Option<EffectQuad> {
7317        if !spec.is_some() || opacity <= 0. {
7318            return None;
7319        }
7320
7321        let scale_factor = self.scale_factor();
7322        let bleed = px(spec.bleed());
7323        // An outer glow needs somewhere to land, so the drawn quad is the
7324        // border box dilated by `bleed` — with the corner radii dilated to
7325        // match, which keeps the dilated shape a true Minkowski offset and
7326        // therefore keeps the SDF relationship the shader relies on exact.
7327        let draw_bounds = bounds.dilate(bleed);
7328        let draw_radii = Corners {
7329            top_left: corner_radii.top_left + bleed,
7330            top_right: corner_radii.top_right + bleed,
7331            bottom_right: corner_radii.bottom_right + bleed,
7332            bottom_left: corner_radii.bottom_left + bleed,
7333        };
7334
7335        let mut params = spec.params;
7336        for (index, param) in params.iter_mut().enumerate() {
7337            if spec.length_mask & (1 << index) != 0 {
7338                *param *= scale_factor;
7339            }
7340        }
7341        crate::write_effect_texture_sizes(&spec, textures, &mut params);
7342
7343        // vue-native fork: as for the backdrop blur — no `transformation`
7344        // field, so the element transform is folded into the rect, and a
7345        // rotated effect is not drawn rather than drawn unrotated elsewhere.
7346        let Some((draw_bounds, k)) = crate::scene::axis_aligned_through(
7347            self.snap_bounds(draw_bounds),
7348            self.element_transform,
7349        ) else {
7350            return None;
7351        };
7352        let bleed = bleed.scale(scale_factor);
7353        let now = crate::effect_clock_seconds();
7354
7355        if let Some(slot) = spec.pointer_param.map(usize::from)
7356            && slot + 2 <= params.len()
7357        {
7358            // The element box as the shader recovers it from the drawn quad.
7359            let origin = draw_bounds.origin.map(|c| c.0 + bleed.0);
7360            let size = draw_bounds.size.map(|c| (c.0 - 2. * bleed.0).max(1.));
7361            let pointer = self.mouse_position.map(|c| c.0 * scale_factor);
7362            params[slot] = (pointer.x - origin.x) / size.width;
7363            params[slot + 1] = (pointer.y - origin.y) / size.height;
7364        }
7365        if let Some(slot) = spec.pointer_times_param.map(usize::from)
7366            && slot + 3 <= params.len()
7367        {
7368            let times = &self.vn_effect_pointer;
7369            params[slot..slot + 3].copy_from_slice(&[times.moved, times.entered, times.left]);
7370        }
7371        if spec.follows_pointer() {
7372            let view = self.current_view();
7373            self.vn_effect_pointer.views.insert(view);
7374        }
7375        if let Some(slot) = spec.animated_param.map(usize::from)
7376            && slot < params.len()
7377            && element != 0
7378        {
7379            let key = vn_phase_key(element, &spec);
7380            let previous = self.vn_effect_phases.get(&key).copied();
7381            let phase = VnEffectPhase::advance(previous, params[slot], now);
7382            self.vn_effect_phases.insert(key, phase);
7383            if let Some(speed) = phase.speed(now) {
7384                params[slot] = speed;
7385            }
7386        }
7387
7388        let mut clocked = spec;
7389        clocked.params = params;
7390        if spec.animated || clocked.clock_running(now) {
7391            // Nothing else in the frame is going to ask for the next one.
7392            self.request_animation_frame();
7393        }
7394
7395        Some(EffectQuad {
7396            order: 0,
7397            effect_id: spec.id,
7398            bounds: draw_bounds,
7399            content_mask: self.snapped_content_mask(),
7400            corner_radii: draw_radii.scale(scale_factor * k),
7401            params,
7402            opacity,
7403            time: now,
7404            bleed,
7405            backdrop_blur_radius: px(spec.backdrop_blur_radius()).scale(scale_factor),
7406            scale: scale_factor,
7407            flags: spec.flags,
7408            corner_shapes: CornerShapes::new(&corner_shapes),
7409        })
7410    }
7411
7412    /// vue-native: makes `bounds` (rounded by `corner_radii`) transparent in
7413    /// this window's surface, erasing what was painted there so far; what is
7414    /// painted after it draws over the hole as usual. The window has to
7415    /// present with alpha for anything to show through (on Windows,
7416    /// DirectComposition: `Window::vn_composition_underlay`).
7417    ///
7418    /// This method should only be called as part of the paint phase of element
7419    /// drawing.
7420    pub fn vn_paint_punch(&mut self, bounds: Bounds<Pixels>, corner_radii: Corners<Pixels>) {
7421        self.invalidator.debug_assert_paint();
7422        let opacity = self.element_opacity();
7423        if opacity <= 0. {
7424            return;
7425        }
7426        let scale_factor = self.scale_factor();
7427        // No `transformation` field, as for the effects: a rotated box is not
7428        // punched rather than punched somewhere else.
7429        let Some((draw_bounds, k)) =
7430            crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7431        else {
7432            return;
7433        };
7434        self.next_frame.scene.insert_primitive(EffectQuad {
7435            order: 0,
7436            effect_id: crate::effect_id::PUNCH,
7437            bounds: draw_bounds,
7438            content_mask: self.snapped_content_mask(),
7439            corner_radii: corner_radii.scale(scale_factor * k),
7440            params: [0.; crate::EFFECT_PARAM_SLOTS],
7441            opacity,
7442            time: 0.,
7443            bleed: ScaledPixels(0.),
7444            backdrop_blur_radius: ScaledPixels(0.),
7445            scale: scale_factor,
7446            flags: 0,
7447            corner_shapes: CornerShapes::default(),
7448        });
7449    }
7450
7451    /// Paint the given `Path` into the scene for the next frame at the current z-index.
7452    ///
7453    /// This method should only be called as part of the paint phase of element drawing.
7454    pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
7455        self.invalidator.debug_assert_paint();
7456
7457        let scale_factor = self.scale_factor();
7458        let content_mask = self.content_mask();
7459        let opacity = self.element_opacity();
7460        let color: Background = color.into();
7461        // vue-native fork: every other primitive carries `element_transform`;
7462        // a path painted under one (a `<select>`'s chevron in a dialog centred
7463        // with `translate(-50%, -50%)`) stayed at its layout position, and was
7464        // culled against a content mask that is already in window space.
7465        let path = if self.element_transform.is_unit() {
7466            path
7467        } else {
7468            path.transformed(self.element_transform, scale_factor)
7469        };
7470        self.next_frame.scene.insert_primitive(PaintedPath::new(
7471            path,
7472            scale_factor,
7473            content_mask,
7474            color.opacity(opacity),
7475        ));
7476    }
7477
7478    /// Paint an underline into the scene for the next frame at the current z-index.
7479    ///
7480    /// This method should only be called as part of the paint phase of element drawing.
7481    pub fn paint_underline(
7482        &mut self,
7483        origin: Point<Pixels>,
7484        width: Pixels,
7485        style: &UnderlineStyle,
7486    ) {
7487        self.invalidator.debug_assert_paint();
7488        // vue-native fork: `Self::underline` carries `element_transform`.
7489        let underline = self.underline(origin, width, style);
7490        self.next_frame.scene.insert_primitive(underline);
7491    }
7492
7493    /// Paint a strikethrough into the scene for the next frame at the current z-index.
7494    ///
7495    /// This method should only be called as part of the paint phase of element drawing.
7496    pub fn paint_strikethrough(
7497        &mut self,
7498        origin: Point<Pixels>,
7499        width: Pixels,
7500        style: &StrikethroughStyle,
7501    ) {
7502        self.invalidator.debug_assert_paint();
7503
7504        let scale_factor = self.scale_factor();
7505        let height = style.thickness;
7506        let bounds = Bounds {
7507            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
7508            size: size(self.snap_stroke(width), self.snap_stroke(height)),
7509        };
7510        let opacity = self.element_opacity();
7511
7512        self.next_frame.scene.insert_primitive(Underline {
7513            order: 0,
7514            pad: 0,
7515            bounds,
7516            content_mask: self.snapped_content_mask(),
7517            thickness: self.snap_stroke(style.thickness),
7518            color: style.color.unwrap_or_default().opacity(opacity),
7519            wavy: false.into(),
7520            transformation: self.element_transform,
7521        });
7522    }
7523
7524    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
7525    ///
7526    /// The y component of the origin is the baseline of the glyph.
7527    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
7528    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
7529    /// This method is only useful if you need to paint a single glyph that has already been shaped.
7530    ///
7531    /// This method should only be called as part of the paint phase of element drawing.
7532    pub fn paint_glyph(
7533        &mut self,
7534        origin: Point<Pixels>,
7535        font_id: FontId,
7536        glyph_id: GlyphId,
7537        font_size: Pixels,
7538        color: Hsla,
7539    ) -> Result<()> {
7540        self.invalidator.debug_assert_paint();
7541
7542        let element_opacity = self.element_opacity();
7543        let scale_factor = self.scale_factor();
7544        let glyph_origin = origin.scale(scale_factor);
7545
7546        let quantized_origin = Point::new(
7547            round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7548                / SUBPIXEL_VARIANTS_X as f32,
7549            round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7550                / SUBPIXEL_VARIANTS_Y as f32,
7551        );
7552        let subpixel_variant = Point::new(
7553            (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7554            (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7555        );
7556        let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
7557        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
7558        let dilation = self.text_system().glyph_dilation_for_color(color);
7559        let params = RenderGlyphParams {
7560            font_id,
7561            glyph_id,
7562            font_size,
7563            subpixel_variant,
7564            scale_factor,
7565            is_emoji: false,
7566            subpixel_rendering,
7567            dilation,
7568        };
7569
7570        let raster_bounds = self.text_system().raster_bounds(&params)?;
7571        if !raster_bounds.is_zero() {
7572            let tile = self
7573                .sprite_atlas
7574                .get_or_insert_with(params.clone().into(), &mut || {
7575                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
7576                    Ok(Some((size, Cow::Owned(bytes))))
7577                })?
7578                .expect("Callback above only errors or returns Some");
7579            let bounds = Bounds {
7580                origin: integer_origin + raster_bounds.origin.map(Into::into),
7581                size: tile.bounds.size.map(Into::into),
7582            };
7583            let content_mask = self.snapped_content_mask();
7584
7585            if subpixel_rendering {
7586                self.next_frame.scene.insert_primitive(SubpixelSprite {
7587                    order: 0,
7588                    pad: 0,
7589                    bounds,
7590                    content_mask,
7591                    color: color.opacity(element_opacity),
7592                    tile,
7593                    transformation: self.element_transform,
7594                });
7595            } else {
7596                self.next_frame.scene.insert_primitive(MonochromeSprite {
7597                    order: 0,
7598                    raw_coverage: false.into(),
7599                    animation: SpriteAnimationId::NONE,
7600                    pad: 0,
7601                    bounds,
7602                    content_mask,
7603                    color: color.opacity(element_opacity),
7604                    tile,
7605                    transformation: self.element_transform,
7606                });
7607            }
7608        }
7609        Ok(())
7610    }
7611
7612    /// vue-native fork: paints a glyph's CSS `text-shadow`, its coverage in `color` blurred by
7613    /// `blur_radius`. `origin` is the shadow's baseline origin, offset included.
7614    pub fn paint_glyph_shadow(
7615        &mut self,
7616        origin: Point<Pixels>,
7617        font_id: FontId,
7618        glyph_id: GlyphId,
7619        font_size: Pixels,
7620        is_emoji: bool,
7621        color: Hsla,
7622        blur_radius: Pixels,
7623    ) -> Result<()> {
7624        self.invalidator.debug_assert_paint();
7625        if blur_radius <= px(0.) && !is_emoji {
7626            return self.paint_glyph(origin, font_id, glyph_id, font_size, color);
7627        }
7628
7629        let scale_factor = self.scale_factor();
7630        let glyph_origin = origin.scale(scale_factor);
7631        let (integer_origin, subpixel_variant) = if is_emoji {
7632            (
7633                glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0))),
7634                Point::default(),
7635            )
7636        } else {
7637            let quantized_origin = Point::new(
7638                round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7639                    / SUBPIXEL_VARIANTS_X as f32,
7640                round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7641                    / SUBPIXEL_VARIANTS_Y as f32,
7642            );
7643            (
7644                quantized_origin.map(|c| ScaledPixels(c.trunc())),
7645                Point::new(
7646                    (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7647                    (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7648                ),
7649            )
7650        };
7651        let glyph = RenderGlyphParams {
7652            font_id,
7653            glyph_id,
7654            font_size,
7655            subpixel_variant,
7656            scale_factor,
7657            is_emoji,
7658            subpixel_rendering: false,
7659            dilation: if is_emoji {
7660                0
7661            } else {
7662                self.text_system().glyph_dilation_for_color(color)
7663            },
7664        };
7665        let raster_bounds = self.text_system().raster_bounds(&glyph)?;
7666        if raster_bounds.is_zero() {
7667            return Ok(());
7668        }
7669        let params = GlyphShadowParams {
7670            sigma_quarters: GlyphShadowParams::quantize_sigma(blur_radius.0 / 2. * scale_factor),
7671            glyph,
7672        };
7673        let padding = params.padding();
7674        let sigma = params.sigma();
7675        let Some(tile) = self.sprite_atlas.get_or_insert_with(
7676            AtlasKey::GlyphShadow(params.clone()),
7677            &mut || {
7678                let (size, coverage) = self.text_system().rasterize_glyph(&params.glyph)?;
7679                let (size, blurred) = blur_glyph_coverage(size, &coverage, sigma);
7680                Ok(Some((size, Cow::Owned(blurred))))
7681            },
7682        )?
7683        else {
7684            return Ok(());
7685        };
7686        let bounds = Bounds {
7687            origin: integer_origin
7688                + raster_bounds.origin.map(Into::into)
7689                - point(ScaledPixels(padding as f32), ScaledPixels(padding as f32)),
7690            size: tile.bounds.size.map(Into::into),
7691        };
7692        let content_mask = self.snapped_content_mask();
7693        self.next_frame.scene.insert_primitive(MonochromeSprite {
7694            order: 0,
7695            raw_coverage: true.into(),
7696            animation: SpriteAnimationId::NONE,
7697            pad: 0,
7698            bounds,
7699            content_mask,
7700            color: color.opacity(self.element_opacity()),
7701            tile,
7702            transformation: self.element_transform,
7703        });
7704        Ok(())
7705    }
7706
7707    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
7708        // Checked first because it's cheap, while some platforms lock the window to read its
7709        // background appearance, and this runs for every glyph.
7710        if !self.platform_window.is_subpixel_rendering_supported() {
7711            return false;
7712        }
7713        // vue-native fork: an isolated layer starts transparent, and
7714        // subpixel text has no alpha of its own to composite it with
7715        // (Chromium too draws grayscale text into a layer that is not opaque).
7716        if self.next_frame.scene.vn_is_isolating() {
7717            return false;
7718        }
7719
7720        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
7721            return false;
7722        }
7723
7724        let mode = match self.text_rendering_mode.get() {
7725            TextRenderingMode::PlatformDefault => self
7726                .text_system()
7727                .recommended_rendering_mode(font_id, font_size),
7728            mode => mode,
7729        };
7730
7731        mode == TextRenderingMode::Subpixel
7732    }
7733
7734    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
7735    ///
7736    /// The y component of the origin is the baseline of the glyph.
7737    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
7738    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
7739    /// This method is only useful if you need to paint a single emoji that has already been shaped.
7740    ///
7741    /// This method should only be called as part of the paint phase of element drawing.
7742    pub fn paint_emoji(
7743        &mut self,
7744        origin: Point<Pixels>,
7745        font_id: FontId,
7746        glyph_id: GlyphId,
7747        font_size: Pixels,
7748    ) -> Result<()> {
7749        self.invalidator.debug_assert_paint();
7750
7751        let scale_factor = self.scale_factor();
7752        let glyph_origin = origin.scale(scale_factor);
7753        let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
7754        let params = RenderGlyphParams {
7755            font_id,
7756            glyph_id,
7757            font_size,
7758            subpixel_variant: Default::default(),
7759            scale_factor,
7760            is_emoji: true,
7761            subpixel_rendering: false,
7762            dilation: 0,
7763        };
7764
7765        let raster_bounds = self.text_system().raster_bounds(&params)?;
7766        if !raster_bounds.is_zero() {
7767            let tile = self
7768                .sprite_atlas
7769                .get_or_insert_with(params.clone().into(), &mut || {
7770                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
7771                    Ok(Some((size, Cow::Owned(bytes))))
7772                })?
7773                .expect("Callback above only errors or returns Some");
7774
7775            let bounds = Bounds {
7776                origin: integer_origin + raster_bounds.origin.map(Into::into),
7777                size: tile.bounds.size.map(Into::into),
7778            };
7779            let content_mask = self.snapped_content_mask();
7780            let opacity = self.element_opacity();
7781
7782            self.next_frame.scene.insert_primitive(PolychromeSprite {
7783                order: 0,
7784                pad: 0,
7785                grayscale: false.into(),
7786                bounds,
7787                corner_radii: Default::default(),
7788                content_mask,
7789                tile,
7790                opacity,
7791                transformation: self.element_transform,
7792                tint: Hsla::transparent_black(),
7793                corner_shapes: CornerShapes::default(),
7794            });
7795        }
7796        Ok(())
7797    }
7798
7799    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
7800    ///
7801    /// This method should only be called as part of the paint phase of element drawing.
7802    pub fn paint_svg(
7803        &mut self,
7804        bounds: Bounds<Pixels>,
7805        path: SharedString,
7806        data: Option<&[u8]>,
7807        transformation: TransformationMatrix,
7808        color: Hsla,
7809        cx: &App,
7810    ) -> Result<()> {
7811        self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
7812    }
7813
7814    /// Like [`Self::paint_svg`], with an `animation` the window applies before every
7815    /// present, so the view isn't re-rendered to advance it.
7816    pub(crate) fn paint_animated_svg(
7817        &mut self,
7818        bounds: Bounds<Pixels>,
7819        path: SharedString,
7820        data: Option<&[u8]>,
7821        transformation: TransformationMatrix,
7822        animation: Option<SpriteAnimation>,
7823        color: Hsla,
7824        cx: &App,
7825    ) -> Result<()> {
7826        self.invalidator.debug_assert_paint();
7827
7828        let element_opacity = self.element_opacity();
7829        let bounds = self.snap_bounds(bounds);
7830
7831        let params = RenderSvgParams {
7832            path,
7833            size: bounds.size.map(|pixels| {
7834                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
7835            }),
7836        };
7837
7838        let Some(tile) =
7839            self.sprite_atlas
7840                .get_or_insert_with(params.clone().into(), &mut || {
7841                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
7842                    else {
7843                        return Ok(None);
7844                    };
7845                    Ok(Some((size, Cow::Owned(bytes))))
7846                })?
7847        else {
7848            return Ok(());
7849        };
7850        let content_mask = self.snapped_content_mask();
7851        let svg_bounds = Bounds {
7852            origin: bounds.center()
7853                - Point::new(
7854                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7855                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7856                ),
7857            size: tile
7858                .bounds
7859                .size
7860                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
7861        };
7862        let final_bounds = svg_bounds
7863            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
7864            .map_size(|size| size.ceil());
7865
7866        let sprite = MonochromeSprite {
7867            order: 0,
7868            raw_coverage: false.into(),
7869            animation: SpriteAnimationId::NONE,
7870            pad: 0,
7871            bounds: final_bounds,
7872            content_mask,
7873            color: color.opacity(element_opacity),
7874            tile,
7875            // The caller's own matrix (gpui's `Svg::with_transformation`)
7876            // composed under whatever CSS `transform` an ancestor pushed.
7877            transformation: self.element_transform.compose(transformation),
7878        };
7879        match animation {
7880            Some(animation) => self.next_frame.scene.insert_animated_sprite(
7881                sprite,
7882                animation.under(self.element_transform),
7883            ),
7884            None => self.next_frame.scene.insert_primitive(sprite),
7885        }
7886
7887        Ok(())
7888    }
7889
7890    /// Paint an image into the scene for the next frame at the current z-index.
7891    /// This method will panic if the frame_index is not valid
7892    ///
7893    /// This method should only be called as part of the paint phase of element drawing.
7894    /// Paint an image into `bounds`, positioning and scaling it according to `image_bounds`.
7895    ///
7896    /// vue-native: with an [`ImageResampler`] installed, an image that is not
7897    /// [`RenderImage::dynamic`] may be drawn from the smaller copy it returns.
7898    ///
7899    /// The visible region rendered is `bounds.intersect(&image_bounds)`, with `corner_radii`
7900    /// applied to `bounds`.
7901    pub fn paint_image(
7902        &mut self,
7903        bounds: Bounds<Pixels>,
7904        image_bounds: Bounds<Pixels>,
7905        corner_radii: Corners<Pixels>,
7906        data: Arc<RenderImage>,
7907        frame_index: usize,
7908        grayscale: bool,
7909    ) -> Result<()> {
7910        self.invalidator.debug_assert_paint();
7911
7912        let visible_bounds = bounds.intersect(&image_bounds);
7913        if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
7914            return Ok(());
7915        }
7916        if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
7917            return Ok(());
7918        }
7919
7920        // vue-native: an image drawn well below its own size is drawn from the
7921        // host's smaller copy, when it has one (see `ImageResampler`).
7922        let (data, frame_index) = match IMAGE_RESAMPLER.get() {
7923            Some(resample) if !data.is_dynamic() => {
7924                let scale = self.scale_factor();
7925                let device = size(
7926                    DevicePixels((image_bounds.size.width.0 * scale).round() as i32),
7927                    DevicePixels((image_bounds.size.height.0 * scale).round() as i32),
7928                );
7929                match resample(&data, frame_index, device) {
7930                    Some(smaller) => (smaller, 0),
7931                    None => (data, frame_index),
7932                }
7933            }
7934            _ => (data, frame_index),
7935        };
7936
7937        let params = RenderImageParams {
7938            image_id: data.id,
7939            frame_index,
7940        };
7941
7942        let tile = self.sprite_atlas.get_or_insert_with(params.into(), &mut || {
7943            Ok(data.as_bytes(frame_index).map(|bytes| (data.size(frame_index), Cow::Borrowed(bytes))))
7944        })?;
7945        let Some(tile) = tile else { return Ok(()); };
7946
7947        let visible_bounds_snapped = self.snap_bounds(visible_bounds);
7948
7949        let sub_tile = if visible_bounds == image_bounds {
7950            tile
7951        } else {
7952            let x_offset_ratio =
7953                (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
7954            let y_offset_ratio =
7955                (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
7956            let width_ratio = visible_bounds.size.width / image_bounds.size.width;
7957            let height_ratio = visible_bounds.size.height / image_bounds.size.height;
7958
7959            let tile_origin_x = tile.bounds.origin.x.0;
7960            let tile_origin_y = tile.bounds.origin.y.0;
7961            let tile_width = tile.bounds.size.width.0;
7962            let tile_height = tile.bounds.size.height.0;
7963
7964            let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
7965            let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
7966            let sub_width = (width_ratio * tile_width as f32).round() as i32;
7967            let sub_height = (height_ratio * tile_height as f32).round() as i32;
7968
7969            let max_x = tile_origin_x + tile_width;
7970            let max_y = tile_origin_y + tile_height;
7971
7972            let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
7973            let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
7974            let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
7975            let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
7976
7977            AtlasTile {
7978                bounds: Bounds {
7979                    origin: point(
7980                        DevicePixels(clamped_origin_x),
7981                        DevicePixels(clamped_origin_y),
7982                    ),
7983                    size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
7984                },
7985                ..tile
7986            }
7987        };
7988
7989        let content_mask = self.snapped_content_mask();
7990        let corner_radii = corner_radii
7991            .clamp_radii_for_quad_size(visible_bounds.size)
7992            .scale(self.scale_factor());
7993        let opacity = self.element_opacity();
7994
7995        // An HDR tile carries its headroom in `pad`, as f32 bits; the shaders take a non-zero
7996        // `pad` as linear values to clamp to it and encode.
7997        let pad = if sub_tile.texture_id.kind == AtlasTextureKind::PolychromeHdr {
7998            self.element_image_headroom.to_bits()
7999        } else {
8000            0
8001        };
8002        self.next_frame.scene.insert_primitive(PolychromeSprite {
8003            order: 0,
8004            pad,
8005            grayscale: grayscale.into(),
8006            bounds: visible_bounds_snapped,
8007            content_mask,
8008            corner_radii,
8009            tile: sub_tile,
8010            opacity,
8011            transformation: self.element_transform,
8012            tint: self.element_image_tint,
8013            corner_shapes: CornerShapes::default(),
8014        });
8015        Ok(())
8016    }
8017
8018    /// Paint a surface into the scene for the next frame at the current z-index.
8019    ///
8020    /// This method should only be called as part of the paint phase of element drawing.
8021    #[cfg(any(target_os = "macos", target_os = "ios"))]
8022    pub fn paint_surface(
8023        &mut self,
8024        bounds: Bounds<Pixels>,
8025        image_buffer: CFRetained<CVPixelBuffer>,
8026    ) {
8027        use crate::PaintSurface;
8028
8029        self.invalidator.debug_assert_paint();
8030
8031        let bounds = self.snap_bounds(bounds);
8032        let content_mask = self.snapped_content_mask();
8033        self.next_frame.scene.insert_primitive(PaintSurface {
8034            order: 0,
8035            bounds,
8036            content_mask,
8037            image_buffer,
8038        });
8039    }
8040
8041    /// Fills the sprite-atlas tile that backs `data` from a texture that is
8042    /// already in the renderer's own GPU memory, with no CPU round trip.
8043    ///
8044    /// `data` is used for its **identity and its size only** — its pixel buffer
8045    /// is never read on this path, so a producer that decodes onto the GPU can
8046    /// keep one zero-filled `RenderImage` alive for the life of the element and
8047    /// overwrite its tile every frame. `paint_image` then finds the tile
8048    /// already populated and never runs its `build` closure.
8049    ///
8050    /// Returns `Ok(false)` when the platform has no GPU path or refused the
8051    /// texture (wrong device, wrong format, too small) — the caller is expected
8052    /// to fall back to a `RenderImage` carrying real bytes. This is not a paint
8053    /// method: call it from a frame pump, before the draw that paints the image.
8054    ///
8055    /// # Contract
8056    ///
8057    /// See [`PlatformAtlas::upload_from_gpu`]. On Windows `texture` must be an
8058    /// `ID3D11Texture2D` on the device `gpui_windows::renderer_d3d11_device()`
8059    /// publishes, in `DXGI_FORMAT_B8G8R8A8_UNORM`, at least as large as
8060    /// `data.size(frame_index)`.
8061    pub fn upload_image_from_gpu(
8062        &mut self,
8063        data: &RenderImage,
8064        frame_index: usize,
8065        texture: GpuTextureHandle,
8066    ) -> Result<bool> {
8067        Ok(self.write_image_tile(data, frame_index, TileSource::Gpu(texture))? != TileWrite::Refused)
8068    }
8069
8070    /// vue-native fork: writes a new frame into the sprite-atlas tile that backs
8071    /// `image`, outside any draw, and says whether the frame already drawn will
8072    /// show it.
8073    ///
8074    /// The tile is keyed by `image.id`. A producer that keeps one id for the
8075    /// life of a picture (a zero-copy video placeholder, or
8076    /// [`RenderImage::successor`] for CPU frames) keeps one tile, and the
8077    /// scene that painted it samples whatever was written last. When the write
8078    /// lands [`TileWrite::InPlace`], [`Window::request_present`] shows it with
8079    /// no layout, prepaint or paint. The size is `image.size(frame_index)`.
8080    /// Call it from a frame callback, before the frame's draw, never during one.
8081    ///
8082    /// `TileSource::Bytes` writes `image`'s own pixels (premultiplied BGRA).
8083    /// It always succeeds: a backend with no in-place path re-inserts the key,
8084    /// which reports [`TileWrite::Placed`]. `TileSource::Gpu` has the contract
8085    /// of [`PlatformAtlas::upload_from_gpu`] and reports
8086    /// [`TileWrite::Refused`] where that returns `None`.
8087    pub fn write_image_tile(
8088        &mut self,
8089        image: &RenderImage,
8090        frame_index: usize,
8091        source: TileSource,
8092    ) -> Result<TileWrite> {
8093        let key: AtlasKey = RenderImageParams {
8094            image_id: image.id,
8095            frame_index,
8096        }
8097        .into();
8098        let size = image.size(frame_index);
8099        let before = self.sprite_atlas.tile(&key);
8100        let after = match source {
8101            TileSource::Gpu(texture) => {
8102                match self.sprite_atlas.upload_from_gpu(&key, size, texture)? {
8103                    Some(tile) => tile,
8104                    None => return Ok(TileWrite::Refused),
8105                }
8106            }
8107            TileSource::Bytes => {
8108                let bytes = image
8109                    .as_bytes(frame_index)
8110                    .ok_or_else(|| anyhow!("write_image_tile: no frame {frame_index}"))?;
8111                match self.sprite_atlas.write_bytes(&key, size, bytes)? {
8112                    Some(tile) => tile,
8113                    None => {
8114                        self.sprite_atlas.remove(&key);
8115                        self.sprite_atlas
8116                            .get_or_insert_with(key, &mut || {
8117                                Ok(Some((size, Cow::Borrowed(bytes))))
8118                            })?
8119                            .ok_or_else(|| anyhow!("write_image_tile: the atlas took no tile"))?;
8120                        return Ok(TileWrite::Placed);
8121                    }
8122                }
8123            }
8124        };
8125        Ok(match before {
8126            Some(tile) if tile == after => TileWrite::InPlace,
8127            _ => TileWrite::Placed,
8128        })
8129    }
8130
8131    /// vue-native fork: [`Window::write_image_tile`] from RGBA half floats in linear extended
8132    /// sRGB, into an [`AtlasTextureKind::PolychromeHdr`] tile. [`TileWrite::Refused`] from a
8133    /// backend without HDR tiles.
8134    pub fn write_image_tile_rgba16f(
8135        &mut self,
8136        image: &RenderImage,
8137        frame_index: usize,
8138        halves: &[u16],
8139    ) -> Result<TileWrite> {
8140        let key: AtlasKey = RenderImageParams {
8141            image_id: image.id,
8142            frame_index,
8143        }
8144        .into();
8145        let before = self.sprite_atlas.tile(&key);
8146        // SAFETY: a u16 slice is readable as twice as many bytes; every target is little-endian.
8147        let bytes = unsafe {
8148            std::slice::from_raw_parts(halves.as_ptr().cast::<u8>(), std::mem::size_of_val(halves))
8149        };
8150        let Some(after) =
8151            self.sprite_atlas
8152                .write_hdr_bytes(&key, image.size(frame_index), bytes)?
8153        else {
8154            return Ok(TileWrite::Refused);
8155        };
8156        Ok(match before {
8157            Some(tile) if tile == after => TileWrite::InPlace,
8158            _ => TileWrite::Placed,
8159        })
8160    }
8161
8162    /// Writes a GPU frame while retaining its producer until the asynchronous
8163    /// atlas copy completes. See [`PlatformAtlas::upload_from_d3d12`].
8164    pub fn write_image_tile_d3d12(
8165        &mut self,
8166        image: &RenderImage,
8167        frame_index: usize,
8168        texture: crate::D3D12TextureHandle,
8169        owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
8170    ) -> Result<TileWrite> {
8171        let key: AtlasKey = RenderImageParams {
8172            image_id: image.id,
8173            frame_index,
8174        }
8175        .into();
8176        let before = self.sprite_atlas.tile(&key);
8177        let Some(after) = self.sprite_atlas.upload_from_d3d12(
8178            &key,
8179            image.size(frame_index),
8180            texture,
8181            owner,
8182        )? else {
8183            return Ok(TileWrite::Refused);
8184        };
8185        Ok(match before {
8186            Some(tile) if tile == after => TileWrite::InPlace,
8187            _ => TileWrite::Placed,
8188        })
8189    }
8190
8191    /// vue-native fork: [`Window::write_image_tile`] from a finished Metal
8192    /// texture. See [`PlatformAtlas::upload_from_metal`].
8193    pub fn write_image_tile_metal(
8194        &mut self,
8195        image: &RenderImage,
8196        frame_index: usize,
8197        texture: GpuTextureHandle,
8198        ready: Option<(*mut std::ffi::c_void, u64)>,
8199        owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
8200    ) -> Result<TileWrite> {
8201        let key: AtlasKey = RenderImageParams {
8202            image_id: image.id,
8203            frame_index,
8204        }
8205        .into();
8206        let before = self.sprite_atlas.tile(&key);
8207        let Some(after) =
8208            self.sprite_atlas
8209                .upload_from_metal(&key, image.size(frame_index), texture, ready, owner)?
8210        else {
8211            return Ok(TileWrite::Refused);
8212        };
8213        Ok(match before {
8214            Some(tile) if tile == after => TileWrite::InPlace,
8215            _ => TileWrite::Placed,
8216        })
8217    }
8218
8219    /// vue-native fork: presents the frame already drawn once more, with no
8220    /// layout, prepaint or paint: the renderer encodes the same scene again, so
8221    /// an atlas tile overwritten in place since ([`Window::write_image_tile`],
8222    /// [`TileWrite::InPlace`]) shows its new pixels. From an `on_next_frame`
8223    /// callback it takes effect in that frame; elsewhere, on the next one. A
8224    /// frame that draws anyway presents what it drew.
8225    pub fn request_present(&self) {
8226        self.needs_present.set(true);
8227        self.invalidator.wake_platform();
8228    }
8229
8230    /// Removes an image from the sprite atlas.
8231    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
8232        for frame_index in 0..data.frame_count() {
8233            let params = RenderImageParams {
8234                image_id: data.id,
8235                frame_index,
8236            };
8237
8238            self.sprite_atlas.remove(&params.into());
8239        }
8240
8241        Ok(())
8242    }
8243
8244    /// vue-native fork: this window's sprite atlas footprint (pages and bytes
8245    /// per texture kind, keys, image tiles), for an embedder's memory report.
8246    /// `None` when the platform's atlas does not keep count.
8247    pub fn sprite_atlas_stats(&self) -> Option<AtlasStats> {
8248        self.sprite_atlas.stats()
8249    }
8250
8251    /// Reports a live atlas tile on backends supporting GPU image imports.
8252    pub fn has_image_atlas_tile(&self, data: &RenderImage, frame_index: usize) -> bool {
8253        self.sprite_atlas.tile(&RenderImageParams {image_id:data.id,frame_index}.into()).is_some()
8254    }
8255
8256    /// Returns whether every frame of an image is present in the sprite atlas.
8257    #[cfg(any(test, feature = "test-support"))]
8258    pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
8259        data.frame_count() > 0
8260            && (0..data.frame_count()).all(|frame_index| {
8261                self.sprite_atlas.contains(
8262                    &RenderImageParams {
8263                        image_id: data.id,
8264                        frame_index,
8265                    }
8266                    .into(),
8267                )
8268            })
8269    }
8270
8271    /// Enable node retention for this window before its first layout request.
8272    /// Generic GPUI windows retain upstream's per-frame layout by default.
8273    pub fn vn_enable_retained_layout(&mut self) {
8274        self.layout_engine.as_mut().unwrap().enable_retention();
8275    }
8276
8277    /// Enable counters only while a profiling capture is active.
8278    pub fn vn_profile_retained_layout(&mut self, enabled: bool) {
8279        self.layout_engine
8280            .as_mut()
8281            .unwrap()
8282            .profile_retention(enabled);
8283    }
8284
8285    /// Drain this window's retention counters, or None while profiling is off.
8286    pub fn vn_take_retained_layout_stats(&mut self) -> Option<crate::VnRetainedLayoutStats> {
8287        self.layout_engine.as_mut().unwrap().take_retention_stats()
8288    }
8289
8290    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
8291    /// layout is being requested, along with the layout ids of any children. This method is called during
8292    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
8293    ///
8294    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
8295    #[must_use]
8296    pub fn request_layout(
8297        &mut self,
8298        style: Style,
8299        children: impl IntoIterator<Item = LayoutId>,
8300        cx: &mut App,
8301    ) -> LayoutId {
8302        self.invalidator.debug_assert_prepaint();
8303
8304        cx.layout_id_buffer.clear();
8305        cx.layout_id_buffer.extend(children);
8306        let rem_size = self.rem_size();
8307        let scale_factor = self.scale_factor();
8308
8309        let scope = self
8310            .layout_engine
8311            .as_ref()
8312            .unwrap()
8313            .retention_enabled()
8314            .then(|| self.element_id_stack.global_id());
8315        let engine = self.layout_engine.as_mut().unwrap();
8316        if let Some(scope) = scope {
8317            engine.request_layout_in_scope(
8318                Some(scope),
8319                style,
8320                rem_size,
8321                scale_factor,
8322                &cx.layout_id_buffer,
8323            )
8324        } else {
8325            engine.request_layout(style, rem_size, scale_factor, &cx.layout_id_buffer)
8326        }
8327    }
8328
8329    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
8330    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
8331    /// determine the element's size. One place this is used internally is when measuring text.
8332    ///
8333    /// The given closure is invoked at layout time with the known dimensions and available space and
8334    /// returns a `Size`.
8335    ///
8336    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
8337    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
8338    where
8339        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
8340            + 'static,
8341    {
8342        self.invalidator.debug_assert_prepaint();
8343
8344        let rem_size = self.rem_size();
8345        let scale_factor = self.scale_factor();
8346        let scope = self
8347            .layout_engine
8348            .as_ref()
8349            .unwrap()
8350            .retention_enabled()
8351            .then(|| self.element_id_stack.global_id());
8352        let engine = self.layout_engine.as_mut().unwrap();
8353        if let Some(scope) = scope {
8354            engine.request_measured_layout_in_scope(
8355                Some(scope),
8356                style,
8357                rem_size,
8358                scale_factor,
8359                measure,
8360            )
8361        } else {
8362            engine.request_measured_layout(style, rem_size, scale_factor, measure)
8363        }
8364    }
8365
8366    /// Compute the layout for the given id within the given available space.
8367    /// This method is called for its side effect, typically by the framework prior to painting.
8368    /// After calling it, you can request the bounds of the given layout node id or any descendant.
8369    ///
8370    /// This method should only be called as part of the prepaint phase of element drawing.
8371    pub fn compute_layout(
8372        &mut self,
8373        layout_id: LayoutId,
8374        available_space: Size<AvailableSpace>,
8375        cx: &mut App,
8376    ) {
8377        self.invalidator.debug_assert_prepaint();
8378
8379        let mut layout_engine = self.layout_engine.take().unwrap();
8380        layout_engine.compute_layout(layout_id, available_space, self, cx);
8381        self.layout_engine = Some(layout_engine);
8382    }
8383
8384    /// vue-native fork: whether the layout node is out of flow (`position:
8385    /// absolute`).
8386    pub fn layout_is_absolute(&self, layout_id: LayoutId) -> bool {
8387        self.layout_engine
8388            .as_ref()
8389            .is_some_and(|engine| engine.is_absolute(layout_id))
8390    }
8391
8392    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
8393    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
8394    ///
8395    /// This method should only be called as part of element drawing.
8396    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
8397        self.invalidator.debug_assert_prepaint();
8398
8399        let scale_factor = self.scale_factor();
8400        let mut bounds = self
8401            .layout_engine
8402            .as_mut()
8403            .unwrap()
8404            .layout_bounds(layout_id, scale_factor)
8405            .map(Into::into);
8406        let snapped_offset = self.pixel_snap_point(self.element_offset());
8407        bounds.origin += snapped_offset;
8408        bounds
8409    }
8410
8411    /// This method should be called during `prepaint`. You can use
8412    /// the returned [Hitbox] during `paint` or in an event handler
8413    /// to determine whether the inserted hitbox was the topmost.
8414    ///
8415    /// This method should only be called as part of the prepaint phase of element drawing.
8416    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
8417        self.invalidator.debug_assert_prepaint();
8418
8419        let content_mask = self.content_mask();
8420        let id = self.next_hitbox_id;
8421        self.next_hitbox_id = self.next_hitbox_id.next();
8422        let hitbox = Hitbox {
8423            id,
8424            bounds,
8425            content_mask,
8426            behavior,
8427            // Whatever CSS `transform` the paint walk is inside. Prepaint
8428            // pushes the same matrix paint does, so a rotated element's hitbox
8429            // knows it is rotated (see `Frame::hit_test`).
8430            transformation: self.element_transform,
8431            vn_clip: self.vn_clip_stack.clone(),
8432        };
8433        self.next_frame.hitboxes.push(hitbox.clone());
8434        // vue-native fork.
8435        if self.vn_hitbox_tag != 0 {
8436            self.next_frame
8437                .vn_tagged_hitboxes
8438                .push((self.vn_hitbox_tag, hitbox.clone()));
8439        }
8440        hitbox
8441    }
8442
8443    /// vue-native fork: tag every hitbox inserted from now until the tag is set
8444    /// back, with an embedder node id. Returns the previous tag, which the
8445    /// caller must restore — the pair brackets one node's prepaint, so a child
8446    /// tags itself and hands the parent's tag back on the way out.
8447    ///
8448    /// `0` disables tagging. See [`Frame::vn_tagged_hitboxes`].
8449    pub fn set_hitbox_tag(&mut self, tag: u32) -> u32 {
8450        mem::replace(&mut self.vn_hitbox_tag, tag)
8451    }
8452
8453    /// vue-native fork: [`Window::set_hitbox_tag`] for the duration of `f`,
8454    /// which prepaints one embedder node, answering also the node's whole CSS
8455    /// `transform` (its ancestors' composed with its own) when it has one of
8456    /// its own. `None` means its picture moved only with its ancestors', by
8457    /// [`Window::element_transform`] as it stood before `f`.
8458    ///
8459    /// "The node's own" is the FIRST element to prepaint inside `f`: the
8460    /// node's element runs before anything inside it, and what it builds
8461    /// internally under the same tag (a `::before` box, a list marker) after,
8462    /// so a transformed pseudo-element does not move its node.
8463    pub fn with_hitbox_tag<R>(
8464        &mut self,
8465        tag: u32,
8466        f: impl FnOnce(&mut Self) -> R,
8467    ) -> (R, Option<TransformationMatrix>) {
8468        let tag = mem::replace(&mut self.vn_hitbox_tag, tag);
8469        let fresh = mem::replace(&mut self.vn_tag_fresh, true);
8470        let noted = self.vn_tag_transform.take();
8471        let result = f(self);
8472        let own = mem::replace(&mut self.vn_tag_transform, noted);
8473        self.vn_tag_fresh = fresh;
8474        self.vn_hitbox_tag = tag;
8475        (result, own)
8476    }
8477
8478    /// vue-native fork: called by every element's prepaint once its own
8479    /// `transform` is pushed. The first one inside a
8480    /// [`Window::with_hitbox_tag`] is the tagged node's.
8481    pub(crate) fn note_tagged_transform(&mut self, own_is_unit: bool) {
8482        if self.vn_tag_fresh {
8483            self.vn_tag_fresh = false;
8484            if !own_is_unit {
8485                self.vn_tag_transform = Some(self.element_transform);
8486            }
8487        }
8488    }
8489
8490    /// vue-native fork: the axis-aligned bounding box of `bounds` (logical
8491    /// pixels) under `matrix` (device space, as [`Window::element_transform`]
8492    /// is) — the rectangle a browser's `getBoundingClientRect()` reports for a
8493    /// transformed box.
8494    pub fn transformed_bounds(
8495        &self,
8496        matrix: TransformationMatrix,
8497        bounds: Bounds<Pixels>,
8498    ) -> Bounds<Pixels> {
8499        transform_bounds(matrix, bounds, self.scale_factor)
8500    }
8501
8502    /// vue-native fork: give EVERY element a hitbox, not only an interactive
8503    /// one, so that [`Window::tagged_hitbox`] can answer for any node. Costs
8504    /// one `Hitbox` per element per frame and the same number of rectangle
8505    /// tests per mouse move, so it is opt-in; a dev host turns it on at boot
8506    /// and a shipped one never does.
8507    pub fn set_tag_every_hitbox(&mut self, on: bool) {
8508        self.vn_tag_every_hitbox = on;
8509    }
8510
8511    /// vue-native fork: is [`Window::set_tag_every_hitbox`] on?
8512    pub fn tags_every_hitbox(&self) -> bool {
8513        self.vn_tag_every_hitbox
8514    }
8515
8516    /// vue-native fork: the hitbox the RENDERED frame made for the element
8517    /// tagged `tag` — the handle [`Hitbox::is_hovered_at`] takes.
8518    ///
8519    /// The first entry wins: an element's own hitbox is inserted before any box
8520    /// its subtree makes, and boxes a node's build produces internally (a
8521    /// pseudo-element, a list marker) carry the same tag. A pick
8522    /// ([`Window::vn_insert_pick`]) is not a hitbox and is passed over.
8523    pub fn tagged_hitbox(&self, tag: u32) -> Option<&Hitbox> {
8524        self.rendered_frame
8525            .vn_tagged_hitboxes
8526            .iter()
8527            .find(|(t, hitbox)| *t == tag && hitbox.id != HitboxId::VN_PICK)
8528            .map(|(_, hitbox)| hitbox)
8529    }
8530
8531    /// vue-native fork: the embedder tags of the hitboxes under `position` in
8532    /// the RENDERED frame, topmost first — the order a press resolves in
8533    /// ([`Frame::hit_test`], so a deferred draw's boxes sort where it paints).
8534    /// A hitbox no node tagged is left out; a node with several boxes there
8535    /// appears once per box.
8536    ///
8537    /// An embedder asks it to learn which of ITS nodes is on top under the
8538    /// pointer, which gpui's own answer (`Hitbox::is_hovered`, true for every
8539    /// box under the pointer) cannot say. One hit test plus one pass over the
8540    /// frame's tagged boxes: meant for a press or a drag, not for every mouse
8541    /// move.
8542    ///
8543    /// The PICK records ([`Window::vn_insert_pick`]) are boxes too, so with
8544    /// [`Window::set_vn_pick_every_box`] on this answers for every element,
8545    /// listening or not. It walks the tagged list in paint order itself rather
8546    /// than asking [`Frame::hit_test`], whose list has no picks; a
8547    /// `BlockMouse` box ends it, as it ends gpui's.
8548    ///
8549    /// A box tagged [`VN_TAG_PASSIVE`] is left out: it is a node's, but it is
8550    /// not where the node is (a scroll container's wheel viewport, which lies
8551    /// over the content it scrolls).
8552    pub fn vn_tags_at(&self, position: Point<Pixels>) -> Vec<u32> {
8553        let frame = &self.rendered_frame;
8554        let tagged = &frame.vn_tagged_hitboxes;
8555        let mut out = Vec::new();
8556        let mut visit = |(tag, hitbox): &(u32, Hitbox)| {
8557            if tag & VN_TAG_PASSIVE != 0 || !Frame::box_contains(hitbox, position, self.scale_factor) {
8558                return true;
8559            }
8560            out.push(*tag);
8561            hitbox.behavior != HitboxBehavior::BlockMouse
8562        };
8563        match frame.vn_tagged_paint_order() {
8564            Some(order) => {
8565                for &ix in order.iter().rev() {
8566                    if !visit(&tagged[ix as usize]) {
8567                        break;
8568                    }
8569                }
8570            }
8571            None => {
8572                for entry in tagged.iter().rev() {
8573                    if !visit(entry) {
8574                        break;
8575                    }
8576                }
8577            }
8578        }
8579        out
8580    }
8581
8582    /// vue-native fork: give an element that needs no hitbox a PICK record
8583    /// instead — its box, content mask, transform and tag, in
8584    /// [`Frame::vn_tagged_hitboxes`] only. gpui's own hit test (the one every
8585    /// mouse move runs) never sees a pick, so it costs a move nothing; it is
8586    /// there for [`Window::vn_tags_at`], which an embedder asks at a press to
8587    /// learn the topmost of ALL its elements, the way a browser targets an
8588    /// event. Replayed with the rest of a cached view's prepaint.
8589    pub fn set_vn_pick_every_box(&mut self, on: bool) {
8590        self.vn_pick_every_box = on;
8591    }
8592
8593    /// vue-native fork: is [`Window::set_vn_pick_every_box`] on?
8594    pub fn vn_picks_every_box(&self) -> bool {
8595        self.vn_pick_every_box
8596    }
8597
8598    /// vue-native fork: records a pick for `bounds` under the current tag
8599    /// (nothing outside a tag). Called where an element would insert its
8600    /// hitbox, so the content mask and transform are the ones a hitbox there
8601    /// would carry.
8602    pub fn vn_insert_pick(&mut self, bounds: Bounds<Pixels>) {
8603        self.invalidator.debug_assert_prepaint();
8604        if self.vn_hitbox_tag == 0 {
8605            return;
8606        }
8607        let hitbox = Hitbox {
8608            id: HitboxId::VN_PICK,
8609            bounds,
8610            content_mask: self.content_mask(),
8611            behavior: HitboxBehavior::Normal,
8612            transformation: self.element_transform,
8613            vn_clip: self.vn_clip_stack.clone(),
8614        };
8615        self.next_frame
8616            .vn_tagged_hitboxes
8617            .push((self.vn_hitbox_tag, hitbox));
8618    }
8619
8620    /// vue-native fork: installs (or removes) the embedder's hit refiner.
8621    ///
8622    /// gpui hands a mouse event to EVERY hitbox under the pointer, so a box
8623    /// that listens takes a press through anything painted over it that does
8624    /// not, and a box that does not listen is never anybody's target. A
8625    /// browser targets the topmost element and bubbles from there. The
8626    /// refiner is run at the start of the dispatch of each press, release and
8627    /// wheel event, before any listener, and may narrow what the event is for
8628    /// with [`Window::vn_restrict_mouse_hit`]. Moves are not refined.
8629    pub fn set_vn_hit_refiner(&mut self, refiner: Option<VnHitRefiner>) {
8630        self.vn_hit_refiner = refiner;
8631    }
8632
8633    /// vue-native fork: is a hit refiner installed?
8634    pub fn has_vn_hit_refiner(&self) -> bool {
8635        self.vn_hit_refiner.is_some()
8636    }
8637
8638    /// vue-native fork: which key event this window is dispatching — one
8639    /// number per key-down, key-up or modifiers change, taken before the
8640    /// keystroke interceptors run, so everything that hears one event (an
8641    /// interceptor, the capture listeners, the bubble listeners) reads the
8642    /// same number and the next event reads another.
8643    ///
8644    /// gpui hands a key event to every listener on the focus path, and an
8645    /// editor's interceptor sees it before any of them. An embedder that turns
8646    /// it into ONE event of its own (a browser's `keydown`, dispatched once at
8647    /// the focused element) records the number it dispatched for and lets the
8648    /// others pass. Interceptor order and listener order do not matter, and a
8649    /// listener whose element the first dispatch removed still reads the same
8650    /// number, because gpui walks the path it computed before any of them ran.
8651    pub fn vn_key_event_seq(&self) -> u64 {
8652        self.vn_key_event_seq
8653    }
8654
8655    /// vue-native fork: is the pointer in this window? `false` once it has
8656    /// left (a `MouseExited`, the end of a file drag over it), `true` again at
8657    /// the next pointer event here. [`Window::mouse_position`] keeps the last
8658    /// position inside either way, so an embedder that decides hover itself
8659    /// (a browser's `:hover` and `mouseenter`, from its own hit test) asks
8660    /// this to know that nothing is hovered, as [`Hitbox::is_hovered`] does.
8661    pub fn vn_pointer_inside(&self) -> bool {
8662        self.pointer_inside
8663    }
8664
8665    /// vue-native fork: a browser's pointer lock. Until [`Window::vn_unlock_pointer`], every
8666    /// mouse event is delivered at the position the pointer had now, and a move's motion is
8667    /// [`Window::vn_mouse_movement`]. Locking again changes the mode.
8668    pub fn vn_lock_pointer(&mut self, how: VnPointerLock) -> Result<(), crate::PointerLockError> {
8669        let anchor = match self.vn_pointer_lock.take() {
8670            Some((previous, anchor)) => {
8671                if matches!(previous, VnPointerLock::System { .. }) {
8672                    self.platform_window.unlock_pointer();
8673                }
8674                anchor
8675            }
8676            None => self.mouse_position,
8677        };
8678        if let VnPointerLock::System { unadjusted } = how {
8679            self.platform_window.lock_pointer(unadjusted)?;
8680        }
8681        self.vn_pointer_lock = Some((how, anchor));
8682        self.vn_raw_mouse_position = None;
8683        Ok(())
8684    }
8685
8686    /// vue-native fork: releases [`Window::vn_lock_pointer`]'s lock, if any.
8687    pub fn vn_unlock_pointer(&mut self) {
8688        if let Some((VnPointerLock::System { .. }, _)) = self.vn_pointer_lock.take() {
8689            self.platform_window.unlock_pointer();
8690        }
8691        self.vn_raw_mouse_position = None;
8692    }
8693
8694    /// vue-native fork: is the pointer still locked? The platform lets go by itself when the
8695    /// window loses activation.
8696    pub fn vn_pointer_locked(&self) -> bool {
8697        match self.vn_pointer_lock {
8698            Some((VnPointerLock::System { .. }, _)) => self.platform_window.is_pointer_locked(),
8699            Some((VnPointerLock::Simulated, _)) => true,
8700            None => false,
8701        }
8702    }
8703
8704    /// vue-native fork: how far the mouse move being dispatched moved the pointer since the
8705    /// previous move, logical pixels: a browser's `movementX`/`movementY`. While the pointer is
8706    /// locked by the system it is the platform's measure (device counts when unadjusted).
8707    pub fn vn_mouse_movement(&self) -> Point<Pixels> {
8708        self.vn_mouse_movement
8709    }
8710
8711    fn vn_pin_to_pointer_lock(&mut self, mut event: PlatformInput) -> PlatformInput {
8712        let system = matches!(
8713            self.vn_pointer_lock,
8714            Some((VnPointerLock::System { .. }, _))
8715        );
8716        if system && !self.platform_window.is_pointer_locked() {
8717            self.vn_pointer_lock = None;
8718            self.vn_raw_mouse_position = None;
8719        }
8720        if let PlatformInput::MouseMove(mouse_move) = &event {
8721            let previous = self.vn_raw_mouse_position.replace(mouse_move.position);
8722            let motion = system.then(|| self.platform_window.take_pointer_motion());
8723            self.vn_mouse_movement = motion.flatten().unwrap_or_else(|| {
8724                previous.map_or_else(Point::default, |previous| mouse_move.position - previous)
8725            });
8726        }
8727        let Some((_, anchor)) = self.vn_pointer_lock else {
8728            return event;
8729        };
8730        match &mut event {
8731            PlatformInput::MouseMove(e) => e.position = anchor,
8732            PlatformInput::MouseDown(e) => e.position = anchor,
8733            PlatformInput::MouseUp(e) => e.position = anchor,
8734            PlatformInput::Scroll(e) => e.position = anchor,
8735            PlatformInput::MouseExited(e) => e.position = anchor,
8736            _ => {}
8737        }
8738        event
8739    }
8740
8741    /// vue-native fork: will this frame draw the window? `true` once anything
8742    /// invalidated it since its last draw (a notify, a `refresh`, a resize).
8743    /// An embedder with work that must follow the frame's layout and precede
8744    /// its paint (a browser's ResizeObserver delivery) draws the window itself
8745    /// from an `on_next_frame` callback when this is set; the frame then finds
8746    /// it clean and presents what that draw produced.
8747    pub fn vn_is_dirty(&self) -> bool {
8748        self.invalidator.is_dirty()
8749    }
8750
8751    /// vue-native fork: for the mouse event being dispatched, keep only the
8752    /// hitboxes whose tag `keep` accepts (an untagged hitbox is not the
8753    /// embedder's and stays). With `add`, the accepted tags' boxes that do
8754    /// NOT contain the pointer join the hovered set as well: a browser's
8755    /// event reaches every ancestor of its target, wherever their boxes are.
8756    ///
8757    /// Only meant from inside a [`VnHitRefiner`]. The next frame or the next
8758    /// mouse event recomputes the hit test from geometry.
8759    pub fn vn_restrict_mouse_hit(&mut self, keep: &dyn Fn(u32) -> bool, add: bool) {
8760        let frame = &self.rendered_frame;
8761        let mut tag_of: FxHashMap<HitboxId, u32> = FxHashMap::default();
8762        // A passive box is judged by the node it belongs to.
8763        for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8764            if hitbox.id != HitboxId::VN_PICK {
8765                tag_of.entry(hitbox.id).or_insert(tag & !VN_TAG_PASSIVE);
8766            }
8767        }
8768        let old = mem::take(&mut self.mouse_hit_test);
8769        let mut ids: SmallVec<[HitboxId; 8]> = SmallVec::new();
8770        let mut hover = 0;
8771        for (ix, id) in old.ids.iter().enumerate() {
8772            if tag_of.get(id).is_none_or(|tag| keep(*tag)) {
8773                ids.push(*id);
8774                if ix < old.hover_hitbox_count {
8775                    hover += 1;
8776                }
8777            }
8778        }
8779        // Nothing was cut from hover by a `BlockMouseExceptScroll` box: the
8780        // added boxes are hovered too.
8781        let all_hovered = old.hover_hitbox_count == old.ids.len();
8782        if add {
8783            for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8784                if hitbox.id != HitboxId::VN_PICK
8785                    && keep(tag & !VN_TAG_PASSIVE)
8786                    && !ids.contains(&hitbox.id)
8787                {
8788                    ids.push(hitbox.id);
8789                }
8790            }
8791        }
8792        if all_hovered {
8793            hover = ids.len();
8794        }
8795        self.mouse_hit_test = HitTest {
8796            ids,
8797            hover_hitbox_count: hover,
8798        };
8799    }
8800
8801    /// Resolves native caption behavior at a point in the current painted frame.
8802    /// This does not reuse or modify the hit set narrowed for a DOM input event.
8803    pub fn window_control_area_at(&self, position: Point<Pixels>) -> Option<WindowControlArea> {
8804        for hitbox in self.rendered_frame.topmost_hitboxes() {
8805            if !Frame::box_contains(hitbox, position, self.scale_factor) {
8806                continue;
8807            }
8808            if let Some((area, _)) = self.rendered_frame.window_control_hitboxes.iter()
8809                .find(|(_, control)| control.id == hitbox.id)
8810            {
8811                return Some(*area);
8812            }
8813            if hitbox.behavior == HitboxBehavior::BlockMouse {
8814                break;
8815            }
8816        }
8817        None
8818    }
8819
8820    /// Set a hitbox which will act as a control area of the platform window.
8821    ///
8822    /// This method should only be called as part of the paint phase of element drawing.
8823    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
8824        self.invalidator.debug_assert_paint();
8825        self.next_frame.window_control_hitboxes.push((area, hitbox));
8826    }
8827
8828    /// Sets the key context for the current element. This context will be used to translate
8829    /// keybindings into actions.
8830    ///
8831    /// This method should only be called as part of the paint phase of element drawing.
8832    pub fn set_key_context(&mut self, context: KeyContext) {
8833        self.invalidator.debug_assert_paint();
8834        self.next_frame.dispatch_tree.set_key_context(context);
8835    }
8836
8837    /// Sets the focus handle for the current element. This handle will be used to manage focus state
8838    /// and keyboard event dispatch for the element.
8839    ///
8840    /// This method should only be called as part of the prepaint phase of element drawing.
8841    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
8842        self.invalidator.debug_assert_prepaint();
8843        if focus_handle.is_focused(self) {
8844            self.next_frame.focus = Some(focus_handle.id);
8845        }
8846        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
8847    }
8848
8849    /// Sets the view id for the current element, which will be used to manage view caching.
8850    ///
8851    /// This method should only be called as part of element prepaint. We plan on removing this
8852    /// method eventually when we solve some issues that require us to construct editor elements
8853    /// directly instead of always using editors via views.
8854    pub fn set_view_id(&mut self, view_id: EntityId) {
8855        self.invalidator.debug_assert_prepaint();
8856        self.next_frame.dispatch_tree.set_view_id(view_id);
8857    }
8858
8859    /// Get the entity ID for the currently rendering view
8860    pub fn current_view(&self) -> EntityId {
8861        self.invalidator.debug_assert_paint_or_prepaint();
8862        self.rendered_entity_stack.last().copied().unwrap()
8863    }
8864
8865    #[inline]
8866    pub(crate) fn with_rendered_view<R>(
8867        &mut self,
8868        id: EntityId,
8869        f: impl FnOnce(&mut Self) -> R,
8870    ) -> R {
8871        self.rendered_entity_stack.push(id);
8872        let result = f(self);
8873        self.rendered_entity_stack.pop();
8874        result
8875    }
8876
8877    /// Executes the provided function with the specified image cache.
8878    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
8879    where
8880        F: FnOnce(&mut Self) -> R,
8881    {
8882        if let Some(image_cache) = image_cache {
8883            self.image_cache_stack.push(image_cache);
8884            let result = f(self);
8885            self.image_cache_stack.pop();
8886            result
8887        } else {
8888            f(self)
8889        }
8890    }
8891
8892    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
8893    /// platform to receive textual input with proper integration with concerns such
8894    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
8895    /// rendered.
8896    ///
8897    /// This method should only be called as part of the paint phase of element drawing.
8898    ///
8899    /// [element_input_handler]: crate::ElementInputHandler
8900    pub fn handle_input(
8901        &mut self,
8902        focus_handle: &FocusHandle,
8903        input_handler: impl InputHandler,
8904        cx: &App,
8905    ) {
8906        self.invalidator.debug_assert_paint();
8907
8908        if focus_handle.is_focused(self) {
8909            let cx = self.to_async(cx);
8910            self.next_frame.input_handlers.push(Some(
8911                PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
8912            ));
8913        }
8914    }
8915
8916    /// Notifies native text services that the focused component's text changed.
8917    ///
8918    /// Text components should call this after application-driven edits, in addition
8919    /// to notifying GPUI to redraw. Unfocused or unregistered components are ignored.
8920    pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
8921        if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8922            self.platform_window
8923                .text_input_state_changed(TextInputStateChange::ContentChanged);
8924        }
8925    }
8926
8927    /// Notifies native text services that the focused component's selection changed.
8928    ///
8929    /// Text components should call this after application-driven selection changes,
8930    /// in addition to notifying GPUI to redraw.
8931    pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
8932        if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8933            self.platform_window
8934                .text_input_state_changed(TextInputStateChange::SelectionChanged);
8935        }
8936    }
8937
8938    /// Forwards the focused input handler's [`TextInputConfiguration`] to the
8939    /// platform window when it differs from the last forwarded value. With no
8940    /// input handler the default configuration applies, so a field's
8941    /// preferences don't outlive its focus.
8942    fn apply_text_input_configuration(&mut self, cx: &mut App) {
8943        let configuration = match self.platform_window.take_input_handler() {
8944            Some(mut input_handler) => {
8945                let configuration = input_handler.text_input_configuration(self, cx);
8946                self.platform_window.set_input_handler(input_handler);
8947                configuration
8948            }
8949            None => TextInputConfiguration::default(),
8950        };
8951        if self.last_text_input_configuration.as_ref() != Some(&configuration) {
8952            self.platform_window
8953                .set_text_input_configuration(configuration.clone());
8954            self.last_text_input_configuration = Some(configuration);
8955        }
8956    }
8957
8958    /// Register a mouse event listener on the window for the next frame. The type of event
8959    /// is determined by the first parameter of the given listener. When the next frame is rendered
8960    /// the listener will be cleared.
8961    ///
8962    /// This method should only be called as part of the paint phase of element drawing.
8963    pub fn on_mouse_event<Event: MouseEvent>(
8964        &mut self,
8965        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8966    ) {
8967        self.invalidator.debug_assert_paint();
8968
8969        self.next_frame.mouse_listeners.push(Some(Box::new(
8970            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
8971                if let Some(event) = event.downcast_ref() {
8972                    listener(event, phase, window, cx)
8973                }
8974            },
8975        )));
8976    }
8977
8978    /// Register a key event listener on this node for the next frame. The type of event
8979    /// is determined by the first parameter of the given listener. When the next frame is rendered
8980    /// the listener will be cleared.
8981    ///
8982    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
8983    /// a specific need to register a listener yourself.
8984    ///
8985    /// This method should only be called as part of the paint phase of element drawing.
8986    pub fn on_key_event<Event: KeyEvent>(
8987        &mut self,
8988        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8989    ) {
8990        self.invalidator.debug_assert_paint();
8991
8992        self.next_frame.dispatch_tree.on_key_event(Rc::new(
8993            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
8994                if let Some(event) = event.downcast_ref::<Event>() {
8995                    listener(event, phase, window, cx)
8996                }
8997            },
8998        ));
8999    }
9000
9001    /// Register a modifiers changed event listener on the window for the next frame.
9002    ///
9003    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
9004    /// a specific need to register a global listener.
9005    ///
9006    /// This method should only be called as part of the paint phase of element drawing.
9007    pub fn on_modifiers_changed(
9008        &mut self,
9009        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
9010    ) {
9011        self.invalidator.debug_assert_paint();
9012
9013        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
9014            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
9015                listener(event, window, cx)
9016            },
9017        ));
9018    }
9019
9020    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
9021    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
9022    /// Returns a subscription and persists until the subscription is dropped.
9023    pub fn on_focus_in(
9024        &mut self,
9025        handle: &FocusHandle,
9026        cx: &mut App,
9027        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
9028    ) -> Subscription {
9029        let focus_id = handle.id;
9030        let (subscription, activate) =
9031            self.new_focus_listener(Box::new(move |event, window, cx| {
9032                if event.is_focus_in(focus_id) {
9033                    listener(window, cx);
9034                }
9035                true
9036            }));
9037        cx.defer(move |_| activate());
9038        subscription
9039    }
9040
9041    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
9042    /// Returns a subscription and persists until the subscription is dropped.
9043    pub fn on_focus_out(
9044        &mut self,
9045        handle: &FocusHandle,
9046        cx: &mut App,
9047        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
9048    ) -> Subscription {
9049        let focus_id = handle.id;
9050        let (subscription, activate) =
9051            self.new_focus_listener(Box::new(move |event, window, cx| {
9052                if let Some(blurred_id) = event.previous_focus_path.last().copied()
9053                    && event.is_focus_out(focus_id)
9054                {
9055                    let event = FocusOutEvent {
9056                        blurred: WeakFocusHandle {
9057                            id: blurred_id,
9058                            handles: Arc::downgrade(&cx.focus_handles),
9059                        },
9060                    };
9061                    listener(event, window, cx)
9062                }
9063                true
9064            }));
9065        cx.defer(move |_| activate());
9066        subscription
9067    }
9068
9069    fn reset_cursor_style(&self, cx: &mut App) {
9070        // Set the cursor only if we're the active window.
9071        if self.is_window_hovered() {
9072            // A drag can start before the next paint records its cursor in the frame.
9073            let style = cx
9074                .active_drag_cursor_style()
9075                .or_else(|| self.rendered_frame.cursor_style(self))
9076                .unwrap_or(CursorStyle::Arrow);
9077            cx.platform.set_cursor_style(style);
9078        }
9079    }
9080
9081    /// Dispatch a given keystroke as though the user had typed it.
9082    /// You can create a keystroke with Keystroke::parse("").
9083    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
9084        let keystroke = keystroke.with_simulated_ime();
9085        let result = self.dispatch_event(
9086            PlatformInput::KeyDown(KeyDownEvent {
9087                keystroke: keystroke.clone(),
9088                is_held: false,
9089                prefer_character_input: false,
9090            }),
9091            cx,
9092        );
9093        if !result.propagate {
9094            return true;
9095        }
9096
9097        if let Some(input) = keystroke.key_char
9098            && let Some(mut input_handler) = self.platform_window.take_input_handler()
9099        {
9100            input_handler.dispatch_input(&input, self, cx);
9101            self.platform_window.set_input_handler(input_handler);
9102            return true;
9103        }
9104
9105        false
9106    }
9107
9108    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
9109    /// binding for the action (last binding added to the keymap).
9110    pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
9111        self.highest_precedence_binding_for_action(action)
9112            .map(|binding| {
9113                binding
9114                    .keystrokes()
9115                    .iter()
9116                    .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
9117                    .collect::<Vec<_>>()
9118                    .join(" ")
9119            })
9120            .unwrap_or_else(|| action.name().to_string())
9121    }
9122
9123    /// Installs a modal input interceptor. Return true to consume the event
9124    /// before normal dispatch. Passing None restores the ordinary input path.
9125    /// The callback may remove itself. No callback runs while it is absent.
9126    pub fn set_input_interceptor(
9127        &mut self,
9128        interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
9129    ) {
9130        self.input_interceptor = interceptor;
9131    }
9132
9133    /// Dispatch a mouse, keyboard, or touch event on the window.
9134    #[profiling::function]
9135    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
9136        // A modal tool consumes the complete gesture before focus, native widgets,
9137        // click tracking and application listeners can observe it. Cloning the
9138        // Rc permits the interceptor to remove itself while handling an event.
9139        if let Some(intercept) = self.input_interceptor.clone() {
9140            if intercept(&event, self, cx) {
9141                return DispatchEventResult { propagate: false, default_prevented: true };
9142            }
9143        }
9144        #[cfg(feature = "profiler")]
9145        self.window_profiler.begin_input(event.kind_name());
9146        let update_count_before = self.invalidator.update_count();
9147        // Track input modality for focus-visible styling and hover suppression.
9148        // Hover is suppressed during keyboard modality so that keyboard navigation
9149        // doesn't show hover highlights on the item under the mouse cursor.
9150        let old_modality = self.last_input_modality;
9151        self.last_input_modality = match &event {
9152            PlatformInput::KeyDown(_) => InputModality::Keyboard,
9153            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
9154            PlatformInput::Touch(_) => InputModality::Touch,
9155            _ => self.last_input_modality,
9156        };
9157        if self.last_input_modality != old_modality {
9158            self.refresh();
9159        }
9160        let was_inside = self.pointer_inside;
9161        let pointer_moved = matches!(event, PlatformInput::MouseMove(_));
9162        // vue-native fork: [`Window::pointer_inside`]. Exhaustive on purpose,
9163        // so a new kind of input has to say which side it is on. A leave
9164        // applies AFTER the event is dispatched, so the listeners that handle
9165        // it (a file drag's exit, say) still see the element the pointer left.
9166        let pointer_leaves = match &event {
9167            PlatformInput::MouseMove(_)
9168            | PlatformInput::MouseDown(_)
9169            | PlatformInput::MouseUp(_)
9170            | PlatformInput::MousePressure(_)
9171            | PlatformInput::Scroll(_)
9172            | PlatformInput::Pinch(_)
9173            | PlatformInput::LongPress(_)
9174            | PlatformInput::TouchDrag(_)
9175            | PlatformInput::BackGesture(_)
9176            | PlatformInput::Touch(_) => {
9177                self.pointer_inside = true;
9178                false
9179            }
9180            PlatformInput::FileDrop(FileDropEvent::Exited) | PlatformInput::MouseExited(_) => true,
9181            PlatformInput::FileDrop(_) => {
9182                self.pointer_inside = true;
9183                false
9184            }
9185            PlatformInput::KeyDown(_)
9186            | PlatformInput::KeyUp(_)
9187            | PlatformInput::ModifiersChanged(_) => false,
9188        };
9189
9190        // Handlers may set this to false by calling `stop_propagation`.
9191        cx.propagate_event = true;
9192        // Handlers may set this to true by calling `prevent_default`.
9193        self.default_prevented = false;
9194
9195        let event = self.vn_pin_to_pointer_lock(event);
9196        let event = match event {
9197            // Track the mouse position with our own state, since accessing the platform
9198            // API for the mouse position can only occur on the main thread.
9199            PlatformInput::MouseMove(mouse_move) => {
9200                self.mouse_position = mouse_move.position;
9201                self.modifiers = mouse_move.modifiers;
9202                PlatformInput::MouseMove(mouse_move)
9203            }
9204            PlatformInput::MouseDown(mouse_down) => {
9205                self.mouse_position = mouse_down.position;
9206                self.modifiers = mouse_down.modifiers;
9207                PlatformInput::MouseDown(mouse_down)
9208            }
9209            PlatformInput::MouseUp(mouse_up) => {
9210                self.mouse_position = mouse_up.position;
9211                self.modifiers = mouse_up.modifiers;
9212                PlatformInput::MouseUp(mouse_up)
9213            }
9214            PlatformInput::MousePressure(mouse_pressure) => {
9215                PlatformInput::MousePressure(mouse_pressure)
9216            }
9217            PlatformInput::MouseExited(mouse_exited) => {
9218                self.modifiers = mouse_exited.modifiers;
9219                PlatformInput::MouseExited(mouse_exited)
9220            }
9221            PlatformInput::ModifiersChanged(modifiers_changed) => {
9222                self.modifiers = modifiers_changed.modifiers;
9223                self.capslock = modifiers_changed.capslock;
9224                PlatformInput::ModifiersChanged(modifiers_changed)
9225            }
9226            PlatformInput::Scroll(scroll_wheel) => {
9227                self.mouse_position = scroll_wheel.position;
9228                self.modifiers = scroll_wheel.modifiers;
9229                PlatformInput::Scroll(scroll_wheel)
9230            }
9231            PlatformInput::Pinch(pinch) => {
9232                self.mouse_position = pinch.position;
9233                self.modifiers = pinch.modifiers;
9234                PlatformInput::Pinch(pinch)
9235            }
9236            // Translate dragging and dropping of external files from the operating system
9237            // to internal drag and drop events.
9238            PlatformInput::FileDrop(file_drop) => match file_drop {
9239                FileDropEvent::Entered { position, paths } => {
9240                    self.mouse_position = position;
9241                    let source_window = self.handle.window_id();
9242                    if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
9243                        cx.active_drag = Some(AnyDrag {
9244                            value: Arc::new(paths.clone()),
9245                            view: cx.new(|_| paths).into(),
9246                            cursor_offset: position,
9247                            cursor_style: None,
9248                            external_payload_source: None,
9249                        });
9250                    }
9251                    PlatformInput::MouseMove(MouseMoveEvent {
9252                        position,
9253                        pressed_button: Some(MouseButton::Left),
9254                        modifiers: Modifiers::default(),
9255                    })
9256                }
9257                FileDropEvent::Pending { position } => {
9258                    self.mouse_position = position;
9259                    PlatformInput::MouseMove(MouseMoveEvent {
9260                        position,
9261                        pressed_button: Some(MouseButton::Left),
9262                        modifiers: Modifiers::default(),
9263                    })
9264                }
9265                FileDropEvent::Submit { position } => {
9266                    cx.activate(true);
9267                    self.mouse_position = position;
9268                    PlatformInput::MouseUp(MouseUpEvent {
9269                        button: MouseButton::Left,
9270                        position,
9271                        modifiers: Modifiers::default(),
9272                        click_count: 1,
9273                    })
9274                }
9275                FileDropEvent::Exited => {
9276                    if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
9277                        cx.active_drag.take();
9278                    }
9279                    self.refresh();
9280                    PlatformInput::FileDrop(FileDropEvent::Exited)
9281                }
9282                FileDropEvent::Ended => {
9283                    cx.end_platform_drag(self.handle.window_id());
9284                    self.refresh();
9285                    PlatformInput::FileDrop(FileDropEvent::Ended)
9286                }
9287            },
9288            PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
9289            PlatformInput::LongPress(long_press) => {
9290                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9291                    long_press.start_position
9292                } else {
9293                    long_press.position
9294                };
9295                if long_press.phase == crate::TouchPhase::Started {
9296                    self.long_press_capture = None;
9297                }
9298                PlatformInput::LongPress(long_press)
9299            }
9300            PlatformInput::TouchDrag(touch_drag) => {
9301                self.mouse_position = touch_drag.start_position;
9302                PlatformInput::TouchDrag(touch_drag)
9303            }
9304            PlatformInput::BackGesture(back) => {
9305                self.mouse_position = back.start_position;
9306                PlatformInput::BackGesture(back)
9307            }
9308            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
9309        };
9310
9311        if let Some(any_mouse_event) = event.mouse_event() {
9312            self.dispatch_mouse_event(any_mouse_event, cx);
9313        } else if let Some(any_key_event) = event.keyboard_event() {
9314            self.dispatch_key_event(any_key_event, cx);
9315        } else if let Some(touch_event) = event.touch_event() {
9316            self.dispatch_touch_event(touch_event, cx);
9317        }
9318        if let PlatformInput::LongPress(long_press) = &event {
9319            match long_press.phase {
9320                crate::TouchPhase::Started if !self.default_prevented => {
9321                    self.long_press_capture = None;
9322                }
9323                crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
9324                    self.long_press_capture = None;
9325                }
9326                crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
9327            }
9328        }
9329
9330        // Must run after the move is dispatched: the platform owns the gesture afterwards, so this
9331        // is the last chance for drag listeners to see the pointer leave and reset their state.
9332        self.promote_external_drag_to_platform(&event, cx);
9333
9334        // vue-native fork: the leave, now that its listeners have run. The
9335        // frame that drops the hover styles is asked for here.
9336        if pointer_leaves && std::mem::replace(&mut self.pointer_inside, false) {
9337            self.refresh();
9338        }
9339        self.vn_effect_pointer
9340            .update(was_inside, self.pointer_inside, pointer_moved, cx);
9341
9342        let caused_invalidation = self.invalidator.update_count() > update_count_before;
9343        if caused_invalidation {
9344            self.input_rate_tracker.borrow_mut().record_input();
9345        }
9346        #[cfg(feature = "profiler")]
9347        self.window_profiler.end_input(caused_invalidation);
9348
9349        DispatchEventResult {
9350            propagate: cx.propagate_event,
9351            default_prevented: self.default_prevented,
9352        }
9353    }
9354
9355    fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
9356        let PlatformInput::MouseMove(mouse_move) = event else {
9357            return;
9358        };
9359        if mouse_move.pressed_button != Some(MouseButton::Left) {
9360            return;
9361        }
9362        if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
9363            return;
9364        }
9365        if !self.platform_window.can_start_external_drag() {
9366            return;
9367        }
9368        let Some(payload_source) = cx
9369            .active_drag
9370            .as_mut()
9371            .and_then(|drag| drag.external_payload_source.take())
9372        else {
9373            return;
9374        };
9375        let Some(payload) = payload_source(self, cx) else {
9376            return;
9377        };
9378        if self.platform_window.start_external_drag(&payload)
9379            && cx.hand_active_drag_to_platform(self.handle.window_id())
9380        {
9381            self.refresh();
9382        }
9383    }
9384
9385    /// Whether recognized touch pans may use the platform's predicted touch
9386    /// positions ([`TouchEvent::predicted_position`]) to compensate for input
9387    /// latency. Defaults to true.
9388    pub fn touch_prediction_enabled(&self) -> bool {
9389        self.touch_prediction_enabled
9390    }
9391
9392    /// Sets whether recognized touch pans may use the platform's predicted
9393    /// touch positions. Disabling drops [`TouchEvent::predicted_position`]
9394    /// before gesture recognition, so pans track only raw touch positions.
9395    pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
9396        self.touch_prediction_enabled = enabled;
9397    }
9398
9399    /// Runs the portable gesture recognizer over a raw touch event and
9400    /// dispatches whatever it resolves (scroll steps, synthesized taps)
9401    /// through the ordinary mouse-event path.
9402    fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
9403        let mut event = event.clone();
9404        if !self.touch_prediction_enabled {
9405            event.predicted_position = None;
9406        }
9407        let recognized_gestures = self.touch_gestures.handle_event(&event);
9408        if event.phase == crate::TouchPhase::Started
9409            && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
9410        {
9411            self.dispatch_recognized_touch_gesture(touch_drag, cx);
9412        }
9413        if event.phase == crate::TouchPhase::Started
9414            && self.touch_gestures.pending_long_press().is_some()
9415        {
9416            self.long_press_capture = None;
9417        }
9418        let mut tapped = false;
9419        for gesture in recognized_gestures {
9420            tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
9421            self.dispatch_recognized_touch_gesture(gesture, cx);
9422        }
9423        if event.phase == crate::TouchPhase::Started {
9424            self.schedule_long_press_timer(cx);
9425        } else if self.touch_gestures.pending_long_press().is_none() {
9426            self.long_press_timer.take();
9427        }
9428        // The platform's touch-release handler may inspect the input handler
9429        // as soon as this dispatch returns (the web platform decides virtual
9430        // keyboard visibility there, inside the user gesture). Input handlers
9431        // are registered during draw, so draw now to make them reflect any
9432        // focus change the tap just caused.
9433        if tapped && self.invalidator.is_dirty() {
9434            self.draw(cx).clear(cx);
9435        }
9436        if self.touch_gestures.has_momentum() {
9437            self.schedule_touch_momentum_tick();
9438        }
9439    }
9440
9441    fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
9442        match gesture {
9443            RecognizedTouchGesture::Scroll(scroll_wheel) => {
9444                self.mouse_position = scroll_wheel.position;
9445                cx.propagate_event = true;
9446                self.dispatch_mouse_event(&scroll_wheel, cx);
9447            }
9448            RecognizedTouchGesture::Tap { down, up } => {
9449                self.mouse_position = up.position;
9450                cx.propagate_event = true;
9451                self.dispatch_mouse_event(&down, cx);
9452                cx.propagate_event = true;
9453                self.dispatch_mouse_event(&up, cx);
9454            }
9455            RecognizedTouchGesture::TouchDrag(touch_drag) => {
9456                self.mouse_position = touch_drag.start_position;
9457                cx.propagate_event = true;
9458                self.default_prevented = false;
9459                let started = touch_drag.phase == crate::TouchPhase::Started;
9460                self.dispatch_mouse_event(&touch_drag, cx);
9461                if started {
9462                    self.touch_gestures
9463                        .resolve_touch_drag(self.default_prevented);
9464                }
9465            }
9466            RecognizedTouchGesture::LongPress(long_press) => {
9467                self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9468                    long_press.start_position
9469                } else {
9470                    long_press.position
9471                };
9472                cx.propagate_event = true;
9473                self.default_prevented = false;
9474                let started = long_press.phase == crate::TouchPhase::Started;
9475                let ended = matches!(
9476                    long_press.phase,
9477                    crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
9478                );
9479                self.dispatch_mouse_event(&long_press, cx);
9480                if started {
9481                    let claimed = self.default_prevented;
9482                    self.touch_gestures.resolve_long_press(claimed);
9483                    if !claimed {
9484                        self.long_press_capture = None;
9485                    }
9486                }
9487                if ended {
9488                    self.long_press_capture = None;
9489                }
9490            }
9491        }
9492    }
9493
9494    fn schedule_long_press_timer(&mut self, cx: &mut App) {
9495        self.long_press_timer.take();
9496        let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
9497            return;
9498        };
9499        self.long_press_timer = Some(self.spawn(cx, async move |cx| {
9500            cx.background_executor.timer(duration).await;
9501            cx.update(move |window, cx| {
9502                window.long_press_timer.take();
9503                if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
9504                    window.dispatch_recognized_touch_gesture(gesture, cx);
9505                }
9506            })
9507            .with_context(|| {
9508                format!(
9509                    "handling long-press timer for window {:?}",
9510                    cx.window_handle().window_id()
9511                )
9512            })
9513            .log_err();
9514        }));
9515    }
9516
9517    fn schedule_touch_momentum_tick(&mut self) {
9518        self.on_next_frame(|window, cx| {
9519            if let Some(gesture) = window.touch_gestures.tick_momentum() {
9520                window.dispatch_recognized_touch_gesture(gesture, cx);
9521            }
9522            if window.touch_gestures.has_momentum() {
9523                window.schedule_touch_momentum_tick();
9524            }
9525        });
9526    }
9527
9528    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
9529        self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position(), self.scale_factor);
9530
9531        // vue-native fork: the embedder narrows a press, a release or a wheel
9532        // to the hitboxes it is FOR, before anyone hears it.
9533        if let Some(refiner) = self.vn_hit_refiner.clone() {
9534            let kind = if event.is::<crate::MouseDownEvent>() {
9535                Some(VnHitKind::Down)
9536            } else if event.is::<MouseUpEvent>() {
9537                Some(VnHitKind::Up)
9538            } else if event.is::<crate::ScrollEvent>() {
9539                Some(VnHitKind::Scroll)
9540            } else {
9541                None
9542            };
9543            if let Some(kind) = kind {
9544                let position = self.mouse_position();
9545                refiner(kind, position, self, cx);
9546            }
9547        }
9548
9549        #[cfg(any(feature = "inspector", debug_assertions))]
9550        if self.is_inspector_picking(cx) {
9551            self.reset_cursor_style(cx);
9552            self.handle_inspector_mouse_event(event, cx);
9553            // When inspector is picking, all other mouse handling is skipped.
9554            return;
9555        }
9556
9557        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
9558
9559        // Capture phase, events bubble from back to front. Handlers for this phase are used for
9560        // special purposes, such as detecting events outside of a given Bounds.
9561        for listener in &mut mouse_listeners {
9562            let listener = listener.as_mut().unwrap();
9563            listener(event, DispatchPhase::Capture, self, cx);
9564            if !cx.propagate_event {
9565                break;
9566            }
9567        }
9568
9569        // Bubble phase, where most normal handlers do their work.
9570        if cx.propagate_event {
9571            for listener in mouse_listeners.iter_mut().rev() {
9572                let listener = listener.as_mut().unwrap();
9573                listener(event, DispatchPhase::Bubble, self, cx);
9574                if !cx.propagate_event {
9575                    break;
9576                }
9577            }
9578        }
9579
9580        self.rendered_frame.mouse_listeners = mouse_listeners;
9581
9582        if cx.has_active_drag() {
9583            if event.is::<MouseMoveEvent>() {
9584                // If this was a mouse move event, redraw the window so that the
9585                // active drag can follow the mouse cursor.
9586                self.refresh();
9587            } else if event.is::<MouseUpEvent>() {
9588                // If this was a mouse up event, cancel the active drag and redraw
9589                // the window.
9590                cx.active_drag = None;
9591                self.refresh();
9592            }
9593        }
9594
9595        // Auto-release pointer capture on mouse up
9596        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
9597            self.captured_hitbox = None;
9598        }
9599
9600        // Runs after the listeners so that a drag they start takes effect in this event. Resolving
9601        // the cursor any earlier would briefly select whatever is under the pointer instead.
9602        self.reset_cursor_style(cx);
9603    }
9604
9605    // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
9606    // we prefer the text input over bindings.
9607    fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
9608        let prefer_character_input = event
9609            .downcast_ref::<KeyDownEvent>()
9610            .is_some_and(|key_down_event| key_down_event.prefer_character_input);
9611        if !prefer_character_input {
9612            return InputPreference::KeyBindings;
9613        }
9614        let Some(mut input_handler) = self.platform_window.take_input_handler() else {
9615            return InputPreference::KeyBindings;
9616        };
9617        let accepts_text_input = input_handler.accepts_text_input(self, cx);
9618        self.platform_window.set_input_handler(input_handler);
9619        if accepts_text_input {
9620            InputPreference::CharacterInput
9621        } else {
9622            InputPreference::KeyBindings
9623        }
9624    }
9625
9626    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
9627        if self.invalidator.is_dirty() {
9628            self.draw(cx).clear(cx);
9629        }
9630        // vue-native fork: `Window::vn_key_event_seq`.
9631        self.vn_key_event_seq = self.vn_key_event_seq.wrapping_add(1);
9632
9633        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9634        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9635
9636        let mut keystroke: Option<Keystroke> = None;
9637
9638        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
9639            if event.modifiers.number_of_modifiers() == 0
9640                && self.pending_modifier.modifiers.number_of_modifiers() == 1
9641                && !self.pending_modifier.saw_other_input
9642            {
9643                let key = match self.pending_modifier.modifiers {
9644                    modifiers if modifiers.shift => Some("shift"),
9645                    modifiers if modifiers.control => Some("control"),
9646                    modifiers if modifiers.alt => Some("alt"),
9647                    modifiers if modifiers.platform => Some("platform"),
9648                    modifiers if modifiers.function => Some("function"),
9649                    _ => None,
9650                };
9651                if let Some(key) = key {
9652                    keystroke = Some(Keystroke {
9653                        key: key.to_string(),
9654                        key_char: None,
9655                        modifiers: Modifiers::default(),
9656                    });
9657                }
9658            }
9659
9660            if self.pending_modifier.modifiers.number_of_modifiers() == 0
9661                && event.modifiers.number_of_modifiers() == 1
9662            {
9663                self.pending_modifier.saw_other_input = false
9664            } else if event.modifiers.number_of_modifiers() > 1 {
9665                self.pending_modifier.saw_other_input = true
9666            }
9667            self.pending_modifier.modifiers = event.modifiers
9668        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
9669            self.pending_modifier.saw_other_input = true;
9670            keystroke = Some(key_down_event.keystroke.clone());
9671            if key_down_event.keystroke.key_char.is_some()
9672                && matches!(
9673                    cx.cursor_hide_mode,
9674                    CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
9675                )
9676            {
9677                cx.platform.hide_cursor_until_mouse_moves();
9678            }
9679        }
9680
9681        let Some(keystroke) = keystroke else {
9682            self.finish_dispatch_key_event(
9683                event,
9684                None,
9685                InputPreference::KeyBindings,
9686                dispatch_path,
9687                self.context_stack(),
9688                cx,
9689            );
9690            return;
9691        };
9692
9693        let input_preference = self.input_preference(event, cx);
9694
9695        cx.propagate_event = true;
9696        self.dispatch_keystroke_interceptors(
9697            &keystroke,
9698            input_preference,
9699            self.context_stack(),
9700            cx,
9701        );
9702        if !cx.propagate_event {
9703            self.finish_dispatch_key_event(
9704                event,
9705                Some(&keystroke),
9706                input_preference,
9707                dispatch_path,
9708                self.context_stack(),
9709                cx,
9710            );
9711            return;
9712        }
9713
9714        let mut currently_pending = self.pending_input.take().unwrap_or_default();
9715        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
9716            currently_pending = PendingInput::default();
9717        }
9718
9719        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
9720            currently_pending.keystrokes,
9721            keystroke.clone(),
9722            &dispatch_path,
9723        );
9724
9725        if !match_result.to_replay.is_empty() {
9726            self.replay_pending_input(match_result.to_replay, cx);
9727            cx.propagate_event = true;
9728        }
9729
9730        if !match_result.pending.is_empty() {
9731            let previous_timeout = currently_pending.timeout.take();
9732            currently_pending.keystrokes = match_result.pending;
9733            currently_pending.focus = self.focus;
9734
9735            let text_input_requires_timeout = event
9736                .downcast_ref::<KeyDownEvent>()
9737                .filter(|key_down| key_down.keystroke.key_char.is_some())
9738                .and_then(|_| self.platform_window.take_input_handler())
9739                .map_or(false, |mut input_handler| {
9740                    let accepts = input_handler.accepts_text_input(self, cx);
9741                    self.platform_window.set_input_handler(input_handler);
9742                    accepts
9743                });
9744
9745            let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
9746            let needs_timeout = previous_timeout.is_some()
9747                || match_result.pending_has_binding
9748                || text_input_requires_timeout
9749                || standalone_modifier;
9750            currently_pending.timeout = if needs_timeout {
9751                match previous_timeout {
9752                    Some(mut timeout) if timeout.is_paused() => {
9753                        timeout.reset_duration(PENDING_INPUT_TIMEOUT);
9754                        Some(timeout)
9755                    }
9756                    previous_timeout => {
9757                        drop(previous_timeout);
9758                        Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
9759                    }
9760                }
9761            } else {
9762                None
9763            };
9764            self.pending_input = Some(currently_pending);
9765            self.pending_input_changed(cx);
9766            cx.propagate_event = false;
9767            return;
9768        }
9769
9770        // Interceptors or replayed actions may have changed whether the input handler accepts text.
9771        let input_preference = self.input_preference(event, cx);
9772        if input_preference == InputPreference::KeyBindings {
9773            for binding in match_result.bindings {
9774                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
9775                if !cx.propagate_event {
9776                    self.dispatch_keystroke_observers(
9777                        &keystroke,
9778                        input_preference,
9779                        Some(binding.action.as_ref()),
9780                        match_result.context_stack,
9781                        cx,
9782                    );
9783                    self.pending_input_changed(cx);
9784                    return;
9785                }
9786            }
9787        }
9788
9789        self.finish_dispatch_key_event(
9790            event,
9791            Some(&keystroke),
9792            input_preference,
9793            dispatch_path,
9794            match_result.context_stack,
9795            cx,
9796        );
9797        self.pending_input_changed(cx);
9798    }
9799
9800    fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
9801        let (started_at, task) = self.start_pending_input_timeout(duration, cx);
9802        PendingInputTimeout {
9803            duration,
9804            remaining: duration,
9805            state: PendingInputTimeoutState::Running { started_at, task },
9806        }
9807    }
9808
9809    fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
9810        let started_at = cx.background_executor().now();
9811        let task = self.spawn(cx, async move |cx| {
9812            cx.background_executor.timer(remaining).await;
9813            cx.update(move |window, cx| {
9814                let Some(currently_pending) = window
9815                    .pending_input
9816                    .take()
9817                    .filter(|pending| pending.focus == window.focus)
9818                else {
9819                    return;
9820                };
9821
9822                let node_id = window.focus_node_id_in_rendered_frame(window.focus);
9823                let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
9824
9825                let to_replay = window
9826                    .rendered_frame
9827                    .dispatch_tree
9828                    .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
9829
9830                window.pending_input_changed(cx);
9831                window.replay_pending_input(to_replay, cx)
9832            })
9833            .with_context(|| {
9834                format!(
9835                    "handling pending input timeout for window {:?}",
9836                    cx.window_handle().window_id()
9837                )
9838            })
9839            .log_err();
9840        });
9841        (started_at, task)
9842    }
9843
9844    fn finish_dispatch_key_event(
9845        &mut self,
9846        event: &dyn Any,
9847        recognized_keystroke: Option<&Keystroke>,
9848        input_preference: InputPreference,
9849        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
9850        context_stack: Vec<KeyContext>,
9851        cx: &mut App,
9852    ) {
9853        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
9854        if !cx.propagate_event {
9855            return;
9856        }
9857
9858        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
9859        if !cx.propagate_event {
9860            return;
9861        }
9862
9863        if let Some(keystroke) = recognized_keystroke {
9864            self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
9865        }
9866    }
9867
9868    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
9869        self.pending_input_observers
9870            .clone()
9871            .retain(|callback| callback(self, cx));
9872    }
9873
9874    fn defer_pending_input_changed(&self, cx: &mut App) {
9875        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
9876        // current effect cycle, and only for this window.
9877        let window_handle = self.handle;
9878        cx.defer(move |cx| {
9879            window_handle
9880                .update(cx, |_, window, cx| {
9881                    window.pending_input_changed(cx);
9882                })
9883                .ok();
9884        });
9885    }
9886
9887    fn dispatch_key_down_up_event(
9888        &mut self,
9889        event: &dyn Any,
9890        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9891        cx: &mut App,
9892    ) {
9893        // Capture phase
9894        for node_id in dispatch_path {
9895            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9896
9897            for key_listener in node.key_listeners.clone() {
9898                key_listener(event, DispatchPhase::Capture, self, cx);
9899                if !cx.propagate_event {
9900                    return;
9901                }
9902            }
9903        }
9904
9905        // Bubble phase
9906        for node_id in dispatch_path.iter().rev() {
9907            // Handle low level key events
9908            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9909            for key_listener in node.key_listeners.clone() {
9910                key_listener(event, DispatchPhase::Bubble, self, cx);
9911                if !cx.propagate_event {
9912                    return;
9913                }
9914            }
9915        }
9916    }
9917
9918    fn dispatch_modifiers_changed_event(
9919        &mut self,
9920        event: &dyn Any,
9921        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9922        cx: &mut App,
9923    ) {
9924        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
9925            return;
9926        };
9927        for node_id in dispatch_path.iter().rev() {
9928            let node = self.rendered_frame.dispatch_tree.node(*node_id);
9929            for listener in node.modifiers_changed_listeners.clone() {
9930                listener(event, self, cx);
9931                if !cx.propagate_event {
9932                    return;
9933                }
9934            }
9935        }
9936    }
9937
9938    /// Determine whether a potential multi-stroke key binding is in progress on this window.
9939    pub fn has_pending_keystrokes(&self) -> bool {
9940        self.pending_input().is_some()
9941    }
9942
9943    #[cfg(test)]
9944    pub(crate) fn pending_input_is_none(&self) -> bool {
9945        self.pending_input.is_none()
9946    }
9947
9948    pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
9949        if self.pending_input.take().is_some() {
9950            self.defer_pending_input_changed(cx);
9951        }
9952    }
9953
9954    /// Returns pending input that can still complete a multi-stroke key binding. Input left over
9955    /// from a previous focus can never complete one.
9956    pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
9957        self.pending_input
9958            .as_ref()
9959            .filter(|pending_input| pending_input.focus == self.focus)
9960            .map(|pending_input| PendingInputStatus {
9961                keystrokes: pending_input.keystrokes.as_slice(),
9962                timeout: pending_input
9963                    .timeout
9964                    .as_ref()
9965                    .map(PendingInputTimeout::status),
9966            })
9967    }
9968
9969    /// Pauses or resumes the current pending input timeout on behalf of `owner`.
9970    ///
9971    /// A paused timeout resumes automatically if `owner` is released. Returns whether the timeout
9972    /// state changed. A timeout paused by one owner cannot be resumed by another.
9973    pub fn set_pending_input_timeout_paused<T: 'static>(
9974        &mut self,
9975        owner: &Entity<T>,
9976        paused: bool,
9977        cx: &mut App,
9978    ) -> bool {
9979        let owner_id = owner.entity_id();
9980        if !paused {
9981            return self.resume_pending_input_timeout(owner_id, cx);
9982        }
9983
9984        let timeout = self
9985            .pending_input
9986            .as_ref()
9987            .filter(|pending_input| pending_input.focus == self.focus)
9988            .and_then(|pending_input| pending_input.timeout.as_ref());
9989        let Some(timeout) = timeout else {
9990            return false;
9991        };
9992        if timeout.is_paused() {
9993            return false;
9994        }
9995
9996        let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
9997            window.resume_pending_input_timeout(owner_id, cx);
9998        });
9999        let now = cx.background_executor().now();
10000        let changed = self
10001            .pending_input
10002            .as_mut()
10003            .filter(|pending_input| pending_input.focus == self.focus)
10004            .and_then(|pending_input| pending_input.timeout.as_mut())
10005            .is_some_and(|timeout| {
10006                timeout.pause(
10007                    PendingInputTimeoutPause {
10008                        owner_id,
10009                        _release_subscription: release_subscription,
10010                    },
10011                    now,
10012                )
10013            });
10014
10015        if changed {
10016            self.defer_pending_input_changed(cx);
10017        }
10018        changed
10019    }
10020
10021    fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
10022        let Some(remaining) = self
10023            .pending_input
10024            .as_ref()
10025            .and_then(|pending_input| pending_input.timeout.as_ref())
10026            .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
10027            .map(|timeout| timeout.remaining)
10028        else {
10029            return false;
10030        };
10031
10032        let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
10033        let changed = self
10034            .pending_input
10035            .as_mut()
10036            .and_then(|pending_input| pending_input.timeout.as_mut())
10037            .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
10038
10039        if changed {
10040            self.defer_pending_input_changed(cx);
10041        }
10042        changed
10043    }
10044
10045    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
10046    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
10047        self.pending_input()
10048            .map(|pending_input| pending_input.keystrokes())
10049    }
10050
10051    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
10052        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10053        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
10054
10055        'replay: for replay in replays {
10056            let event = KeyDownEvent {
10057                keystroke: replay.keystroke.clone(),
10058                is_held: false,
10059                prefer_character_input: true,
10060            };
10061
10062            cx.propagate_event = true;
10063            for binding in replay.bindings {
10064                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
10065                if !cx.propagate_event {
10066                    self.dispatch_keystroke_observers(
10067                        &replay.keystroke,
10068                        InputPreference::KeyBindings,
10069                        Some(binding.action.as_ref()),
10070                        Vec::default(),
10071                        cx,
10072                    );
10073                    continue 'replay;
10074                }
10075            }
10076
10077            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
10078            if !cx.propagate_event {
10079                continue 'replay;
10080            }
10081            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
10082                && let Some(mut input_handler) = self.platform_window.take_input_handler()
10083            {
10084                input_handler.dispatch_input(&input, self, cx);
10085                self.platform_window.set_input_handler(input_handler)
10086            }
10087        }
10088    }
10089
10090    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
10091        focus_id
10092            .and_then(|focus_id| {
10093                self.rendered_frame
10094                    .dispatch_tree
10095                    .focusable_node_id(focus_id)
10096            })
10097            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
10098    }
10099
10100    fn dispatch_action_on_node(
10101        &mut self,
10102        node_id: DispatchNodeId,
10103        action: &dyn Action,
10104        cx: &mut App,
10105    ) {
10106        self.dispatch_action_on_node_inner(node_id, action, cx);
10107
10108        if !cx.propagate_event
10109            && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
10110            && self.last_input_was_keyboard()
10111        {
10112            cx.platform.hide_cursor_until_mouse_moves();
10113        }
10114    }
10115
10116    fn dispatch_action_on_node_inner(
10117        &mut self,
10118        node_id: DispatchNodeId,
10119        action: &dyn Action,
10120        cx: &mut App,
10121    ) {
10122        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
10123
10124        // Capture phase for global actions.
10125        cx.propagate_event = true;
10126        if let Some(mut global_listeners) = cx
10127            .global_action_listeners
10128            .remove(&action.as_any().type_id())
10129        {
10130            for listener in &global_listeners {
10131                #[cfg(feature = "profiler")]
10132                self.window_profiler.begin_action_handler(action, cx);
10133                listener(action.as_any(), DispatchPhase::Capture, cx);
10134                #[cfg(feature = "profiler")]
10135                self.window_profiler.end_action_handler();
10136                if !cx.propagate_event {
10137                    break;
10138                }
10139            }
10140
10141            global_listeners.extend(
10142                cx.global_action_listeners
10143                    .remove(&action.as_any().type_id())
10144                    .unwrap_or_default(),
10145            );
10146
10147            cx.global_action_listeners
10148                .insert(action.as_any().type_id(), global_listeners);
10149        }
10150
10151        if !cx.propagate_event {
10152            return;
10153        }
10154
10155        // Capture phase for window actions.
10156        for node_id in &dispatch_path {
10157            let node = self.rendered_frame.dispatch_tree.node(*node_id);
10158            for DispatchActionListener {
10159                action_type,
10160                listener,
10161            } in node.action_listeners.clone()
10162            {
10163                let any_action = action.as_any();
10164                if action_type == any_action.type_id() {
10165                    #[cfg(feature = "profiler")]
10166                    self.window_profiler.begin_action_handler(action, cx);
10167                    listener(any_action, DispatchPhase::Capture, self, cx);
10168                    #[cfg(feature = "profiler")]
10169                    self.window_profiler.end_action_handler();
10170
10171                    if !cx.propagate_event {
10172                        return;
10173                    }
10174                }
10175            }
10176        }
10177
10178        // Bubble phase for window actions.
10179        for node_id in dispatch_path.iter().rev() {
10180            let node = self.rendered_frame.dispatch_tree.node(*node_id);
10181            for DispatchActionListener {
10182                action_type,
10183                listener,
10184            } in node.action_listeners.clone()
10185            {
10186                let any_action = action.as_any();
10187                if action_type == any_action.type_id() {
10188                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
10189                    #[cfg(feature = "profiler")]
10190                    self.window_profiler.begin_action_handler(action, cx);
10191                    listener(any_action, DispatchPhase::Bubble, self, cx);
10192                    #[cfg(feature = "profiler")]
10193                    self.window_profiler.end_action_handler();
10194
10195                    if !cx.propagate_event {
10196                        return;
10197                    }
10198                }
10199            }
10200        }
10201
10202        // Bubble phase for global actions.
10203        if let Some(mut global_listeners) = cx
10204            .global_action_listeners
10205            .remove(&action.as_any().type_id())
10206        {
10207            for listener in global_listeners.iter().rev() {
10208                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
10209
10210                #[cfg(feature = "profiler")]
10211                self.window_profiler.begin_action_handler(action, cx);
10212                listener(action.as_any(), DispatchPhase::Bubble, cx);
10213                #[cfg(feature = "profiler")]
10214                self.window_profiler.end_action_handler();
10215                if !cx.propagate_event {
10216                    break;
10217                }
10218            }
10219
10220            global_listeners.extend(
10221                cx.global_action_listeners
10222                    .remove(&action.as_any().type_id())
10223                    .unwrap_or_default(),
10224            );
10225
10226            cx.global_action_listeners
10227                .insert(action.as_any().type_id(), global_listeners);
10228        }
10229    }
10230
10231    /// Register the given handler to be invoked whenever the global of the given type
10232    /// is updated.
10233    pub fn observe_global<G: Global>(
10234        &mut self,
10235        cx: &mut App,
10236        f: impl Fn(&mut Window, &mut App) + 'static,
10237    ) -> Subscription {
10238        let window_handle = self.handle;
10239        let (subscription, activate) = cx.global_observers.insert_pending(
10240            TypeId::of::<G>(),
10241            Box::new(move |cx| {
10242                window_handle
10243                    .update(cx, |_, window, cx| f(window, cx))
10244                    .is_ok()
10245            }),
10246        );
10247        cx.defer(move |_| activate());
10248        subscription
10249    }
10250
10251    /// Focus the current window and bring it to the foreground at the platform level.
10252    pub fn activate_window(&self) {
10253        self.platform_window.activate();
10254    }
10255
10256    /// Shows a previously hidden window, optionally requesting focus. Returns
10257    /// false if unsupported; otherwise `completed` reports the native result.
10258    pub fn show_window(
10259        &self,
10260        activate: bool,
10261        should_show: impl FnOnce() -> bool + 'static,
10262        completed: impl FnOnce(bool) + 'static,
10263    ) -> bool {
10264        self.platform_window.show_window(activate, Box::new(should_show), Box::new(completed))
10265    }
10266
10267    /// Requests that the operating system draw attention to this window.
10268    pub fn request_attention(&self) {
10269        self.platform_window.request_attention();
10270    }
10271
10272    /// Minimize the current window at the platform level.
10273    pub fn minimize_window(&self) {
10274        self.platform_window.minimize();
10275    }
10276
10277    /// Toggle full screen status on the current window at the platform level.
10278    pub fn toggle_fullscreen(&self) {
10279        self.platform_window.toggle_fullscreen();
10280    }
10281
10282    /// Toggle simple (borderless) fullscreen, where the window covers the entire
10283    /// screen including the menu bar and, on notched displays, the area around the
10284    /// notch. Unlike [`Window::toggle_fullscreen`], this does not move the window
10285    /// into its own Mission Control space. Only has an effect on macOS.
10286    pub fn toggle_simple_fullscreen(&self) {
10287        self.platform_window.toggle_simple_fullscreen();
10288    }
10289
10290    /// Updates the IME panel position suggestions for languages like japanese, chinese.
10291    pub fn invalidate_character_coordinates(&self) {
10292        self.on_next_frame(|window, cx| {
10293            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
10294                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
10295                    window.platform_window.update_ime_position(bounds);
10296                }
10297                window.platform_window.set_input_handler(input_handler);
10298            }
10299        });
10300    }
10301
10302    /// Present a platform dialog.
10303    /// The provided message will be presented, along with buttons for each answer.
10304    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
10305    pub fn prompt<T>(
10306        &mut self,
10307        level: PromptLevel,
10308        message: &str,
10309        detail: Option<&str>,
10310        answers: &[T],
10311        cx: &mut App,
10312    ) -> oneshot::Receiver<usize>
10313    where
10314        T: Clone + Into<PromptButton>,
10315    {
10316        let prompt_builder = cx.prompt_builder.take();
10317        let Some(prompt_builder) = prompt_builder else {
10318            unreachable!("Re-entrant window prompting is not supported by GPUI");
10319        };
10320
10321        let answers = answers
10322            .iter()
10323            .map(|answer| answer.clone().into())
10324            .collect::<Vec<_>>();
10325
10326        let receiver = match &prompt_builder {
10327            PromptBuilder::Default => self
10328                .platform_window
10329                .prompt(level, message, detail, &answers)
10330                .unwrap_or_else(|| {
10331                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10332                }),
10333            PromptBuilder::Custom(_) => {
10334                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10335            }
10336        };
10337
10338        cx.prompt_builder = Some(prompt_builder);
10339
10340        receiver
10341    }
10342
10343    fn build_custom_prompt(
10344        &mut self,
10345        prompt_builder: &PromptBuilder,
10346        level: PromptLevel,
10347        message: &str,
10348        detail: Option<&str>,
10349        answers: &[PromptButton],
10350        cx: &mut App,
10351    ) -> oneshot::Receiver<usize> {
10352        let (sender, receiver) = oneshot::channel();
10353        let handle = PromptHandle::new(sender);
10354        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
10355        self.prompt = Some(handle);
10356        receiver
10357    }
10358
10359    /// Returns whether a prompt rendered by GPUI is currently active in this window.
10360    ///
10361    /// This is only true for prompts rendered in the window (see
10362    /// [`App::set_prompt_builder`]), not for platform-native prompt dialogs.
10363    pub fn has_active_prompt(&self) -> bool {
10364        self.prompt.is_some()
10365    }
10366
10367    /// Returns the current context stack.
10368    pub fn context_stack(&self) -> Vec<KeyContext> {
10369        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10370        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10371        dispatch_tree
10372            .dispatch_path(node_id)
10373            .iter()
10374            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
10375            .collect()
10376    }
10377
10378    /// Returns all available actions for the focused element.
10379    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
10380        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10381        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
10382        for action_type in cx.global_action_listeners.keys() {
10383            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
10384                let action = cx.actions.build_action_type(action_type).ok();
10385                if let Some(action) = action {
10386                    actions.insert(ix, action);
10387                }
10388            }
10389        }
10390        actions
10391    }
10392
10393    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
10394    /// returned in the order they were added. For display, the last binding should take precedence.
10395    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
10396        self.rendered_frame
10397            .dispatch_tree
10398            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
10399    }
10400
10401    /// Returns the highest precedence key binding that invokes an action on the currently focused
10402    /// element. This is more efficient than getting the last result of `bindings_for_action`.
10403    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
10404        self.rendered_frame
10405            .dispatch_tree
10406            .highest_precedence_binding_for_action(
10407                action,
10408                &self.rendered_frame.dispatch_tree.context_stack,
10409            )
10410    }
10411
10412    /// Returns the key bindings for an action in a context.
10413    pub fn bindings_for_action_in_context(
10414        &self,
10415        action: &dyn Action,
10416        context: KeyContext,
10417    ) -> Vec<KeyBinding> {
10418        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10419        dispatch_tree.bindings_for_action(action, &[context])
10420    }
10421
10422    /// Returns the highest precedence key binding for an action in a context. This is more
10423    /// efficient than getting the last result of `bindings_for_action_in_context`.
10424    pub fn highest_precedence_binding_for_action_in_context(
10425        &self,
10426        action: &dyn Action,
10427        context: KeyContext,
10428    ) -> Option<KeyBinding> {
10429        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10430        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
10431    }
10432
10433    /// Returns any bindings that would invoke an action on the given focus handle if it were
10434    /// focused. Bindings are returned in the order they were added. For display, the last binding
10435    /// should take precedence.
10436    pub fn bindings_for_action_in(
10437        &self,
10438        action: &dyn Action,
10439        focus_handle: &FocusHandle,
10440    ) -> Vec<KeyBinding> {
10441        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10442        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
10443            return vec![];
10444        };
10445        dispatch_tree.bindings_for_action(action, &context_stack)
10446    }
10447
10448    /// Returns the highest precedence key binding that would invoke an action on the given focus
10449    /// handle if it were focused. This is more efficient than getting the last result of
10450    /// `bindings_for_action_in`.
10451    pub fn highest_precedence_binding_for_action_in(
10452        &self,
10453        action: &dyn Action,
10454        focus_handle: &FocusHandle,
10455    ) -> Option<KeyBinding> {
10456        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10457        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
10458        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
10459    }
10460
10461    /// Find the bindings that can follow the current input sequence for the current context stack.
10462    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
10463        self.rendered_frame
10464            .dispatch_tree
10465            .possible_next_bindings_for_input(input, &self.context_stack())
10466    }
10467
10468    fn context_stack_for_focus_handle(
10469        &self,
10470        focus_handle: &FocusHandle,
10471    ) -> Option<Vec<KeyContext>> {
10472        let dispatch_tree = &self.rendered_frame.dispatch_tree;
10473        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
10474        let context_stack: Vec<_> = dispatch_tree
10475            .dispatch_path(node_id)
10476            .into_iter()
10477            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
10478            .collect();
10479        Some(context_stack)
10480    }
10481
10482    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
10483    pub fn listener_for<T: 'static, E>(
10484        &self,
10485        view: &Entity<T>,
10486        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
10487    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
10488        let view = view.downgrade();
10489        move |e: &E, window: &mut Window, cx: &mut App| {
10490            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
10491        }
10492    }
10493
10494    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
10495    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
10496        &self,
10497        entity: &Entity<E>,
10498        f: Callback,
10499    ) -> impl Fn(&mut Window, &mut App) + 'static {
10500        let entity = entity.downgrade();
10501        move |window: &mut Window, cx: &mut App| {
10502            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
10503        }
10504    }
10505
10506    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
10507    /// If the callback returns false, the window won't be closed.
10508    pub fn on_window_should_close(
10509        &self,
10510        cx: &App,
10511        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
10512    ) {
10513        let mut cx = self.to_async(cx);
10514        self.platform_window.on_should_close(Box::new(move || {
10515            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
10516        }))
10517    }
10518
10519    /// Register an action listener on this node for the next frame. The type of action
10520    /// is determined by the first parameter of the given listener. When the next frame is rendered
10521    /// the listener will be cleared.
10522    ///
10523    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
10524    /// a specific need to register a listener yourself.
10525    ///
10526    /// This method should only be called as part of the paint phase of element drawing.
10527    pub fn on_action(
10528        &mut self,
10529        action_type: TypeId,
10530        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10531    ) {
10532        self.invalidator.debug_assert_paint();
10533
10534        self.next_frame
10535            .dispatch_tree
10536            .on_action(action_type, Rc::new(listener));
10537    }
10538
10539    /// Register a capturing action listener on this node for the next frame if the condition is true.
10540    /// The type of action is determined by the first parameter of the given listener. When the next
10541    /// frame is rendered the listener will be cleared.
10542    ///
10543    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
10544    /// a specific need to register a listener yourself.
10545    ///
10546    /// This method should only be called as part of the paint phase of element drawing.
10547    pub fn on_action_when(
10548        &mut self,
10549        condition: bool,
10550        action_type: TypeId,
10551        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10552    ) {
10553        self.invalidator.debug_assert_paint();
10554
10555        if condition {
10556            self.next_frame
10557                .dispatch_tree
10558                .on_action(action_type, Rc::new(listener));
10559        }
10560    }
10561
10562    /// Read information about the GPU backing this window.
10563    /// Currently returns None on Mac and Windows.
10564    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
10565        self.platform_window.gpu_specs()
10566    }
10567
10568    /// Perform titlebar double-click action.
10569    /// This is macOS specific.
10570    pub fn titlebar_double_click(&self) {
10571        self.platform_window
10572            .titlebar_double_click(self.is_resizable, self.is_minimizable);
10573    }
10574
10575    /// Gets the window's title at the platform level.
10576    /// This is macOS specific.
10577    pub fn window_title(&self) -> String {
10578        self.platform_window.get_title()
10579    }
10580
10581    /// Returns a list of all tabbed windows and their titles.
10582    /// This is macOS specific.
10583    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
10584        self.platform_window.tabbed_windows()
10585    }
10586
10587    /// Returns the tab bar visibility.
10588    /// This is macOS specific.
10589    pub fn tab_bar_visible(&self) -> bool {
10590        self.platform_window.tab_bar_visible()
10591    }
10592
10593    /// Merges all open windows into a single tabbed window.
10594    /// This is macOS specific.
10595    pub fn merge_all_windows(&self) {
10596        self.platform_window.merge_all_windows()
10597    }
10598
10599    /// Moves the tab to a new containing window.
10600    /// This is macOS specific.
10601    pub fn move_tab_to_new_window(&self) {
10602        self.platform_window.move_tab_to_new_window()
10603    }
10604
10605    /// Shows or hides the window tab overview.
10606    /// This is macOS specific.
10607    pub fn toggle_window_tab_overview(&self) {
10608        self.platform_window.toggle_window_tab_overview()
10609    }
10610
10611    /// Sets the tabbing identifier for the window.
10612    /// This is macOS specific.
10613    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
10614        self.platform_window
10615            .set_tabbing_identifier(tabbing_identifier)
10616    }
10617
10618    /// Request the OS to play an alert sound. On some platforms this is associated
10619    /// with the window, for others it's just a simple global function call.
10620    pub fn play_system_bell(&self) {
10621        self.platform_window.play_system_bell()
10622    }
10623
10624    /// Returns whether accessibility support is enabled for this window.
10625    ///
10626    /// This is false when the app was created with [`crate::Application::new_inaccessible`].
10627    /// Unlike [`Self::is_a11y_active`], this does not depend on whether assistive
10628    /// technology is currently connected, so it can be used to gate subscriptions
10629    /// that are only needed for accessibility.
10630    pub fn is_a11y_enabled(&self) -> bool {
10631        self.a11y.is_enabled()
10632    }
10633
10634    /// Returns whether accessibility features are active for this frame,
10635    /// i.e. whether assistive technology (such as a screen reader) is
10636    /// connected and an accessibility tree is being built.
10637    ///
10638    /// Use this to skip computing data during rendering that is only
10639    /// observable through the accessibility tree. When accessibility is
10640    /// activated, a redraw is forced, so gated work is recomputed before the
10641    /// next tree update is sent to the platform.
10642    ///
10643    /// See the [accessibility guide](crate::_accessibility) for an overview.
10644    pub fn is_a11y_active(&self) -> bool {
10645        self.a11y.is_active()
10646    }
10647
10648    /// Debug representation of the last frame's accessibility information.
10649    pub fn debug_a11y_tree_json(&self) -> Option<String> {
10650        self.a11y.debug_tree_json()
10651    }
10652
10653    /// Register a listener for an accessibility action on a specific node.
10654    /// The listener will be called when a screen reader requests the given
10655    /// action on the node identified by `node_id`.
10656    ///
10657    /// See the [accessibility guide](crate::_accessibility) for an overview.
10658    pub fn on_a11y_action(
10659        &mut self,
10660        node_id: accesskit::NodeId,
10661        action: accesskit::Action,
10662        listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
10663    ) {
10664        self.a11y
10665            .action_listeners
10666            .entry(node_id)
10667            .or_default()
10668            .push((action, Box::new(listener)));
10669    }
10670
10671    #[cfg(not(target_family = "wasm"))]
10672    pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
10673        // Take listeners out temporarily so the closures can borrow Window
10674        // mutably, then restore them afterward.
10675        if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
10676            let extra_data = request.data.as_ref();
10677            let mut matched = false;
10678            for (action, listener) in &mut listeners {
10679                if *action == request.action {
10680                    listener(extra_data, self, cx);
10681                    matched = true;
10682                }
10683            }
10684            self.a11y
10685                .action_listeners
10686                .insert(request.target_node, listeners);
10687            if matched {
10688                return;
10689            }
10690        }
10691
10692        // Fall back to built-in action handling.
10693        match request.action {
10694            accesskit::Action::Click => {
10695                if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
10696                    let center = bounds.center();
10697                    let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
10698                        button: MouseButton::Left,
10699                        position: center,
10700                        modifiers: Modifiers::default(),
10701                        click_count: 1,
10702                        first_mouse: false,
10703                    });
10704                    let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
10705                        button: MouseButton::Left,
10706                        position: center,
10707                        modifiers: Modifiers::default(),
10708                        click_count: 1,
10709                    });
10710                    self.dispatch_event(mouse_down, cx);
10711                    self.dispatch_event(mouse_up, cx);
10712                }
10713            }
10714            accesskit::Action::Focus => {
10715                if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
10716                    && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
10717                {
10718                    self.focus(&handle, cx);
10719                }
10720            }
10721            accesskit::Action::Blur => {
10722                self.blur(cx);
10723            }
10724            _ => {
10725                log::debug!(
10726                    "Unhandled a11y action: {:?} on {:?}",
10727                    request.action,
10728                    request.target_node
10729                );
10730            }
10731        }
10732    }
10733
10734    /// Toggles the inspector mode on this window.
10735    #[cfg(any(feature = "inspector", debug_assertions))]
10736    pub fn toggle_inspector(&mut self, cx: &mut App) {
10737        self.inspector = match self.inspector {
10738            None => Some(cx.new(|_| Inspector::new())),
10739            Some(_) => {
10740                self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
10741                self.rendered_frame.inspector_hitboxes = FxHashMap::default();
10742                self.next_frame.next_inspector_instance_ids = FxHashMap::default();
10743                self.next_frame.inspector_hitboxes = FxHashMap::default();
10744                None
10745            }
10746        };
10747        self.refresh();
10748    }
10749
10750    /// Returns true if the window is in inspector mode.
10751    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
10752        #[cfg(any(feature = "inspector", debug_assertions))]
10753        {
10754            if let Some(inspector) = &self.inspector {
10755                return inspector.read(_cx).is_picking();
10756            }
10757        }
10758        false
10759    }
10760
10761    /// Executes the provided function with mutable access to an inspector state.
10762    #[cfg(any(feature = "inspector", debug_assertions))]
10763    pub fn with_inspector_state<T: 'static, R>(
10764        &mut self,
10765        inspector_id: Option<&crate::InspectorElementId>,
10766        cx: &mut App,
10767        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
10768    ) -> Option<R> {
10769        let inspector_id = inspector_id?;
10770        let inspector = self.inspector.as_ref()?;
10771        if inspector.read(cx).active_element_id() != Some(inspector_id) {
10772            return None;
10773        }
10774        let inspector = inspector.clone();
10775        Some(inspector.update(cx, |inspector, _cx| {
10776            inspector.with_active_element_state(self, f)
10777        }))
10778    }
10779
10780    #[cfg(any(feature = "inspector", debug_assertions))]
10781    pub(crate) fn inspector_enabled(&self) -> bool {
10782        self.inspector.is_some()
10783    }
10784
10785    #[cfg(any(feature = "inspector", debug_assertions))]
10786    pub(crate) fn build_inspector_element_id(
10787        &mut self,
10788        path: crate::InspectorElementPath,
10789    ) -> crate::InspectorElementId {
10790        self.invalidator.debug_assert_paint_or_prepaint();
10791        let path = Rc::new(path);
10792        let next_instance_id = self
10793            .next_frame
10794            .next_inspector_instance_ids
10795            .entry(path.clone())
10796            .or_insert(0);
10797        let instance_id = *next_instance_id;
10798        *next_instance_id += 1;
10799        crate::InspectorElementId { path, instance_id }
10800    }
10801
10802    #[cfg(any(feature = "inspector", debug_assertions))]
10803    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
10804        if let Some(inspector) = self.inspector.take() {
10805            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
10806            inspector_element.prepaint_as_root(
10807                point(self.viewport_size.width - inspector_width, px(0.0)),
10808                size(inspector_width, self.viewport_size.height).into(),
10809                self,
10810                cx,
10811            );
10812            self.inspector = Some(inspector);
10813            Some(inspector_element)
10814        } else {
10815            None
10816        }
10817    }
10818
10819    #[cfg(any(feature = "inspector", debug_assertions))]
10820    fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
10821        if let Some(mut inspector_element) = inspector_element {
10822            inspector_element.paint(self, cx);
10823        };
10824    }
10825
10826    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
10827    /// inspect UI elements by clicking on them.
10828    #[cfg(any(feature = "inspector", debug_assertions))]
10829    pub fn insert_inspector_hitbox(
10830        &mut self,
10831        hitbox_id: HitboxId,
10832        inspector_id: Option<&crate::InspectorElementId>,
10833        cx: &App,
10834    ) {
10835        self.invalidator.debug_assert_paint_or_prepaint();
10836        if !self.is_inspector_picking(cx) {
10837            return;
10838        }
10839        if let Some(inspector_id) = inspector_id {
10840            self.next_frame
10841                .inspector_hitboxes
10842                .insert(hitbox_id, inspector_id.clone());
10843        }
10844    }
10845
10846    #[cfg(any(feature = "inspector", debug_assertions))]
10847    fn paint_inspector_hitbox(&mut self, cx: &App) {
10848        if let Some(inspector) = self.inspector.as_ref() {
10849            let inspector = inspector.read(cx);
10850            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
10851                && let Some(hitbox) = self
10852                    .next_frame
10853                    .hitboxes
10854                    .iter()
10855                    .find(|hitbox| hitbox.id == hitbox_id)
10856            {
10857                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
10858            }
10859        }
10860    }
10861
10862    #[cfg(any(feature = "inspector", debug_assertions))]
10863    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
10864        let Some(inspector) = self.inspector.clone() else {
10865            return;
10866        };
10867        if event.downcast_ref::<MouseMoveEvent>().is_some() {
10868            inspector.update(cx, |inspector, _cx| {
10869                if let Some((_, inspector_id)) =
10870                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10871                {
10872                    inspector.hover(inspector_id, self);
10873                }
10874            });
10875        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
10876            inspector.update(cx, |inspector, _cx| {
10877                if let Some((_, inspector_id)) =
10878                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10879                {
10880                    inspector.select(inspector_id, self);
10881                }
10882            });
10883        } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
10884            // This should be kept in sync with SCROLL_LINES in x11 platform.
10885            const SCROLL_LINES: f32 = 3.0;
10886            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
10887            let delta_y = event
10888                .delta
10889                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
10890                .y;
10891            if let Some(inspector) = self.inspector.clone() {
10892                inspector.update(cx, |inspector, _cx| {
10893                    if let Some(depth) = inspector.pick_depth.as_mut() {
10894                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
10895                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
10896                        if *depth < 0.0 {
10897                            *depth = 0.0;
10898                        } else if *depth > max_depth {
10899                            *depth = max_depth;
10900                        }
10901                        if let Some((_, inspector_id)) =
10902                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10903                        {
10904                            inspector.set_active_element_id(inspector_id, self);
10905                        }
10906                    }
10907                });
10908            }
10909        }
10910    }
10911
10912    #[cfg(any(feature = "inspector", debug_assertions))]
10913    fn hovered_inspector_hitbox(
10914        &self,
10915        inspector: &Inspector,
10916        frame: &Frame,
10917    ) -> Option<(HitboxId, crate::InspectorElementId)> {
10918        if let Some(pick_depth) = inspector.pick_depth {
10919            let depth = (pick_depth as i64).try_into().unwrap_or(0);
10920            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
10921            let skip_count = (depth as usize).min(max_skipped);
10922            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
10923                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
10924                    return Some((*hitbox_id, inspector_id.clone()));
10925                }
10926            }
10927        }
10928        None
10929    }
10930
10931    /// For testing: set the current modifier keys state.
10932    /// This does not generate any events.
10933    #[cfg(any(test, feature = "test-support"))]
10934    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
10935        self.modifiers = modifiers;
10936    }
10937
10938    /// For testing: simulate a mouse move event to the given position.
10939    /// This dispatches the event through the normal event handling path,
10940    /// which will trigger hover states and tooltips.
10941    #[cfg(any(test, feature = "test-support"))]
10942    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
10943        let event = PlatformInput::MouseMove(MouseMoveEvent {
10944            position,
10945            modifiers: self.modifiers,
10946            pressed_button: None,
10947        });
10948        let _ = self.dispatch_event(event, cx);
10949    }
10950
10951    #[inline(never)]
10952    fn take_element_state(
10953        &mut self,
10954        global_id: &GlobalElementId,
10955        state_type: TypeId,
10956    ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
10957        let key = (global_id.clone(), state_type);
10958        self.next_frame.accessed_element_states.push(key.clone());
10959        let state = self
10960            .next_frame
10961            .element_states
10962            .remove(&key)
10963            .or_else(|| self.rendered_frame.element_states.remove(&key));
10964        (key, state)
10965    }
10966
10967    #[inline(never)]
10968    fn insert_element_state(
10969        &mut self,
10970        key: (GlobalElementId, TypeId),
10971        state: ElementStateBox,
10972    ) -> Option<ElementStateBox> {
10973        self.next_frame.element_states.insert(key, state)
10974    }
10975
10976    #[inline(never)]
10977    fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
10978        cx.observe(state, move |_, cx| {
10979            cx.notify(current_view);
10980        })
10981        .detach();
10982    }
10983}
10984
10985// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
10986slotmap::new_key_type! {
10987    /// A unique identifier for a window.
10988    pub struct WindowId;
10989}
10990
10991impl WindowId {
10992    /// Converts this window ID to a `u64`.
10993    pub fn as_u64(&self) -> u64 {
10994        self.0.as_ffi()
10995    }
10996}
10997
10998impl From<u64> for WindowId {
10999    fn from(value: u64) -> Self {
11000        WindowId(slotmap::KeyData::from_ffi(value))
11001    }
11002}
11003
11004/// A handle to a window with a specific root view type.
11005/// Note that this does not keep the window alive on its own.
11006pub struct WindowHandle<V> {
11007    pub(crate) any_handle: AnyWindowHandle,
11008    state_type: PhantomData<fn(V) -> V>,
11009}
11010
11011impl_deref!([V] WindowHandle<V> => mut any_handle: AnyWindowHandle);
11012
11013impl<V> Debug for WindowHandle<V> {
11014    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11015        f.debug_struct("WindowHandle")
11016            .field("any_handle", &self.any_handle.id.as_u64())
11017            .finish()
11018    }
11019}
11020
11021impl<V: 'static + Render> WindowHandle<V> {
11022    /// Creates a new handle from a window ID.
11023    /// This does not check if the root type of the window is `V`.
11024    pub fn new(id: WindowId) -> Self {
11025        WindowHandle {
11026            any_handle: AnyWindowHandle {
11027                id,
11028                state_type: TypeId::of::<V>(),
11029                root_entity_type_name: std::any::type_name::<V>(),
11030            },
11031            state_type: PhantomData,
11032        }
11033    }
11034
11035    /// Get the root view out of this window.
11036    ///
11037    /// This will fail if the window is closed or if the root view's type does not match `V`.
11038    #[cfg(any(test, feature = "test-support"))]
11039    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
11040    where
11041        C: AppContext,
11042    {
11043        cx.update_window(self.any_handle, |root_view, _, _| {
11044            root_view
11045                .downcast::<V>()
11046                .map_err(|_| anyhow!("the type of the window's root view has changed"))
11047        })?
11048    }
11049
11050    /// Updates the root view of this window.
11051    ///
11052    /// This will fail if the window has been closed or if the root view's type does not match
11053    #[track_caller]
11054    pub fn update<C, R>(
11055        &self,
11056        cx: &mut C,
11057        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
11058    ) -> Result<R>
11059    where
11060        C: AppContext,
11061    {
11062        cx.update_window(self.any_handle, |root_view, window, cx| {
11063            let view = root_view
11064                .downcast::<V>()
11065                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
11066
11067            Ok(view.update(cx, |view, cx| update(view, window, cx)))
11068        })?
11069    }
11070
11071    /// Read the root view out of this window.
11072    ///
11073    /// This will fail if the window is closed or if the root view's type does not match `V`.
11074    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
11075        let x = cx
11076            .windows
11077            .get(self.id)
11078            .and_then(|window| {
11079                window
11080                    .as_deref()
11081                    .and_then(|window| window.root.clone())
11082                    .map(|root_view| root_view.downcast::<V>())
11083            })
11084            .context("window not found")?
11085            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
11086
11087        Ok(x.read(cx))
11088    }
11089
11090    /// Read the root view out of this window, with a callback
11091    ///
11092    /// This will fail if the window is closed or if the root view's type does not match `V`.
11093    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
11094    where
11095        C: AppContext,
11096    {
11097        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
11098    }
11099
11100    /// Read the root view pointer off of this window.
11101    ///
11102    /// This will fail if the window is closed or if the root view's type does not match `V`.
11103    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
11104    where
11105        C: AppContext,
11106    {
11107        cx.read_window(self, |root_view, _cx| root_view)
11108    }
11109
11110    /// Check if this window is 'active'.
11111    ///
11112    /// Will return `None` if the window is closed or currently
11113    /// borrowed.
11114    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
11115        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
11116            .ok()
11117    }
11118}
11119
11120impl<V> Copy for WindowHandle<V> {}
11121
11122impl<V> Clone for WindowHandle<V> {
11123    fn clone(&self) -> Self {
11124        *self
11125    }
11126}
11127
11128impl<V> PartialEq for WindowHandle<V> {
11129    fn eq(&self, other: &Self) -> bool {
11130        self.any_handle == other.any_handle
11131    }
11132}
11133
11134impl<V> Eq for WindowHandle<V> {}
11135
11136impl<V> Hash for WindowHandle<V> {
11137    fn hash<H: Hasher>(&self, state: &mut H) {
11138        self.any_handle.hash(state);
11139    }
11140}
11141
11142impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
11143    fn from(val: WindowHandle<V>) -> Self {
11144        val.any_handle
11145    }
11146}
11147
11148/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
11149#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
11150pub struct AnyWindowHandle {
11151    pub(crate) id: WindowId,
11152    state_type: TypeId,
11153    root_entity_type_name: &'static str,
11154}
11155
11156impl AnyWindowHandle {
11157    /// Get the ID of this window.
11158    pub fn window_id(&self) -> WindowId {
11159        self.id
11160    }
11161
11162    /// Returns the name of the window's declared root entity type.
11163    pub fn root_entity_type_name(&self) -> &'static str {
11164        self.root_entity_type_name
11165    }
11166
11167    /// Attempt to convert this handle to a window handle with a specific root view type.
11168    /// If the types do not match, this will return `None`.
11169    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
11170        if TypeId::of::<T>() == self.state_type {
11171            Some(WindowHandle {
11172                any_handle: *self,
11173                state_type: PhantomData,
11174            })
11175        } else {
11176            None
11177        }
11178    }
11179
11180    /// Updates the state of the root view of this window.
11181    ///
11182    /// This will fail if the window has been closed.
11183    #[track_caller]
11184    pub fn update<C, R>(
11185        self,
11186        cx: &mut C,
11187        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
11188    ) -> Result<R>
11189    where
11190        C: AppContext,
11191    {
11192        cx.update_window(self, update)
11193    }
11194
11195    /// Read the state of the root view of this window.
11196    ///
11197    /// This will fail if the window has been closed.
11198    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
11199    where
11200        C: AppContext,
11201        T: 'static,
11202    {
11203        let view = self
11204            .downcast::<T>()
11205            .context("the type of the window's root view has changed")?;
11206
11207        cx.read_window(&view, read)
11208    }
11209}
11210
11211impl HasWindowHandle for Window {
11212    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
11213        self.platform_window.window_handle()
11214    }
11215}
11216
11217impl HasDisplayHandle for Window {
11218    fn display_handle(
11219        &self,
11220    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
11221        self.platform_window.display_handle()
11222    }
11223}
11224
11225/// An identifier for an [`Element`].
11226///
11227/// Can be constructed with a string, a number, or both, as well
11228/// as other internal representations.
11229#[derive(Clone, Debug, Eq, PartialEq, Hash)]
11230pub enum ElementId {
11231    /// The ID of a View element
11232    View(EntityId),
11233    /// An integer ID.
11234    Integer(u64),
11235    /// A string based ID.
11236    Name(SharedString),
11237    /// A UUID.
11238    Uuid(Uuid),
11239    /// An ID that's equated with a focus handle.
11240    FocusHandle(FocusId),
11241    /// A combination of a name and an integer.
11242    NamedInteger(SharedString, u64),
11243    /// A path.
11244    Path(Arc<std::path::Path>),
11245    /// A code location.
11246    CodeLocation(core::panic::Location<'static>),
11247    /// A labeled child of an element.
11248    NamedChild(Arc<ElementId>, SharedString),
11249    /// A byte array ID (used for text-anchors)
11250    OpaqueId([u8; 20]),
11251}
11252
11253impl ElementId {
11254    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
11255    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
11256        Self::NamedInteger(name.into(), integer as u64)
11257    }
11258}
11259
11260impl Display for ElementId {
11261    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11262        match self {
11263            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
11264            ElementId::Integer(ix) => write!(f, "{}", ix)?,
11265            ElementId::Name(name) => write!(f, "{}", name)?,
11266            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
11267            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
11268            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
11269            ElementId::Path(path) => write!(f, "{}", path.display())?,
11270            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
11271            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
11272            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
11273        }
11274
11275        Ok(())
11276    }
11277}
11278
11279impl TryInto<SharedString> for ElementId {
11280    type Error = anyhow::Error;
11281
11282    fn try_into(self) -> anyhow::Result<SharedString> {
11283        if let ElementId::Name(name) = self {
11284            Ok(name)
11285        } else {
11286            anyhow::bail!("element id is not string")
11287        }
11288    }
11289}
11290
11291impl From<u64> for ElementId {
11292    fn from(id: u64) -> Self {
11293        ElementId::Integer(id)
11294    }
11295}
11296
11297impl From<usize> for ElementId {
11298    fn from(id: usize) -> Self {
11299        ElementId::Integer(id as u64)
11300    }
11301}
11302
11303impl From<i32> for ElementId {
11304    fn from(id: i32) -> Self {
11305        Self::Integer(id as u64)
11306    }
11307}
11308
11309impl From<SharedString> for ElementId {
11310    fn from(name: SharedString) -> Self {
11311        ElementId::Name(name)
11312    }
11313}
11314
11315impl From<String> for ElementId {
11316    fn from(name: String) -> Self {
11317        ElementId::Name(name.into())
11318    }
11319}
11320
11321impl From<Arc<str>> for ElementId {
11322    fn from(name: Arc<str>) -> Self {
11323        ElementId::Name(name.into())
11324    }
11325}
11326
11327impl From<Arc<std::path::Path>> for ElementId {
11328    fn from(path: Arc<std::path::Path>) -> Self {
11329        ElementId::Path(path)
11330    }
11331}
11332
11333impl From<&'static str> for ElementId {
11334    fn from(name: &'static str) -> Self {
11335        ElementId::Name(SharedString::new_static(name))
11336    }
11337}
11338
11339impl<'a> From<&'a FocusHandle> for ElementId {
11340    fn from(handle: &'a FocusHandle) -> Self {
11341        ElementId::FocusHandle(handle.id)
11342    }
11343}
11344
11345impl From<(&'static str, EntityId)> for ElementId {
11346    fn from((name, id): (&'static str, EntityId)) -> Self {
11347        ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
11348    }
11349}
11350
11351impl From<(&'static str, usize)> for ElementId {
11352    fn from((name, id): (&'static str, usize)) -> Self {
11353        ElementId::NamedInteger(SharedString::new_static(name), id as u64)
11354    }
11355}
11356
11357impl From<(SharedString, usize)> for ElementId {
11358    fn from((name, id): (SharedString, usize)) -> Self {
11359        ElementId::NamedInteger(name, id as u64)
11360    }
11361}
11362
11363impl From<(&'static str, u64)> for ElementId {
11364    fn from((name, id): (&'static str, u64)) -> Self {
11365        ElementId::NamedInteger(SharedString::new_static(name), id)
11366    }
11367}
11368
11369impl From<Uuid> for ElementId {
11370    fn from(value: Uuid) -> Self {
11371        Self::Uuid(value)
11372    }
11373}
11374
11375impl From<(&'static str, u32)> for ElementId {
11376    fn from((name, id): (&'static str, u32)) -> Self {
11377        ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
11378    }
11379}
11380
11381impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
11382    fn from((id, name): (ElementId, T)) -> Self {
11383        ElementId::NamedChild(Arc::new(id), name.into())
11384    }
11385}
11386
11387impl From<&'static core::panic::Location<'static>> for ElementId {
11388    fn from(location: &'static core::panic::Location<'static>) -> Self {
11389        ElementId::CodeLocation(*location)
11390    }
11391}
11392
11393impl From<[u8; 20]> for ElementId {
11394    fn from(opaque_id: [u8; 20]) -> Self {
11395        ElementId::OpaqueId(opaque_id)
11396    }
11397}
11398
11399/// A rectangle to be rendered in the window at the given position and size.
11400/// Passed as an argument [`Window::paint_quad`].
11401#[derive(Clone)]
11402pub struct PaintQuad {
11403    /// The bounds of the quad within the window.
11404    pub bounds: Bounds<Pixels>,
11405    /// The radii of the quad's corners.
11406    pub corner_radii: Corners<Pixels>,
11407    /// The background color of the quad.
11408    pub background: Background,
11409    /// The widths of the quad's borders.
11410    pub border_widths: Edges<Pixels>,
11411    /// The color of the quad's borders.
11412    pub border_color: Hsla,
11413    /// The style of the quad's borders.
11414    pub border_style: BorderStyle,
11415    /// vue-native fork: CSS `corner-shape` of `corner_radii`.
11416    pub corner_shapes: Corners<CornerShape>,
11417}
11418
11419/// Options for [`Window::paint_backdrop_blur_rect`].
11420#[derive(Clone, Copy, Debug)]
11421pub struct BackdropBlurEffect {
11422    /// Approximate uniform backdrop blur radius in logical pixels, matching the
11423    /// CSS `backdrop-filter: blur(<length>)` radius.
11424    ///
11425    /// Non-positive values are treated as zero. Renderers may clamp large radii
11426    /// to a fixed implementation limit.
11427    pub radius: Pixels,
11428    /// Tint color composited over the blurred backdrop.
11429    ///
11430    /// CSS models the element's own `background-color` as a separate paint over
11431    /// the filtered backdrop, so callers implementing `backdrop-filter` should
11432    /// leave this transparent and paint a normal quad instead.
11433    pub tint: Hsla,
11434}
11435
11436impl BackdropBlurEffect {
11437    /// Create a backdrop blur effect with a uniform CSS-like radius.
11438    ///
11439    /// Non-positive values disable blur while still allowing a tint to be painted.
11440    pub fn new(radius: Pixels) -> Self {
11441        Self {
11442            radius,
11443            ..Self::default()
11444        }
11445    }
11446
11447    /// Set a tint color composited over the blurred backdrop.
11448    pub fn tint(mut self, tint: impl Into<Hsla>) -> Self {
11449        self.tint = tint.into();
11450        self
11451    }
11452}
11453
11454impl Default for BackdropBlurEffect {
11455    fn default() -> Self {
11456        Self {
11457            radius: px(20.),
11458            tint: transparent_black(),
11459        }
11460    }
11461}
11462
11463impl PaintQuad {
11464    /// Sets the corner radii of the quad.
11465    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
11466        PaintQuad {
11467            corner_radii: corner_radii.into(),
11468            ..self
11469        }
11470    }
11471
11472    /// Sets the border widths of the quad.
11473    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
11474        PaintQuad {
11475            border_widths: border_widths.into(),
11476            ..self
11477        }
11478    }
11479
11480    /// Sets the border color of the quad.
11481    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
11482        PaintQuad {
11483            border_color: border_color.into(),
11484            ..self
11485        }
11486    }
11487
11488    /// Sets the background color of the quad.
11489    pub fn background(self, background: impl Into<Background>) -> Self {
11490        PaintQuad {
11491            background: background.into(),
11492            ..self
11493        }
11494    }
11495
11496    /// vue-native fork: sets the CSS `corner-shape` of the quad's corners.
11497    pub fn corner_shapes(self, corner_shapes: Corners<CornerShape>) -> Self {
11498        PaintQuad {
11499            corner_shapes,
11500            ..self
11501        }
11502    }
11503}
11504
11505/// vue-native: a host's smaller copy of an image that is about to be drawn
11506/// well below its own size.
11507///
11508/// The sprite atlas keeps one mip level and samples it LINEARLY, so a 1080 px
11509/// picture drawn at 40 px reads a 2×2 neighbourhood out of every 27×27 block
11510/// and aliases. [`Window::paint_image`] asks this function first, with the
11511/// image, the frame, and the size in device pixels the frame is about to be
11512/// drawn at; `Some` is drawn instead (its frame 0), from its own atlas tile.
11513/// `None` draws the image as it is. Called during paint, so it must be cheap
11514/// whenever it says `None`.
11515pub type ImageResampler =
11516    fn(&Arc<RenderImage>, usize, Size<DevicePixels>) -> Option<Arc<RenderImage>>;
11517
11518static IMAGE_RESAMPLER: std::sync::OnceLock<ImageResampler> = std::sync::OnceLock::new();
11519
11520/// vue-native: installs the process's [`ImageResampler`]. The first one
11521/// installed stays.
11522pub fn set_image_resampler(resampler: ImageResampler) {
11523    let _ = IMAGE_RESAMPLER.set(resampler);
11524}
11525
11526/// Creates a quad with the given parameters.
11527pub fn quad(
11528    bounds: Bounds<Pixels>,
11529    corner_radii: impl Into<Corners<Pixels>>,
11530    background: impl Into<Background>,
11531    border_widths: impl Into<Edges<Pixels>>,
11532    border_color: impl Into<Hsla>,
11533    border_style: BorderStyle,
11534) -> PaintQuad {
11535    PaintQuad {
11536        bounds,
11537        corner_radii: corner_radii.into(),
11538        background: background.into(),
11539        border_widths: border_widths.into(),
11540        border_color: border_color.into(),
11541        border_style,
11542        corner_shapes: Corners::default(),
11543    }
11544}
11545
11546/// Creates a filled quad with the given bounds and background color.
11547pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
11548    PaintQuad {
11549        bounds: bounds.into(),
11550        corner_radii: (0.).into(),
11551        background: background.into(),
11552        border_widths: (0.).into(),
11553        border_color: transparent_black(),
11554        border_style: BorderStyle::default(),
11555        corner_shapes: Corners::default(),
11556    }
11557}
11558
11559/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
11560pub fn outline(
11561    bounds: impl Into<Bounds<Pixels>>,
11562    border_color: impl Into<Hsla>,
11563    border_style: BorderStyle,
11564) -> PaintQuad {
11565    PaintQuad {
11566        bounds: bounds.into(),
11567        corner_radii: (0.).into(),
11568        background: transparent_black().into(),
11569        border_widths: (1.).into(),
11570        border_color: border_color.into(),
11571        border_style,
11572        corner_shapes: Corners::default(),
11573    }
11574}
11575
11576/// vue-native fork: [`Shadow::inset`] for an outer shadow drawn outside the
11577/// element's border box only (CSS). The shaders cut the element out of it.
11578pub(crate) const SHADOW_OUTSIDE_BOX: u32 = 0;
11579/// vue-native fork: [`Shadow::inset`] for an inset shadow.
11580pub(crate) const SHADOW_INSET: u32 = 1;
11581/// vue-native fork: [`Shadow::inset`] for an outer shadow that also fills the
11582/// area under the border box ([`Window::paint_drop_shadows_under_box`]).
11583pub(crate) const SHADOW_UNDER_BOX: u32 = 2;
11584
11585/// vue-native fork: an outer shadow's corner radius for a border-box corner of
11586/// radius `radius` and a spread of `spread` (CSS Backgrounds 3 §7.1.1). A
11587/// positive spread grows a rounded corner by the spread, and a corner rounded
11588/// by less than the spread by less, so a square corner stays square. A
11589/// negative spread shrinks it, down to 0.
11590fn spread_shadow_radius(radius: Pixels, spread: Pixels) -> Pixels {
11591    if spread <= Pixels::ZERO {
11592        return (radius + spread).max(Pixels::ZERO);
11593    }
11594    let ratio = radius / spread;
11595    if ratio >= 1.0 {
11596        radius + spread
11597    } else {
11598        radius + spread * (1.0 + (ratio - 1.0).powi(3))
11599    }
11600}
11601
11602#[inline(never)]
11603fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
11604    if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
11605        // SAFETY: The pointer is valid for the duration of the draw operation
11606        // that set it, and we're being called during that same draw.
11607        let arena_cell = unsafe { &*arena_pointer };
11608        callback(&mut arena_cell.borrow_mut());
11609        Ok(())
11610    } else {
11611        ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
11612    }
11613}
11614
11615#[cfg(test)]
11616mod tests {
11617    use std::{
11618        cell::{Cell, RefCell},
11619        path::PathBuf,
11620        rc::Rc,
11621        time::Duration,
11622    };
11623
11624    use crate::{
11625        AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
11626        Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
11627        ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
11628        InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
11629        MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
11630        Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
11631        TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
11632        UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
11633        size,
11634    };
11635
11636    #[gpui::test]
11637    async fn test_focus_handle_release(cx: &mut TestAppContext) {
11638        let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
11639        let handle_id = handle.id;
11640        let weak_handle = handle.downgrade();
11641        let retained = handle.clone();
11642        drop(handle);
11643
11644        cx.update(|_| {});
11645        cx.read(|cx| {
11646            let handles = cx.focus_handles.read();
11647            assert_eq!(handles.handles.len(), 2);
11648            assert!(handles.dropped_handles.is_empty());
11649        });
11650        assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
11651
11652        cx.background_spawn(async move { drop(retained) }).await;
11653        assert_eq!(weak_handle.upgrade(), None);
11654        cx.read(|cx| {
11655            assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
11656        });
11657        cx.update(|_| {});
11658        cx.read(|cx| {
11659            let handles = cx.focus_handles.read();
11660            assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
11661            assert!(handles.dropped_handles.is_empty());
11662        });
11663
11664        let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
11665        assert_eq!(weak_handle.upgrade(), None);
11666        cx.update(|cx| {
11667            drop(replacements);
11668            cx.defer(move |_| drop(survivor));
11669        });
11670        cx.read(|cx| {
11671            let handles = cx.focus_handles.read();
11672            assert_eq!(handles.handles.len(), 0);
11673            assert!(handles.dropped_handles.is_empty());
11674        });
11675    }
11676
11677    #[gpui::test]
11678    fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
11679        let windows = [
11680            cx.add_window(|_, _| EmptyView),
11681            cx.add_window(|_, _| EmptyView),
11682            cx.add_window(|_, _| EmptyView),
11683            cx.add_window(|_, _| EmptyView),
11684            cx.add_window(|_, _| EmptyView),
11685        ];
11686        let (handle, other_handle, survivor) =
11687            cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
11688        for window in &windows[..2] {
11689            window
11690                .update(cx, |_, window, cx| window.focus(&handle, cx))
11691                .expect("window exists");
11692        }
11693        windows[2]
11694            .update(cx, |_, window, cx| window.focus(&other_handle, cx))
11695            .expect("window exists");
11696        windows[3]
11697            .update(cx, |_, window, cx| window.focus(&survivor, cx))
11698            .expect("window exists");
11699
11700        cx.update(|cx| {
11701            for _ in 0..1_000 {
11702                drop(cx.focus_handle());
11703            }
11704            drop((handle, other_handle));
11705        });
11706        for window in &windows[..3] {
11707            window
11708                .update(cx, |_, window, _| assert_eq!(window.focus, None))
11709                .expect("window exists");
11710        }
11711        windows[3]
11712            .update(cx, |_, window, cx| {
11713                assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
11714                assert_eq!(window.focus_generation, 1);
11715            })
11716            .expect("window exists");
11717        windows[4]
11718            .update(cx, |_, window, _| {
11719                assert_eq!(window.focus, None);
11720                assert_eq!(window.focus_generation, 0);
11721            })
11722            .expect("window exists");
11723    }
11724
11725    #[gpui::test]
11726    fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
11727        let window = cx.add_window(|_, _| EmptyView);
11728        let platform_window = cx.test_window(window.into());
11729        {
11730            let app = cx.app.borrow_mut();
11731            platform_window.simulate_close();
11732            assert!(app.windows.contains_key(window.window_id()));
11733        }
11734        cx.run_until_parked();
11735        assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
11736    }
11737
11738    #[cfg(feature = "profiler")]
11739    #[gpui::test]
11740    fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
11741        use crate::FrameRequestSource;
11742        use crate::profiler::journal::{
11743            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11744        };
11745        use scheduler::Instant;
11746
11747        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11748        let window = cx.add_window(|_, _| EmptyView);
11749        let platform_window = cx.test_window(window.into());
11750        platform_window.simulate_frame_request(RequestFrameOptions::default());
11751        let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
11752        let mut collector = journal.collector();
11753
11754        for (signal_at, source) in [
11755            (Some(Instant::now()), FrameRequestSource::NativeCallback),
11756            (Some(Instant::now()), FrameRequestSource::LocalSchedule),
11757            (None, FrameRequestSource::NativeCallback),
11758        ] {
11759            platform_window.simulate_frame_request(RequestFrameOptions {
11760                signal_at,
11761                signal_source: source,
11762                require_presentation: true,
11763                ..Default::default()
11764            });
11765            let entries = collector.collect_unseen().entries;
11766            let signal_index = entries
11767                .iter()
11768                .position(|entry| {
11769                    matches!(
11770                        entry,
11771                        ForegroundJournalEntry::PlatformSignal(signal)
11772                            if signal.window_id == window.window_id()
11773                                && signal.signal_at == signal_at
11774                                && signal.source == source
11775                                && signal_at.is_none_or(|at| signal.handled_at >= at)
11776                    )
11777                })
11778                .expect("frame request metadata");
11779            let skip_index = entries
11780                .iter()
11781                .position(|entry| {
11782                    matches!(
11783                        entry,
11784                        ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11785                            if skipped.window_id == window.window_id()
11786                                && skipped.reason == FrameSkipReason::NoRenderNeeded
11787                    )
11788                })
11789                .expect("completed no-render boundary");
11790            assert!(signal_index < skip_index);
11791        }
11792    }
11793
11794    #[cfg(feature = "profiler")]
11795    #[gpui::test]
11796    fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
11797        use crate::profiler::journal::{
11798            self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11799        };
11800        use scheduler::Instant;
11801
11802        // Test mode draws during effect flushing, bypassing platform frame throttling.
11803        cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11804        let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
11805        let mut collector = journal.collector();
11806        for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
11807            // Keep the throttle closed without depending on short wall-clock deadlines.
11808            let window = cx
11809                .app
11810                .borrow_mut()
11811                .open_window(
11812                    WindowOptions {
11813                        inactive_frame_interval: Some(Duration::from_secs(3600)),
11814                        ..Default::default()
11815                    },
11816                    |_, cx| cx.new(|_| EmptyView),
11817                )
11818                .expect("open inactive test window");
11819            let platform_window = cx.test_window(window.into());
11820            platform_window.simulate_active_status_change(false);
11821            platform_window.simulate_frame_request(RequestFrameOptions::default());
11822            let callback_ran = Rc::new(Cell::new(false));
11823            let draws_before = window
11824                .update(cx, |_, window, _| {
11825                    let draws_before = window
11826                        .frame_duration_snapshot()
11827                        .draw_duration_histogram
11828                        .len();
11829                    if initially_dirty {
11830                        window.refresh();
11831                    }
11832                    if schedule_callback {
11833                        window.on_next_frame({
11834                            let callback_ran = callback_ran.clone();
11835                            move |window, _| {
11836                                callback_ran.set(true);
11837                                window.refresh();
11838                            }
11839                        });
11840                    }
11841                    draws_before
11842                })
11843                .expect("schedule throttled frame");
11844            // Skips only seal retained work, so give the throttled skip some.
11845            let input_at = Instant::now();
11846            journal::record_input(journal::InputTiming {
11847                kind: "test",
11848                start: input_at,
11849                end: input_at,
11850                caused_invalidation: false,
11851            });
11852            collector.collect_unseen();
11853            let wakes_before = platform_window.frame_wake_count();
11854            platform_window.simulate_frame_request(RequestFrameOptions {
11855                signal_at: Some(Instant::now()),
11856                ..Default::default()
11857            });
11858            window
11859                .update(cx, |_, window, _| {
11860                    assert_eq!(
11861                        window
11862                            .frame_duration_snapshot()
11863                            .draw_duration_histogram
11864                            .len(),
11865                        draws_before,
11866                    );
11867                })
11868                .expect("inspect deferred frame");
11869            assert!(!callback_ran.get());
11870            assert!(platform_window.frame_scheduled());
11871            assert!(platform_window.frame_wake_count() > wakes_before);
11872            assert!(collector.collect_unseen().entries.iter().any(|entry| {
11873                matches!(
11874                    entry,
11875                    ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11876                        if skipped.window_id == window.window_id()
11877                            && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
11878                )
11879            }));
11880            platform_window.simulate_frame_request(RequestFrameOptions {
11881                signal_at: Some(Instant::now()),
11882                require_presentation: true,
11883                ..Default::default()
11884            });
11885            window
11886                .update(cx, |_, window, _| {
11887                    assert_eq!(
11888                        window
11889                            .frame_duration_snapshot()
11890                            .draw_duration_histogram
11891                            .len(),
11892                        draws_before + 1,
11893                    );
11894                })
11895                .expect("inspect presented frame");
11896            assert_eq!(callback_ran.get(), schedule_callback);
11897        }
11898    }
11899
11900    /// A stale cache is only visible if the snapshot reports GPUI's cached
11901    /// value separately from what the platform reports now.
11902    #[gpui::test]
11903    fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
11904        use crate::WindowVisibility;
11905
11906        let window = cx.add_window(|_, _| EmptyView);
11907        let window_id = window.window_id().as_u64();
11908        let window_state = |cx: &mut TestAppContext| {
11909            let state = cx.update(|cx| cx.debug_state());
11910            state["windows"]
11911                .as_array()
11912                .and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
11913                .cloned()
11914                .expect("the open window is listed")
11915        };
11916
11917        let state = window_state(cx);
11918        assert_eq!(state["visibility"]["cached"], "Visible");
11919        assert_eq!(state["visibility"]["platform"], "Visible");
11920
11921        cx.test_window(window.into())
11922            .simulate_visibility_change(WindowVisibility::Hidden);
11923        let state = window_state(cx);
11924        assert_eq!(state["visibility"]["cached"], "Hidden");
11925        assert_eq!(state["visibility"]["platform"], "Hidden");
11926    }
11927
11928    /// Visibility transitions reach observers exactly once each, with the new
11929    /// state already stored on the window, and never wake the platform for a
11930    /// frame: the platform requests one itself when it resumes presenting.
11931    #[gpui::test]
11932    fn test_window_visibility(cx: &mut TestAppContext) {
11933        use crate::WindowVisibility;
11934
11935        let window = cx.add_window(|_, _| EmptyView);
11936        let observed = Rc::new(RefCell::new(Vec::new()));
11937        let _subscription = window
11938            .update(cx, {
11939                let observed = observed.clone();
11940                move |_, window, _| {
11941                    assert_eq!(window.visibility(), WindowVisibility::Visible);
11942                    assert!(window.is_visible());
11943                    window.observe_window_visibility(move |visibility, window, _| {
11944                        assert_eq!(window.visibility(), visibility);
11945                        observed.borrow_mut().push(visibility);
11946                    })
11947                }
11948            })
11949            .unwrap();
11950        let test_window = cx.test_window(window.into());
11951        let frame_wake_count = test_window.frame_wake_count();
11952
11953        test_window.simulate_visibility_change(WindowVisibility::Hidden);
11954        assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
11955        window
11956            .update(cx, |_, window, _| assert!(!window.is_visible()))
11957            .unwrap();
11958
11959        // Platforms may report the same state again; observers only see changes.
11960        test_window.simulate_visibility_change(WindowVisibility::Hidden);
11961        assert_eq!(observed.borrow().len(), 1);
11962
11963        test_window.simulate_visibility_change(WindowVisibility::Visible);
11964        assert_eq!(
11965            *observed.borrow(),
11966            [WindowVisibility::Hidden, WindowVisibility::Visible]
11967        );
11968        window
11969            .update(cx, |_, window, _| assert!(window.is_visible()))
11970            .unwrap();
11971        assert_eq!(test_window.frame_wake_count(), frame_wake_count);
11972    }
11973
11974    /// App learns display state from the platform's display notifications,
11975    /// and a window from the platform's report of which display it is on.
11976    #[gpui::test]
11977    fn test_display_tracking(cx: &mut TestAppContext) {
11978        use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
11979
11980        let sixty_hertz = Duration::from_secs(1) / 60;
11981        let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
11982        let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
11983
11984        let display_events = Rc::new(RefCell::new(Vec::new()));
11985        let _display_subscription = cx.update({
11986            let display_events = display_events.clone();
11987            move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
11988        });
11989
11990        let window = cx.add_window(|window, cx| DisplayTracker {
11991            refresh_intervals: Vec::new(),
11992            _subscription: cx.observe_window_display(
11993                window,
11994                |tracker: &mut DisplayTracker, window, cx| {
11995                    tracker.refresh_intervals.push(window.refresh_interval(cx));
11996                },
11997            ),
11998        });
11999        let window_notifications = Rc::new(RefCell::new(Vec::new()));
12000        let _window_subscription = window
12001            .update(cx, {
12002                let window_notifications = window_notifications.clone();
12003                move |_, window, cx| {
12004                    assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
12005                    window.observe_window_display(move |window, cx| {
12006                        window_notifications
12007                            .borrow_mut()
12008                            .push((window.display_id, window.refresh_interval(cx)));
12009                    })
12010                }
12011            })
12012            .unwrap();
12013        let test_window = cx.test_window(window.into());
12014
12015        // The window may hear that it moved before App hears the display was
12016        // connected. App learns about the display before the window's
12017        // observers run, and the platform's later notification changes
12018        // nothing.
12019        cx.test_platform()
12020            .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
12021        test_window.simulate_move_to_display(DisplayId(2));
12022        assert_eq!(
12023            window_notifications.take(),
12024            [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
12025        );
12026        assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
12027        cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
12028        assert!(window_notifications.borrow().is_empty());
12029
12030        // Platforms may report a move that isn't one.
12031        test_window.simulate_move_to_display(DisplayId(2));
12032        assert!(window_notifications.borrow().is_empty());
12033
12034        cx.simulate_display_refresh_interval_change(
12035            DisplayId(2),
12036            Some(one_hundred_forty_four_hertz),
12037        );
12038        assert_eq!(
12039            window_notifications.take(),
12040            [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
12041        );
12042
12043        // Changes to a display the window isn't on don't notify it.
12044        cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
12045        cx.simulate_display_removed(DisplayId(1));
12046        assert!(window_notifications.borrow().is_empty());
12047
12048        assert_eq!(
12049            display_events.take(),
12050            [
12051                DisplayEvent::Changed {
12052                    id: DisplayId(2),
12053                    changes: DisplayChanges::REFRESH_INTERVAL,
12054                },
12055                DisplayEvent::Changed {
12056                    id: DisplayId(1),
12057                    changes: DisplayChanges::REFRESH_INTERVAL,
12058                },
12059                DisplayEvent::Removed(DisplayId(1)),
12060            ]
12061        );
12062        window
12063            .update(cx, |tracker, _, _| {
12064                assert_eq!(
12065                    tracker.refresh_intervals,
12066                    [
12067                        Some(one_hundred_twenty_hertz),
12068                        Some(one_hundred_forty_four_hertz)
12069                    ]
12070                );
12071            })
12072            .unwrap();
12073
12074        struct DisplayTracker {
12075            refresh_intervals: Vec<Option<Duration>>,
12076            _subscription: Subscription,
12077        }
12078
12079        impl Render for DisplayTracker {
12080            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12081                Empty
12082            }
12083        }
12084    }
12085
12086    #[gpui::test]
12087    fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
12088        use crate::Subscription;
12089
12090        struct BoundsObserver {
12091            _subscription: Subscription,
12092        }
12093
12094        impl Render for BoundsObserver {
12095            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12096                Empty
12097            }
12098        }
12099
12100        let opened_window = Rc::new(Cell::new(None));
12101        let window = cx.add_window({
12102            let opened_window = opened_window.clone();
12103            move |window, cx| BoundsObserver {
12104                _subscription: cx.observe_window_bounds(window, move |_, _, cx| {
12105                    let handle = cx
12106                        .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12107                        .unwrap();
12108                    opened_window.set(Some(AnyWindowHandle::from(handle)));
12109                }),
12110            }
12111        });
12112        window
12113            .update(cx, |_, window, _| window.activate_window())
12114            .unwrap();
12115
12116        let new_size = size(px(400.), px(300.));
12117        cx.simulate_window_resize(window.into(), new_size);
12118
12119        let opened_window = opened_window
12120            .take()
12121            .expect("bounds observer should have opened a window");
12122        let opened_size = opened_window
12123            .update(cx, |_, window, _| window.bounds().size)
12124            .unwrap();
12125        assert_eq!(opened_size, new_size);
12126    }
12127
12128    #[gpui::test]
12129    fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
12130        let window = cx.add_window(|_, _| EmptyView);
12131        let mut platform_window = cx.test_window(window.into());
12132        platform_window.simulate_resize(size(px(400.), px(800.)));
12133        window
12134            .update(cx, |_, window, _| {
12135                assert_eq!(
12136                    window.visual_viewport_bounds(),
12137                    Bounds::new(Point::default(), size(px(400.), px(800.)))
12138                );
12139                assert_eq!(
12140                    window.fully_visible_bounds(),
12141                    window.visual_viewport_bounds()
12142                );
12143            })
12144            .unwrap();
12145
12146        platform_window.simulate_frame_request(RequestFrameOptions::default());
12147        let wakes = platform_window.frame_wake_count();
12148        let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
12149        platform_window.simulate_visual_viewport_change(visual_bounds);
12150        assert!(platform_window.frame_wake_count() > wakes);
12151        platform_window.simulate_frame_request(RequestFrameOptions::default());
12152        let wakes = platform_window.frame_wake_count();
12153        let insets = crate::WindowInsets {
12154            safe_area: crate::Edges {
12155                top: px(60.),
12156                right: px(20.),
12157                bottom: px(30.),
12158                left: px(-10.),
12159            },
12160            ime: crate::Edges {
12161                bottom: px(350.),
12162                ..Default::default()
12163            },
12164            ..Default::default()
12165        };
12166        platform_window.simulate_insets_change(insets.clone());
12167        assert!(platform_window.frame_wake_count() > wakes);
12168        window
12169            .update(cx, |_, window, cx| {
12170                let focus = cx.focus_handle();
12171                window.focus(&focus, cx);
12172                assert_eq!(window.insets(), insets);
12173                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
12174                assert_eq!(window.visual_viewport_bounds(), visual_bounds);
12175                assert_eq!(
12176                    window.fully_visible_bounds(),
12177                    Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
12178                );
12179                window.request_virtual_keyboard();
12180                window.dismiss_virtual_keyboard();
12181                assert!(focus.is_focused(window));
12182                assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
12183            })
12184            .unwrap();
12185        assert_eq!(platform_window.virtual_keyboard_requests(), 1);
12186        assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
12187
12188        platform_window.simulate_insets_change(crate::WindowInsets {
12189            safe_area: crate::Edges {
12190                top: px(900.),
12191                left: px(500.),
12192                ..Default::default()
12193            },
12194            ..Default::default()
12195        });
12196        window
12197            .update(cx, |_, window, _| {
12198                assert_eq!(
12199                    window.fully_visible_bounds().size,
12200                    size(Pixels::ZERO, Pixels::ZERO)
12201                );
12202            })
12203            .unwrap();
12204
12205        // Some backends update geometry snapshots without delivering inset callbacks.
12206        use crate::PlatformWindow as _;
12207        platform_window.on_insets_changed(Box::new(|_| {}));
12208        platform_window.simulate_insets_change(crate::WindowInsets::default());
12209        window
12210            .update(cx, |_, window, _| {
12211                assert_eq!(window.insets(), crate::WindowInsets::default());
12212            })
12213            .unwrap();
12214    }
12215
12216    #[test]
12217    fn frame_throttle_tracks_display_refreshes() {
12218        let start = super::Instant::now();
12219        for (elapsed, interval) in [
12220            (Duration::from_micros(16_666), Duration::from_micros(16_667)),
12221            (Duration::from_micros(33_332), Duration::from_micros(33_333)),
12222        ] {
12223            let mut pacer = super::FramePacer::default();
12224            assert!(!pacer.should_defer(start, Some(interval)));
12225            assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
12226            assert!(!pacer.should_defer(start + elapsed, Some(interval)));
12227        }
12228    }
12229
12230    #[test]
12231    fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
12232        let start = super::Instant::now();
12233        let interval = Duration::from_micros(33_333);
12234        let mut pacer = super::FramePacer::default();
12235        assert!(!pacer.should_defer(start, Some(interval)));
12236        let delayed_frame = start + interval + Duration::from_millis(5);
12237        assert!(!pacer.should_defer(delayed_frame, Some(interval)));
12238        assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
12239        assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
12240
12241        // Even a stall just short of another full interval must not cause a burst.
12242        let after_stall = start + interval * 4 - Duration::from_millis(1);
12243        assert!(!pacer.should_defer(after_stall, Some(interval)));
12244        assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
12245        assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
12246        // Mandatory presentation bypasses the limit and establishes a fresh cadence.
12247        let mandatory_frame = after_stall + interval + Duration::from_millis(2);
12248        assert!(!pacer.should_defer(mandatory_frame, None));
12249        assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
12250    }
12251
12252    #[test]
12253    fn power_modes_preserve_frame_limits() {
12254        let options = WindowOptions::default();
12255        for (power_mode, active_interval, thermal_interval) in [
12256            (
12257                crate::PowerMode::LowPower,
12258                Some(Duration::from_micros(33_333)),
12259                Duration::from_micros(33_333),
12260            ),
12261            (
12262                crate::PowerMode::Unknown,
12263                None,
12264                Duration::from_micros(16_667),
12265            ),
12266            (
12267                crate::PowerMode::Balanced,
12268                None,
12269                Duration::from_micros(16_667),
12270            ),
12271            (
12272                crate::PowerMode::HighPower,
12273                None,
12274                Duration::from_micros(16_667),
12275            ),
12276        ] {
12277            assert_eq!(
12278                super::minimum_frame_interval(
12279                    true,
12280                    false,
12281                    options.inactive_frame_interval,
12282                    options.low_power_frame_interval,
12283                    options.thermal_frame_interval,
12284                    ThermalState::Nominal,
12285                    power_mode,
12286                ),
12287                active_interval,
12288            );
12289            assert_eq!(
12290                super::minimum_frame_interval(
12291                    true,
12292                    false,
12293                    options.inactive_frame_interval,
12294                    options.low_power_frame_interval,
12295                    options.thermal_frame_interval,
12296                    ThermalState::Serious,
12297                    power_mode,
12298                ),
12299                Some(thermal_interval),
12300            );
12301        }
12302    }
12303
12304    #[test]
12305    fn frame_limits_combine_enabled_intervals() {
12306        let short = Some(Duration::from_millis(10));
12307        let long = Some(Duration::from_millis(100));
12308        for (inactive, low_power, thermal, expected) in [
12309            (long, short, short, long),
12310            (short, long, short, long),
12311            (short, short, long, long),
12312            (long, None, None, long),
12313            (None, long, None, long),
12314            (None, None, long, long),
12315            (None, None, None, None),
12316        ] {
12317            assert_eq!(
12318                super::minimum_frame_interval(
12319                    true,
12320                    true,
12321                    inactive,
12322                    low_power,
12323                    thermal,
12324                    ThermalState::Critical,
12325                    crate::PowerMode::LowPower,
12326                ),
12327                expected,
12328            );
12329        }
12330        assert_eq!(
12331            super::minimum_frame_interval(
12332                false,
12333                true,
12334                long,
12335                long,
12336                long,
12337                ThermalState::Critical,
12338                crate::PowerMode::LowPower,
12339            ),
12340            None,
12341        );
12342    }
12343
12344    struct EmptyView;
12345
12346    impl Render for EmptyView {
12347        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12348            div()
12349        }
12350    }
12351
12352    struct OpensWindowOnPaint {
12353        opened: Rc<Cell<bool>>,
12354    }
12355
12356    impl Render for OpensWindowOnPaint {
12357        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12358            let opened = self.opened.clone();
12359            div()
12360                .size_full()
12361                .child(canvas(
12362                    |_, _, _| {},
12363                    move |_, _, _window, cx| {
12364                        if !opened.replace(true) {
12365                            cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12366                                .unwrap();
12367                        }
12368                    },
12369                ))
12370                // Siblings painted after the canvas: their elements were
12371                // allocated in the arena before the nested draw, so they detect
12372                // a mid-draw arena clear when painted afterwards.
12373                .child(div().child("after"))
12374        }
12375    }
12376
12377    /// Opening a window synchronously draws it and requests an element arena
12378    /// clear. When that happens from within another window's draw (here: from
12379    /// an element's paint), the clear must be deferred until the outer draw
12380    /// finishes, or the outer draw's arena-allocated elements would be freed
12381    /// out from under it.
12382    #[test]
12383    fn test_window_opened_during_draw_defers_arena_clear() {
12384        let mut cx = TestAppContext::single();
12385
12386        let opened = Rc::new(Cell::new(false));
12387        // add_window draws once, which runs the nested open_window mid-draw.
12388        let window = cx.add_window({
12389            let opened = opened.clone();
12390            move |_, _| OpensWindowOnPaint { opened }
12391        });
12392
12393        assert!(opened.get());
12394        assert_eq!(cx.windows().len(), 2);
12395
12396        // The deferred clear must actually run once the outer draw unwinds:
12397        // subsequent draws of both windows work against a fresh arena.
12398        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12399            .unwrap();
12400    }
12401
12402    #[test]
12403    fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
12404        let mut cx = TestAppContext::single();
12405        let window = cx.add_window(|_, _| EmptyView);
12406        let handle: AnyWindowHandle = window.into();
12407        let window_state = |cx: &mut TestAppContext| {
12408            cx.update_window(handle, |_, window, _| {
12409                (
12410                    window.scale_factor(),
12411                    window.bounds(),
12412                    window.viewport_size(),
12413                )
12414            })
12415            .unwrap()
12416        };
12417
12418        let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
12419        assert_eq!(scale_factor, 2.0);
12420
12421        for (scale_factor, resized_size) in [
12422            (1.0, size(px(800.), px(600.))),
12423            (1.25, size(px(640.), px(480.))),
12424            (2.0, size(px(1024.), px(768.))),
12425        ] {
12426            cx.simulate_window_scale_factor_change(handle, scale_factor);
12427            assert_eq!(
12428                window_state(&mut cx),
12429                (scale_factor, expected_bounds, expected_bounds.size)
12430            );
12431
12432            cx.simulate_window_resize(handle, resized_size);
12433            expected_bounds.size = resized_size;
12434            assert_eq!(
12435                window_state(&mut cx),
12436                (scale_factor, expected_bounds, resized_size)
12437            );
12438        }
12439    }
12440
12441    #[gpui::test]
12442    fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
12443        let window = cx.add_window(|_, _| EmptyView);
12444        let handle = AnyWindowHandle::from(window);
12445        let notifications = Rc::new(Cell::new(0));
12446        window
12447            .update(cx, {
12448                let notifications = notifications.clone();
12449                |_, window, cx| {
12450                    cx.observe_window_bounds(window, move |_, _, _| {
12451                        notifications.set(notifications.get() + 1)
12452                    })
12453                    .detach();
12454                }
12455            })
12456            .unwrap();
12457        let window_state = |cx: &mut TestAppContext| {
12458            cx.update_window(handle, |_, window, _| {
12459                (
12460                    window.is_fullscreen(),
12461                    window.bounds().size,
12462                    window.viewport_size(),
12463                )
12464            })
12465            .unwrap()
12466        };
12467        let initial_size = window_state(cx).1;
12468
12469        window
12470            .update(cx, |_, window, _| window.toggle_fullscreen())
12471            .unwrap();
12472        cx.run_until_parked();
12473        assert_eq!(window_state(cx), (true, initial_size, initial_size));
12474        assert_eq!(notifications.get(), 1);
12475
12476        let resized_size = size(px(800.), px(600.));
12477        window
12478            .update(cx, |_, window, _| window.toggle_fullscreen())
12479            .unwrap();
12480        cx.simulate_window_resize(handle, resized_size);
12481        cx.run_until_parked();
12482        assert_eq!(window_state(cx), (false, resized_size, resized_size));
12483    }
12484
12485    /// Platforms that stop requesting frames for idle windows (currently web)
12486    /// rely on the frame waker firing whenever frame demand arises; a demand
12487    /// source that skips the waker shows up there as a window that silently
12488    /// stops repainting until unrelated activity wakes it.
12489    #[gpui::test]
12490    fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
12491        let window = cx.add_window(|_, _| EmptyView);
12492        let test_window = cx.test_window(window.into());
12493        // This test exercises idle wakeups, not the inactive-window frame limit.
12494        test_window.simulate_active_status_change(true);
12495
12496        // Windows start dirty, and that can predate waker installation;
12497        // installing the waker must deliver the pending wake or the first
12498        // frame would never be requested.
12499        assert!(
12500            test_window.frame_wake_count() >= 1,
12501            "opening a window must wake the frame source for the initial frame"
12502        );
12503
12504        // Serve outstanding demand (present the frame drawn by `add_window`).
12505        test_window.simulate_frame_request(RequestFrameOptions::default());
12506
12507        // An idle window must not wake on clean frames or plain updates, or
12508        // the frame source could never stop.
12509        let baseline = test_window.frame_wake_count();
12510        test_window.simulate_frame_request(RequestFrameOptions::default());
12511        window.update(cx, |_, _, _| {}).unwrap();
12512        assert_eq!(
12513            test_window.frame_wake_count(),
12514            baseline,
12515            "clean frames and non-notifying updates must not wake the frame source"
12516        );
12517
12518        // Notifying a view in an idle window is the core demand signal.
12519        window.update(cx, |_, _, cx| cx.notify()).unwrap();
12520        assert!(
12521            test_window.frame_wake_count() > baseline,
12522            "notifying a view in an idle window must wake the frame source"
12523        );
12524
12525        // Serving that demand returns to idle without further wakes.
12526        test_window.simulate_frame_request(RequestFrameOptions::default());
12527        let baseline = test_window.frame_wake_count();
12528        test_window.simulate_frame_request(RequestFrameOptions::default());
12529        assert_eq!(
12530            test_window.frame_wake_count(),
12531            baseline,
12532            "serving demand must return the window to idle"
12533        );
12534
12535        // Next-frame callbacks create demand without dirtying the window.
12536        window
12537            .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
12538            .unwrap();
12539        assert!(
12540            test_window.frame_wake_count() > baseline,
12541            "scheduling a next-frame callback in an idle window must wake the frame source"
12542        );
12543    }
12544
12545    /// A passive next-frame callback rides along with the next delivered frame
12546    /// but never wakes the frame source, even when it re-arms itself.
12547    #[gpui::test]
12548    fn test_passive_next_frame_callbacks_are_not_demand(cx: &mut TestAppContext) {
12549        fn rearm(window: &mut Window, runs: Rc<Cell<usize>>) {
12550            runs.set(runs.get() + 1);
12551            window.on_next_frame_passive(move |window, _| rearm(window, runs));
12552        }
12553        let window = cx.add_window(|_, _| EmptyView);
12554        let test_window = cx.test_window(window.into());
12555        test_window.simulate_frame_request(RequestFrameOptions::default());
12556
12557        let runs = Rc::new(Cell::new(0));
12558        let baseline = test_window.frame_wake_count();
12559        window
12560            .update(cx, {
12561                let runs = runs.clone();
12562                move |_, window, _| window.on_next_frame_passive(move |window, _| rearm(window, runs))
12563            })
12564            .unwrap();
12565        assert_eq!(test_window.frame_wake_count(), baseline, "queueing a passive callback is not demand");
12566
12567        test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12568        test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12569        assert_eq!(runs.get(), 2, "a passive callback runs with every delivered frame");
12570        assert_eq!(test_window.frame_wake_count(), baseline, "a re-arming passive pump never wakes the frame source");
12571
12572        // Real demand next to the passive pump still wakes it.
12573        window.update(cx, |_, window, _| window.on_next_frame(|_, _| {})).unwrap();
12574        assert!(test_window.frame_wake_count() > baseline);
12575    }
12576
12577    /// A frame request that arrives while next-frame callbacks are pending
12578    /// must never strand them: either the frame runs them, or (when the
12579    /// inactive-window frame-rate throttle defers the frame) the waker fires
12580    /// so another request is delivered.
12581    #[gpui::test]
12582    fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
12583        let window = cx.add_window(|_, _| EmptyView);
12584        let test_window = cx.test_window(window.into());
12585        // Establish a recent last-frame time so the inactive-window throttle
12586        // can engage on the next request.
12587        test_window.simulate_frame_request(RequestFrameOptions::default());
12588
12589        let callback_ran = Rc::new(Cell::new(false));
12590        window
12591            .update(cx, {
12592                let callback_ran = callback_ran.clone();
12593                move |_, window, _| {
12594                    window.on_next_frame(move |_, _| callback_ran.set(true));
12595                }
12596            })
12597            .unwrap();
12598
12599        let baseline = test_window.frame_wake_count();
12600        test_window.simulate_frame_request(RequestFrameOptions::default());
12601        // The test window is inactive, so this request throttles to ~30fps
12602        // when it lands within the throttle interval of the previous frame
12603        // (the common case here, but timing-dependent): the callback is
12604        // deferred and the waker must re-arm the frame source. On a slow run
12605        // the request instead lands outside the interval and runs the
12606        // callback directly.
12607        assert!(
12608            test_window.frame_wake_count() > baseline || callback_ran.get(),
12609            "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
12610        );
12611    }
12612
12613    #[gpui::test]
12614    fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
12615        use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
12616
12617        let window = cx.add_window(|_, _| EmptyView);
12618        window
12619            .update(cx, |_, window, _| {
12620                assert!(matches!(
12621                    window.window_handle(),
12622                    Err(HandleError::NotSupported)
12623                ));
12624                assert!(matches!(
12625                    window.display_handle(),
12626                    Err(HandleError::NotSupported)
12627                ));
12628            })
12629            .unwrap();
12630    }
12631
12632    #[gpui::test]
12633    fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
12634        let window = cx.add_window(|_, _| EmptyView);
12635        let observed_appearance = Rc::new(Cell::new(None));
12636        let _subscription = window
12637            .update(cx, {
12638                let observed_appearance = observed_appearance.clone();
12639                move |_, window, _| {
12640                    window.observe_window_appearance(move |window, _| {
12641                        observed_appearance.set(Some(window.appearance()));
12642                    })
12643                }
12644            })
12645            .unwrap();
12646        let test_window = cx.test_window(window.into());
12647
12648        cx.update(|_| {
12649            test_window.simulate_appearance_change(WindowAppearance::Dark);
12650            assert_eq!(observed_appearance.get(), None);
12651        });
12652        cx.run_until_parked();
12653
12654        assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
12655    }
12656
12657    #[gpui::test]
12658    fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12659        let window = cx.add_window(|_, _| Empty);
12660        let test_window = cx.test_window(window.into());
12661
12662        assert!(test_window.simulate_scheduled_frame());
12663        assert!(test_window.simulate_scheduled_frame());
12664        assert!(!test_window.frame_scheduled());
12665
12666        cx.update_window(window.into(), |_, window, _| {
12667            window.active.set(true);
12668            window.on_next_frame(|_, _| {});
12669        })
12670        .unwrap();
12671        assert!(
12672            test_window.frame_scheduled(),
12673            "queuing work on a parked window must wake the render loop"
12674        );
12675
12676        assert!(test_window.simulate_scheduled_frame());
12677        assert!(
12678            test_window.frame_scheduled(),
12679            "presenting the frame must await one compositor callback"
12680        );
12681        assert!(test_window.simulate_scheduled_frame());
12682        assert!(!test_window.frame_scheduled());
12683    }
12684
12685    #[gpui::test]
12686    fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12687        let window = cx.add_window(|_, _| Empty);
12688        let test_window = cx.test_window(window.into());
12689
12690        assert!(test_window.simulate_scheduled_frame());
12691        assert!(test_window.simulate_scheduled_frame());
12692        assert!(!test_window.frame_scheduled());
12693
12694        cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12695            .unwrap();
12696
12697        assert!(
12698            test_window.frame_scheduled(),
12699            "a rendered scene awaiting presentation must wake the render loop"
12700        );
12701    }
12702
12703    #[gpui::test]
12704    fn reentrant_frame_request_preserves_pending_callbacks(cx: &mut TestAppContext) {
12705        let window = cx.add_window(|_, _| Empty);
12706        let test_window = cx.test_window(window.into());
12707        let callback_count = Rc::new(Cell::new(0));
12708
12709        cx.update_window(window.into(), |_, window, _| {
12710            window.active.set(true);
12711            let callback_count = callback_count.clone();
12712            window.on_next_frame(move |window, _| {
12713                callback_count.set(callback_count.get() + 1);
12714                window.on_next_frame(move |_, _| {
12715                    callback_count.set(callback_count.get() + 1);
12716                });
12717            });
12718        })
12719        .unwrap();
12720
12721        // Win32 can deliver WM_PAINT from a nested native message loop while
12722        // an input listener or host call still owns the App borrow.
12723        let wake_count = test_window.frame_wake_count();
12724        cx.update(|_| {
12725            test_window.simulate_frame_request(RequestFrameOptions::default());
12726        });
12727        assert_eq!(callback_count.get(), 0);
12728        cx.update_window(window.into(), |_, window, _| {
12729            assert_eq!(window.next_frame_callbacks.borrow().len(), 1);
12730        })
12731        .unwrap();
12732        assert!(
12733            test_window.frame_wake_count() > wake_count,
12734            "a deferred frame callback must wake the frame source for a retry"
12735        );
12736
12737        test_window.simulate_frame_request(RequestFrameOptions::default());
12738        assert_eq!(callback_count.get(), 1);
12739        test_window.simulate_frame_request(RequestFrameOptions::default());
12740        assert_eq!(callback_count.get(), 2);
12741        test_window.simulate_frame_request(RequestFrameOptions::default());
12742        assert_eq!(callback_count.get(), 2);
12743    }
12744
12745    #[gpui::test]
12746    fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
12747        let window = cx.add_window(|_, _| Empty);
12748        let test_window = cx.test_window(window.into());
12749
12750        let callback_ran = Rc::new(Cell::new(false));
12751        cx.update_window(window.into(), |_, window, _| {
12752            // Inactive windows are frame-rate throttled, which would defer the
12753            // ticks this test drives manually.
12754            window.active.set(true);
12755            let callback_ran = callback_ran.clone();
12756            window.on_next_frame(move |window, _| {
12757                window.on_next_frame(move |_, _| callback_ran.set(true));
12758            });
12759        })
12760        .unwrap();
12761
12762        assert!(test_window.simulate_scheduled_frame());
12763        assert!(!callback_ran.get());
12764        assert!(
12765            test_window.frame_scheduled(),
12766            "a callback queued mid-frame must schedule a follow-up before the loop parks"
12767        );
12768
12769        assert!(test_window.simulate_scheduled_frame());
12770        assert!(callback_ran.get());
12771    }
12772
12773    struct RootView {
12774        explicit_size: bool,
12775        child_bounds: Rc<Cell<Bounds<Pixels>>>,
12776    }
12777
12778    impl Render for RootView {
12779        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12780            let child_bounds = self.child_bounds.clone();
12781            let root = div().flex().flex_col().child(
12782                canvas(
12783                    move |bounds, _, _| child_bounds.set(bounds),
12784                    |_, _, _, _| {},
12785                )
12786                .size_full(),
12787            );
12788            if self.explicit_size {
12789                root.w(px(300.)).h(px(200.))
12790            } else {
12791                root
12792            }
12793        }
12794    }
12795
12796    #[test]
12797    fn auto_sized_window_root_fills_the_window() {
12798        let mut cx = TestAppContext::single();
12799        let child_bounds = Rc::new(Cell::new(Bounds::default()));
12800        let window = cx.add_window({
12801            let child_bounds = child_bounds.clone();
12802            move |_, _| RootView {
12803                explicit_size: false,
12804                child_bounds,
12805            }
12806        });
12807
12808        let viewport_size = cx
12809            .update_window(window.into(), |_, window, cx| {
12810                window.draw(cx).clear(cx);
12811                window.viewport_size()
12812            })
12813            .unwrap();
12814
12815        assert_eq!(child_bounds.get().size, viewport_size);
12816    }
12817
12818    #[test]
12819    fn explicitly_sized_window_root_keeps_its_size() {
12820        let mut cx = TestAppContext::single();
12821        let child_bounds = Rc::new(Cell::new(Bounds::default()));
12822        let window = cx.add_window({
12823            let child_bounds = child_bounds.clone();
12824            move |_, _| RootView {
12825                explicit_size: true,
12826                child_bounds,
12827            }
12828        });
12829
12830        cx.update_window(window.into(), |_, window, cx| {
12831            window.draw(cx).clear(cx);
12832        })
12833        .unwrap();
12834
12835        assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
12836    }
12837
12838    struct FileDragView {
12839        path: PathBuf,
12840        observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12841        observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12842    }
12843
12844    struct FileDropExitView(Rc<Cell<usize>>);
12845
12846    impl Render for FileDropExitView {
12847        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12848            div().size_full().on_file_drop_exit({
12849                let observed_file_drop_exit = self.0.clone();
12850                move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
12851            })
12852        }
12853    }
12854
12855    impl Render for FileDragView {
12856        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12857            div()
12858                .id("file-drag")
12859                .size_full()
12860                .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
12861                .external_drag_payload(|path: &PathBuf, _, _| {
12862                    Some(ExternalDragPayload::Files(FileDragPaths::new([(
12863                        path.clone(),
12864                        true,
12865                    )])))
12866                })
12867                .on_drag_move({
12868                    let observed_drag_moves = self.observed_drag_moves.clone();
12869                    move |event: &DragMoveEvent<PathBuf>, _, _| {
12870                        observed_drag_moves.borrow_mut().push(event.event.position);
12871                    }
12872                })
12873                .on_drop({
12874                    let observed_drops = self.observed_drops.clone();
12875                    move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
12876                })
12877        }
12878    }
12879
12880    #[gpui::test]
12881    fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
12882        struct Drag {
12883            window: AnyWindowHandle,
12884            observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12885            observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12886        }
12887
12888        fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
12889            let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
12890            let observed_drops = Rc::new(RefCell::new(Vec::new()));
12891            let window: AnyWindowHandle = cx
12892                .add_window({
12893                    let observed_drag_moves = observed_drag_moves.clone();
12894                    let observed_drops = observed_drops.clone();
12895                    move |_, _| FileDragView {
12896                        path,
12897                        observed_drag_moves,
12898                        observed_drops,
12899                    }
12900                })
12901                .into();
12902            cx.test_window(window)
12903                .set_start_external_drag_result(platform_result);
12904
12905            let update_result = cx.update_window(window, |_, window, cx| {
12906                window.draw(cx).clear(cx);
12907                window.dispatch_event(
12908                    MouseDownEvent {
12909                        position: point(px(10.), px(10.)),
12910                        button: MouseButton::Left,
12911                        modifiers: Default::default(),
12912                        click_count: 1,
12913                        first_mouse: false,
12914                    }
12915                    .to_platform_input(),
12916                    cx,
12917                );
12918                window.dispatch_event(
12919                    MouseMoveEvent {
12920                        position: point(px(20.), px(20.)),
12921                        pressed_button: Some(MouseButton::Left),
12922                        modifiers: Default::default(),
12923                    }
12924                    .to_platform_input(),
12925                    cx,
12926                );
12927                assert!(cx.active_drag.is_some());
12928            });
12929            assert!(
12930                update_result.is_ok(),
12931                "failed to start drag: {update_result:?}"
12932            );
12933
12934            assert!(cx.test_window(window).external_drag_files().is_empty());
12935            Drag {
12936                window,
12937                observed_drag_moves,
12938                observed_drops,
12939            }
12940        }
12941
12942        let successful_path = PathBuf::from("/tmp/successful-drag");
12943        let successful = start_drag(cx, successful_path.clone(), true);
12944        let outside_position = point(px(-1.), px(20.));
12945        let update_result = cx.update_window(successful.window, |_, window, cx| {
12946            window.dispatch_event(
12947                MouseMoveEvent {
12948                    position: outside_position,
12949                    pressed_button: Some(MouseButton::Left),
12950                    modifiers: Default::default(),
12951                }
12952                .to_platform_input(),
12953                cx,
12954            );
12955            assert!(cx.active_drag.is_none());
12956        });
12957        assert!(
12958            update_result.is_ok(),
12959            "failed to promote drag: {update_result:?}"
12960        );
12961        assert_eq!(
12962            cx.test_window(successful.window).external_drag_files(),
12963            [(successful_path.clone(), true)]
12964        );
12965        // Views must still see the move that leaves the window, otherwise they never learn to tear
12966        // down the drag state they built up while the pointer was inside.
12967        assert_eq!(
12968            successful.observed_drag_moves.borrow().last(),
12969            Some(&outside_position)
12970        );
12971
12972        let first_destination_exit_count = Rc::new(Cell::new(0));
12973        let first_destination: AnyWindowHandle = cx
12974            .add_window({
12975                let first_destination_exit_count = first_destination_exit_count.clone();
12976                move |_, _| FileDropExitView(first_destination_exit_count)
12977            })
12978            .into();
12979        let second_destination_exit_count = Rc::new(Cell::new(0));
12980        let second_destination: AnyWindowHandle = cx
12981            .add_window({
12982                let second_destination_exit_count = second_destination_exit_count.clone();
12983                move |_, _| FileDropExitView(second_destination_exit_count)
12984            })
12985            .into();
12986        let reentry_position = point(px(30.), px(30.));
12987        let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
12988        let update_result = cx.update_window(first_destination, |_, window, cx| {
12989            window.draw(cx).clear(cx);
12990            window.dispatch_event(
12991                FileDropEvent::Entered {
12992                    position: reentry_position,
12993                    paths: external_paths(),
12994                }
12995                .to_platform_input(),
12996                cx,
12997            );
12998            assert!(
12999                cx.active_drag
13000                    .as_ref()
13001                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
13002            );
13003            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13004            assert!(cx.active_drag.is_none());
13005            assert_eq!(first_destination_exit_count.get(), 1);
13006            assert_eq!(second_destination_exit_count.get(), 0);
13007        });
13008        assert!(
13009            update_result.is_ok(),
13010            "failed to handle drag in first destination window: {update_result:?}"
13011        );
13012
13013        let update_result = cx.update_window(second_destination, |_, window, cx| {
13014            window.draw(cx).clear(cx);
13015            window.dispatch_event(
13016                PlatformInput::KeyDown(KeyDownEvent {
13017                    keystroke: Keystroke::parse("down").expect("valid keystroke"),
13018                    is_held: false,
13019                    prefer_character_input: false,
13020                }),
13021                cx,
13022            );
13023            window.dispatch_event(
13024                FileDropEvent::Entered {
13025                    position: reentry_position,
13026                    paths: external_paths(),
13027                }
13028                .to_platform_input(),
13029                cx,
13030            );
13031            assert!(
13032                cx.active_drag
13033                    .as_ref()
13034                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
13035            );
13036            assert_eq!(first_destination_exit_count.get(), 1);
13037            assert_eq!(second_destination_exit_count.get(), 0);
13038
13039            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13040            assert!(cx.active_drag.is_none());
13041            assert_eq!(first_destination_exit_count.get(), 1);
13042            assert_eq!(second_destination_exit_count.get(), 1);
13043        });
13044        assert!(
13045            update_result.is_ok(),
13046            "failed to handle drag in second destination window: {update_result:?}"
13047        );
13048
13049        let update_result = cx.update_window(successful.window, |_, window, cx| {
13050            window.dispatch_event(
13051                FileDropEvent::Entered {
13052                    position: reentry_position,
13053                    paths: external_paths(),
13054                }
13055                .to_platform_input(),
13056                cx,
13057            );
13058            assert!(
13059                cx.active_drag
13060                    .as_ref()
13061                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
13062            );
13063            assert_eq!(
13064                successful.observed_drag_moves.borrow().last(),
13065                Some(&reentry_position)
13066            );
13067
13068            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13069            assert!(cx.active_drag.is_none());
13070
13071            window.dispatch_event(
13072                FileDropEvent::Entered {
13073                    position: reentry_position,
13074                    paths: external_paths(),
13075                }
13076                .to_platform_input(),
13077                cx,
13078            );
13079            assert!(
13080                cx.active_drag
13081                    .as_ref()
13082                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
13083            );
13084
13085            window.dispatch_event(
13086                FileDropEvent::Submit {
13087                    position: reentry_position,
13088                }
13089                .to_platform_input(),
13090                cx,
13091            );
13092            assert_eq!(
13093                successful.observed_drops.borrow().as_slice(),
13094                std::slice::from_ref(&successful_path)
13095            );
13096            assert!(cx.active_drag.is_none());
13097
13098            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13099            assert!(cx.active_drag.is_none());
13100            window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
13101            assert!(cx.active_drag.is_none());
13102
13103            window.dispatch_event(
13104                FileDropEvent::Entered {
13105                    position: reentry_position,
13106                    paths: external_paths(),
13107                }
13108                .to_platform_input(),
13109                cx,
13110            );
13111            assert!(
13112                cx.active_drag
13113                    .as_ref()
13114                    .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
13115            );
13116            window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13117        });
13118        assert!(
13119            update_result.is_ok(),
13120            "failed to restore drag in source window: {update_result:?}"
13121        );
13122
13123        let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
13124        let cancelled = start_drag(cx, cancelled_path.clone(), true);
13125        let update_result = cx.update_window(cancelled.window, |_, window, cx| {
13126            window.dispatch_event(
13127                MouseMoveEvent {
13128                    position: outside_position,
13129                    pressed_button: Some(MouseButton::Left),
13130                    modifiers: Default::default(),
13131                }
13132                .to_platform_input(),
13133                cx,
13134            );
13135            assert!(cx.active_drag.is_none());
13136
13137            window.dispatch_event(
13138                FileDropEvent::Entered {
13139                    position: reentry_position,
13140                    paths: ExternalPaths([cancelled_path].into_iter().collect()),
13141                }
13142                .to_platform_input(),
13143                cx,
13144            );
13145            assert!(
13146                cx.active_drag
13147                    .as_ref()
13148                    .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
13149            );
13150            assert!(cx.stop_active_drag(window));
13151            assert!(cx.active_drag.is_none());
13152        });
13153        assert!(
13154            update_result.is_ok(),
13155            "failed to cancel restored drag: {update_result:?}"
13156        );
13157        assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
13158
13159        let removed_path = PathBuf::from("/tmp/removed-window-drag");
13160        let removed = start_drag(cx, removed_path, true);
13161        let removed_window_id = removed.window.window_id();
13162        let update_result = cx.update_window(removed.window, |_, window, cx| {
13163            window.dispatch_event(
13164                MouseMoveEvent {
13165                    position: outside_position,
13166                    pressed_button: Some(MouseButton::Left),
13167                    modifiers: Default::default(),
13168                }
13169                .to_platform_input(),
13170                cx,
13171            );
13172            assert!(cx.active_drag.is_none());
13173            window.remove_window();
13174        });
13175        assert!(
13176            update_result.is_ok(),
13177            "failed to remove drag source window: {update_result:?}"
13178        );
13179        assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
13180
13181        let failed_path = PathBuf::from("/tmp/failed-drag");
13182        let failed = start_drag(cx, failed_path.clone(), false);
13183        let update_result = cx.update_window(failed.window, |_, window, cx| {
13184            for x_position in [-1., -2.] {
13185                window.dispatch_event(
13186                    MouseMoveEvent {
13187                        position: point(px(x_position), px(20.)),
13188                        pressed_button: Some(MouseButton::Left),
13189                        modifiers: Default::default(),
13190                    }
13191                    .to_platform_input(),
13192                    cx,
13193                );
13194            }
13195            assert!(cx.active_drag.is_some());
13196        });
13197        assert!(
13198            update_result.is_ok(),
13199            "failed to retain drag after platform failure: {update_result:?}"
13200        );
13201        assert_eq!(
13202            cx.test_window(failed.window).external_drag_files(),
13203            [(failed_path, true)]
13204        );
13205    }
13206
13207    struct FocusForwarder {
13208        a: FocusHandle,
13209        b: FocusHandle,
13210    }
13211
13212    impl Render for FocusForwarder {
13213        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13214            div()
13215                .size_full()
13216                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
13217                .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
13218        }
13219    }
13220
13221    /// When a focus listener moves focus again (e.g. a dock forwarding focus to its
13222    /// active panel), the resulting focus events must be dispatched without waiting
13223    /// for an unrelated redraw of the window.
13224    #[gpui::test]
13225    fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
13226        let b_focus_count = Rc::new(Cell::new(0));
13227        let window = cx.add_window({
13228            let b_focus_count = b_focus_count.clone();
13229            move |window, cx| {
13230                let a = cx.focus_handle();
13231                let b = cx.focus_handle();
13232                cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
13233                    let b = this.b.clone();
13234                    window.focus(&b, cx);
13235                })
13236                .detach();
13237                cx.on_focus(&b, window, move |_, _, _| {
13238                    b_focus_count.set(b_focus_count.get() + 1);
13239                })
13240                .detach();
13241                FocusForwarder { a, b }
13242            }
13243        });
13244
13245        window
13246            .update(cx, |_, window, _| window.activate_window())
13247            .unwrap();
13248        cx.executor().run_until_parked();
13249
13250        window
13251            .update(cx, |this, window, cx| {
13252                let a = this.a.clone();
13253                window.focus(&a, cx);
13254            })
13255            .unwrap();
13256        cx.executor().run_until_parked();
13257
13258        window
13259            .update(cx, |this, window, _| {
13260                assert!(this.b.is_focused(window));
13261            })
13262            .unwrap();
13263        assert_eq!(b_focus_count.get(), 1);
13264    }
13265
13266    #[gpui::test]
13267    fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
13268        let events = Rc::new(RefCell::new(Vec::new()));
13269        let window = cx.add_window({
13270            let events = events.clone();
13271            move |_, _| TouchDragListener { events }
13272        });
13273        let touch = TouchId(1);
13274
13275        dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
13276        dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
13277        dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
13278
13279        assert_eq!(
13280            events.borrow().as_slice(),
13281            [
13282                (TouchPhase::Started, px(10.)),
13283                (TouchPhase::Moved, px(30.)),
13284                (TouchPhase::Ended, px(40.)),
13285            ]
13286        );
13287    }
13288
13289    #[gpui::test]
13290    fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
13291        let claims = Rc::new(RefCell::new(Vec::new()));
13292        let window = cx.add_window({
13293            let claims = claims.clone();
13294            move |_, _| BackListeners { claims }
13295        });
13296        let dispatch_back = |cx: &mut TestAppContext, x: f32| {
13297            window
13298                .update(cx, |_, window, cx| {
13299                    window
13300                        .dispatch_event(
13301                            BackGestureEvent {
13302                                phase: BackGesturePhase::Started,
13303                                start_position: point(px(x), px(10.)),
13304                                progress: 0.,
13305                            }
13306                            .to_platform_input(),
13307                            cx,
13308                        )
13309                        .default_prevented
13310                })
13311                .unwrap()
13312        };
13313        assert!(dispatch_back(cx, 10.));
13314        assert!(dispatch_back(cx, 80.));
13315        assert!(!dispatch_back(cx, 150.));
13316        assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
13317    }
13318
13319    struct BackListeners {
13320        claims: Rc<RefCell<Vec<&'static str>>>,
13321    }
13322
13323    impl Render for BackListeners {
13324        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13325            let claim = |name: &'static str| {
13326                let claims = self.claims.clone();
13327                move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
13328                    claims.borrow_mut().push(name)
13329                }
13330            };
13331            div().size_full().child(
13332                div()
13333                    .w(px(100.))
13334                    .h_full()
13335                    .on_back_gesture(claim("outer"))
13336                    .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
13337            )
13338        }
13339    }
13340
13341    struct TouchDragListener {
13342        events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
13343    }
13344
13345    impl Render for TouchDragListener {
13346        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13347            let events = self.events.clone();
13348            canvas(
13349                |_, _, _| {},
13350                move |_, _, window, _| {
13351                    window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
13352                        if phase != DispatchPhase::Bubble {
13353                            return;
13354                        }
13355                        events.borrow_mut().push((event.phase, event.position.x));
13356                        if event.phase == TouchPhase::Started {
13357                            window.prevent_default();
13358                        }
13359                    });
13360                },
13361            )
13362        }
13363    }
13364
13365    #[gpui::test]
13366    fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
13367        for response in [
13368            LongPressResponse::PreventDefault,
13369            LongPressResponse::StopPropagation,
13370            LongPressResponse::None,
13371        ] {
13372            let phases = Rc::new(RefCell::new(Vec::new()));
13373            let window = cx.add_window({
13374                let phases = phases.clone();
13375                move |_, _| LongPressListener { phases, response }
13376            });
13377            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13378            cx.executor().advance_clock(Duration::from_millis(501));
13379            cx.executor().run_until_parked();
13380            window
13381                .update(cx, |_, window, _| {
13382                    assert_eq!(
13383                        window.long_press_capture.is_some(),
13384                        response == LongPressResponse::PreventDefault
13385                    );
13386                })
13387                .unwrap();
13388            dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13389            dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
13390            window
13391                .update(cx, |_, window, _| {
13392                    assert!(window.long_press_capture.is_none());
13393                })
13394                .unwrap();
13395
13396            let phases = phases.borrow();
13397            if response == LongPressResponse::PreventDefault {
13398                assert_eq!(
13399                    phases.as_slice(),
13400                    [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
13401                );
13402            } else {
13403                assert_eq!(phases.as_slice(), [TouchPhase::Started]);
13404            }
13405        }
13406    }
13407
13408    #[gpui::test]
13409    fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
13410        let phases = Rc::new(RefCell::new(Vec::new()));
13411        let window = cx.add_window({
13412            let phases = phases.clone();
13413            move |_, _| LongPressListener {
13414                phases,
13415                response: LongPressResponse::None,
13416            }
13417        });
13418        window
13419            .update(cx, |_, window, _| {
13420                window.prevent_default();
13421            })
13422            .unwrap();
13423
13424        dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13425        cx.executor().advance_clock(Duration::from_millis(501));
13426        cx.executor().run_until_parked();
13427        dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13428
13429        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13430    }
13431
13432    #[gpui::test]
13433    fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
13434        for (phase, position) in [
13435            (TouchPhase::Ended, 0.),
13436            (TouchPhase::Cancelled, 0.),
13437            (TouchPhase::Moved, 20.),
13438        ] {
13439            let phases = Rc::new(RefCell::new(Vec::new()));
13440            let window = cx.add_window({
13441                let phases = phases.clone();
13442                move |_, _| LongPressListener {
13443                    phases,
13444                    response: LongPressResponse::PreventDefault,
13445                }
13446            });
13447            dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13448            dispatch_touch(window, cx, TouchId(1), phase, position);
13449            cx.executor().advance_clock(Duration::from_millis(501));
13450            cx.executor().run_until_parked();
13451
13452            assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
13453        }
13454    }
13455
13456    #[gpui::test]
13457    fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
13458        let phases = Rc::new(RefCell::new(Vec::new()));
13459        let window = cx.add_window({
13460            let phases = phases.clone();
13461            move |_, _| LongPressListener {
13462                phases,
13463                response: LongPressResponse::PreventDefault,
13464            }
13465        });
13466        let first_touch = TouchId(1);
13467        dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
13468        cx.executor().advance_clock(Duration::from_millis(250));
13469        dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
13470        dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
13471
13472        cx.executor().advance_clock(Duration::from_millis(251));
13473        cx.executor().run_until_parked();
13474        assert!(phases.borrow().is_empty());
13475
13476        cx.executor().advance_clock(Duration::from_millis(250));
13477        cx.executor().run_until_parked();
13478        assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13479    }
13480
13481    #[gpui::test]
13482    fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
13483        test_underline_paint_at_scales(cx, |window| {
13484            let (numerator, denominator) = match window.scale_factor() {
13485                1.0 => (1, 1),
13486                1.25 => (5, 4),
13487                1.5 => (3, 2),
13488                2.0 => (2, 1),
13489                3.0 => (3, 1),
13490                scale => panic!("unexpected scale {scale}"),
13491            };
13492            let snap = |quarters: i32| {
13493                let scaled = quarters * numerator;
13494                let divisor = 4 * denominator;
13495                let rounded =
13496                    scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
13497                ScaledPixels((scaled.signum() * rounded) as f32)
13498            };
13499            let stroke = |quarters| {
13500                if quarters == 0 {
13501                    ScaledPixels(0.)
13502                } else {
13503                    snap(quarters).max(ScaledPixels(1.))
13504                }
13505            };
13506
13507            for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
13508                for width in [0, 1, 3, 84] {
13509                    for thickness in [0, 1, 4, 7] {
13510                        for wavy in [false, true] {
13511                            let style = UnderlineStyle {
13512                                thickness: px(thickness as f32 / 4.),
13513                                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13514                                wavy,
13515                                offset: px(0.),
13516                            };
13517                            let bounds = Bounds::new(
13518                                point(snap(origin), snap(-origin)),
13519                                size(
13520                                    stroke(width),
13521                                    stroke(thickness) * if wavy { 3. } else { 1. },
13522                                ),
13523                            );
13524                            let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
13525                            let width = px(width as f32 / 4.);
13526                            assert_eq!(window.underline_bounds(origin, width, &style), bounds);
13527                            let original = paint_test_underlines(window, |window| {
13528                                window.paint_underline(origin, width, &style);
13529                            })
13530                            .to_vec();
13531                            assert_eq!(original.len(), usize::from(!bounds.is_empty()));
13532                            if let Some(underline) = original.first() {
13533                                assert_eq!(underline.bounds, bounds);
13534                                assert_eq!(underline.thickness, stroke(thickness));
13535                                assert_eq!(underline.wavy, wavy.into());
13536                                assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
13537                            }
13538
13539                            let underlines = paint_test_underlines(window, |window| {
13540                                window.paint_underline_with_exclusions(origin, width, &style, &[]);
13541                            });
13542                            assert_eq!(underlines.len(), original.len());
13543                            for (actual, original) in underlines.iter().zip(&original) {
13544                                assert_same_underline_geometry(actual, original);
13545                                assert_eq!(actual.content_mask, original.content_mask);
13546                            }
13547
13548                            let left = bounds.left().0 as i32;
13549                            let right = bounds.right().0 as i32;
13550                            let exclusions = [
13551                                (15, 25),
13552                                (3, 7),
13553                                (5, 10),
13554                                (10, 12),
13555                                (0, 0),
13556                                (4, 2),
13557                                (-50, -1),
13558                                (70, 100),
13559                            ]
13560                            .map(|(start, end)| {
13561                                ScaledPixels((left + start) as f32)
13562                                    ..ScaledPixels((left + end) as f32)
13563                            });
13564                            let underlines = paint_test_underlines(window, |window| {
13565                                window.paint_underline_with_exclusions(
13566                                    origin,
13567                                    width,
13568                                    &style,
13569                                    &exclusions,
13570                                );
13571                            });
13572                            let expected = (left..right)
13573                                .filter(|column| {
13574                                    !bounds.is_empty()
13575                                        && !exclusions.iter().any(|span| {
13576                                            span.contains(&ScaledPixels(*column as f32))
13577                                        })
13578                                })
13579                                .collect::<Vec<_>>();
13580                            assert_eq!(underline_device_columns(underlines), expected);
13581                            for underline in underlines {
13582                                assert_same_underline_geometry(underline, &original[0]);
13583                            }
13584                        }
13585                    }
13586                }
13587            }
13588        });
13589    }
13590
13591    #[gpui::test]
13592    fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
13593        test_underline_paint_at_scales(cx, |window| {
13594            if window.scale_factor() != 2.0 {
13595                return;
13596            }
13597            let style = UnderlineStyle {
13598                thickness: px(1.),
13599                color: None,
13600                wavy: true,
13601                offset: px(0.),
13602            };
13603            let origin = point(px(2.888_183_8), px(15.357_917));
13604            let width = px(23.848_145) - origin.x;
13605            let original = paint_test_underlines(window, |window| {
13606                window.paint_underline(origin, width, &style);
13607            })[0];
13608            assert_eq!(original.bounds.left(), ScaledPixels(6.));
13609            assert_eq!(original.bounds.right(), ScaledPixels(48.));
13610            let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
13611            assert_eq!(point_bounds.left(), ScaledPixels(6.));
13612            assert_eq!(point_bounds.right(), ScaledPixels(28.));
13613
13614            let underlines = paint_test_underlines(window, |window| {
13615                window.paint_underline_with_exclusions(
13616                    origin,
13617                    width,
13618                    &style,
13619                    &[point_bounds.left()..point_bounds.right()],
13620                );
13621            });
13622            assert_eq!(underlines.len(), 1);
13623            assert_same_underline_geometry(&underlines[0], &original);
13624            assert_eq!(
13625                underline_device_columns(underlines),
13626                (28..48).collect::<Vec<_>>()
13627            );
13628        });
13629    }
13630
13631    #[gpui::test]
13632    fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
13633        test_underline_paint_at_scales(cx, |window| {
13634            let scale = window.scale_factor();
13635            let original_mask = window.content_mask();
13636            let original_opacity = window.element_opacity();
13637            let mask = ContentMask {
13638                bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
13639                ..Default::default()
13640            };
13641            let style = UnderlineStyle {
13642                thickness: px(2.),
13643                color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13644                wavy: true,
13645                offset: px(0.),
13646            };
13647            let origin = point(px(-1.25), px(9.25));
13648            let width = px(24.);
13649            window.with_content_mask(Some(mask), |window| {
13650                window.with_element_opacity(Some(0.5), |window| {
13651                    window.with_element_opacity(Some(0.5), |window| {
13652                        let original = paint_test_underlines(window, |window| {
13653                            window.paint_underline(origin, width, &style);
13654                        })[0];
13655                        assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
13656                        let underlines = paint_test_underlines(window, |window| {
13657                            window.paint_underline_with_exclusions(
13658                                origin,
13659                                width,
13660                                &style,
13661                                &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
13662                            );
13663                        });
13664                        assert_eq!(underlines.len(), 2);
13665                        let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
13666                            |(left, right)| {
13667                                Bounds::from_corners(
13668                                    point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
13669                                    point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
13670                                )
13671                            },
13672                        );
13673                        assert_eq!(
13674                            underlines
13675                                .iter()
13676                                .map(|underline| underline.content_mask.bounds)
13677                                .collect::<Vec<_>>(),
13678                            expected
13679                        );
13680                        for underline in underlines {
13681                            assert_same_underline_geometry(underline, &original);
13682                        }
13683                    });
13684                });
13685            });
13686            assert_eq!(window.content_mask(), original_mask);
13687            assert_eq!(window.element_opacity(), original_opacity);
13688        });
13689    }
13690
13691    #[gpui::test]
13692    fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
13693        test_underline_paint_at_scales(cx, |window| {
13694            let style = UnderlineStyle {
13695                thickness: px(1.),
13696                color: None,
13697                wavy: true,
13698                offset: px(0.),
13699            };
13700            let origin = point(px(-4.), px(-1.));
13701            let width = px(8.);
13702            let left = (-4. * window.scale_factor()) as i32;
13703            let right = (4. * window.scale_factor()) as i32;
13704            let endpoints = [-16, -8, -1, 0, 1, 8, 16];
13705            for first_start in endpoints {
13706                for first_end in endpoints {
13707                    for second_start in endpoints {
13708                        for second_end in endpoints {
13709                            let exclusions = [first_start..first_end, second_start..second_end];
13710                            let expected = (left..right)
13711                                .filter(|column| {
13712                                    !exclusions.iter().any(|span| span.contains(column))
13713                                })
13714                                .collect::<Vec<_>>();
13715                            let exclusions = exclusions.map(|span| {
13716                                ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
13717                            });
13718                            let underlines = paint_test_underlines(window, |window| {
13719                                window.paint_underline_with_exclusions(
13720                                    origin,
13721                                    width,
13722                                    &style,
13723                                    &exclusions,
13724                                );
13725                            });
13726                            assert_eq!(
13727                                underline_device_columns(underlines),
13728                                expected,
13729                                "{exclusions:?}"
13730                            );
13731                        }
13732                    }
13733                }
13734            }
13735        });
13736    }
13737
13738    #[derive(Clone, Copy, PartialEq)]
13739    enum LongPressResponse {
13740        PreventDefault,
13741        StopPropagation,
13742        None,
13743    }
13744
13745    struct LongPressListener {
13746        phases: Rc<RefCell<Vec<TouchPhase>>>,
13747        response: LongPressResponse,
13748    }
13749
13750    impl Render for LongPressListener {
13751        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13752            let entity = cx.entity();
13753            let phases = self.phases.clone();
13754            let response = self.response;
13755            canvas(
13756                |_, _, _| {},
13757                move |_, _, window, _| {
13758                    window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
13759                        if phase != DispatchPhase::Bubble {
13760                            return;
13761                        }
13762                        phases.borrow_mut().push(event.phase);
13763                        match response {
13764                            LongPressResponse::PreventDefault => {
13765                                window.capture_long_press(&entity);
13766                                window.prevent_default();
13767                            }
13768                            LongPressResponse::StopPropagation => cx.stop_propagation(),
13769                            LongPressResponse::None => {}
13770                        }
13771                    });
13772                },
13773            )
13774        }
13775    }
13776
13777    struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
13778
13779    impl Render for UnderlineTestView {
13780        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13781            let paint = self.0.clone();
13782            canvas(
13783                |_, _, _| {},
13784                move |_, _, window, _| {
13785                    window.content_mask_stack.push(ContentMask::rect(Bounds::from_corners(
13786                        point(px(-1000.), px(-1000.)),
13787                        point(px(1000.), px(1000.)),
13788                    )));
13789                    paint(window);
13790                    window.content_mask_stack.pop();
13791                },
13792            )
13793            .size_full()
13794        }
13795    }
13796
13797    fn test_underline_paint_at_scales(
13798        cx: &mut TestAppContext,
13799        paint: impl Fn(&mut Window) + 'static,
13800    ) {
13801        let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
13802        for scale in [1., 1.25, 1.5, 2., 3.] {
13803            cx.simulate_window_scale_factor_change(window.into(), scale);
13804            cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
13805                .unwrap();
13806        }
13807    }
13808
13809    fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
13810        window.next_frame.scene.clear();
13811        paint(window);
13812        &window.next_frame.scene.underlines
13813    }
13814
13815    fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
13816        assert_eq!(actual.bounds, expected.bounds);
13817        assert_eq!(actual.thickness, expected.thickness);
13818        assert_eq!(actual.wavy, expected.wavy);
13819        assert_eq!(actual.color, expected.color);
13820        assert_eq!(actual.pad, expected.pad);
13821    }
13822
13823    fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
13824        underlines
13825            .iter()
13826            .flat_map(|underline| {
13827                let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
13828                bounds.left().0 as i32..bounds.right().0 as i32
13829            })
13830            .collect()
13831    }
13832
13833    actions!(window_test, [StandaloneModifierAction]);
13834
13835    struct StandaloneModifierView {
13836        focus_handle: FocusHandle,
13837        action_count: usize,
13838    }
13839
13840    impl Render for StandaloneModifierView {
13841        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13842            div()
13843                .key_context("StandaloneModifier")
13844                .track_focus(&self.focus_handle)
13845                .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
13846                    this.action_count += 1;
13847                }))
13848        }
13849    }
13850
13851    #[gpui::test]
13852    fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
13853        use crate::{KeyBinding, Modifiers};
13854
13855        cx.update(|cx| {
13856            cx.bind_keys([KeyBinding::new(
13857                "shift shift",
13858                StandaloneModifierAction,
13859                Some("StandaloneModifier"),
13860            )]);
13861        });
13862        let (view, cx) = cx.add_window_view(|window, cx| {
13863            let focus_handle = cx.focus_handle();
13864            window.focus(&focus_handle, cx);
13865            StandaloneModifierView {
13866                focus_handle,
13867                action_count: 0,
13868            }
13869        });
13870        let shift = Modifiers {
13871            shift: true,
13872            ..Modifiers::default()
13873        };
13874        cx.simulate_modifiers_change(shift);
13875        cx.simulate_modifiers_change(Modifiers::default());
13876        cx.update(|window, _| {
13877            assert_eq!(
13878                window.pending_input_keystrokes(),
13879                Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
13880            );
13881        });
13882        cx.background_executor.advance_clock(Duration::from_secs(2));
13883        cx.run_until_parked();
13884        cx.update(|window, cx| {
13885            assert!(!window.has_pending_keystrokes());
13886            assert_eq!(view.read(cx).action_count, 0);
13887        });
13888
13889        cx.simulate_modifiers_change(shift);
13890        cx.simulate_modifiers_change(Modifiers::default());
13891        cx.update(|window, cx| {
13892            assert!(window.has_pending_keystrokes());
13893            assert_eq!(view.read(cx).action_count, 0);
13894        });
13895
13896        cx.simulate_modifiers_change(shift);
13897        cx.simulate_modifiers_change(Modifiers::default());
13898        cx.update(|window, cx| {
13899            assert!(!window.has_pending_keystrokes());
13900            assert_eq!(view.read(cx).action_count, 1);
13901        });
13902    }
13903
13904    #[gpui::test]
13905    fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
13906        use crate::{KeyBinding, Modifiers};
13907
13908        cx.update(|cx| {
13909            cx.bind_keys([KeyBinding::new(
13910                "shift shift",
13911                StandaloneModifierAction,
13912                Some("StandaloneModifier"),
13913            )]);
13914        });
13915        let (view, cx) = cx.add_window_view(|window, cx| {
13916            let focus_handle = cx.focus_handle();
13917            window.focus(&focus_handle, cx);
13918            StandaloneModifierView {
13919                focus_handle,
13920                action_count: 0,
13921            }
13922        });
13923        let shift = Modifiers {
13924            shift: true,
13925            ..Modifiers::default()
13926        };
13927        cx.simulate_modifiers_change(shift);
13928        cx.simulate_modifiers_change(Modifiers::default());
13929        cx.background_executor
13930            .advance_clock(Duration::from_millis(500));
13931        cx.update(|window, cx| {
13932            assert!(window.has_pending_keystrokes());
13933            assert_eq!(view.read(cx).action_count, 0);
13934        });
13935        cx.simulate_modifiers_change(shift);
13936        cx.simulate_modifiers_change(Modifiers::default());
13937        cx.update(|window, cx| {
13938            assert!(!window.has_pending_keystrokes());
13939            assert_eq!(view.read(cx).action_count, 1);
13940        });
13941        cx.background_executor.advance_clock(Duration::from_secs(2));
13942        cx.run_until_parked();
13943        cx.update(|window, cx| {
13944            assert!(!window.has_pending_keystrokes());
13945            assert_eq!(view.read(cx).action_count, 1);
13946        });
13947    }
13948
13949    fn dispatch_touch<T: 'static>(
13950        window: crate::WindowHandle<T>,
13951        cx: &mut TestAppContext,
13952        id: TouchId,
13953        phase: TouchPhase,
13954        x: f32,
13955    ) {
13956        window
13957            .update(cx, |_, window, cx| {
13958                window.dispatch_event(
13959                    TouchEvent {
13960                        id,
13961                        phase,
13962                        position: point(px(x), px(0.)),
13963                        predicted_position: None,
13964                        force: None,
13965                    }
13966                    .to_platform_input(),
13967                    cx,
13968                );
13969            })
13970            .unwrap();
13971    }
13972
13973    #[gpui::test]
13974    fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
13975        struct Child {
13976            renders: usize,
13977        }
13978
13979        impl Render for Child {
13980            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13981                self.renders += 1;
13982                div().size_full().bg(crate::rgb(0xff0000))
13983            }
13984        }
13985
13986        struct Root {
13987            opacity: f32,
13988            width: Pixels,
13989            child: crate::Entity<Child>,
13990        }
13991
13992        impl Render for Root {
13993            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13994                div()
13995                    .w(self.width)
13996                    .h(px(200.))
13997                    .opacity(self.opacity)
13998                    .hover(|style| style.opacity(1.))
13999                    .child(
14000                        self.child
14001                            .clone()
14002                            .cached(crate::StyleRefinement::default().size(px(100.))),
14003                    )
14004            }
14005        }
14006
14007        /// Updates the root, draws until no more frames are requested, and returns the
14008        /// child's painted alpha and how many times it has rendered.
14009        fn update_and_draw(
14010            window: crate::WindowHandle<Root>,
14011            child: &crate::Entity<Child>,
14012            cx: &mut TestAppContext,
14013            update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
14014        ) -> (f32, usize) {
14015            window
14016                .update(cx, |root, window, cx| {
14017                    update(root, window, cx);
14018                    cx.notify();
14019                })
14020                .expect("update root");
14021            for _ in 0..3 {
14022                let (alpha, renders, requested_frames) = cx
14023                    .update_window(window.into(), |_, window, cx| {
14024                        window.draw(cx).clear(cx);
14025                        let quads = &window.rendered_frame.scene.quads;
14026                        assert_eq!(quads.len(), 1);
14027                        let alpha = quads.first().expect("child quad").background.solid.a;
14028                        (
14029                            alpha,
14030                            child.read(cx).renders,
14031                            window.simulate_next_frame(cx),
14032                        )
14033                    })
14034                    .expect("draw window");
14035                if requested_frames == 0 {
14036                    return (alpha, renders);
14037                }
14038            }
14039            panic!("cached child kept requesting frames");
14040        }
14041
14042        let child = cx.new(|_| Child { renders: 0 });
14043        let window = cx.add_window(|_, _| Root {
14044            opacity: 1.,
14045            width: px(200.),
14046            child: child.clone(),
14047        });
14048        let outside = point(px(500.), px(500.));
14049        let inside = point(px(50.), px(50.));
14050        let beside = point(px(250.), px(50.));
14051
14052        // Changing the wrapper's opacity redraws the child; unchanged opacity reuses it.
14053        let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
14054            window.simulate_mouse_move(outside, cx)
14055        };
14056        assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
14057        assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
14058        let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
14059        assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
14060        assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
14061
14062        // Hover opacity applies when the mouse enters and leaves.
14063        let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
14064            window.simulate_mouse_move(inside, cx)
14065        };
14066        assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
14067        let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
14068            window.simulate_mouse_move(beside, cx)
14069        };
14070        assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
14071
14072        // Widening the wrapper puts it under a still mouse, so only paint's hit test sees
14073        // the hover.
14074        let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
14075        assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
14076    }
14077
14078    #[gpui::test]
14079    fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
14080        struct ResizeHandle;
14081
14082        impl Render for ResizeHandle {
14083            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14084                div().size_full().cursor_text().child(
14085                    div()
14086                        .id("resize-handle")
14087                        .w(px(4.))
14088                        .h_full()
14089                        .cursor_col_resize()
14090                        .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
14091                )
14092            }
14093        }
14094
14095        let window = cx.add_window(|_, _| ResizeHandle);
14096        let handle_position = point(px(1.), px(10.));
14097        let drag_position = point(px(20.), px(10.));
14098        let cursor_observer = cx.clone();
14099
14100        let update_result = cx.update_window(window.into(), |_, window, cx| {
14101            window.hovered.set(true);
14102            window.active.set(true);
14103            window.draw(cx).clear(cx);
14104            window.dispatch_event(
14105                MouseMoveEvent {
14106                    position: handle_position,
14107                    ..Default::default()
14108                }
14109                .to_platform_input(),
14110                cx,
14111            );
14112            window.dispatch_event(
14113                MouseDownEvent {
14114                    position: handle_position,
14115                    button: MouseButton::Left,
14116                    ..Default::default()
14117                }
14118                .to_platform_input(),
14119                cx,
14120            );
14121            window.dispatch_event(
14122                MouseMoveEvent {
14123                    position: drag_position,
14124                    pressed_button: Some(MouseButton::Left),
14125                    ..Default::default()
14126                }
14127                .to_platform_input(),
14128                cx,
14129            );
14130            assert!(cx.has_active_drag());
14131            // Asserted here because leaving this update flushes effects, which paints a frame.
14132            assert_eq!(
14133                cursor_observer.test_platform().cursor_style(),
14134                CursorStyle::ResizeColumn
14135            );
14136
14137            window.draw(cx).clear(cx);
14138            window.dispatch_event(
14139                MouseUpEvent {
14140                    position: drag_position,
14141                    button: MouseButton::Left,
14142                    ..Default::default()
14143                }
14144                .to_platform_input(),
14145                cx,
14146            );
14147            window.draw(cx).clear(cx);
14148        });
14149        assert!(
14150            update_result.is_ok(),
14151            "failed to run drag: {update_result:?}"
14152        );
14153        assert_eq!(
14154            cursor_observer.test_platform().cursor_style(),
14155            CursorStyle::IBeam
14156        );
14157    }
14158}
14159
14160#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
14161mod inspector_tests {
14162    use super::*;
14163    use crate::{
14164        DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
14165    };
14166
14167    #[gpui::test]
14168    fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
14169        let windows = [
14170            cx.add_window(|_, cx| InspectorTestRoot {
14171                child: cx.new(|_| InspectorTestView::default()),
14172            }),
14173            cx.add_window(|_, cx| InspectorTestRoot {
14174                child: cx.new(|_| InspectorTestView::default()),
14175            }),
14176        ];
14177        for window in windows {
14178            assert_closed_inspector(window.into(), cx);
14179        }
14180        for _ in 0..2 {
14181            cx.update_window(windows[0].into(), |root, window, cx| {
14182                let root = root.downcast::<InspectorTestRoot>().expect("test root");
14183                let child_widths = root.read(cx).child.read(cx).child_widths.clone();
14184                window.toggle_inspector(cx);
14185                window.draw(cx).clear(cx);
14186                assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
14187                let path = window
14188                    .rendered_frame
14189                    .next_inspector_instance_ids
14190                    .iter()
14191                    .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
14192                    .expect("anonymous siblings share an inspector path");
14193                let selected_id = InspectorElementId {
14194                    path,
14195                    instance_id: 1,
14196                };
14197                let position = window
14198                    .rendered_frame
14199                    .hitboxes
14200                    .iter()
14201                    .find(|hitbox| {
14202                        window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
14203                            == Some(&selected_id)
14204                    })
14205                    .expect("middle sibling is pickable")
14206                    .bounds
14207                    .center();
14208                window.simulate_mouse_move(position, cx);
14209                window.dispatch_event(
14210                    PlatformInput::MouseDown(MouseDownEvent {
14211                        position,
14212                        button: MouseButton::Left,
14213                        modifiers: Modifiers::default(),
14214                        click_count: 1,
14215                        first_mouse: false,
14216                    }),
14217                    cx,
14218                );
14219                window.dispatch_event(
14220                    PlatformInput::MouseUp(MouseUpEvent {
14221                        position,
14222                        button: MouseButton::Left,
14223                        modifiers: Modifiers::default(),
14224                        click_count: 1,
14225                    }),
14226                    cx,
14227                );
14228                assert!(!window.is_inspector_picking(cx));
14229                assert_eq!(
14230                    window
14231                        .inspector
14232                        .as_ref()
14233                        .expect("open inspector")
14234                        .read(cx)
14235                        .active_element_id(),
14236                    Some(&selected_id)
14237                );
14238                window.draw(cx).clear(cx);
14239                window.with_inspector_state::<DivInspectorState, _>(
14240                    Some(&selected_id),
14241                    cx,
14242                    |state, _| {
14243                        let state = state.as_mut().expect("selected div has style state");
14244                        assert_eq!(
14245                            state.base_style.size.width,
14246                            Some(crate::Length::from(px(10.)))
14247                        );
14248                        state.base_style.size.width = Some(crate::Length::from(px(25.)));
14249                    },
14250                );
14251                window.refresh();
14252                window.draw(cx).clear(cx);
14253                assert_eq!(
14254                    child_widths.borrow().as_slice(),
14255                    &[px(10.), px(25.), px(10.)]
14256                );
14257            })
14258            .expect("pick and edit a cached child");
14259            assert_closed_inspector(windows[1].into(), cx);
14260            windows[0]
14261                .update(cx, |_, window, cx| window.toggle_inspector(cx))
14262                .expect("close inspector");
14263            assert_closed_inspector(windows[0].into(), cx);
14264        }
14265    }
14266
14267    struct InspectorTestRoot {
14268        child: Entity<InspectorTestView>,
14269    }
14270
14271    impl Render for InspectorTestRoot {
14272        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14273            self.child
14274                .clone()
14275                .cached(StyleRefinement::default().size(px(100.)))
14276        }
14277    }
14278
14279    #[derive(Default)]
14280    struct InspectorTestView {
14281        child_widths: Rc<RefCell<Vec<Pixels>>>,
14282    }
14283
14284    impl Render for InspectorTestView {
14285        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14286            let child_widths = self.child_widths.clone();
14287            div()
14288                .on_children_prepainted(move |bounds, _, _| {
14289                    *child_widths.borrow_mut() =
14290                        bounds.iter().map(|bounds| bounds.size.width).collect();
14291                })
14292                .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
14293                .id("inspector-root")
14294                .flex()
14295                .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
14296        }
14297    }
14298
14299    fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
14300        cx.update_window(window, |root, window, cx| {
14301            window.draw(cx).clear(cx);
14302            window.draw(cx).clear(cx);
14303            let root = root.downcast::<InspectorTestRoot>().expect("test root");
14304            assert_eq!(
14305                root.read(cx)
14306                    .child
14307                    .read(cx)
14308                    .child_widths
14309                    .borrow()
14310                    .as_slice(),
14311                &[px(10.); 3]
14312            );
14313            for frame in [&window.rendered_frame, &window.next_frame] {
14314                assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
14315                assert_eq!(frame.inspector_hitboxes.capacity(), 0);
14316            }
14317        })
14318        .expect("closed inspector has no bookkeeping and no style overrides");
14319    }
14320}
14321
14322/// vue-native fork: `Window::set_assume_active`.
14323#[cfg(test)]
14324mod vn_assume_active_tests {
14325    use crate::{
14326        Context, FocusHandle, Render, Subscription, TestAppContext, Window, div, prelude::*, px,
14327        size,
14328    };
14329    use std::{cell::Cell, rc::Rc};
14330
14331    struct Focusable {
14332        handle: FocusHandle,
14333        _on_focus: Subscription,
14334    }
14335
14336    impl Render for Focusable {
14337        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14338            div().size_full().track_focus(&self.handle)
14339        }
14340    }
14341
14342    #[gpui::test]
14343    fn an_assumed_active_window_runs_focus_and_ignores_the_os(cx: &mut TestAppContext) {
14344        let focused = Rc::new(Cell::new(0u32));
14345        let counter = focused.clone();
14346        let window = cx.open_window(size(px(200.), px(200.)), move |window, cx| {
14347            let handle = cx.focus_handle();
14348            let on_focus = cx.on_focus(&handle, window, move |_, _, _| counter.set(counter.get() + 1));
14349            Focusable { handle, _on_focus: on_focus }
14350        });
14351        let platform = cx.test_window(window.into());
14352        platform.simulate_active_status_change(false);
14353        cx.run_until_parked();
14354
14355        // An inactive window's focus events carry no path, so nothing hears
14356        // the focus move.
14357        window
14358            .update(cx, |view, window, cx| window.focus(&view.handle, cx))
14359            .unwrap();
14360        cx.run_until_parked();
14361        assert_eq!(focused.get(), 0, "no focus event without activation");
14362
14363        // Assumed active: the focused element hears it on the next frame.
14364        window
14365            .update(cx, |_, window, _| window.set_assume_active(true))
14366            .unwrap();
14367        cx.run_until_parked();
14368        assert_eq!(focused.get(), 1, "the focus event carries the path");
14369        let active = |cx: &mut TestAppContext| {
14370            window
14371                .update(cx, |_, window, _| window.is_window_active())
14372                .unwrap()
14373        };
14374        assert!(active(cx));
14375
14376        // The OS's activation changes are ignored while it is set.
14377        platform.simulate_active_status_change(false);
14378        cx.run_until_parked();
14379        assert!(active(cx), "still active after the OS says otherwise");
14380
14381        // Off: back to what the platform reports (a test window: inactive).
14382        window
14383            .update(cx, |_, window, _| window.set_assume_active(false))
14384            .unwrap();
14385        assert!(!active(cx));
14386    }
14387}
14388
14389/// vue-native fork: rounded content masks, `ContentMask::intersect`'s corner
14390/// rule, `contains` and `transform_mask`.
14391/// vue-native fork: outer shadows are cut out of the border box
14392/// ([`Window::paint_drop_shadows`]), with CSS's spread radii.
14393#[cfg(test)]
14394mod vn_shadow_tests {
14395    use super::{SHADOW_INSET, SHADOW_OUTSIDE_BOX, SHADOW_UNDER_BOX, spread_shadow_radius};
14396    use crate::{
14397        BoxShadow, Context, Hsla, TestAppContext, Window, div, point, prelude::*, px, size,
14398    };
14399
14400    #[test]
14401    fn a_spread_grows_a_rounded_corner_and_keeps_a_square_one_square() {
14402        // A focus ring: rounded-md (6px) and a 3px spread.
14403        assert_eq!(spread_shadow_radius(px(6.), px(3.)), px(9.));
14404        assert_eq!(spread_shadow_radius(px(0.), px(3.)), px(0.));
14405        // Rounded by less than the spread: 1 + (r/s - 1)^3 of the spread.
14406        assert_eq!(spread_shadow_radius(px(1.5), px(3.)), px(1.5 + 3. * 0.875));
14407        assert_eq!(spread_shadow_radius(px(6.), px(0.)), px(6.));
14408        assert_eq!(spread_shadow_radius(px(6.), px(-2.)), px(4.));
14409        assert_eq!(spread_shadow_radius(px(1.), px(-2.)), px(0.));
14410    }
14411
14412    struct Ring {
14413        under_box: bool,
14414    }
14415
14416    impl Render for Ring {
14417        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14418            let shadow = |inset: bool| BoxShadow {
14419                color: Hsla::white().opacity(0.5),
14420                offset: point(px(0.), px(0.)),
14421                blur_radius: px(0.),
14422                spread_radius: px(3.),
14423                inset,
14424            };
14425            let mut d = div()
14426                .w(px(100.))
14427                .h(px(36.))
14428                .rounded_md()
14429                .shadow(vec![shadow(false), shadow(true)]);
14430            d.style().vn_shadow_under_box = Some(self.under_box);
14431            d
14432        }
14433    }
14434
14435    /// The frame's shadows as (kind, top-left radius, element top-left radius), in device px.
14436    fn paint(under_box: bool, cx: &mut TestAppContext) -> (Vec<(u32, f32, f32)>, f32) {
14437        let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Ring { under_box });
14438        cx.run_until_parked();
14439        window
14440            .update(cx, |_, window, _| {
14441                let shadows = window
14442                    .rendered_frame
14443                    .scene
14444                    .shadows
14445                    .iter()
14446                    .map(|s| (s.inset, s.shape_corner_radii.top_left.0, s.corner_radii.top_left.0))
14447                    .collect();
14448                (shadows, window.scale_factor())
14449            })
14450            .unwrap()
14451    }
14452
14453    #[gpui::test]
14454    fn an_outer_shadow_is_cut_out_of_the_border_box_unless_it_stands_in_for_the_box(
14455        cx: &mut TestAppContext,
14456    ) {
14457        let (shadows, scale) = paint(false, cx);
14458        let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14459        assert_eq!(outer.0, SHADOW_OUTSIDE_BOX, "the shaders cut the border box out of it");
14460        assert_eq!(outer.1, 9. * scale, "6px corner + 3px spread");
14461        assert_eq!(outer.2, 6. * scale, "the cut-out is the border box itself");
14462        assert!(shadows.iter().any(|s| s.0 == SHADOW_INSET), "the inset shadow is unchanged");
14463
14464        let (shadows, _) = paint(true, cx);
14465        let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14466        assert_eq!(outer.0, SHADOW_UNDER_BOX);
14467    }
14468}
14469
14470#[cfg(test)]
14471mod vn_rounded_mask_tests {
14472    use super::transform_mask;
14473    use crate::{Bounds, ContentMask, Corners, TransformationMatrix, point, px, size};
14474
14475    fn mask(x: f32, y: f32, w: f32, h: f32, radius: f32) -> ContentMask<crate::Pixels> {
14476        ContentMask {
14477            bounds: Bounds::new(point(px(x), px(y)), size(px(w), px(h))),
14478            corner_radii: Corners::all(px(radius)),
14479            ..Default::default()
14480        }
14481    }
14482
14483    #[test]
14484    fn rectangles_intersect_exactly_and_stay_square() {
14485        let a = mask(0., 0., 100., 100., 0.);
14486        let b = mask(50., 20., 100., 30., 0.);
14487        let both = a.intersect(&b);
14488        assert_eq!(both.bounds, Bounds::new(point(px(50.), px(20.)), size(px(50.), px(30.))));
14489        assert!(!both.is_rounded());
14490    }
14491
14492    #[test]
14493    fn a_corner_keeps_the_radius_of_the_mask_it_belongs_to() {
14494        // A rounded card and the square scroller that fills it.
14495        let card = mask(10., 10., 200., 160., 24.);
14496        let scroller = mask(10., 10., 200., 160., 0.);
14497        assert_eq!(scroller.intersect(&card).corner_radii, Corners::all(px(24.)));
14498        assert_eq!(card.intersect(&scroller).corner_radii, Corners::all(px(24.)));
14499
14500        // A rect that shares only the card's top edge: its top corners are
14501        // the card's, its bottom ones are its own.
14502        let header = mask(10., 10., 200., 60., 0.);
14503        let clipped = header.intersect(&card);
14504        assert_eq!(clipped.corner_radii.top_left, px(24.));
14505        assert_eq!(clipped.corner_radii.top_right, px(24.));
14506        assert_eq!(clipped.corner_radii.bottom_left, px(0.));
14507        assert_eq!(clipped.corner_radii.bottom_right, px(0.));
14508
14509        // Two rounded corners at one point nest; the larger radius is the
14510        // smaller region.
14511        let inner = mask(10., 10., 200., 160., 8.);
14512        assert_eq!(inner.intersect(&card).corner_radii, Corners::all(px(24.)));
14513
14514        // A rect inside the card's straight span is square, which is exact.
14515        let row = mask(40., 60., 100., 20., 0.);
14516        assert!(!row.intersect(&card).is_rounded());
14517
14518        // The radii still fit the result.
14519        let sliver = mask(10., 10., 200., 10., 0.);
14520        let clipped = sliver.intersect(&card);
14521        assert_eq!(clipped.corner_radii.top_left, px(5.));
14522    }
14523
14524    #[test]
14525    fn contains_follows_the_curve() {
14526        let avatar = mask(0., 0., 64., 64., 32.);
14527        assert!(avatar.contains(&point(px(32.), px(32.))));
14528        assert!(avatar.contains(&point(px(32.), px(1.))), "the top edge's middle");
14529        assert!(!avatar.contains(&point(px(2.), px(2.))), "outside the curve");
14530        assert!(!avatar.contains(&point(px(62.), px(62.))));
14531        assert!(avatar.contains(&point(px(10.), px(10.))), "inside the curve");
14532        assert!(!avatar.contains(&point(px(70.), px(32.))), "outside the rect");
14533        assert!(mask(0., 0., 64., 64., 0.).contains(&point(px(1.), px(1.))));
14534    }
14535
14536    #[test]
14537    fn a_transform_keeps_the_radii_only_while_corners_stay_round() {
14538        let card = mask(0., 0., 100., 100., 10.);
14539        let moved = TransformationMatrix {
14540            rotation_scale: [[1., 0.], [0., 1.]],
14541            translation: [5., 7.],
14542        };
14543        assert_eq!(transform_mask(moved, card, 1.).corner_radii, Corners::all(px(10.)));
14544
14545        let scaled = TransformationMatrix {
14546            rotation_scale: [[2., 0.], [0., 3.]],
14547            translation: [0., 0.],
14548        };
14549        assert_eq!(
14550            transform_mask(scaled, card, 1.).corner_radii,
14551            Corners::all(px(20.)),
14552            "the smaller factor"
14553        );
14554
14555        let rotated = TransformationMatrix {
14556            rotation_scale: [[0., 1.], [-1., 0.]],
14557            translation: [0., 0.],
14558        };
14559        assert!(!transform_mask(rotated, card, 1.).is_rounded());
14560    }
14561}
14562
14563/// vue-native fork: `Window::pointer_inside`.
14564#[cfg(test)]
14565mod vn_pointer_inside_tests {
14566    use crate::{
14567        Context, Modifiers, MouseExitEvent, MouseMoveEvent, PlatformInput, Render,
14568        TestAppContext, Window, div, point, prelude::*, px, size,
14569    };
14570    use std::{cell::Cell, rc::Rc};
14571
14572    struct Hoverable {
14573        hovered: Rc<Cell<bool>>,
14574    }
14575
14576    impl Render for Hoverable {
14577        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14578            let hovered = self.hovered.clone();
14579            div()
14580                .id("box")
14581                .size_full()
14582                .on_hover(move |is_hovered, _, _| hovered.set(*is_hovered))
14583        }
14584    }
14585
14586    #[gpui::test]
14587    fn a_pointer_outside_the_window_hovers_nothing(cx: &mut TestAppContext) {
14588        let hovered = Rc::new(Cell::new(false));
14589        let state = hovered.clone();
14590        let window = cx.open_window(size(px(200.), px(200.)), move |_, _| Hoverable {
14591            hovered: state,
14592        });
14593        let mut platform = cx.test_window(window.into());
14594        let draw = |cx: &mut TestAppContext| {
14595            window.update(cx, |_, window, _| window.refresh()).unwrap();
14596            cx.run_until_parked();
14597        };
14598        let at = |x: f32, y: f32| point(px(x), px(y));
14599        let moved = |x: f32, y: f32| {
14600            PlatformInput::MouseMove(MouseMoveEvent {
14601                position: at(x, y),
14602                pressed_button: None,
14603                modifiers: Modifiers::default(),
14604            })
14605        };
14606
14607        // The test platform reports the cursor at (0, 0), inside the box, as
14608        // Windows reports wherever the cursor projects. No pointer input has
14609        // reached the window, so nothing is hovered.
14610        draw(cx);
14611        assert!(!hovered.get(), "a cursor that never entered hovers nothing");
14612
14613        platform.simulate_input(moved(50., 50.));
14614        draw(cx);
14615        assert!(hovered.get(), "a move into the box hovers it");
14616
14617        // The platform says the pointer left (`WM_MOUSELEAVE`). The position
14618        // is still inside the box, and the next frame's hit test still finds
14619        // it there.
14620        platform.simulate_hover_status_change(false);
14621        draw(cx);
14622        assert!(!hovered.get(), "a pointer that left hovers nothing");
14623
14624        platform.simulate_input(moved(60., 60.));
14625        draw(cx);
14626        assert!(hovered.get(), "back in");
14627
14628        platform.simulate_input(PlatformInput::MouseExited(MouseExitEvent {
14629            position: at(60., 60.),
14630            pressed_button: None,
14631            modifiers: Modifiers::default(),
14632        }));
14633        draw(cx);
14634        assert!(!hovered.get(), "MouseExited");
14635    }
14636
14637    struct Shaded {
14638        effect: bool,
14639        renders: Rc<Cell<usize>>,
14640    }
14641
14642    impl Render for Shaded {
14643        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14644            self.renders.set(self.renders.get() + 1);
14645            let mut element = div().size_full();
14646            if self.effect {
14647                let mut spec = crate::EffectSpec::NONE;
14648                spec.id = 0;
14649                spec.pointer_param = Some(4);
14650                element.style().vn_effect = Some(spec);
14651            }
14652            element
14653        }
14654    }
14655
14656    #[gpui::test]
14657    fn only_a_pointer_effect_repaints_when_the_pointer_moves(cx: &mut TestAppContext) {
14658        let open = |cx: &mut TestAppContext, effect: bool| {
14659            let renders = Rc::new(Cell::new(0));
14660            let counted = renders.clone();
14661            let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Shaded {
14662                effect,
14663                renders: counted,
14664            });
14665            cx.run_until_parked();
14666            (window, cx.test_window(window.into()), renders)
14667        };
14668        let moved = |x: f32, y: f32| {
14669            PlatformInput::MouseMove(MouseMoveEvent {
14670                position: point(px(x), px(y)),
14671                pressed_button: None,
14672                modifiers: Modifiers::default(),
14673            })
14674        };
14675
14676        let (_, mut platform, renders) = open(cx, false);
14677        platform.simulate_input(moved(10., 10.));
14678        cx.run_until_parked();
14679        let before = renders.get();
14680        platform.simulate_input(moved(20., 20.));
14681        cx.run_until_parked();
14682        assert_eq!(renders.get(), before, "no pointer effect, no repaint");
14683
14684        let (shaded, mut platform, renders) = open(cx, true);
14685        platform.simulate_input(moved(10., 10.));
14686        cx.run_until_parked();
14687        let before = renders.get();
14688        platform.simulate_input(moved(150., 25.));
14689        cx.run_until_parked();
14690        assert!(renders.get() > before, "a pointer effect repaints");
14691        let params = shaded
14692            .update(cx, |_, window, _| {
14693                window.rendered_frame.scene.effect_quads[0].params
14694            })
14695            .unwrap();
14696        assert!((params[4] - 0.75).abs() < 1e-4 && (params[5] - 0.25).abs() < 1e-4);
14697    }
14698
14699    struct Spinning {
14700        speed: Rc<Cell<f32>>,
14701    }
14702
14703    impl Render for Spinning {
14704        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14705            let mut spec = crate::EffectSpec::NONE;
14706            spec.id = 0;
14707            spec.animated_param = Some(0);
14708            spec.params[0] = self.speed.get();
14709            let mut element = div().id("spinning").size_full();
14710            element.style().vn_effect = Some(spec);
14711            element
14712        }
14713    }
14714
14715    #[gpui::test]
14716    fn a_speed_change_continues_the_phase_instead_of_rescaling_the_clock(
14717        cx: &mut TestAppContext,
14718    ) {
14719        let speed = Rc::new(Cell::new(1.));
14720        let shared = speed.clone();
14721        let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Spinning {
14722            speed: shared,
14723        });
14724        cx.run_until_parked();
14725        let repaint = |cx: &mut TestAppContext| {
14726            window.update(cx, |_, window, _| window.refresh()).unwrap();
14727            cx.run_until_parked();
14728            window
14729                .update(cx, |_, window, _| {
14730                    let quad = window.rendered_frame.scene.effect_quads[0];
14731                    (quad.params[0] * quad.time, quad.time)
14732                })
14733                .unwrap()
14734        };
14735        // A rescale is only visible once the clock is away from zero.
14736        std::thread::sleep(std::time::Duration::from_millis(200));
14737        let (before, then) = repaint(cx);
14738        assert!((before - then).abs() < 1e-3, "an unchanged speed is `speed * time`");
14739
14740        speed.set(8.);
14741        let (after, now) = repaint(cx);
14742        let advanced = after - before;
14743        assert!(
14744            advanced >= -1e-3 && advanced <= 8. * (now - then) + 1e-3,
14745            "the phase moved by {advanced} in {}s",
14746            now - then
14747        );
14748    }
14749}
14750
14751#[cfg(test)]
14752mod vn_tagged_transform_tests {
14753    use crate::{
14754        AnyElement, App, Bounds, Context, Element, GlobalElementId, InspectorElementId,
14755        IntoElement, LayoutId, Pixels, Render, TestAppContext, TransformLength, TransformSpec,
14756        Window, div, prelude::*, px, size,
14757    };
14758    use std::{cell::RefCell, rc::Rc};
14759
14760    type Seen = Rc<RefCell<Vec<(u32, Bounds<Pixels>, Bounds<Pixels>)>>>;
14761
14762    /// What an embedder's per-node probe does: tag the subtree, prepaint it,
14763    /// take the node's transform, and map its layout box through it.
14764    struct Probe {
14765        tag: u32,
14766        inner: AnyElement,
14767        seen: Seen,
14768    }
14769
14770    impl Element for Probe {
14771        type RequestLayoutState = ();
14772        type PrepaintState = ();
14773        fn id(&self) -> Option<crate::ElementId> {
14774            None
14775        }
14776        fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
14777            None
14778        }
14779        fn request_layout(
14780            &mut self,
14781            _: Option<&GlobalElementId>,
14782            _: Option<&InspectorElementId>,
14783            window: &mut Window,
14784            cx: &mut App,
14785        ) -> (LayoutId, ()) {
14786            (self.inner.request_layout(window, cx), ())
14787        }
14788        fn prepaint(
14789            &mut self,
14790            _: Option<&GlobalElementId>,
14791            _: Option<&InspectorElementId>,
14792            bounds: Bounds<Pixels>,
14793            _: &mut (),
14794            window: &mut Window,
14795            cx: &mut App,
14796        ) {
14797            let ancestors = window.element_transform();
14798            let (_, own) =
14799                window.with_hitbox_tag(self.tag, |window| self.inner.prepaint(window, cx));
14800            let seen = window.transformed_bounds(own.unwrap_or(ancestors), bounds);
14801            self.seen.borrow_mut().push((self.tag, bounds, seen));
14802        }
14803        fn paint(
14804            &mut self,
14805            _: Option<&GlobalElementId>,
14806            _: Option<&InspectorElementId>,
14807            _: Bounds<Pixels>,
14808            _: &mut (),
14809            _: &mut (),
14810            window: &mut Window,
14811            cx: &mut App,
14812        ) {
14813            self.inner.paint(window, cx);
14814        }
14815    }
14816
14817    fn moved(x: TransformLength, y: TransformLength, scale: f32) -> TransformSpec {
14818        TransformSpec { translate: (x, y), scale: (scale, scale), ..TransformSpec::IDENTITY }
14819    }
14820
14821    /// A popper wrapper laid out at (0, 0) and moved by `translate`, a button
14822    /// inside it, and a third box scaled inside that.
14823    struct Popper {
14824        seen: Seen,
14825    }
14826
14827    impl Render for Popper {
14828        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14829            let probe = |tag, inner: AnyElement| Probe { tag, inner, seen: self.seen.clone() };
14830            let mut wrapper = div().w(px(100.)).h(px(80.));
14831            wrapper.style().vn_transform =
14832                Some(moved(TransformLength::Pixels(300.), TransformLength::Pixels(200.), 1.0));
14833            let mut scaled = div().w(px(20.)).h(px(10.));
14834            scaled.style().vn_transform =
14835                Some(moved(TransformLength::ZERO, TransformLength::ZERO, 2.0));
14836            // Built inside the button under the button's tag, like a
14837            // `::before` box: its own transform is not the button's.
14838            let mut pseudo = div().w(px(4.)).h(px(4.));
14839            pseudo.style().vn_transform =
14840                Some(moved(TransformLength::Pixels(50.), TransformLength::ZERO, 1.0));
14841            let button = div()
14842                .ml(px(10.))
14843                .w(px(30.))
14844                .h(px(20.))
14845                .child(probe(3, scaled.into_any_element()))
14846                .child(pseudo);
14847            div().size_full().child(probe(
14848                1,
14849                wrapper.child(probe(2, button.into_any_element())).into_any_element(),
14850            ))
14851        }
14852    }
14853
14854    #[gpui::test]
14855    fn a_probe_sees_its_node_where_the_transforms_put_it(cx: &mut TestAppContext) {
14856        let seen: Seen = Rc::default();
14857        let state = seen.clone();
14858        let window =
14859            cx.open_window(size(px(800.), px(600.)), move |_, _| Popper { seen: state });
14860        window.update(cx, |_, window, _| window.refresh()).unwrap();
14861        cx.run_until_parked();
14862        let seen = seen.borrow();
14863        let at = |tag: u32| *seen.iter().rev().find(|s| s.0 == tag).expect("probed");
14864        let b = |x: f32, y: f32, w: f32, h: f32| {
14865            Bounds::new(crate::point(px(x), px(y)), size(px(w), px(h)))
14866        };
14867        // Its own translate moves the wrapper; the layout box stays at 0, 0.
14868        assert_eq!(at(1).1, b(0., 0., 100., 80.));
14869        assert_eq!(at(1).2, b(300., 200., 100., 80.));
14870        // A child with no transform of its own moves with its ancestor, and
14871        // not with the one a box built inside it has.
14872        assert_eq!(at(2).1, b(10., 0., 30., 20.));
14873        assert_eq!(at(2).2, b(310., 200., 30., 20.));
14874        // Its own scale (about its centre) composes with the ancestor's move.
14875        assert_eq!(at(3).1, b(10., 0., 20., 10.));
14876        assert_eq!(at(3).2, b(300., 195., 40., 20.));
14877    }
14878}