window.rs

   1#[cfg(any(feature = "inspector", debug_assertions))]
   2use crate::Inspector;
   3use crate::{
   4    Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
   5    AsyncWindowContext, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow, Capslock,
   6    Context, Corners, CursorStyle, Decorations, DevicePixels, DispatchActionListener,
   7    DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
   8    FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, IsZero,
   9    KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId,
  10    LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
  11    MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
  12    PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, Priority, PromptButton,
  13    PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams,
  14    Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y,
  15    ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite,
  16    SubscriberSet, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap,
  17    TaffyLayoutEngine, Task, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
  18    TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
  19    WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
  20    point, prelude::*, px, rems, size, transparent_black,
  21};
  22use anyhow::{Context as _, Result, anyhow};
  23use collections::{FxHashMap, FxHashSet};
  24#[cfg(target_os = "macos")]
  25use core_video::pixel_buffer::CVPixelBuffer;
  26use derive_more::{Deref, DerefMut};
  27use futures::FutureExt;
  28use futures::channel::oneshot;
  29use gpui_util::post_inc;
  30use gpui_util::{ResultExt, measure};
  31use itertools::FoldWhile::{Continue, Done};
  32use itertools::Itertools;
  33use parking_lot::RwLock;
  34use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
  35use refineable::Refineable;
  36use scheduler::Instant;
  37use slotmap::SlotMap;
  38use smallvec::SmallVec;
  39use std::{
  40    any::{Any, TypeId},
  41    borrow::Cow,
  42    cell::{Cell, RefCell},
  43    cmp,
  44    fmt::{Debug, Display},
  45    hash::{Hash, Hasher},
  46    marker::PhantomData,
  47    mem,
  48    ops::{DerefMut, Range},
  49    rc::Rc,
  50    sync::{
  51        Arc, Weak,
  52        atomic::{AtomicUsize, Ordering::SeqCst},
  53    },
  54    time::Duration,
  55};
  56use uuid::Uuid;
  57
  58mod prompts;
  59
  60use crate::util::atomic_incr_if_not_zero;
  61pub use prompts::*;
  62
  63/// Default window size used when no explicit size is provided.
  64pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
  65
  66/// A 6:5 aspect ratio minimum window size to be used for functional,
  67/// additional-to-main-Zed windows, like the settings and rules library windows.
  68pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
  69    width: Pixels(900.),
  70    height: Pixels(750.),
  71};
  72
  73/// Represents the two different phases when dispatching events.
  74#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  75pub enum DispatchPhase {
  76    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  77    /// invoked front to back and keyboard event listeners are invoked from the focused element
  78    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  79    /// registering event listeners.
  80    #[default]
  81    Bubble,
  82    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  83    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  84    /// is used for special purposes such as clearing the "pressed" state for click events. If
  85    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  86    /// outside of the immediate region may rely on detecting non-local events during this phase.
  87    Capture,
  88}
  89
  90impl DispatchPhase {
  91    /// Returns true if this represents the "bubble" phase.
  92    #[inline]
  93    pub fn bubble(self) -> bool {
  94        self == DispatchPhase::Bubble
  95    }
  96
  97    /// Returns true if this represents the "capture" phase.
  98    #[inline]
  99    pub fn capture(self) -> bool {
 100        self == DispatchPhase::Capture
 101    }
 102}
 103
 104struct WindowInvalidatorInner {
 105    pub dirty: bool,
 106    pub draw_phase: DrawPhase,
 107    pub dirty_views: FxHashSet<EntityId>,
 108}
 109
 110#[derive(Clone)]
 111pub(crate) struct WindowInvalidator {
 112    inner: Rc<RefCell<WindowInvalidatorInner>>,
 113}
 114
 115impl WindowInvalidator {
 116    pub fn new() -> Self {
 117        WindowInvalidator {
 118            inner: Rc::new(RefCell::new(WindowInvalidatorInner {
 119                dirty: true,
 120                draw_phase: DrawPhase::None,
 121                dirty_views: FxHashSet::default(),
 122            })),
 123        }
 124    }
 125
 126    pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
 127        let mut inner = self.inner.borrow_mut();
 128        inner.dirty_views.insert(entity);
 129        if inner.draw_phase == DrawPhase::None {
 130            inner.dirty = true;
 131            cx.push_effect(Effect::Notify { emitter: entity });
 132            true
 133        } else {
 134            false
 135        }
 136    }
 137
 138    pub fn is_dirty(&self) -> bool {
 139        self.inner.borrow().dirty
 140    }
 141
 142    pub fn set_dirty(&self, dirty: bool) {
 143        self.inner.borrow_mut().dirty = dirty
 144    }
 145
 146    pub fn set_phase(&self, phase: DrawPhase) {
 147        self.inner.borrow_mut().draw_phase = phase
 148    }
 149
 150    pub fn take_views(&self) -> FxHashSet<EntityId> {
 151        mem::take(&mut self.inner.borrow_mut().dirty_views)
 152    }
 153
 154    pub fn replace_views(&self, views: FxHashSet<EntityId>) {
 155        self.inner.borrow_mut().dirty_views = views;
 156    }
 157
 158    pub fn not_drawing(&self) -> bool {
 159        self.inner.borrow().draw_phase == DrawPhase::None
 160    }
 161
 162    #[track_caller]
 163    pub fn debug_assert_paint(&self) {
 164        debug_assert!(
 165            matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
 166            "this method can only be called during paint"
 167        );
 168    }
 169
 170    #[track_caller]
 171    pub fn debug_assert_prepaint(&self) {
 172        debug_assert!(
 173            matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
 174            "this method can only be called during request_layout, or prepaint"
 175        );
 176    }
 177
 178    #[track_caller]
 179    pub fn debug_assert_paint_or_prepaint(&self) {
 180        debug_assert!(
 181            matches!(
 182                self.inner.borrow().draw_phase,
 183                DrawPhase::Paint | DrawPhase::Prepaint
 184            ),
 185            "this method can only be called during request_layout, prepaint, or paint"
 186        );
 187    }
 188}
 189
 190type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
 191
 192pub(crate) type AnyWindowFocusListener =
 193    Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
 194
 195pub(crate) struct WindowFocusEvent {
 196    pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
 197    pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
 198}
 199
 200impl WindowFocusEvent {
 201    pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
 202        !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
 203    }
 204
 205    pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
 206        self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
 207    }
 208}
 209
 210/// This is provided when subscribing for `Context::on_focus_out` events.
 211pub struct FocusOutEvent {
 212    /// A weak focus handle representing what was blurred.
 213    pub blurred: WeakFocusHandle,
 214}
 215
 216slotmap::new_key_type! {
 217    /// A globally unique identifier for a focusable element.
 218    pub struct FocusId;
 219}
 220
 221thread_local! {
 222    /// Fallback arena used when no app-specific arena is active.
 223    /// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena.
 224    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
 225
 226    /// Points to the current App's element arena during draw operations.
 227    /// This allows multiple test Apps to have isolated arenas, preventing
 228    /// cross-session corruption when the scheduler interleaves their tasks.
 229    static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
 230}
 231
 232/// Allocates an element in the current arena. Uses the app-specific arena if one
 233/// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA.
 234pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
 235    CURRENT_ELEMENT_ARENA.with(|current| {
 236        if let Some(arena_ptr) = current.get() {
 237            // SAFETY: The pointer is valid for the duration of the draw operation
 238            // that set it, and we're being called during that same draw.
 239            let arena_cell = unsafe { &*arena_ptr };
 240            f(&mut arena_cell.borrow_mut())
 241        } else {
 242            ELEMENT_ARENA.with_borrow_mut(f)
 243        }
 244    })
 245}
 246
 247/// RAII guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw operation.
 248/// When dropped, restores the previous arena (supporting nested draws).
 249pub(crate) struct ElementArenaScope {
 250    previous: Option<*const RefCell<Arena>>,
 251}
 252
 253impl ElementArenaScope {
 254    /// Enter a scope where element allocations use the given arena.
 255    pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
 256        let previous = CURRENT_ELEMENT_ARENA.with(|current| {
 257            let prev = current.get();
 258            current.set(Some(arena as *const RefCell<Arena>));
 259            prev
 260        });
 261        Self { previous }
 262    }
 263}
 264
 265impl Drop for ElementArenaScope {
 266    fn drop(&mut self) {
 267        CURRENT_ELEMENT_ARENA.with(|current| {
 268            current.set(self.previous);
 269        });
 270    }
 271}
 272
 273/// Returned when the element arena has been used and so must be cleared before the next draw.
 274#[must_use]
 275pub struct ArenaClearNeeded {
 276    arena: *const RefCell<Arena>,
 277}
 278
 279impl ArenaClearNeeded {
 280    /// Create a new ArenaClearNeeded that will clear the given arena.
 281    pub(crate) fn new(arena: &RefCell<Arena>) -> Self {
 282        Self {
 283            arena: arena as *const RefCell<Arena>,
 284        }
 285    }
 286
 287    /// Clear the element arena.
 288    pub fn clear(self) {
 289        // SAFETY: The arena pointer is valid because ArenaClearNeeded is created
 290        // at the end of draw() and must be cleared before the next draw.
 291        let arena_cell = unsafe { &*self.arena };
 292        arena_cell.borrow_mut().clear();
 293    }
 294}
 295
 296pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
 297pub(crate) struct FocusRef {
 298    pub(crate) ref_count: AtomicUsize,
 299    pub(crate) tab_index: isize,
 300    pub(crate) tab_stop: bool,
 301}
 302
 303impl FocusId {
 304    /// Obtains whether the element associated with this handle is currently focused.
 305    pub fn is_focused(&self, window: &Window) -> bool {
 306        window.focus == Some(*self)
 307    }
 308
 309    /// Obtains whether the element associated with this handle contains the focused
 310    /// element or is itself focused.
 311    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
 312        window
 313            .focused(cx)
 314            .is_some_and(|focused| self.contains(focused.id, window))
 315    }
 316
 317    /// Obtains whether the element associated with this handle is contained within the
 318    /// focused element or is itself focused.
 319    pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
 320        let focused = window.focused(cx);
 321        focused.is_some_and(|focused| focused.id.contains(*self, window))
 322    }
 323
 324    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 325    pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
 326        window
 327            .rendered_frame
 328            .dispatch_tree
 329            .focus_contains(*self, other)
 330    }
 331}
 332
 333/// A handle which can be used to track and manipulate the focused element in a window.
 334pub struct FocusHandle {
 335    pub(crate) id: FocusId,
 336    handles: Arc<FocusMap>,
 337    /// The index of this element in the tab order.
 338    pub tab_index: isize,
 339    /// Whether this element can be focused by tab navigation.
 340    pub tab_stop: bool,
 341}
 342
 343impl std::fmt::Debug for FocusHandle {
 344    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 345        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 346    }
 347}
 348
 349impl FocusHandle {
 350    pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
 351        let id = handles.write().insert(FocusRef {
 352            ref_count: AtomicUsize::new(1),
 353            tab_index: 0,
 354            tab_stop: false,
 355        });
 356
 357        Self {
 358            id,
 359            tab_index: 0,
 360            tab_stop: false,
 361            handles: handles.clone(),
 362        }
 363    }
 364
 365    pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
 366        let lock = handles.read();
 367        let focus = lock.get(id)?;
 368        if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
 369            return None;
 370        }
 371        Some(Self {
 372            id,
 373            tab_index: focus.tab_index,
 374            tab_stop: focus.tab_stop,
 375            handles: handles.clone(),
 376        })
 377    }
 378
 379    /// Sets the tab index of the element associated with this handle.
 380    pub fn tab_index(mut self, index: isize) -> Self {
 381        self.tab_index = index;
 382        if let Some(focus) = self.handles.write().get_mut(self.id) {
 383            focus.tab_index = index;
 384        }
 385        self
 386    }
 387
 388    /// Sets whether the element associated with this handle is a tab stop.
 389    ///
 390    /// When `false`, the element will not be included in the tab order.
 391    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
 392        self.tab_stop = tab_stop;
 393        if let Some(focus) = self.handles.write().get_mut(self.id) {
 394            focus.tab_stop = tab_stop;
 395        }
 396        self
 397    }
 398
 399    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
 400    pub fn downgrade(&self) -> WeakFocusHandle {
 401        WeakFocusHandle {
 402            id: self.id,
 403            handles: Arc::downgrade(&self.handles),
 404        }
 405    }
 406
 407    /// Moves the focus to the element associated with this handle.
 408    pub fn focus(&self, window: &mut Window, cx: &mut App) {
 409        window.focus(self, cx)
 410    }
 411
 412    /// Obtains whether the element associated with this handle is currently focused.
 413    pub fn is_focused(&self, window: &Window) -> bool {
 414        self.id.is_focused(window)
 415    }
 416
 417    /// Obtains whether the element associated with this handle contains the focused
 418    /// element or is itself focused.
 419    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
 420        self.id.contains_focused(window, cx)
 421    }
 422
 423    /// Obtains whether the element associated with this handle is contained within the
 424    /// focused element or is itself focused.
 425    pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
 426        self.id.within_focused(window, cx)
 427    }
 428
 429    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 430    pub fn contains(&self, other: &Self, window: &Window) -> bool {
 431        self.id.contains(other.id, window)
 432    }
 433
 434    /// Dispatch an action on the element that rendered this focus handle
 435    pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
 436        if let Some(node_id) = window
 437            .rendered_frame
 438            .dispatch_tree
 439            .focusable_node_id(self.id)
 440        {
 441            window.dispatch_action_on_node(node_id, action, cx)
 442        }
 443    }
 444}
 445
 446impl Clone for FocusHandle {
 447    fn clone(&self) -> Self {
 448        Self::for_id(self.id, &self.handles).unwrap()
 449    }
 450}
 451
 452impl PartialEq for FocusHandle {
 453    fn eq(&self, other: &Self) -> bool {
 454        self.id == other.id
 455    }
 456}
 457
 458impl Eq for FocusHandle {}
 459
 460impl Drop for FocusHandle {
 461    fn drop(&mut self) {
 462        self.handles
 463            .read()
 464            .get(self.id)
 465            .unwrap()
 466            .ref_count
 467            .fetch_sub(1, SeqCst);
 468    }
 469}
 470
 471/// A weak reference to a focus handle.
 472#[derive(Clone, Debug)]
 473pub struct WeakFocusHandle {
 474    pub(crate) id: FocusId,
 475    pub(crate) handles: Weak<FocusMap>,
 476}
 477
 478impl WeakFocusHandle {
 479    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
 480    pub fn upgrade(&self) -> Option<FocusHandle> {
 481        let handles = self.handles.upgrade()?;
 482        FocusHandle::for_id(self.id, &handles)
 483    }
 484}
 485
 486impl PartialEq for WeakFocusHandle {
 487    fn eq(&self, other: &WeakFocusHandle) -> bool {
 488        self.id == other.id
 489    }
 490}
 491
 492impl Eq for WeakFocusHandle {}
 493
 494impl PartialEq<FocusHandle> for WeakFocusHandle {
 495    fn eq(&self, other: &FocusHandle) -> bool {
 496        self.id == other.id
 497    }
 498}
 499
 500impl PartialEq<WeakFocusHandle> for FocusHandle {
 501    fn eq(&self, other: &WeakFocusHandle) -> bool {
 502        self.id == other.id
 503    }
 504}
 505
 506/// Focusable allows users of your view to easily
 507/// focus it (using window.focus_view(cx, view))
 508pub trait Focusable: 'static {
 509    /// Returns the focus handle associated with this view.
 510    fn focus_handle(&self, cx: &App) -> FocusHandle;
 511}
 512
 513impl<V: Focusable> Focusable for Entity<V> {
 514    fn focus_handle(&self, cx: &App) -> FocusHandle {
 515        self.read(cx).focus_handle(cx)
 516    }
 517}
 518
 519/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 520/// where the lifecycle of the view is handled by another view.
 521pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
 522
 523impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
 524
 525/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 526pub struct DismissEvent;
 527
 528type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
 529
 530pub(crate) type AnyMouseListener =
 531    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
 532
 533#[derive(Clone)]
 534pub(crate) struct CursorStyleRequest {
 535    pub(crate) hitbox_id: Option<HitboxId>,
 536    pub(crate) style: CursorStyle,
 537}
 538
 539#[derive(Default, Eq, PartialEq)]
 540pub(crate) struct HitTest {
 541    pub(crate) ids: SmallVec<[HitboxId; 8]>,
 542    pub(crate) hover_hitbox_count: usize,
 543}
 544
 545/// A type of window control area that corresponds to the platform window.
 546#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 547pub enum WindowControlArea {
 548    /// An area that allows dragging of the platform window.
 549    Drag,
 550    /// An area that allows closing of the platform window.
 551    Close,
 552    /// An area that allows maximizing of the platform window.
 553    Max,
 554    /// An area that allows minimizing of the platform window.
 555    Min,
 556}
 557
 558/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
 559#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
 560pub struct HitboxId(u64);
 561
 562impl HitboxId {
 563    /// Checks if the hitbox with this ID is currently hovered. Returns `false` during keyboard
 564    /// input modality so that keyboard navigation suppresses hover highlights. Except when handling
 565    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
 566    /// events or paint hover styles.
 567    ///
 568    /// See [`Hitbox::is_hovered`] for details.
 569    pub fn is_hovered(self, window: &Window) -> bool {
 570        // If this hitbox has captured the pointer, it's always considered hovered
 571        if window.captured_hitbox == Some(self) {
 572            return true;
 573        }
 574        if window.last_input_was_keyboard() {
 575            return false;
 576        }
 577        let hit_test = &window.mouse_hit_test;
 578        for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
 579            if self == *id {
 580                return true;
 581            }
 582        }
 583        false
 584    }
 585
 586    /// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
 587    /// Typically this should only be used when handling `ScrollWheelEvent`, and otherwise
 588    /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
 589    /// this distinction.
 590    pub fn should_handle_scroll(self, window: &Window) -> bool {
 591        window.mouse_hit_test.ids.contains(&self)
 592    }
 593
 594    fn next(mut self) -> HitboxId {
 595        HitboxId(self.0.wrapping_add(1))
 596    }
 597}
 598
 599/// A rectangular region that potentially blocks hitboxes inserted prior.
 600/// See [Window::insert_hitbox] for more details.
 601#[derive(Clone, Debug, Deref)]
 602pub struct Hitbox {
 603    /// A unique identifier for the hitbox.
 604    pub id: HitboxId,
 605    /// The bounds of the hitbox.
 606    #[deref]
 607    pub bounds: Bounds<Pixels>,
 608    /// The content mask when the hitbox was inserted.
 609    pub content_mask: ContentMask<Pixels>,
 610    /// Flags that specify hitbox behavior.
 611    pub behavior: HitboxBehavior,
 612}
 613
 614impl Hitbox {
 615    /// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality
 616    /// so that keyboard navigation suppresses hover highlights. Except when handling
 617    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
 618    /// events or paint hover styles.
 619    ///
 620    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
 621    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
 622    /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`),
 623    /// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]).
 624    ///
 625    /// Handling of `ScrollWheelEvent` should typically use `should_handle_scroll` instead.
 626    /// Concretely, this is due to use-cases like overlays that cause the elements under to be
 627    /// non-interactive while still allowing scrolling. More abstractly, this is because
 628    /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
 629    /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
 630    /// container.
 631    pub fn is_hovered(&self, window: &Window) -> bool {
 632        self.id.is_hovered(window)
 633    }
 634
 635    /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
 636    /// should only be used when handling `ScrollWheelEvent`, and otherwise `is_hovered` should be
 637    /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
 638    ///
 639    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
 640    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
 641    pub fn should_handle_scroll(&self, window: &Window) -> bool {
 642        self.id.should_handle_scroll(window)
 643    }
 644}
 645
 646/// How the hitbox affects mouse behavior.
 647#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
 648pub enum HitboxBehavior {
 649    /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
 650    #[default]
 651    Normal,
 652
 653    /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
 654    /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
 655    /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
 656    /// [`InteractiveElement::occlude`].
 657    ///
 658    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
 659    /// bubble-phase handler for every mouse event type:
 660    ///
 661    /// ```ignore
 662    /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
 663    ///     if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
 664    ///         cx.stop_propagation();
 665    ///     }
 666    /// })
 667    /// ```
 668    ///
 669    /// This has effects beyond event handling - any use of hitbox checking, such as hover
 670    /// styles and tooltips. These other behaviors are the main point of this mechanism. An
 671    /// alternative might be to not affect mouse event handling - but this would allow
 672    /// inconsistent UI where clicks and moves interact with elements that are not considered to
 673    /// be hovered.
 674    BlockMouse,
 675
 676    /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
 677    /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
 678    /// interaction except scroll events to be ignored - see the documentation of
 679    /// [`Hitbox::is_hovered`] for details. This flag is set by
 680    /// [`InteractiveElement::block_mouse_except_scroll`].
 681    ///
 682    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
 683    /// bubble-phase handler for every mouse event type **except** `ScrollWheelEvent`:
 684    ///
 685    /// ```ignore
 686    /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
 687    ///     if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 688    ///         cx.stop_propagation();
 689    ///     }
 690    /// })
 691    /// ```
 692    ///
 693    /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollWheelEvent` is
 694    /// handled differently than other mouse events. If also blocking these scroll events is
 695    /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
 696    ///
 697    /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
 698    /// hover styles and tooltips. These other behaviors are the main point of this mechanism.
 699    /// An alternative might be to not affect mouse event handling - but this would allow
 700    /// inconsistent UI where clicks and moves interact with elements that are not considered to
 701    /// be hovered.
 702    BlockMouseExceptScroll,
 703}
 704
 705/// An identifier for a tooltip.
 706#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 707pub struct TooltipId(usize);
 708
 709impl TooltipId {
 710    /// Checks if the tooltip is currently hovered.
 711    pub fn is_hovered(&self, window: &Window) -> bool {
 712        window
 713            .tooltip_bounds
 714            .as_ref()
 715            .is_some_and(|tooltip_bounds| {
 716                tooltip_bounds.id == *self
 717                    && tooltip_bounds.bounds.contains(&window.mouse_position())
 718            })
 719    }
 720}
 721
 722pub(crate) struct TooltipBounds {
 723    id: TooltipId,
 724    bounds: Bounds<Pixels>,
 725}
 726
 727#[derive(Clone)]
 728pub(crate) struct TooltipRequest {
 729    id: TooltipId,
 730    tooltip: AnyTooltip,
 731}
 732
 733pub(crate) struct DeferredDraw {
 734    current_view: EntityId,
 735    priority: usize,
 736    parent_node: DispatchNodeId,
 737    element_id_stack: SmallVec<[ElementId; 32]>,
 738    text_style_stack: Vec<TextStyleRefinement>,
 739    content_mask: Option<ContentMask<Pixels>>,
 740    rem_size: Pixels,
 741    element: Option<AnyElement>,
 742    absolute_offset: Point<Pixels>,
 743    prepaint_range: Range<PrepaintStateIndex>,
 744    paint_range: Range<PaintIndex>,
 745}
 746
 747pub(crate) struct Frame {
 748    pub(crate) focus: Option<FocusId>,
 749    pub(crate) window_active: bool,
 750    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
 751    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
 752    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
 753    pub(crate) dispatch_tree: DispatchTree,
 754    pub(crate) scene: Scene,
 755    pub(crate) hitboxes: Vec<Hitbox>,
 756    pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
 757    pub(crate) deferred_draws: Vec<DeferredDraw>,
 758    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
 759    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
 760    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
 761    #[cfg(any(test, feature = "test-support"))]
 762    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
 763    #[cfg(any(feature = "inspector", debug_assertions))]
 764    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
 765    #[cfg(any(feature = "inspector", debug_assertions))]
 766    pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
 767    pub(crate) tab_stops: TabStopMap,
 768}
 769
 770#[derive(Clone, Default)]
 771pub(crate) struct PrepaintStateIndex {
 772    hitboxes_index: usize,
 773    tooltips_index: usize,
 774    deferred_draws_index: usize,
 775    dispatch_tree_index: usize,
 776    accessed_element_states_index: usize,
 777    line_layout_index: LineLayoutIndex,
 778}
 779
 780#[derive(Clone, Default)]
 781pub(crate) struct PaintIndex {
 782    scene_index: usize,
 783    mouse_listeners_index: usize,
 784    input_handlers_index: usize,
 785    cursor_styles_index: usize,
 786    accessed_element_states_index: usize,
 787    tab_handle_index: usize,
 788    line_layout_index: LineLayoutIndex,
 789}
 790
 791impl Frame {
 792    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
 793        Frame {
 794            focus: None,
 795            window_active: false,
 796            element_states: FxHashMap::default(),
 797            accessed_element_states: Vec::new(),
 798            mouse_listeners: Vec::new(),
 799            dispatch_tree,
 800            scene: Scene::default(),
 801            hitboxes: Vec::new(),
 802            window_control_hitboxes: Vec::new(),
 803            deferred_draws: Vec::new(),
 804            input_handlers: Vec::new(),
 805            tooltip_requests: Vec::new(),
 806            cursor_styles: Vec::new(),
 807
 808            #[cfg(any(test, feature = "test-support"))]
 809            debug_bounds: FxHashMap::default(),
 810
 811            #[cfg(any(feature = "inspector", debug_assertions))]
 812            next_inspector_instance_ids: FxHashMap::default(),
 813
 814            #[cfg(any(feature = "inspector", debug_assertions))]
 815            inspector_hitboxes: FxHashMap::default(),
 816            tab_stops: TabStopMap::default(),
 817        }
 818    }
 819
 820    pub(crate) fn clear(&mut self) {
 821        self.element_states.clear();
 822        self.accessed_element_states.clear();
 823        self.mouse_listeners.clear();
 824        self.dispatch_tree.clear();
 825        self.scene.clear();
 826        self.input_handlers.clear();
 827        self.tooltip_requests.clear();
 828        self.cursor_styles.clear();
 829        self.hitboxes.clear();
 830        self.window_control_hitboxes.clear();
 831        self.deferred_draws.clear();
 832        self.tab_stops.clear();
 833        self.focus = None;
 834
 835        #[cfg(any(test, feature = "test-support"))]
 836        {
 837            self.debug_bounds.clear();
 838        }
 839
 840        #[cfg(any(feature = "inspector", debug_assertions))]
 841        {
 842            self.next_inspector_instance_ids.clear();
 843            self.inspector_hitboxes.clear();
 844        }
 845    }
 846
 847    pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
 848        self.cursor_styles
 849            .iter()
 850            .rev()
 851            .fold_while(None, |style, request| match request.hitbox_id {
 852                None => Done(Some(request.style)),
 853                Some(hitbox_id) => Continue(
 854                    style.or_else(|| hitbox_id.is_hovered(window).then_some(request.style)),
 855                ),
 856            })
 857            .into_inner()
 858    }
 859
 860    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
 861        let mut set_hover_hitbox_count = false;
 862        let mut hit_test = HitTest::default();
 863        for hitbox in self.hitboxes.iter().rev() {
 864            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
 865            if bounds.contains(&position) {
 866                hit_test.ids.push(hitbox.id);
 867                if !set_hover_hitbox_count
 868                    && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
 869                {
 870                    hit_test.hover_hitbox_count = hit_test.ids.len();
 871                    set_hover_hitbox_count = true;
 872                }
 873                if hitbox.behavior == HitboxBehavior::BlockMouse {
 874                    break;
 875                }
 876            }
 877        }
 878        if !set_hover_hitbox_count {
 879            hit_test.hover_hitbox_count = hit_test.ids.len();
 880        }
 881        hit_test
 882    }
 883
 884    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 885        self.focus
 886            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 887            .unwrap_or_default()
 888    }
 889
 890    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
 891        for element_state_key in &self.accessed_element_states {
 892            if let Some((element_state_key, element_state)) =
 893                prev_frame.element_states.remove_entry(element_state_key)
 894            {
 895                self.element_states.insert(element_state_key, element_state);
 896            }
 897        }
 898
 899        self.scene.finish();
 900    }
 901}
 902
 903#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
 904enum InputModality {
 905    Mouse,
 906    Keyboard,
 907}
 908
 909/// Holds the state for a specific window.
 910pub struct Window {
 911    pub(crate) handle: AnyWindowHandle,
 912    pub(crate) invalidator: WindowInvalidator,
 913    pub(crate) removed: bool,
 914    pub(crate) platform_window: Box<dyn PlatformWindow>,
 915    display_id: Option<DisplayId>,
 916    sprite_atlas: Arc<dyn PlatformAtlas>,
 917    text_system: Arc<WindowTextSystem>,
 918    text_rendering_mode: Rc<Cell<TextRenderingMode>>,
 919    rem_size: Pixels,
 920    /// The stack of override values for the window's rem size.
 921    ///
 922    /// This is used by `with_rem_size` to allow rendering an element tree with
 923    /// a given rem size.
 924    rem_size_override_stack: SmallVec<[Pixels; 8]>,
 925    pub(crate) viewport_size: Size<Pixels>,
 926    layout_engine: Option<TaffyLayoutEngine>,
 927    pub(crate) root: Option<AnyView>,
 928    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
 929    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
 930    pub(crate) rendered_entity_stack: Vec<EntityId>,
 931    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
 932    pub(crate) element_opacity: f32,
 933    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
 934    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
 935    pub(crate) image_cache_stack: Vec<AnyImageCache>,
 936    pub(crate) rendered_frame: Frame,
 937    pub(crate) next_frame: Frame,
 938    next_hitbox_id: HitboxId,
 939    pub(crate) next_tooltip_id: TooltipId,
 940    pub(crate) tooltip_bounds: Option<TooltipBounds>,
 941    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
 942    pub(crate) dirty_views: FxHashSet<EntityId>,
 943    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 944    pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 945    default_prevented: bool,
 946    mouse_position: Point<Pixels>,
 947    mouse_hit_test: HitTest,
 948    modifiers: Modifiers,
 949    capslock: Capslock,
 950    scale_factor: f32,
 951    pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
 952    appearance: WindowAppearance,
 953    pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
 954    pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
 955    active: Rc<Cell<bool>>,
 956    hovered: Rc<Cell<bool>>,
 957    pub(crate) needs_present: Rc<Cell<bool>>,
 958    /// Tracks recent input event timestamps to determine if input is arriving at a high rate.
 959    /// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
 960    pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
 961    last_input_modality: InputModality,
 962    pub(crate) refreshing: bool,
 963    pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
 964    pub(crate) focus: Option<FocusId>,
 965    focus_enabled: bool,
 966    pending_input: Option<PendingInput>,
 967    pending_modifier: ModifierState,
 968    pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
 969    prompt: Option<RenderablePromptHandle>,
 970    pub(crate) client_inset: Option<Pixels>,
 971    /// The hitbox that has captured the pointer, if any.
 972    /// While captured, mouse events route to this hitbox regardless of hit testing.
 973    captured_hitbox: Option<HitboxId>,
 974    #[cfg(any(feature = "inspector", debug_assertions))]
 975    inspector: Option<Entity<Inspector>>,
 976}
 977
 978#[derive(Clone, Debug, Default)]
 979struct ModifierState {
 980    modifiers: Modifiers,
 981    saw_keystroke: bool,
 982}
 983
 984/// Tracks input event timestamps to determine if input is arriving at a high rate.
 985/// Used for selective VRR (Variable Refresh Rate) optimization.
 986#[derive(Clone, Debug)]
 987pub(crate) struct InputRateTracker {
 988    timestamps: Vec<Instant>,
 989    window: Duration,
 990    inputs_per_second: u32,
 991    sustain_until: Instant,
 992    sustain_duration: Duration,
 993}
 994
 995impl Default for InputRateTracker {
 996    fn default() -> Self {
 997        Self {
 998            timestamps: Vec::new(),
 999            window: Duration::from_millis(100),
1000            inputs_per_second: 60,
1001            sustain_until: Instant::now(),
1002            sustain_duration: Duration::from_secs(1),
1003        }
1004    }
1005}
1006
1007impl InputRateTracker {
1008    pub fn record_input(&mut self) {
1009        let now = Instant::now();
1010        self.timestamps.push(now);
1011        self.prune_old_timestamps(now);
1012
1013        let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1014        if self.timestamps.len() as u128 >= min_events {
1015            self.sustain_until = now + self.sustain_duration;
1016        }
1017    }
1018
1019    pub fn is_high_rate(&self) -> bool {
1020        Instant::now() < self.sustain_until
1021    }
1022
1023    fn prune_old_timestamps(&mut self, now: Instant) {
1024        self.timestamps
1025            .retain(|&t| now.duration_since(t) <= self.window);
1026    }
1027}
1028
1029#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1030pub(crate) enum DrawPhase {
1031    None,
1032    Prepaint,
1033    Paint,
1034    Focus,
1035}
1036
1037#[derive(Default, Debug)]
1038struct PendingInput {
1039    keystrokes: SmallVec<[Keystroke; 1]>,
1040    focus: Option<FocusId>,
1041    timer: Option<Task<()>>,
1042    needs_timeout: bool,
1043}
1044
1045pub(crate) struct ElementStateBox {
1046    pub(crate) inner: Box<dyn Any>,
1047    #[cfg(debug_assertions)]
1048    pub(crate) type_name: &'static str,
1049}
1050
1051fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1052    // TODO, BUG: if you open a window with the currently active window
1053    // on the stack, this will erroneously fallback to `None`
1054    //
1055    // TODO these should be the initial window bounds not considering maximized/fullscreen
1056    let active_window_bounds = cx
1057        .active_window()
1058        .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1059
1060    const CASCADE_OFFSET: f32 = 25.0;
1061
1062    let display = display_id
1063        .map(|id| cx.find_display(id))
1064        .unwrap_or_else(|| cx.primary_display());
1065
1066    let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1067
1068    // Use visible_bounds to exclude taskbar/dock areas
1069    let display_bounds = display
1070        .as_ref()
1071        .map(|d| d.visible_bounds())
1072        .unwrap_or_else(default_placement);
1073
1074    let (
1075        Bounds {
1076            origin: base_origin,
1077            size: base_size,
1078        },
1079        window_bounds_ctor,
1080    ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1081        Some(bounds) => match bounds {
1082            WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1083            WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1084            WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1085        },
1086        None => (
1087            display
1088                .as_ref()
1089                .map(|d| d.default_bounds())
1090                .unwrap_or_else(default_placement),
1091            WindowBounds::Windowed,
1092        ),
1093    };
1094
1095    let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1096    let proposed_origin = base_origin + cascade_offset;
1097    let proposed_bounds = Bounds::new(proposed_origin, base_size);
1098
1099    let display_right = display_bounds.origin.x + display_bounds.size.width;
1100    let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1101    let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1102    let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1103
1104    let fits_horizontally = window_right <= display_right;
1105    let fits_vertically = window_bottom <= display_bottom;
1106
1107    let final_origin = match (fits_horizontally, fits_vertically) {
1108        (true, true) => proposed_origin,
1109        (false, true) => point(display_bounds.origin.x, base_origin.y),
1110        (true, false) => point(base_origin.x, display_bounds.origin.y),
1111        (false, false) => display_bounds.origin,
1112    };
1113    window_bounds_ctor(Bounds::new(final_origin, base_size))
1114}
1115
1116impl Window {
1117    pub(crate) fn new(
1118        handle: AnyWindowHandle,
1119        options: WindowOptions,
1120        cx: &mut App,
1121    ) -> Result<Self> {
1122        let WindowOptions {
1123            window_bounds,
1124            titlebar,
1125            focus,
1126            show,
1127            kind,
1128            is_movable,
1129            is_resizable,
1130            is_minimizable,
1131            display_id,
1132            window_background,
1133            app_id,
1134            window_min_size,
1135            window_decorations,
1136            #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1137            tabbing_identifier,
1138        } = options;
1139
1140        let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1141        let mut platform_window = cx.platform.open_window(
1142            handle,
1143            WindowParams {
1144                bounds: window_bounds.get_bounds(),
1145                titlebar,
1146                kind,
1147                is_movable,
1148                is_resizable,
1149                is_minimizable,
1150                focus,
1151                show,
1152                display_id,
1153                window_min_size,
1154                #[cfg(target_os = "macos")]
1155                tabbing_identifier,
1156            },
1157        )?;
1158
1159        let tab_bar_visible = platform_window.tab_bar_visible();
1160        SystemWindowTabController::init_visible(cx, tab_bar_visible);
1161        if let Some(tabs) = platform_window.tabbed_windows() {
1162            SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1163        }
1164
1165        let display_id = platform_window.display().map(|display| display.id());
1166        let sprite_atlas = platform_window.sprite_atlas();
1167        let mouse_position = platform_window.mouse_position();
1168        let modifiers = platform_window.modifiers();
1169        let capslock = platform_window.capslock();
1170        let content_size = platform_window.content_size();
1171        let scale_factor = platform_window.scale_factor();
1172        let appearance = platform_window.appearance();
1173        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1174        let invalidator = WindowInvalidator::new();
1175        let active = Rc::new(Cell::new(platform_window.is_active()));
1176        let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1177        let needs_present = Rc::new(Cell::new(false));
1178        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1179        let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1180        let last_frame_time = Rc::new(Cell::new(None));
1181
1182        platform_window
1183            .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1184        platform_window.set_background_appearance(window_background);
1185
1186        match window_bounds {
1187            WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1188            WindowBounds::Maximized(_) => platform_window.zoom(),
1189            WindowBounds::Windowed(_) => {}
1190        }
1191
1192        platform_window.on_close(Box::new({
1193            let window_id = handle.window_id();
1194            let mut cx = cx.to_async();
1195            move || {
1196                let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1197                let _ = cx.update(|cx| {
1198                    SystemWindowTabController::remove_tab(cx, window_id);
1199                });
1200            }
1201        }));
1202        platform_window.on_request_frame(Box::new({
1203            let mut cx = cx.to_async();
1204            let invalidator = invalidator.clone();
1205            let active = active.clone();
1206            let needs_present = needs_present.clone();
1207            let next_frame_callbacks = next_frame_callbacks.clone();
1208            let input_rate_tracker = input_rate_tracker.clone();
1209            move |request_frame_options| {
1210                let thermal_state = handle
1211                    .update(&mut cx, |_, _, cx| cx.thermal_state())
1212                    .log_err();
1213
1214                // Throttle frame rate based on conditions:
1215                // - Thermal pressure (Serious/Critical): cap to ~60fps
1216                // - Inactive window (not focused): cap to ~30fps to save energy
1217                let min_frame_interval = if !request_frame_options.force_render
1218                    && !request_frame_options.require_presentation
1219                    && next_frame_callbacks.borrow().is_empty()
1220                {
1221                    None
1222                } else if !active.get() {
1223                    Some(Duration::from_micros(33333))
1224                } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1225                    Some(Duration::from_micros(16667))
1226                } else {
1227                    None
1228                };
1229
1230                let now = Instant::now();
1231                if let Some(min_interval) = min_frame_interval {
1232                    if let Some(last_frame) = last_frame_time.get()
1233                        && now.duration_since(last_frame) < min_interval
1234                    {
1235                        // Must still complete the frame on platforms that require it.
1236                        // On Wayland, `surface.frame()` was already called to request the
1237                        // next frame callback, so we must call `surface.commit()` (via
1238                        // `complete_frame`) or the compositor won't send another callback.
1239                        handle
1240                            .update(&mut cx, |_, window, _| window.complete_frame())
1241                            .log_err();
1242                        return;
1243                    }
1244                }
1245                last_frame_time.set(Some(now));
1246
1247                let next_frame_callbacks = next_frame_callbacks.take();
1248                if !next_frame_callbacks.is_empty() {
1249                    handle
1250                        .update(&mut cx, |_, window, cx| {
1251                            for callback in next_frame_callbacks {
1252                                callback(window, cx);
1253                            }
1254                        })
1255                        .log_err();
1256                }
1257
1258                // Keep presenting if input was recently arriving at a high rate (>= 60fps).
1259                // Once high-rate input is detected, we sustain presentation for 1 second
1260                // to prevent display underclocking during active input.
1261                let needs_present = request_frame_options.require_presentation
1262                    || needs_present.get()
1263                    || (active.get() && input_rate_tracker.borrow_mut().is_high_rate());
1264
1265                if invalidator.is_dirty() || request_frame_options.force_render {
1266                    measure("frame duration", || {
1267                        handle
1268                            .update(&mut cx, |_, window, cx| {
1269                                let arena_clear_needed = window.draw(cx);
1270                                window.present();
1271                                arena_clear_needed.clear();
1272                            })
1273                            .log_err();
1274                    })
1275                } else if needs_present {
1276                    handle
1277                        .update(&mut cx, |_, window, _| window.present())
1278                        .log_err();
1279                }
1280
1281                handle
1282                    .update(&mut cx, |_, window, _| {
1283                        window.complete_frame();
1284                    })
1285                    .log_err();
1286            }
1287        }));
1288        platform_window.on_resize(Box::new({
1289            let mut cx = cx.to_async();
1290            move |_, _| {
1291                handle
1292                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1293                    .log_err();
1294            }
1295        }));
1296        platform_window.on_moved(Box::new({
1297            let mut cx = cx.to_async();
1298            move || {
1299                handle
1300                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1301                    .log_err();
1302            }
1303        }));
1304        platform_window.on_appearance_changed(Box::new({
1305            let mut cx = cx.to_async();
1306            move || {
1307                handle
1308                    .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1309                    .log_err();
1310            }
1311        }));
1312        platform_window.on_button_layout_changed(Box::new({
1313            let mut cx = cx.to_async();
1314            move || {
1315                handle
1316                    .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1317                    .log_err();
1318            }
1319        }));
1320        platform_window.on_active_status_change(Box::new({
1321            let mut cx = cx.to_async();
1322            move |active| {
1323                handle
1324                    .update(&mut cx, |_, window, cx| {
1325                        window.active.set(active);
1326                        window.modifiers = window.platform_window.modifiers();
1327                        window.capslock = window.platform_window.capslock();
1328                        window
1329                            .activation_observers
1330                            .clone()
1331                            .retain(&(), |callback| callback(window, cx));
1332
1333                        window.bounds_changed(cx);
1334                        window.refresh();
1335
1336                        SystemWindowTabController::update_last_active(cx, window.handle.id);
1337                    })
1338                    .log_err();
1339            }
1340        }));
1341        platform_window.on_hover_status_change(Box::new({
1342            let mut cx = cx.to_async();
1343            move |active| {
1344                handle
1345                    .update(&mut cx, |_, window, _| {
1346                        window.hovered.set(active);
1347                        window.refresh();
1348                    })
1349                    .log_err();
1350            }
1351        }));
1352        platform_window.on_input({
1353            let mut cx = cx.to_async();
1354            Box::new(move |event| {
1355                handle
1356                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1357                    .log_err()
1358                    .unwrap_or(DispatchEventResult::default())
1359            })
1360        });
1361        platform_window.on_hit_test_window_control({
1362            let mut cx = cx.to_async();
1363            Box::new(move || {
1364                handle
1365                    .update(&mut cx, |_, window, _cx| {
1366                        for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1367                            if window.mouse_hit_test.ids.contains(&hitbox.id) {
1368                                return Some(*area);
1369                            }
1370                        }
1371                        None
1372                    })
1373                    .log_err()
1374                    .unwrap_or(None)
1375            })
1376        });
1377        platform_window.on_move_tab_to_new_window({
1378            let mut cx = cx.to_async();
1379            Box::new(move || {
1380                handle
1381                    .update(&mut cx, |_, _window, cx| {
1382                        SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1383                    })
1384                    .log_err();
1385            })
1386        });
1387        platform_window.on_merge_all_windows({
1388            let mut cx = cx.to_async();
1389            Box::new(move || {
1390                handle
1391                    .update(&mut cx, |_, _window, cx| {
1392                        SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1393                    })
1394                    .log_err();
1395            })
1396        });
1397        platform_window.on_select_next_tab({
1398            let mut cx = cx.to_async();
1399            Box::new(move || {
1400                handle
1401                    .update(&mut cx, |_, _window, cx| {
1402                        SystemWindowTabController::select_next_tab(cx, handle.window_id());
1403                    })
1404                    .log_err();
1405            })
1406        });
1407        platform_window.on_select_previous_tab({
1408            let mut cx = cx.to_async();
1409            Box::new(move || {
1410                handle
1411                    .update(&mut cx, |_, _window, cx| {
1412                        SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1413                    })
1414                    .log_err();
1415            })
1416        });
1417        platform_window.on_toggle_tab_bar({
1418            let mut cx = cx.to_async();
1419            Box::new(move || {
1420                handle
1421                    .update(&mut cx, |_, window, cx| {
1422                        let tab_bar_visible = window.platform_window.tab_bar_visible();
1423                        SystemWindowTabController::set_visible(cx, tab_bar_visible);
1424                    })
1425                    .log_err();
1426            })
1427        });
1428
1429        if let Some(app_id) = app_id {
1430            platform_window.set_app_id(&app_id);
1431        }
1432
1433        platform_window.map_window().unwrap();
1434
1435        Ok(Window {
1436            handle,
1437            invalidator,
1438            removed: false,
1439            platform_window,
1440            display_id,
1441            sprite_atlas,
1442            text_system,
1443            text_rendering_mode: cx.text_rendering_mode.clone(),
1444            rem_size: px(16.),
1445            rem_size_override_stack: SmallVec::new(),
1446            viewport_size: content_size,
1447            layout_engine: Some(TaffyLayoutEngine::new()),
1448            root: None,
1449            element_id_stack: SmallVec::default(),
1450            text_style_stack: Vec::new(),
1451            rendered_entity_stack: Vec::new(),
1452            element_offset_stack: Vec::new(),
1453            content_mask_stack: Vec::new(),
1454            element_opacity: 1.0,
1455            requested_autoscroll: None,
1456            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1457            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1458            next_frame_callbacks,
1459            next_hitbox_id: HitboxId(0),
1460            next_tooltip_id: TooltipId::default(),
1461            tooltip_bounds: None,
1462            dirty_views: FxHashSet::default(),
1463            focus_listeners: SubscriberSet::new(),
1464            focus_lost_listeners: SubscriberSet::new(),
1465            default_prevented: true,
1466            mouse_position,
1467            mouse_hit_test: HitTest::default(),
1468            modifiers,
1469            capslock,
1470            scale_factor,
1471            bounds_observers: SubscriberSet::new(),
1472            appearance,
1473            appearance_observers: SubscriberSet::new(),
1474            button_layout_observers: SubscriberSet::new(),
1475            active,
1476            hovered,
1477            needs_present,
1478            input_rate_tracker,
1479            last_input_modality: InputModality::Mouse,
1480            refreshing: false,
1481            activation_observers: SubscriberSet::new(),
1482            focus: None,
1483            focus_enabled: true,
1484            pending_input: None,
1485            pending_modifier: ModifierState::default(),
1486            pending_input_observers: SubscriberSet::new(),
1487            prompt: None,
1488            client_inset: None,
1489            image_cache_stack: Vec::new(),
1490            captured_hitbox: None,
1491            #[cfg(any(feature = "inspector", debug_assertions))]
1492            inspector: None,
1493        })
1494    }
1495
1496    pub(crate) fn new_focus_listener(
1497        &self,
1498        value: AnyWindowFocusListener,
1499    ) -> (Subscription, impl FnOnce() + use<>) {
1500        self.focus_listeners.insert((), value)
1501    }
1502}
1503
1504#[derive(Clone, Debug, Default, PartialEq, Eq)]
1505#[expect(missing_docs)]
1506pub struct DispatchEventResult {
1507    pub propagate: bool,
1508    pub default_prevented: bool,
1509}
1510
1511/// Indicates which region of the window is visible. Content falling outside of this mask will not be
1512/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
1513/// to leave room to support more complex shapes in the future.
1514#[derive(Clone, Debug, Default, PartialEq, Eq)]
1515#[repr(C)]
1516pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1517    /// The bounds
1518    pub bounds: Bounds<P>,
1519}
1520
1521impl ContentMask<Pixels> {
1522    /// Scale the content mask's pixel units by the given scaling factor.
1523    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1524        ContentMask {
1525            bounds: self.bounds.scale(factor),
1526        }
1527    }
1528
1529    /// Intersect the content mask with the given content mask.
1530    pub fn intersect(&self, other: &Self) -> Self {
1531        let bounds = self.bounds.intersect(&other.bounds);
1532        ContentMask { bounds }
1533    }
1534}
1535
1536impl Window {
1537    fn mark_view_dirty(&mut self, view_id: EntityId) {
1538        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
1539        // should already be dirty.
1540        for view_id in self
1541            .rendered_frame
1542            .dispatch_tree
1543            .view_path_reversed(view_id)
1544        {
1545            if !self.dirty_views.insert(view_id) {
1546                break;
1547            }
1548        }
1549    }
1550
1551    /// Registers a callback to be invoked when the window appearance changes.
1552    pub fn observe_window_appearance(
1553        &self,
1554        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1555    ) -> Subscription {
1556        let (subscription, activate) = self.appearance_observers.insert(
1557            (),
1558            Box::new(move |window, cx| {
1559                callback(window, cx);
1560                true
1561            }),
1562        );
1563        activate();
1564        subscription
1565    }
1566
1567    /// Registers a callback to be invoked when the window button layout changes.
1568    pub fn observe_button_layout_changed(
1569        &self,
1570        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1571    ) -> Subscription {
1572        let (subscription, activate) = self.button_layout_observers.insert(
1573            (),
1574            Box::new(move |window, cx| {
1575                callback(window, cx);
1576                true
1577            }),
1578        );
1579        activate();
1580        subscription
1581    }
1582
1583    /// Replaces the root entity of the window with a new one.
1584    pub fn replace_root<E>(
1585        &mut self,
1586        cx: &mut App,
1587        build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1588    ) -> Entity<E>
1589    where
1590        E: 'static + Render,
1591    {
1592        let view = cx.new(|cx| build_view(self, cx));
1593        self.root = Some(view.clone().into());
1594        self.refresh();
1595        view
1596    }
1597
1598    /// Returns the root entity of the window, if it has one.
1599    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1600    where
1601        E: 'static + Render,
1602    {
1603        self.root
1604            .as_ref()
1605            .map(|view| view.clone().downcast::<E>().ok())
1606    }
1607
1608    /// Obtain a handle to the window that belongs to this context.
1609    pub fn window_handle(&self) -> AnyWindowHandle {
1610        self.handle
1611    }
1612
1613    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1614    pub fn refresh(&mut self) {
1615        if self.invalidator.not_drawing() {
1616            self.refreshing = true;
1617            self.invalidator.set_dirty(true);
1618        }
1619    }
1620
1621    /// Close this window.
1622    pub fn remove_window(&mut self) {
1623        self.removed = true;
1624    }
1625
1626    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1627    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1628        self.focus
1629            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1630    }
1631
1632    /// Move focus to the element associated with the given [`FocusHandle`].
1633    pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
1634        if !self.focus_enabled || self.focus == Some(handle.id) {
1635            return;
1636        }
1637
1638        self.focus = Some(handle.id);
1639        self.clear_pending_keystrokes();
1640
1641        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
1642        // current effect cycle, and only for this window.
1643        let window_handle = self.handle;
1644        cx.defer(move |cx| {
1645            window_handle
1646                .update(cx, |_, window, cx| {
1647                    window.pending_input_changed(cx);
1648                })
1649                .ok();
1650        });
1651
1652        self.refresh();
1653    }
1654
1655    /// Remove focus from all elements within this context's window.
1656    pub fn blur(&mut self) {
1657        if !self.focus_enabled {
1658            return;
1659        }
1660
1661        self.focus = None;
1662        self.refresh();
1663    }
1664
1665    /// Blur the window and don't allow anything in it to be focused again.
1666    pub fn disable_focus(&mut self) {
1667        self.blur();
1668        self.focus_enabled = false;
1669    }
1670
1671    /// Move focus to next tab stop.
1672    pub fn focus_next(&mut self, cx: &mut App) {
1673        if !self.focus_enabled {
1674            return;
1675        }
1676
1677        if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
1678            self.focus(&handle, cx)
1679        }
1680    }
1681
1682    /// Move focus to previous tab stop.
1683    pub fn focus_prev(&mut self, cx: &mut App) {
1684        if !self.focus_enabled {
1685            return;
1686        }
1687
1688        if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
1689            self.focus(&handle, cx)
1690        }
1691    }
1692
1693    /// Accessor for the text system.
1694    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1695        &self.text_system
1696    }
1697
1698    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1699    pub fn text_style(&self) -> TextStyle {
1700        let mut style = TextStyle::default();
1701        for refinement in &self.text_style_stack {
1702            style.refine(refinement);
1703        }
1704        style
1705    }
1706
1707    /// Check if the platform window is maximized.
1708    ///
1709    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1710    pub fn is_maximized(&self) -> bool {
1711        self.platform_window.is_maximized()
1712    }
1713
1714    /// request a certain window decoration (Wayland)
1715    pub fn request_decorations(&self, decorations: WindowDecorations) {
1716        self.platform_window.request_decorations(decorations);
1717    }
1718
1719    /// Start a window resize operation (Wayland)
1720    pub fn start_window_resize(&self, edge: ResizeEdge) {
1721        self.platform_window.start_window_resize(edge);
1722    }
1723
1724    /// Return the `WindowBounds` to indicate that how a window should be opened
1725    /// after it has been closed
1726    pub fn window_bounds(&self) -> WindowBounds {
1727        self.platform_window.window_bounds()
1728    }
1729
1730    /// Return the `WindowBounds` excluding insets (Wayland and X11)
1731    pub fn inner_window_bounds(&self) -> WindowBounds {
1732        self.platform_window.inner_window_bounds()
1733    }
1734
1735    /// Dispatch the given action on the currently focused element.
1736    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1737        let focus_id = self.focused(cx).map(|handle| handle.id);
1738
1739        let window = self.handle;
1740        cx.defer(move |cx| {
1741            window
1742                .update(cx, |_, window, cx| {
1743                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1744                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1745                })
1746                .log_err();
1747        })
1748    }
1749
1750    pub(crate) fn dispatch_keystroke_observers(
1751        &mut self,
1752        event: &dyn Any,
1753        action: Option<Box<dyn Action>>,
1754        context_stack: Vec<KeyContext>,
1755        cx: &mut App,
1756    ) {
1757        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1758            return;
1759        };
1760
1761        cx.keystroke_observers.clone().retain(&(), move |callback| {
1762            (callback)(
1763                &KeystrokeEvent {
1764                    keystroke: key_down_event.keystroke.clone(),
1765                    action: action.as_ref().map(|action| action.boxed_clone()),
1766                    context_stack: context_stack.clone(),
1767                },
1768                self,
1769                cx,
1770            )
1771        });
1772    }
1773
1774    pub(crate) fn dispatch_keystroke_interceptors(
1775        &mut self,
1776        event: &dyn Any,
1777        context_stack: Vec<KeyContext>,
1778        cx: &mut App,
1779    ) {
1780        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1781            return;
1782        };
1783
1784        cx.keystroke_interceptors
1785            .clone()
1786            .retain(&(), move |callback| {
1787                (callback)(
1788                    &KeystrokeEvent {
1789                        keystroke: key_down_event.keystroke.clone(),
1790                        action: None,
1791                        context_stack: context_stack.clone(),
1792                    },
1793                    self,
1794                    cx,
1795                )
1796            });
1797    }
1798
1799    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1800    /// that are currently on the stack to be returned to the app.
1801    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1802        let handle = self.handle;
1803        cx.defer(move |cx| {
1804            handle.update(cx, |_, window, cx| f(window, cx)).ok();
1805        });
1806    }
1807
1808    /// Subscribe to events emitted by a entity.
1809    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1810    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1811    pub fn observe<T: 'static>(
1812        &mut self,
1813        observed: &Entity<T>,
1814        cx: &mut App,
1815        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1816    ) -> Subscription {
1817        let entity_id = observed.entity_id();
1818        let observed = observed.downgrade();
1819        let window_handle = self.handle;
1820        cx.new_observer(
1821            entity_id,
1822            Box::new(move |cx| {
1823                window_handle
1824                    .update(cx, |_, window, cx| {
1825                        if let Some(handle) = observed.upgrade() {
1826                            on_notify(handle, window, cx);
1827                            true
1828                        } else {
1829                            false
1830                        }
1831                    })
1832                    .unwrap_or(false)
1833            }),
1834        )
1835    }
1836
1837    /// Subscribe to events emitted by a entity.
1838    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1839    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1840    pub fn subscribe<Emitter, Evt>(
1841        &mut self,
1842        entity: &Entity<Emitter>,
1843        cx: &mut App,
1844        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1845    ) -> Subscription
1846    where
1847        Emitter: EventEmitter<Evt>,
1848        Evt: 'static,
1849    {
1850        let entity_id = entity.entity_id();
1851        let handle = entity.downgrade();
1852        let window_handle = self.handle;
1853        cx.new_subscription(
1854            entity_id,
1855            (
1856                TypeId::of::<Evt>(),
1857                Box::new(move |event, cx| {
1858                    window_handle
1859                        .update(cx, |_, window, cx| {
1860                            if let Some(entity) = handle.upgrade() {
1861                                let event = event.downcast_ref().expect("invalid event type");
1862                                on_event(entity, event, window, cx);
1863                                true
1864                            } else {
1865                                false
1866                            }
1867                        })
1868                        .unwrap_or(false)
1869                }),
1870            ),
1871        )
1872    }
1873
1874    /// Register a callback to be invoked when the given `Entity` is released.
1875    pub fn observe_release<T>(
1876        &self,
1877        entity: &Entity<T>,
1878        cx: &mut App,
1879        mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1880    ) -> Subscription
1881    where
1882        T: 'static,
1883    {
1884        let entity_id = entity.entity_id();
1885        let window_handle = self.handle;
1886        let (subscription, activate) = cx.release_listeners.insert(
1887            entity_id,
1888            Box::new(move |entity, cx| {
1889                let entity = entity.downcast_mut().expect("invalid entity type");
1890                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1891            }),
1892        );
1893        activate();
1894        subscription
1895    }
1896
1897    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1898    /// await points in async code.
1899    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1900        AsyncWindowContext::new_context(cx.to_async(), self.handle)
1901    }
1902
1903    /// Schedule the given closure to be run directly after the current frame is rendered.
1904    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1905        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1906    }
1907
1908    /// Schedule a frame to be drawn on the next animation frame.
1909    ///
1910    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
1911    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
1912    ///
1913    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
1914    pub fn request_animation_frame(&self) {
1915        let entity = self.current_view();
1916        self.on_next_frame(move |_, cx| cx.notify(entity));
1917    }
1918
1919    /// Spawn the future returned by the given closure on the application thread pool.
1920    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1921    /// use within your future.
1922    #[track_caller]
1923    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
1924    where
1925        R: 'static,
1926        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1927    {
1928        let handle = self.handle;
1929        cx.spawn(async move |app| {
1930            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1931            f(&mut async_window_cx).await
1932        })
1933    }
1934
1935    /// Spawn the future returned by the given closure on the application thread
1936    /// pool, with the given priority. The closure is provided a handle to the
1937    /// current window and an `AsyncWindowContext` for use within your future.
1938    #[track_caller]
1939    pub fn spawn_with_priority<AsyncFn, R>(
1940        &self,
1941        priority: Priority,
1942        cx: &App,
1943        f: AsyncFn,
1944    ) -> Task<R>
1945    where
1946        R: 'static,
1947        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1948    {
1949        let handle = self.handle;
1950        cx.spawn_with_priority(priority, async move |app| {
1951            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1952            f(&mut async_window_cx).await
1953        })
1954    }
1955
1956    /// Notify the window that its bounds have changed.
1957    ///
1958    /// This updates internal state like `viewport_size` and `scale_factor` from
1959    /// the platform window, then notifies observers. Normally called automatically
1960    /// by the platform's resize callback, but exposed publicly for test infrastructure.
1961    pub fn bounds_changed(&mut self, cx: &mut App) {
1962        self.scale_factor = self.platform_window.scale_factor();
1963        self.viewport_size = self.platform_window.content_size();
1964        self.display_id = self.platform_window.display().map(|display| display.id());
1965
1966        self.refresh();
1967
1968        self.bounds_observers
1969            .clone()
1970            .retain(&(), |callback| callback(self, cx));
1971    }
1972
1973    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1974    pub fn bounds(&self) -> Bounds<Pixels> {
1975        self.platform_window.bounds()
1976    }
1977
1978    /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
1979    /// This does not present the frame to screen - useful for visual testing where we want
1980    /// to capture what would be rendered without displaying it or requiring the window to be visible.
1981    #[cfg(any(test, feature = "test-support"))]
1982    pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
1983        self.platform_window
1984            .render_to_image(&self.rendered_frame.scene)
1985    }
1986
1987    /// Set the content size of the window.
1988    pub fn resize(&mut self, size: Size<Pixels>) {
1989        self.platform_window.resize(size);
1990    }
1991
1992    /// Returns whether or not the window is currently fullscreen
1993    pub fn is_fullscreen(&self) -> bool {
1994        self.platform_window.is_fullscreen()
1995    }
1996
1997    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1998        self.appearance = self.platform_window.appearance();
1999
2000        self.appearance_observers
2001            .clone()
2002            .retain(&(), |callback| callback(self, cx));
2003    }
2004
2005    pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2006        self.button_layout_observers
2007            .clone()
2008            .retain(&(), |callback| callback(self, cx));
2009    }
2010
2011    /// Returns the appearance of the current window.
2012    pub fn appearance(&self) -> WindowAppearance {
2013        self.appearance
2014    }
2015
2016    /// Returns the size of the drawable area within the window.
2017    pub fn viewport_size(&self) -> Size<Pixels> {
2018        self.viewport_size
2019    }
2020
2021    /// Returns whether this window is focused by the operating system (receiving key events).
2022    pub fn is_window_active(&self) -> bool {
2023        self.active.get()
2024    }
2025
2026    /// Returns whether this window is considered to be the window
2027    /// that currently owns the mouse cursor.
2028    /// On mac, this is equivalent to `is_window_active`.
2029    pub fn is_window_hovered(&self) -> bool {
2030        if cfg!(any(
2031            target_os = "windows",
2032            target_os = "linux",
2033            target_os = "freebsd"
2034        )) {
2035            self.hovered.get()
2036        } else {
2037            self.is_window_active()
2038        }
2039    }
2040
2041    /// Toggle zoom on the window.
2042    pub fn zoom_window(&self) {
2043        self.platform_window.zoom();
2044    }
2045
2046    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
2047    pub fn show_window_menu(&self, position: Point<Pixels>) {
2048        self.platform_window.show_window_menu(position)
2049    }
2050
2051    /// Handle window movement for Linux and macOS.
2052    /// Tells the compositor to take control of window movement (Wayland and X11)
2053    ///
2054    /// Events may not be received during a move operation.
2055    pub fn start_window_move(&self) {
2056        self.platform_window.start_window_move()
2057    }
2058
2059    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
2060    pub fn set_client_inset(&mut self, inset: Pixels) {
2061        self.client_inset = Some(inset);
2062        self.platform_window.set_client_inset(inset);
2063    }
2064
2065    /// Returns the client_inset value by [`Self::set_client_inset`].
2066    pub fn client_inset(&self) -> Option<Pixels> {
2067        self.client_inset
2068    }
2069
2070    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
2071    pub fn window_decorations(&self) -> Decorations {
2072        self.platform_window.window_decorations()
2073    }
2074
2075    /// Returns which window controls are currently visible (Wayland)
2076    pub fn window_controls(&self) -> WindowControls {
2077        self.platform_window.window_controls()
2078    }
2079
2080    /// Updates the window's title at the platform level.
2081    pub fn set_window_title(&mut self, title: &str) {
2082        self.platform_window.set_title(title);
2083    }
2084
2085    /// Sets the application identifier.
2086    pub fn set_app_id(&mut self, app_id: &str) {
2087        self.platform_window.set_app_id(app_id);
2088    }
2089
2090    /// Sets the window background appearance.
2091    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2092        self.platform_window
2093            .set_background_appearance(background_appearance);
2094    }
2095
2096    /// Mark the window as dirty at the platform level.
2097    pub fn set_window_edited(&mut self, edited: bool) {
2098        self.platform_window.set_edited(edited);
2099    }
2100
2101    /// Determine the display on which the window is visible.
2102    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2103        cx.platform
2104            .displays()
2105            .into_iter()
2106            .find(|display| Some(display.id()) == self.display_id)
2107    }
2108
2109    /// Show the platform character palette.
2110    pub fn show_character_palette(&self) {
2111        self.platform_window.show_character_palette();
2112    }
2113
2114    /// The scale factor of the display associated with the window. For example, it could
2115    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
2116    /// be rendered as two pixels on screen.
2117    pub fn scale_factor(&self) -> f32 {
2118        self.scale_factor
2119    }
2120
2121    /// The size of an em for the base font of the application. Adjusting this value allows the
2122    /// UI to scale, just like zooming a web page.
2123    pub fn rem_size(&self) -> Pixels {
2124        self.rem_size_override_stack
2125            .last()
2126            .copied()
2127            .unwrap_or(self.rem_size)
2128    }
2129
2130    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
2131    /// UI to scale, just like zooming a web page.
2132    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2133        self.rem_size = rem_size.into();
2134    }
2135
2136    /// Acquire a globally unique identifier for the given ElementId.
2137    /// Only valid for the duration of the provided closure.
2138    pub fn with_global_id<R>(
2139        &mut self,
2140        element_id: ElementId,
2141        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2142    ) -> R {
2143        self.with_id(element_id, |this| {
2144            let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2145
2146            f(&global_id, this)
2147        })
2148    }
2149
2150    /// Calls the provided closure with the element ID pushed on the stack.
2151    #[inline]
2152    pub fn with_id<R>(
2153        &mut self,
2154        element_id: impl Into<ElementId>,
2155        f: impl FnOnce(&mut Self) -> R,
2156    ) -> R {
2157        self.element_id_stack.push(element_id.into());
2158        let result = f(self);
2159        self.element_id_stack.pop();
2160        result
2161    }
2162
2163    /// Executes the provided function with the specified rem size.
2164    ///
2165    /// This method must only be called as part of element drawing.
2166    // This function is called in a highly recursive manner in editor
2167    // prepainting, make sure its inlined to reduce the stack burden
2168    #[inline]
2169    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2170    where
2171        F: FnOnce(&mut Self) -> R,
2172    {
2173        self.invalidator.debug_assert_paint_or_prepaint();
2174
2175        if let Some(rem_size) = rem_size {
2176            self.rem_size_override_stack.push(rem_size.into());
2177            let result = f(self);
2178            self.rem_size_override_stack.pop();
2179            result
2180        } else {
2181            f(self)
2182        }
2183    }
2184
2185    /// The line height associated with the current text style.
2186    pub fn line_height(&self) -> Pixels {
2187        self.text_style().line_height_in_pixels(self.rem_size())
2188    }
2189
2190    /// Call to prevent the default action of an event. Currently only used to prevent
2191    /// parent elements from becoming focused on mouse down.
2192    pub fn prevent_default(&mut self) {
2193        self.default_prevented = true;
2194    }
2195
2196    /// Obtain whether default has been prevented for the event currently being dispatched.
2197    pub fn default_prevented(&self) -> bool {
2198        self.default_prevented
2199    }
2200
2201    /// Determine whether the given action is available along the dispatch path to the currently focused element.
2202    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2203        let node_id =
2204            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2205        self.rendered_frame
2206            .dispatch_tree
2207            .is_action_available(action, node_id)
2208    }
2209
2210    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
2211    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2212        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2213        self.rendered_frame
2214            .dispatch_tree
2215            .is_action_available(action, node_id)
2216    }
2217
2218    /// The position of the mouse relative to the window.
2219    pub fn mouse_position(&self) -> Point<Pixels> {
2220        self.mouse_position
2221    }
2222
2223    /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
2224    /// events will be routed to listeners that check this hitbox's `is_hovered` status,
2225    /// regardless of actual hit testing. This enables drag operations that continue
2226    /// even when the pointer moves outside the element's bounds.
2227    ///
2228    /// The capture is automatically released on mouse up.
2229    pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2230        self.captured_hitbox = Some(hitbox_id);
2231    }
2232
2233    /// Releases any active pointer capture.
2234    pub fn release_pointer(&mut self) {
2235        self.captured_hitbox = None;
2236    }
2237
2238    /// Returns the hitbox that has captured the pointer, if any.
2239    pub fn captured_hitbox(&self) -> Option<HitboxId> {
2240        self.captured_hitbox
2241    }
2242
2243    /// The current state of the keyboard's modifiers
2244    pub fn modifiers(&self) -> Modifiers {
2245        self.modifiers
2246    }
2247
2248    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
2249    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
2250    pub fn last_input_was_keyboard(&self) -> bool {
2251        self.last_input_modality == InputModality::Keyboard
2252    }
2253
2254    /// The current state of the keyboard's capslock
2255    pub fn capslock(&self) -> Capslock {
2256        self.capslock
2257    }
2258
2259    fn complete_frame(&self) {
2260        self.platform_window.completed_frame();
2261    }
2262
2263    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
2264    /// the contents of the new [`Scene`], use [`Self::present`].
2265    #[profiling::function]
2266    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2267        // Set up the per-App arena for element allocation during this draw.
2268        // This ensures that multiple test Apps have isolated arenas.
2269        let _arena_scope = ElementArenaScope::enter(&cx.element_arena);
2270
2271        self.invalidate_entities();
2272        cx.entities.clear_accessed();
2273        debug_assert!(self.rendered_entity_stack.is_empty());
2274        self.invalidator.set_dirty(false);
2275        self.requested_autoscroll = None;
2276
2277        // Restore the previously-used input handler.
2278        if let Some(input_handler) = self.platform_window.take_input_handler() {
2279            self.rendered_frame.input_handlers.push(Some(input_handler));
2280        }
2281        if !cx.mode.skip_drawing() {
2282            self.draw_roots(cx);
2283        }
2284        self.dirty_views.clear();
2285        self.next_frame.window_active = self.active.get();
2286
2287        // Register requested input handler with the platform window.
2288        if let Some(input_handler) = self.next_frame.input_handlers.pop() {
2289            self.platform_window
2290                .set_input_handler(input_handler.unwrap());
2291        }
2292
2293        self.layout_engine.as_mut().unwrap().clear();
2294        self.text_system().finish_frame();
2295        self.next_frame.finish(&mut self.rendered_frame);
2296
2297        self.invalidator.set_phase(DrawPhase::Focus);
2298        let previous_focus_path = self.rendered_frame.focus_path();
2299        let previous_window_active = self.rendered_frame.window_active;
2300        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2301        self.next_frame.clear();
2302        let current_focus_path = self.rendered_frame.focus_path();
2303        let current_window_active = self.rendered_frame.window_active;
2304
2305        if previous_focus_path != current_focus_path
2306            || previous_window_active != current_window_active
2307        {
2308            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2309                self.focus_lost_listeners
2310                    .clone()
2311                    .retain(&(), |listener| listener(self, cx));
2312            }
2313
2314            let event = WindowFocusEvent {
2315                previous_focus_path: if previous_window_active {
2316                    previous_focus_path
2317                } else {
2318                    Default::default()
2319                },
2320                current_focus_path: if current_window_active {
2321                    current_focus_path
2322                } else {
2323                    Default::default()
2324                },
2325            };
2326            self.focus_listeners
2327                .clone()
2328                .retain(&(), |listener| listener(&event, self, cx));
2329        }
2330
2331        debug_assert!(self.rendered_entity_stack.is_empty());
2332        self.record_entities_accessed(cx);
2333        self.reset_cursor_style(cx);
2334        self.refreshing = false;
2335        self.invalidator.set_phase(DrawPhase::None);
2336        self.needs_present.set(true);
2337
2338        ArenaClearNeeded::new(&cx.element_arena)
2339    }
2340
2341    fn record_entities_accessed(&mut self, cx: &mut App) {
2342        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2343        let mut entities = mem::take(entities_ref.deref_mut());
2344        let handle = self.handle;
2345        cx.record_entities_accessed(
2346            handle,
2347            // Try moving window invalidator into the Window
2348            self.invalidator.clone(),
2349            &entities,
2350        );
2351        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2352        mem::swap(&mut entities, entities_ref.deref_mut());
2353    }
2354
2355    fn invalidate_entities(&mut self) {
2356        let mut views = self.invalidator.take_views();
2357        for entity in views.drain() {
2358            self.mark_view_dirty(entity);
2359        }
2360        self.invalidator.replace_views(views);
2361    }
2362
2363    #[profiling::function]
2364    fn present(&self) {
2365        self.platform_window.draw(&self.rendered_frame.scene);
2366        self.needs_present.set(false);
2367        profiling::finish_frame!();
2368    }
2369
2370    fn draw_roots(&mut self, cx: &mut App) {
2371        self.invalidator.set_phase(DrawPhase::Prepaint);
2372        self.tooltip_bounds.take();
2373
2374        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2375        let root_size = {
2376            #[cfg(any(feature = "inspector", debug_assertions))]
2377            {
2378                if self.inspector.is_some() {
2379                    let mut size = self.viewport_size;
2380                    size.width = (size.width - _inspector_width).max(px(0.0));
2381                    size
2382                } else {
2383                    self.viewport_size
2384                }
2385            }
2386            #[cfg(not(any(feature = "inspector", debug_assertions)))]
2387            {
2388                self.viewport_size
2389            }
2390        };
2391
2392        // Layout all root elements.
2393        let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2394        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2395
2396        #[cfg(any(feature = "inspector", debug_assertions))]
2397        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2398
2399        self.prepaint_deferred_draws(cx);
2400
2401        let mut prompt_element = None;
2402        let mut active_drag_element = None;
2403        let mut tooltip_element = None;
2404        if let Some(prompt) = self.prompt.take() {
2405            let mut element = prompt.view.any_view().into_any();
2406            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2407            prompt_element = Some(element);
2408            self.prompt = Some(prompt);
2409        } else if let Some(active_drag) = cx.active_drag.take() {
2410            let mut element = active_drag.view.clone().into_any();
2411            let offset = self.mouse_position() - active_drag.cursor_offset;
2412            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2413            active_drag_element = Some(element);
2414            cx.active_drag = Some(active_drag);
2415        } else {
2416            tooltip_element = self.prepaint_tooltip(cx);
2417        }
2418
2419        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2420
2421        // Now actually paint the elements.
2422        self.invalidator.set_phase(DrawPhase::Paint);
2423        root_element.paint(self, cx);
2424
2425        #[cfg(any(feature = "inspector", debug_assertions))]
2426        self.paint_inspector(inspector_element, cx);
2427
2428        self.paint_deferred_draws(cx);
2429
2430        if let Some(mut prompt_element) = prompt_element {
2431            prompt_element.paint(self, cx);
2432        } else if let Some(mut drag_element) = active_drag_element {
2433            drag_element.paint(self, cx);
2434        } else if let Some(mut tooltip_element) = tooltip_element {
2435            tooltip_element.paint(self, cx);
2436        }
2437
2438        #[cfg(any(feature = "inspector", debug_assertions))]
2439        self.paint_inspector_hitbox(cx);
2440    }
2441
2442    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2443        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2444        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2445            let Some(Some(tooltip_request)) = self
2446                .next_frame
2447                .tooltip_requests
2448                .get(tooltip_request_index)
2449                .cloned()
2450            else {
2451                log::error!("Unexpectedly absent TooltipRequest");
2452                continue;
2453            };
2454            let mut element = tooltip_request.tooltip.view.clone().into_any();
2455            let mouse_position = tooltip_request.tooltip.mouse_position;
2456            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2457
2458            let mut tooltip_bounds =
2459                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2460            let window_bounds = Bounds {
2461                origin: Point::default(),
2462                size: self.viewport_size(),
2463            };
2464
2465            if tooltip_bounds.right() > window_bounds.right() {
2466                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2467                if new_x >= Pixels::ZERO {
2468                    tooltip_bounds.origin.x = new_x;
2469                } else {
2470                    tooltip_bounds.origin.x = cmp::max(
2471                        Pixels::ZERO,
2472                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2473                    );
2474                }
2475            }
2476
2477            if tooltip_bounds.bottom() > window_bounds.bottom() {
2478                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2479                if new_y >= Pixels::ZERO {
2480                    tooltip_bounds.origin.y = new_y;
2481                } else {
2482                    tooltip_bounds.origin.y = cmp::max(
2483                        Pixels::ZERO,
2484                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2485                    );
2486                }
2487            }
2488
2489            // It's possible for an element to have an active tooltip while not being painted (e.g.
2490            // via the `visible_on_hover` method). Since mouse listeners are not active in this
2491            // case, instead update the tooltip's visibility here.
2492            let is_visible =
2493                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2494            if !is_visible {
2495                continue;
2496            }
2497
2498            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2499                element.prepaint(window, cx)
2500            });
2501
2502            self.tooltip_bounds = Some(TooltipBounds {
2503                id: tooltip_request.id,
2504                bounds: tooltip_bounds,
2505            });
2506            return Some(element);
2507        }
2508        None
2509    }
2510
2511    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
2512        assert_eq!(self.element_id_stack.len(), 0);
2513
2514        let mut completed_draws = Vec::new();
2515
2516        // Process deferred draws in multiple rounds to support nesting.
2517        // Each round processes all current deferred draws, which may produce new ones.
2518        let mut depth = 0;
2519        loop {
2520            // Limit maximum nesting depth to prevent infinite loops.
2521            assert!(depth < 10, "Exceeded maximum (10) deferred depth");
2522            depth += 1;
2523            let deferred_count = self.next_frame.deferred_draws.len();
2524            if deferred_count == 0 {
2525                break;
2526            }
2527
2528            // Sort by priority for this round
2529            let traversal_order = self.deferred_draw_traversal_order();
2530            let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2531
2532            for deferred_draw_ix in traversal_order {
2533                let deferred_draw = &mut deferred_draws[deferred_draw_ix];
2534                self.element_id_stack
2535                    .clone_from(&deferred_draw.element_id_stack);
2536                self.text_style_stack
2537                    .clone_from(&deferred_draw.text_style_stack);
2538                self.next_frame
2539                    .dispatch_tree
2540                    .set_active_node(deferred_draw.parent_node);
2541
2542                let prepaint_start = self.prepaint_index();
2543                if let Some(element) = deferred_draw.element.as_mut() {
2544                    self.with_rendered_view(deferred_draw.current_view, |window| {
2545                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2546                            window.with_absolute_element_offset(
2547                                deferred_draw.absolute_offset,
2548                                |window| {
2549                                    element.prepaint(window, cx);
2550                                },
2551                            );
2552                        });
2553                    })
2554                } else {
2555                    self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2556                }
2557                let prepaint_end = self.prepaint_index();
2558                deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2559            }
2560
2561            // Save completed draws and continue with newly added ones
2562            completed_draws.append(&mut deferred_draws);
2563
2564            self.element_id_stack.clear();
2565            self.text_style_stack.clear();
2566        }
2567
2568        // Restore all completed draws
2569        self.next_frame.deferred_draws = completed_draws;
2570    }
2571
2572    fn paint_deferred_draws(&mut self, cx: &mut App) {
2573        assert_eq!(self.element_id_stack.len(), 0);
2574
2575        // Paint all deferred draws in priority order.
2576        // Since prepaint has already processed nested deferreds, we just paint them all.
2577        if self.next_frame.deferred_draws.len() == 0 {
2578            return;
2579        }
2580
2581        let traversal_order = self.deferred_draw_traversal_order();
2582        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2583        for deferred_draw_ix in traversal_order {
2584            let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
2585            self.element_id_stack
2586                .clone_from(&deferred_draw.element_id_stack);
2587            self.next_frame
2588                .dispatch_tree
2589                .set_active_node(deferred_draw.parent_node);
2590
2591            let paint_start = self.paint_index();
2592            let content_mask = deferred_draw.content_mask.clone();
2593            if let Some(element) = deferred_draw.element.as_mut() {
2594                self.with_rendered_view(deferred_draw.current_view, |window| {
2595                    window.with_content_mask(content_mask, |window| {
2596                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2597                            element.paint(window, cx);
2598                        });
2599                    })
2600                })
2601            } else {
2602                self.reuse_paint(deferred_draw.paint_range.clone());
2603            }
2604            let paint_end = self.paint_index();
2605            deferred_draw.paint_range = paint_start..paint_end;
2606        }
2607        self.next_frame.deferred_draws = deferred_draws;
2608        self.element_id_stack.clear();
2609    }
2610
2611    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
2612        let deferred_count = self.next_frame.deferred_draws.len();
2613        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
2614        sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2615        sorted_indices
2616    }
2617
2618    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2619        PrepaintStateIndex {
2620            hitboxes_index: self.next_frame.hitboxes.len(),
2621            tooltips_index: self.next_frame.tooltip_requests.len(),
2622            deferred_draws_index: self.next_frame.deferred_draws.len(),
2623            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2624            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2625            line_layout_index: self.text_system.layout_index(),
2626        }
2627    }
2628
2629    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2630        self.next_frame.hitboxes.extend(
2631            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2632                .iter()
2633                .cloned(),
2634        );
2635        self.next_frame.tooltip_requests.extend(
2636            self.rendered_frame.tooltip_requests
2637                [range.start.tooltips_index..range.end.tooltips_index]
2638                .iter_mut()
2639                .map(|request| request.take()),
2640        );
2641        self.next_frame.accessed_element_states.extend(
2642            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2643                ..range.end.accessed_element_states_index]
2644                .iter()
2645                .map(|(id, type_id)| (id.clone(), *type_id)),
2646        );
2647        self.text_system
2648            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2649
2650        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2651            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2652            &mut self.rendered_frame.dispatch_tree,
2653            self.focus,
2654        );
2655
2656        if reused_subtree.contains_focus() {
2657            self.next_frame.focus = self.focus;
2658        }
2659
2660        self.next_frame.deferred_draws.extend(
2661            self.rendered_frame.deferred_draws
2662                [range.start.deferred_draws_index..range.end.deferred_draws_index]
2663                .iter()
2664                .map(|deferred_draw| DeferredDraw {
2665                    current_view: deferred_draw.current_view,
2666                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2667                    element_id_stack: deferred_draw.element_id_stack.clone(),
2668                    text_style_stack: deferred_draw.text_style_stack.clone(),
2669                    content_mask: deferred_draw.content_mask.clone(),
2670                    rem_size: deferred_draw.rem_size,
2671                    priority: deferred_draw.priority,
2672                    element: None,
2673                    absolute_offset: deferred_draw.absolute_offset,
2674                    prepaint_range: deferred_draw.prepaint_range.clone(),
2675                    paint_range: deferred_draw.paint_range.clone(),
2676                }),
2677        );
2678    }
2679
2680    pub(crate) fn paint_index(&self) -> PaintIndex {
2681        PaintIndex {
2682            scene_index: self.next_frame.scene.len(),
2683            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2684            input_handlers_index: self.next_frame.input_handlers.len(),
2685            cursor_styles_index: self.next_frame.cursor_styles.len(),
2686            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2687            tab_handle_index: self.next_frame.tab_stops.paint_index(),
2688            line_layout_index: self.text_system.layout_index(),
2689        }
2690    }
2691
2692    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2693        self.next_frame.cursor_styles.extend(
2694            self.rendered_frame.cursor_styles
2695                [range.start.cursor_styles_index..range.end.cursor_styles_index]
2696                .iter()
2697                .cloned(),
2698        );
2699        self.next_frame.input_handlers.extend(
2700            self.rendered_frame.input_handlers
2701                [range.start.input_handlers_index..range.end.input_handlers_index]
2702                .iter_mut()
2703                .map(|handler| handler.take()),
2704        );
2705        self.next_frame.mouse_listeners.extend(
2706            self.rendered_frame.mouse_listeners
2707                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2708                .iter_mut()
2709                .map(|listener| listener.take()),
2710        );
2711        self.next_frame.accessed_element_states.extend(
2712            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2713                ..range.end.accessed_element_states_index]
2714                .iter()
2715                .map(|(id, type_id)| (id.clone(), *type_id)),
2716        );
2717        self.next_frame.tab_stops.replay(
2718            &self.rendered_frame.tab_stops.insertion_history
2719                [range.start.tab_handle_index..range.end.tab_handle_index],
2720        );
2721
2722        self.text_system
2723            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2724        self.next_frame.scene.replay(
2725            range.start.scene_index..range.end.scene_index,
2726            &self.rendered_frame.scene,
2727        );
2728    }
2729
2730    /// Push a text style onto the stack, and call a function with that style active.
2731    /// Use [`Window::text_style`] to get the current, combined text style. This method
2732    /// should only be called as part of element drawing.
2733    // This function is called in a highly recursive manner in editor
2734    // prepainting, make sure its inlined to reduce the stack burden
2735    #[inline]
2736    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2737    where
2738        F: FnOnce(&mut Self) -> R,
2739    {
2740        self.invalidator.debug_assert_paint_or_prepaint();
2741        if let Some(style) = style {
2742            self.text_style_stack.push(style);
2743            let result = f(self);
2744            self.text_style_stack.pop();
2745            result
2746        } else {
2747            f(self)
2748        }
2749    }
2750
2751    /// Updates the cursor style at the platform level. This method should only be called
2752    /// during the paint phase of element drawing.
2753    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2754        self.invalidator.debug_assert_paint();
2755        self.next_frame.cursor_styles.push(CursorStyleRequest {
2756            hitbox_id: Some(hitbox.id),
2757            style,
2758        });
2759    }
2760
2761    /// Updates the cursor style for the entire window at the platform level. A cursor
2762    /// style using this method will have precedence over any cursor style set using
2763    /// `set_cursor_style`. This method should only be called during the paint
2764    /// phase of element drawing.
2765    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2766        self.invalidator.debug_assert_paint();
2767        self.next_frame.cursor_styles.push(CursorStyleRequest {
2768            hitbox_id: None,
2769            style,
2770        })
2771    }
2772
2773    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2774    /// during the paint phase of element drawing.
2775    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2776        self.invalidator.debug_assert_prepaint();
2777        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2778        self.next_frame
2779            .tooltip_requests
2780            .push(Some(TooltipRequest { id, tooltip }));
2781        id
2782    }
2783
2784    /// Invoke the given function with the given content mask after intersecting it
2785    /// with the current mask. This method should only be called during element drawing.
2786    // This function is called in a highly recursive manner in editor
2787    // prepainting, make sure its inlined to reduce the stack burden
2788    #[inline]
2789    pub fn with_content_mask<R>(
2790        &mut self,
2791        mask: Option<ContentMask<Pixels>>,
2792        f: impl FnOnce(&mut Self) -> R,
2793    ) -> R {
2794        self.invalidator.debug_assert_paint_or_prepaint();
2795        if let Some(mask) = mask {
2796            let mask = mask.intersect(&self.content_mask());
2797            self.content_mask_stack.push(mask);
2798            let result = f(self);
2799            self.content_mask_stack.pop();
2800            result
2801        } else {
2802            f(self)
2803        }
2804    }
2805
2806    /// Updates the global element offset relative to the current offset. This is used to implement
2807    /// scrolling. This method should only be called during the prepaint phase of element drawing.
2808    pub fn with_element_offset<R>(
2809        &mut self,
2810        offset: Point<Pixels>,
2811        f: impl FnOnce(&mut Self) -> R,
2812    ) -> R {
2813        self.invalidator.debug_assert_prepaint();
2814
2815        if offset.is_zero() {
2816            return f(self);
2817        };
2818
2819        let abs_offset = self.element_offset() + offset;
2820        self.with_absolute_element_offset(abs_offset, f)
2821    }
2822
2823    /// Updates the global element offset based on the given offset. This is used to implement
2824    /// drag handles and other manual painting of elements. This method should only be called during
2825    /// the prepaint phase of element drawing.
2826    pub fn with_absolute_element_offset<R>(
2827        &mut self,
2828        offset: Point<Pixels>,
2829        f: impl FnOnce(&mut Self) -> R,
2830    ) -> R {
2831        self.invalidator.debug_assert_prepaint();
2832        self.element_offset_stack.push(offset);
2833        let result = f(self);
2834        self.element_offset_stack.pop();
2835        result
2836    }
2837
2838    pub(crate) fn with_element_opacity<R>(
2839        &mut self,
2840        opacity: Option<f32>,
2841        f: impl FnOnce(&mut Self) -> R,
2842    ) -> R {
2843        self.invalidator.debug_assert_paint_or_prepaint();
2844
2845        let Some(opacity) = opacity else {
2846            return f(self);
2847        };
2848
2849        let previous_opacity = self.element_opacity;
2850        self.element_opacity = previous_opacity * opacity;
2851        let result = f(self);
2852        self.element_opacity = previous_opacity;
2853        result
2854    }
2855
2856    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2857    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2858    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2859    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
2860    /// called during the prepaint phase of element drawing.
2861    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2862        self.invalidator.debug_assert_prepaint();
2863        let index = self.prepaint_index();
2864        let result = f(self);
2865        if result.is_err() {
2866            self.next_frame.hitboxes.truncate(index.hitboxes_index);
2867            self.next_frame
2868                .tooltip_requests
2869                .truncate(index.tooltips_index);
2870            self.next_frame
2871                .deferred_draws
2872                .truncate(index.deferred_draws_index);
2873            self.next_frame
2874                .dispatch_tree
2875                .truncate(index.dispatch_tree_index);
2876            self.next_frame
2877                .accessed_element_states
2878                .truncate(index.accessed_element_states_index);
2879            self.text_system.truncate_layouts(index.line_layout_index);
2880        }
2881        result
2882    }
2883
2884    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
2885    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2886    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
2887    /// that supports this method being called on the elements it contains. This method should only be
2888    /// called during the prepaint phase of element drawing.
2889    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2890        self.invalidator.debug_assert_prepaint();
2891        self.requested_autoscroll = Some(bounds);
2892    }
2893
2894    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
2895    /// described in [`Self::request_autoscroll`].
2896    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2897        self.invalidator.debug_assert_prepaint();
2898        self.requested_autoscroll.take()
2899    }
2900
2901    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2902    /// Your view will be re-drawn once the asset has finished loading.
2903    ///
2904    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2905    /// time.
2906    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2907        let (task, is_first) = cx.fetch_asset::<A>(source);
2908        task.clone().now_or_never().or_else(|| {
2909            if is_first {
2910                let entity_id = self.current_view();
2911                self.spawn(cx, {
2912                    let task = task.clone();
2913                    async move |cx| {
2914                        task.await;
2915
2916                        cx.on_next_frame(move |_, cx| {
2917                            cx.notify(entity_id);
2918                        });
2919                    }
2920                })
2921                .detach();
2922            }
2923
2924            None
2925        })
2926    }
2927
2928    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
2929    /// Your view will not be re-drawn once the asset has finished loading.
2930    ///
2931    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2932    /// time.
2933    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2934        let (task, _) = cx.fetch_asset::<A>(source);
2935        task.now_or_never()
2936    }
2937    /// Obtain the current element offset. This method should only be called during the
2938    /// prepaint phase of element drawing.
2939    pub fn element_offset(&self) -> Point<Pixels> {
2940        self.invalidator.debug_assert_prepaint();
2941        self.element_offset_stack
2942            .last()
2943            .copied()
2944            .unwrap_or_default()
2945    }
2946
2947    /// Obtain the current element opacity. This method should only be called during the
2948    /// prepaint phase of element drawing.
2949    #[inline]
2950    pub(crate) fn element_opacity(&self) -> f32 {
2951        self.invalidator.debug_assert_paint_or_prepaint();
2952        self.element_opacity
2953    }
2954
2955    /// Obtain the current content mask. This method should only be called during element drawing.
2956    pub fn content_mask(&self) -> ContentMask<Pixels> {
2957        self.invalidator.debug_assert_paint_or_prepaint();
2958        self.content_mask_stack
2959            .last()
2960            .cloned()
2961            .unwrap_or_else(|| ContentMask {
2962                bounds: Bounds {
2963                    origin: Point::default(),
2964                    size: self.viewport_size,
2965                },
2966            })
2967    }
2968
2969    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2970    /// This can be used within a custom element to distinguish multiple sets of child elements.
2971    pub fn with_element_namespace<R>(
2972        &mut self,
2973        element_id: impl Into<ElementId>,
2974        f: impl FnOnce(&mut Self) -> R,
2975    ) -> R {
2976        self.element_id_stack.push(element_id.into());
2977        let result = f(self);
2978        self.element_id_stack.pop();
2979        result
2980    }
2981
2982    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
2983    pub fn use_keyed_state<S: 'static>(
2984        &mut self,
2985        key: impl Into<ElementId>,
2986        cx: &mut App,
2987        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2988    ) -> Entity<S> {
2989        let current_view = self.current_view();
2990        self.with_global_id(key.into(), |global_id, window| {
2991            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
2992                if let Some(state) = state {
2993                    (state.clone(), state)
2994                } else {
2995                    let new_state = cx.new(|cx| init(window, cx));
2996                    cx.observe(&new_state, move |_, cx| {
2997                        cx.notify(current_view);
2998                    })
2999                    .detach();
3000                    (new_state.clone(), new_state)
3001                }
3002            })
3003        })
3004    }
3005
3006    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
3007    ///
3008    /// NOTE: This method uses the location of the caller to generate an ID for this state.
3009    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
3010    ///       you can provide a custom ElementID using the `use_keyed_state` method.
3011    #[track_caller]
3012    pub fn use_state<S: 'static>(
3013        &mut self,
3014        cx: &mut App,
3015        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3016    ) -> Entity<S> {
3017        self.use_keyed_state(
3018            ElementId::CodeLocation(*core::panic::Location::caller()),
3019            cx,
3020            init,
3021        )
3022    }
3023
3024    /// Updates or initializes state for an element with the given id that lives across multiple
3025    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
3026    /// to the given closure. The state returned by the closure will be stored so it can be referenced
3027    /// when drawing the next frame. This method should only be called as part of element drawing.
3028    pub fn with_element_state<S, R>(
3029        &mut self,
3030        global_id: &GlobalElementId,
3031        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3032    ) -> R
3033    where
3034        S: 'static,
3035    {
3036        self.invalidator.debug_assert_paint_or_prepaint();
3037
3038        let key = (global_id.clone(), TypeId::of::<S>());
3039        self.next_frame.accessed_element_states.push(key.clone());
3040
3041        if let Some(any) = self
3042            .next_frame
3043            .element_states
3044            .remove(&key)
3045            .or_else(|| self.rendered_frame.element_states.remove(&key))
3046        {
3047            let ElementStateBox {
3048                inner,
3049                #[cfg(debug_assertions)]
3050                type_name,
3051            } = any;
3052            // Using the extra inner option to avoid needing to reallocate a new box.
3053            let mut state_box = inner
3054                .downcast::<Option<S>>()
3055                .map_err(|_| {
3056                    #[cfg(debug_assertions)]
3057                    {
3058                        anyhow::anyhow!(
3059                            "invalid element state type for id, requested {:?}, actual: {:?}",
3060                            std::any::type_name::<S>(),
3061                            type_name
3062                        )
3063                    }
3064
3065                    #[cfg(not(debug_assertions))]
3066                    {
3067                        anyhow::anyhow!(
3068                            "invalid element state type for id, requested {:?}",
3069                            std::any::type_name::<S>(),
3070                        )
3071                    }
3072                })
3073                .unwrap();
3074
3075            let state = state_box.take().expect(
3076                "reentrant call to with_element_state for the same state type and element id",
3077            );
3078            let (result, state) = f(Some(state), self);
3079            state_box.replace(state);
3080            self.next_frame.element_states.insert(
3081                key,
3082                ElementStateBox {
3083                    inner: state_box,
3084                    #[cfg(debug_assertions)]
3085                    type_name,
3086                },
3087            );
3088            result
3089        } else {
3090            let (result, state) = f(None, self);
3091            self.next_frame.element_states.insert(
3092                key,
3093                ElementStateBox {
3094                    inner: Box::new(Some(state)),
3095                    #[cfg(debug_assertions)]
3096                    type_name: std::any::type_name::<S>(),
3097                },
3098            );
3099            result
3100        }
3101    }
3102
3103    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
3104    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
3105    /// when the element is guaranteed to have an id.
3106    ///
3107    /// The first option means 'no ID provided'
3108    /// The second option means 'not yet initialized'
3109    pub fn with_optional_element_state<S, R>(
3110        &mut self,
3111        global_id: Option<&GlobalElementId>,
3112        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3113    ) -> R
3114    where
3115        S: 'static,
3116    {
3117        self.invalidator.debug_assert_paint_or_prepaint();
3118
3119        if let Some(global_id) = global_id {
3120            self.with_element_state(global_id, |state, cx| {
3121                let (result, state) = f(Some(state), cx);
3122                let state =
3123                    state.expect("you must return some state when you pass some element id");
3124                (result, state)
3125            })
3126        } else {
3127            let (result, state) = f(None, self);
3128            debug_assert!(
3129                state.is_none(),
3130                "you must not return an element state when passing None for the global id"
3131            );
3132            result
3133        }
3134    }
3135
3136    /// Executes the given closure within the context of a tab group.
3137    #[inline]
3138    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3139        if let Some(index) = index {
3140            self.next_frame.tab_stops.begin_group(index);
3141            let result = f(self);
3142            self.next_frame.tab_stops.end_group();
3143            result
3144        } else {
3145            f(self)
3146        }
3147    }
3148
3149    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
3150    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3151    /// with higher values being drawn on top.
3152    ///
3153    /// When `content_mask` is provided, the deferred element will be clipped to that region during
3154    /// both prepaint and paint. When `None`, no additional clipping is applied.
3155    ///
3156    /// This method should only be called as part of the prepaint phase of element drawing.
3157    pub fn defer_draw(
3158        &mut self,
3159        element: AnyElement,
3160        absolute_offset: Point<Pixels>,
3161        priority: usize,
3162        content_mask: Option<ContentMask<Pixels>>,
3163    ) {
3164        self.invalidator.debug_assert_prepaint();
3165        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3166        self.next_frame.deferred_draws.push(DeferredDraw {
3167            current_view: self.current_view(),
3168            parent_node,
3169            element_id_stack: self.element_id_stack.clone(),
3170            text_style_stack: self.text_style_stack.clone(),
3171            content_mask,
3172            rem_size: self.rem_size(),
3173            priority,
3174            element: Some(element),
3175            absolute_offset,
3176            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3177            paint_range: PaintIndex::default()..PaintIndex::default(),
3178        });
3179    }
3180
3181    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3182    /// of geometry that are non-overlapping and have the same draw order. This is typically used
3183    /// for performance reasons.
3184    ///
3185    /// This method should only be called as part of the paint phase of element drawing.
3186    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3187        self.invalidator.debug_assert_paint();
3188
3189        let scale_factor = self.scale_factor();
3190        let content_mask = self.content_mask();
3191        let clipped_bounds = bounds.intersect(&content_mask.bounds);
3192        if !clipped_bounds.is_empty() {
3193            self.next_frame
3194                .scene
3195                .push_layer(clipped_bounds.scale(scale_factor));
3196        }
3197
3198        let result = f(self);
3199
3200        if !clipped_bounds.is_empty() {
3201            self.next_frame.scene.pop_layer();
3202        }
3203
3204        result
3205    }
3206
3207    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
3208    ///
3209    /// This method should only be called as part of the paint phase of element drawing.
3210    pub fn paint_shadows(
3211        &mut self,
3212        bounds: Bounds<Pixels>,
3213        corner_radii: Corners<Pixels>,
3214        shadows: &[BoxShadow],
3215    ) {
3216        self.invalidator.debug_assert_paint();
3217
3218        let scale_factor = self.scale_factor();
3219        let content_mask = self.content_mask();
3220        let opacity = self.element_opacity();
3221        for shadow in shadows {
3222            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3223            self.next_frame.scene.insert_primitive(Shadow {
3224                order: 0,
3225                blur_radius: shadow.blur_radius.scale(scale_factor),
3226                bounds: shadow_bounds.scale(scale_factor),
3227                content_mask: content_mask.scale(scale_factor),
3228                corner_radii: corner_radii.scale(scale_factor),
3229                color: shadow.color.opacity(opacity),
3230            });
3231        }
3232    }
3233
3234    /// Paint one or more quads into the scene for the next frame at the current stacking context.
3235    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3236    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3237    ///
3238    /// This method should only be called as part of the paint phase of element drawing.
3239    ///
3240    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3241    /// where the circular arcs meet. This will not display well when combined with dashed borders.
3242    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3243    pub fn paint_quad(&mut self, quad: PaintQuad) {
3244        self.invalidator.debug_assert_paint();
3245
3246        let scale_factor = self.scale_factor();
3247        let content_mask = self.content_mask();
3248        let opacity = self.element_opacity();
3249        self.next_frame.scene.insert_primitive(Quad {
3250            order: 0,
3251            bounds: quad.bounds.scale(scale_factor),
3252            content_mask: content_mask.scale(scale_factor),
3253            background: quad.background.opacity(opacity),
3254            border_color: quad.border_color.opacity(opacity),
3255            corner_radii: quad.corner_radii.scale(scale_factor),
3256            border_widths: quad.border_widths.scale(scale_factor),
3257            border_style: quad.border_style,
3258        });
3259    }
3260
3261    /// Paint the given `Path` into the scene for the next frame at the current z-index.
3262    ///
3263    /// This method should only be called as part of the paint phase of element drawing.
3264    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3265        self.invalidator.debug_assert_paint();
3266
3267        let scale_factor = self.scale_factor();
3268        let content_mask = self.content_mask();
3269        let opacity = self.element_opacity();
3270        path.content_mask = content_mask;
3271        let color: Background = color.into();
3272        path.color = color.opacity(opacity);
3273        self.next_frame
3274            .scene
3275            .insert_primitive(path.scale(scale_factor));
3276    }
3277
3278    /// Paint an underline into the scene for the next frame at the current z-index.
3279    ///
3280    /// This method should only be called as part of the paint phase of element drawing.
3281    pub fn paint_underline(
3282        &mut self,
3283        origin: Point<Pixels>,
3284        width: Pixels,
3285        style: &UnderlineStyle,
3286    ) {
3287        self.invalidator.debug_assert_paint();
3288
3289        let scale_factor = self.scale_factor();
3290        let height = if style.wavy {
3291            style.thickness * 3.
3292        } else {
3293            style.thickness
3294        };
3295        let bounds = Bounds {
3296            origin,
3297            size: size(width, height),
3298        };
3299        let content_mask = self.content_mask();
3300        let element_opacity = self.element_opacity();
3301
3302        self.next_frame.scene.insert_primitive(Underline {
3303            order: 0,
3304            pad: 0,
3305            bounds: bounds.scale(scale_factor),
3306            content_mask: content_mask.scale(scale_factor),
3307            color: style.color.unwrap_or_default().opacity(element_opacity),
3308            thickness: style.thickness.scale(scale_factor),
3309            wavy: if style.wavy { 1 } else { 0 },
3310        });
3311    }
3312
3313    /// Paint a strikethrough into the scene for the next frame at the current z-index.
3314    ///
3315    /// This method should only be called as part of the paint phase of element drawing.
3316    pub fn paint_strikethrough(
3317        &mut self,
3318        origin: Point<Pixels>,
3319        width: Pixels,
3320        style: &StrikethroughStyle,
3321    ) {
3322        self.invalidator.debug_assert_paint();
3323
3324        let scale_factor = self.scale_factor();
3325        let height = style.thickness;
3326        let bounds = Bounds {
3327            origin,
3328            size: size(width, height),
3329        };
3330        let content_mask = self.content_mask();
3331        let opacity = self.element_opacity();
3332
3333        self.next_frame.scene.insert_primitive(Underline {
3334            order: 0,
3335            pad: 0,
3336            bounds: bounds.scale(scale_factor),
3337            content_mask: content_mask.scale(scale_factor),
3338            thickness: style.thickness.scale(scale_factor),
3339            color: style.color.unwrap_or_default().opacity(opacity),
3340            wavy: 0,
3341        });
3342    }
3343
3344    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3345    ///
3346    /// The y component of the origin is the baseline of the glyph.
3347    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3348    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3349    /// This method is only useful if you need to paint a single glyph that has already been shaped.
3350    ///
3351    /// This method should only be called as part of the paint phase of element drawing.
3352    pub fn paint_glyph(
3353        &mut self,
3354        origin: Point<Pixels>,
3355        font_id: FontId,
3356        glyph_id: GlyphId,
3357        font_size: Pixels,
3358        color: Hsla,
3359    ) -> Result<()> {
3360        self.invalidator.debug_assert_paint();
3361
3362        let element_opacity = self.element_opacity();
3363        let scale_factor = self.scale_factor();
3364        let glyph_origin = origin.scale(scale_factor);
3365
3366        let subpixel_variant = Point {
3367            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS_X as f32).floor() as u8,
3368            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS_Y as f32).floor() as u8,
3369        };
3370        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3371        let params = RenderGlyphParams {
3372            font_id,
3373            glyph_id,
3374            font_size,
3375            subpixel_variant,
3376            scale_factor,
3377            is_emoji: false,
3378            subpixel_rendering,
3379        };
3380
3381        let raster_bounds = self.text_system().raster_bounds(&params)?;
3382        if !raster_bounds.is_zero() {
3383            let tile = self
3384                .sprite_atlas
3385                .get_or_insert_with(&params.clone().into(), &mut || {
3386                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3387                    Ok(Some((size, Cow::Owned(bytes))))
3388                })?
3389                .expect("Callback above only errors or returns Some");
3390            let bounds = Bounds {
3391                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3392                size: tile.bounds.size.map(Into::into),
3393            };
3394            let content_mask = self.content_mask().scale(scale_factor);
3395
3396            if subpixel_rendering {
3397                self.next_frame.scene.insert_primitive(SubpixelSprite {
3398                    order: 0,
3399                    pad: 0,
3400                    bounds,
3401                    content_mask,
3402                    color: color.opacity(element_opacity),
3403                    tile,
3404                    transformation: TransformationMatrix::unit(),
3405                });
3406            } else {
3407                self.next_frame.scene.insert_primitive(MonochromeSprite {
3408                    order: 0,
3409                    pad: 0,
3410                    bounds,
3411                    content_mask,
3412                    color: color.opacity(element_opacity),
3413                    tile,
3414                    transformation: TransformationMatrix::unit(),
3415                });
3416            }
3417        }
3418        Ok(())
3419    }
3420
3421    /// Paints a monochrome glyph with pre-computed raster bounds.
3422    ///
3423    /// This is faster than `paint_glyph` because it skips the per-glyph cache lookup.
3424    /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
3425    pub fn paint_glyph_with_raster_bounds(
3426        &mut self,
3427        origin: Point<Pixels>,
3428        _font_id: FontId,
3429        _glyph_id: GlyphId,
3430        _font_size: Pixels,
3431        color: Hsla,
3432        raster_bounds: Bounds<DevicePixels>,
3433        params: &RenderGlyphParams,
3434    ) -> Result<()> {
3435        self.invalidator.debug_assert_paint();
3436
3437        let element_opacity = self.element_opacity();
3438        let scale_factor = self.scale_factor();
3439        let glyph_origin = origin.scale(scale_factor);
3440
3441        if !raster_bounds.is_zero() {
3442            let tile = self
3443                .sprite_atlas
3444                .get_or_insert_with(&params.clone().into(), &mut || {
3445                    let (size, bytes) = self.text_system().rasterize_glyph(params)?;
3446                    Ok(Some((size, Cow::Owned(bytes))))
3447                })?
3448                .expect("Callback above only errors or returns Some");
3449            let bounds = Bounds {
3450                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3451                size: tile.bounds.size.map(Into::into),
3452            };
3453            let content_mask = self.content_mask().scale(scale_factor);
3454            self.next_frame.scene.insert_primitive(MonochromeSprite {
3455                order: 0,
3456                pad: 0,
3457                bounds,
3458                content_mask,
3459                color: color.opacity(element_opacity),
3460                tile,
3461                transformation: TransformationMatrix::unit(),
3462            });
3463        }
3464        Ok(())
3465    }
3466
3467    /// Paints an emoji glyph with pre-computed raster bounds.
3468    ///
3469    /// This is faster than `paint_emoji` because it skips the per-glyph cache lookup.
3470    /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
3471    pub fn paint_emoji_with_raster_bounds(
3472        &mut self,
3473        origin: Point<Pixels>,
3474        _font_id: FontId,
3475        _glyph_id: GlyphId,
3476        _font_size: Pixels,
3477        raster_bounds: Bounds<DevicePixels>,
3478        params: &RenderGlyphParams,
3479    ) -> Result<()> {
3480        self.invalidator.debug_assert_paint();
3481
3482        let scale_factor = self.scale_factor();
3483        let glyph_origin = origin.scale(scale_factor);
3484
3485        if !raster_bounds.is_zero() {
3486            let tile = self
3487                .sprite_atlas
3488                .get_or_insert_with(&params.clone().into(), &mut || {
3489                    let (size, bytes) = self.text_system().rasterize_glyph(params)?;
3490                    Ok(Some((size, Cow::Owned(bytes))))
3491                })?
3492                .expect("Callback above only errors or returns Some");
3493
3494            let bounds = Bounds {
3495                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3496                size: tile.bounds.size.map(Into::into),
3497            };
3498            let content_mask = self.content_mask().scale(scale_factor);
3499            let opacity = self.element_opacity();
3500
3501            self.next_frame.scene.insert_primitive(PolychromeSprite {
3502                order: 0,
3503                pad: 0,
3504                grayscale: false,
3505                bounds,
3506                corner_radii: Default::default(),
3507                content_mask,
3508                tile,
3509                opacity,
3510            });
3511        }
3512        Ok(())
3513    }
3514
3515    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3516        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3517            return false;
3518        }
3519
3520        if !self.platform_window.is_subpixel_rendering_supported() {
3521            return false;
3522        }
3523
3524        let mode = match self.text_rendering_mode.get() {
3525            TextRenderingMode::PlatformDefault => self
3526                .text_system()
3527                .recommended_rendering_mode(font_id, font_size),
3528            mode => mode,
3529        };
3530
3531        mode == TextRenderingMode::Subpixel
3532    }
3533
3534    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3535    ///
3536    /// The y component of the origin is the baseline of the glyph.
3537    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3538    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3539    /// This method is only useful if you need to paint a single emoji that has already been shaped.
3540    ///
3541    /// This method should only be called as part of the paint phase of element drawing.
3542    pub fn paint_emoji(
3543        &mut self,
3544        origin: Point<Pixels>,
3545        font_id: FontId,
3546        glyph_id: GlyphId,
3547        font_size: Pixels,
3548    ) -> Result<()> {
3549        self.invalidator.debug_assert_paint();
3550
3551        let scale_factor = self.scale_factor();
3552        let glyph_origin = origin.scale(scale_factor);
3553        let params = RenderGlyphParams {
3554            font_id,
3555            glyph_id,
3556            font_size,
3557            // We don't render emojis with subpixel variants.
3558            subpixel_variant: Default::default(),
3559            scale_factor,
3560            is_emoji: true,
3561            subpixel_rendering: false,
3562        };
3563
3564        let raster_bounds = self.text_system().raster_bounds(&params)?;
3565        if !raster_bounds.is_zero() {
3566            let tile = self
3567                .sprite_atlas
3568                .get_or_insert_with(&params.clone().into(), &mut || {
3569                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3570                    Ok(Some((size, Cow::Owned(bytes))))
3571                })?
3572                .expect("Callback above only errors or returns Some");
3573
3574            let bounds = Bounds {
3575                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3576                size: tile.bounds.size.map(Into::into),
3577            };
3578            let content_mask = self.content_mask().scale(scale_factor);
3579            let opacity = self.element_opacity();
3580
3581            self.next_frame.scene.insert_primitive(PolychromeSprite {
3582                order: 0,
3583                pad: 0,
3584                grayscale: false,
3585                bounds,
3586                corner_radii: Default::default(),
3587                content_mask,
3588                tile,
3589                opacity,
3590            });
3591        }
3592        Ok(())
3593    }
3594
3595    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3596    ///
3597    /// This method should only be called as part of the paint phase of element drawing.
3598    pub fn paint_svg(
3599        &mut self,
3600        bounds: Bounds<Pixels>,
3601        path: SharedString,
3602        mut data: Option<&[u8]>,
3603        transformation: TransformationMatrix,
3604        color: Hsla,
3605        cx: &App,
3606    ) -> Result<()> {
3607        self.invalidator.debug_assert_paint();
3608
3609        let element_opacity = self.element_opacity();
3610        let scale_factor = self.scale_factor();
3611
3612        let bounds = bounds.scale(scale_factor);
3613        let params = RenderSvgParams {
3614            path,
3615            size: bounds.size.map(|pixels| {
3616                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3617            }),
3618        };
3619
3620        let Some(tile) =
3621            self.sprite_atlas
3622                .get_or_insert_with(&params.clone().into(), &mut || {
3623                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
3624                    else {
3625                        return Ok(None);
3626                    };
3627                    Ok(Some((size, Cow::Owned(bytes))))
3628                })?
3629        else {
3630            return Ok(());
3631        };
3632        let content_mask = self.content_mask().scale(scale_factor);
3633        let svg_bounds = Bounds {
3634            origin: bounds.center()
3635                - Point::new(
3636                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3637                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3638                ),
3639            size: tile
3640                .bounds
3641                .size
3642                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3643        };
3644
3645        self.next_frame.scene.insert_primitive(MonochromeSprite {
3646            order: 0,
3647            pad: 0,
3648            bounds: svg_bounds
3649                .map_origin(|origin| origin.round())
3650                .map_size(|size| size.ceil()),
3651            content_mask,
3652            color: color.opacity(element_opacity),
3653            tile,
3654            transformation,
3655        });
3656
3657        Ok(())
3658    }
3659
3660    /// Paint an image into the scene for the next frame at the current z-index.
3661    /// This method will panic if the frame_index is not valid
3662    ///
3663    /// This method should only be called as part of the paint phase of element drawing.
3664    pub fn paint_image(
3665        &mut self,
3666        bounds: Bounds<Pixels>,
3667        corner_radii: Corners<Pixels>,
3668        data: Arc<RenderImage>,
3669        frame_index: usize,
3670        grayscale: bool,
3671    ) -> Result<()> {
3672        self.invalidator.debug_assert_paint();
3673
3674        let scale_factor = self.scale_factor();
3675        let bounds = bounds.scale(scale_factor);
3676        let params = RenderImageParams {
3677            image_id: data.id,
3678            frame_index,
3679        };
3680
3681        let tile = self
3682            .sprite_atlas
3683            .get_or_insert_with(&params.into(), &mut || {
3684                Ok(Some((
3685                    data.size(frame_index),
3686                    Cow::Borrowed(
3687                        data.as_bytes(frame_index)
3688                            .expect("It's the caller's job to pass a valid frame index"),
3689                    ),
3690                )))
3691            })?
3692            .expect("Callback above only returns Some");
3693        let content_mask = self.content_mask().scale(scale_factor);
3694        let corner_radii = corner_radii.scale(scale_factor);
3695        let opacity = self.element_opacity();
3696
3697        self.next_frame.scene.insert_primitive(PolychromeSprite {
3698            order: 0,
3699            pad: 0,
3700            grayscale,
3701            bounds: bounds
3702                .map_origin(|origin| origin.floor())
3703                .map_size(|size| size.ceil()),
3704            content_mask,
3705            corner_radii,
3706            tile,
3707            opacity,
3708        });
3709        Ok(())
3710    }
3711
3712    /// Paint a surface into the scene for the next frame at the current z-index.
3713    ///
3714    /// This method should only be called as part of the paint phase of element drawing.
3715    #[cfg(target_os = "macos")]
3716    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3717        use crate::PaintSurface;
3718
3719        self.invalidator.debug_assert_paint();
3720
3721        let scale_factor = self.scale_factor();
3722        let bounds = bounds.scale(scale_factor);
3723        let content_mask = self.content_mask().scale(scale_factor);
3724        self.next_frame.scene.insert_primitive(PaintSurface {
3725            order: 0,
3726            bounds,
3727            content_mask,
3728            image_buffer,
3729        });
3730    }
3731
3732    /// Removes an image from the sprite atlas.
3733    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3734        for frame_index in 0..data.frame_count() {
3735            let params = RenderImageParams {
3736                image_id: data.id,
3737                frame_index,
3738            };
3739
3740            self.sprite_atlas.remove(&params.clone().into());
3741        }
3742
3743        Ok(())
3744    }
3745
3746    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3747    /// layout is being requested, along with the layout ids of any children. This method is called during
3748    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3749    ///
3750    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3751    #[must_use]
3752    pub fn request_layout(
3753        &mut self,
3754        style: Style,
3755        children: impl IntoIterator<Item = LayoutId>,
3756        cx: &mut App,
3757    ) -> LayoutId {
3758        self.invalidator.debug_assert_prepaint();
3759
3760        cx.layout_id_buffer.clear();
3761        cx.layout_id_buffer.extend(children);
3762        let rem_size = self.rem_size();
3763        let scale_factor = self.scale_factor();
3764
3765        self.layout_engine.as_mut().unwrap().request_layout(
3766            style,
3767            rem_size,
3768            scale_factor,
3769            &cx.layout_id_buffer,
3770        )
3771    }
3772
3773    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3774    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3775    /// determine the element's size. One place this is used internally is when measuring text.
3776    ///
3777    /// The given closure is invoked at layout time with the known dimensions and available space and
3778    /// returns a `Size`.
3779    ///
3780    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3781    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3782    where
3783        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3784            + 'static,
3785    {
3786        self.invalidator.debug_assert_prepaint();
3787
3788        let rem_size = self.rem_size();
3789        let scale_factor = self.scale_factor();
3790        self.layout_engine
3791            .as_mut()
3792            .unwrap()
3793            .request_measured_layout(style, rem_size, scale_factor, measure)
3794    }
3795
3796    /// Compute the layout for the given id within the given available space.
3797    /// This method is called for its side effect, typically by the framework prior to painting.
3798    /// After calling it, you can request the bounds of the given layout node id or any descendant.
3799    ///
3800    /// This method should only be called as part of the prepaint phase of element drawing.
3801    pub fn compute_layout(
3802        &mut self,
3803        layout_id: LayoutId,
3804        available_space: Size<AvailableSpace>,
3805        cx: &mut App,
3806    ) {
3807        self.invalidator.debug_assert_prepaint();
3808
3809        let mut layout_engine = self.layout_engine.take().unwrap();
3810        layout_engine.compute_layout(layout_id, available_space, self, cx);
3811        self.layout_engine = Some(layout_engine);
3812    }
3813
3814    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3815    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3816    ///
3817    /// This method should only be called as part of element drawing.
3818    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3819        self.invalidator.debug_assert_prepaint();
3820
3821        let scale_factor = self.scale_factor();
3822        let mut bounds = self
3823            .layout_engine
3824            .as_mut()
3825            .unwrap()
3826            .layout_bounds(layout_id, scale_factor)
3827            .map(Into::into);
3828        bounds.origin += self.element_offset();
3829        bounds
3830    }
3831
3832    /// This method should be called during `prepaint`. You can use
3833    /// the returned [Hitbox] during `paint` or in an event handler
3834    /// to determine whether the inserted hitbox was the topmost.
3835    ///
3836    /// This method should only be called as part of the prepaint phase of element drawing.
3837    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3838        self.invalidator.debug_assert_prepaint();
3839
3840        let content_mask = self.content_mask();
3841        let mut id = self.next_hitbox_id;
3842        self.next_hitbox_id = self.next_hitbox_id.next();
3843        let hitbox = Hitbox {
3844            id,
3845            bounds,
3846            content_mask,
3847            behavior,
3848        };
3849        self.next_frame.hitboxes.push(hitbox.clone());
3850        hitbox
3851    }
3852
3853    /// Set a hitbox which will act as a control area of the platform window.
3854    ///
3855    /// This method should only be called as part of the paint phase of element drawing.
3856    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3857        self.invalidator.debug_assert_paint();
3858        self.next_frame.window_control_hitboxes.push((area, hitbox));
3859    }
3860
3861    /// Sets the key context for the current element. This context will be used to translate
3862    /// keybindings into actions.
3863    ///
3864    /// This method should only be called as part of the paint phase of element drawing.
3865    pub fn set_key_context(&mut self, context: KeyContext) {
3866        self.invalidator.debug_assert_paint();
3867        self.next_frame.dispatch_tree.set_key_context(context);
3868    }
3869
3870    /// Sets the focus handle for the current element. This handle will be used to manage focus state
3871    /// and keyboard event dispatch for the element.
3872    ///
3873    /// This method should only be called as part of the prepaint phase of element drawing.
3874    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3875        self.invalidator.debug_assert_prepaint();
3876        if focus_handle.is_focused(self) {
3877            self.next_frame.focus = Some(focus_handle.id);
3878        }
3879        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3880    }
3881
3882    /// Sets the view id for the current element, which will be used to manage view caching.
3883    ///
3884    /// This method should only be called as part of element prepaint. We plan on removing this
3885    /// method eventually when we solve some issues that require us to construct editor elements
3886    /// directly instead of always using editors via views.
3887    pub fn set_view_id(&mut self, view_id: EntityId) {
3888        self.invalidator.debug_assert_prepaint();
3889        self.next_frame.dispatch_tree.set_view_id(view_id);
3890    }
3891
3892    /// Get the entity ID for the currently rendering view
3893    pub fn current_view(&self) -> EntityId {
3894        self.invalidator.debug_assert_paint_or_prepaint();
3895        self.rendered_entity_stack.last().copied().unwrap()
3896    }
3897
3898    #[inline]
3899    pub(crate) fn with_rendered_view<R>(
3900        &mut self,
3901        id: EntityId,
3902        f: impl FnOnce(&mut Self) -> R,
3903    ) -> R {
3904        self.rendered_entity_stack.push(id);
3905        let result = f(self);
3906        self.rendered_entity_stack.pop();
3907        result
3908    }
3909
3910    /// Executes the provided function with the specified image cache.
3911    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3912    where
3913        F: FnOnce(&mut Self) -> R,
3914    {
3915        if let Some(image_cache) = image_cache {
3916            self.image_cache_stack.push(image_cache);
3917            let result = f(self);
3918            self.image_cache_stack.pop();
3919            result
3920        } else {
3921            f(self)
3922        }
3923    }
3924
3925    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
3926    /// platform to receive textual input with proper integration with concerns such
3927    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
3928    /// rendered.
3929    ///
3930    /// This method should only be called as part of the paint phase of element drawing.
3931    ///
3932    /// [element_input_handler]: crate::ElementInputHandler
3933    pub fn handle_input(
3934        &mut self,
3935        focus_handle: &FocusHandle,
3936        input_handler: impl InputHandler,
3937        cx: &App,
3938    ) {
3939        self.invalidator.debug_assert_paint();
3940
3941        if focus_handle.is_focused(self) {
3942            let cx = self.to_async(cx);
3943            self.next_frame
3944                .input_handlers
3945                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3946        }
3947    }
3948
3949    /// Register a mouse event listener on the window for the next frame. The type of event
3950    /// is determined by the first parameter of the given listener. When the next frame is rendered
3951    /// the listener will be cleared.
3952    ///
3953    /// This method should only be called as part of the paint phase of element drawing.
3954    pub fn on_mouse_event<Event: MouseEvent>(
3955        &mut self,
3956        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3957    ) {
3958        self.invalidator.debug_assert_paint();
3959
3960        self.next_frame.mouse_listeners.push(Some(Box::new(
3961            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3962                if let Some(event) = event.downcast_ref() {
3963                    listener(event, phase, window, cx)
3964                }
3965            },
3966        )));
3967    }
3968
3969    /// Register a key event listener on this node for the next frame. The type of event
3970    /// is determined by the first parameter of the given listener. When the next frame is rendered
3971    /// the listener will be cleared.
3972    ///
3973    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3974    /// a specific need to register a listener yourself.
3975    ///
3976    /// This method should only be called as part of the paint phase of element drawing.
3977    pub fn on_key_event<Event: KeyEvent>(
3978        &mut self,
3979        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3980    ) {
3981        self.invalidator.debug_assert_paint();
3982
3983        self.next_frame.dispatch_tree.on_key_event(Rc::new(
3984            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
3985                if let Some(event) = event.downcast_ref::<Event>() {
3986                    listener(event, phase, window, cx)
3987                }
3988            },
3989        ));
3990    }
3991
3992    /// Register a modifiers changed event listener on the window for the next frame.
3993    ///
3994    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3995    /// a specific need to register a global listener.
3996    ///
3997    /// This method should only be called as part of the paint phase of element drawing.
3998    pub fn on_modifiers_changed(
3999        &mut self,
4000        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4001    ) {
4002        self.invalidator.debug_assert_paint();
4003
4004        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4005            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4006                listener(event, window, cx)
4007            },
4008        ));
4009    }
4010
4011    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4012    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4013    /// Returns a subscription and persists until the subscription is dropped.
4014    pub fn on_focus_in(
4015        &mut self,
4016        handle: &FocusHandle,
4017        cx: &mut App,
4018        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4019    ) -> Subscription {
4020        let focus_id = handle.id;
4021        let (subscription, activate) =
4022            self.new_focus_listener(Box::new(move |event, window, cx| {
4023                if event.is_focus_in(focus_id) {
4024                    listener(window, cx);
4025                }
4026                true
4027            }));
4028        cx.defer(move |_| activate());
4029        subscription
4030    }
4031
4032    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4033    /// Returns a subscription and persists until the subscription is dropped.
4034    pub fn on_focus_out(
4035        &mut self,
4036        handle: &FocusHandle,
4037        cx: &mut App,
4038        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4039    ) -> Subscription {
4040        let focus_id = handle.id;
4041        let (subscription, activate) =
4042            self.new_focus_listener(Box::new(move |event, window, cx| {
4043                if let Some(blurred_id) = event.previous_focus_path.last().copied()
4044                    && event.is_focus_out(focus_id)
4045                {
4046                    let event = FocusOutEvent {
4047                        blurred: WeakFocusHandle {
4048                            id: blurred_id,
4049                            handles: Arc::downgrade(&cx.focus_handles),
4050                        },
4051                    };
4052                    listener(event, window, cx)
4053                }
4054                true
4055            }));
4056        cx.defer(move |_| activate());
4057        subscription
4058    }
4059
4060    fn reset_cursor_style(&self, cx: &mut App) {
4061        // Set the cursor only if we're the active window.
4062        if self.is_window_hovered() {
4063            let style = self
4064                .rendered_frame
4065                .cursor_style(self)
4066                .unwrap_or(CursorStyle::Arrow);
4067            cx.platform.set_cursor_style(style);
4068        }
4069    }
4070
4071    /// Dispatch a given keystroke as though the user had typed it.
4072    /// You can create a keystroke with Keystroke::parse("").
4073    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4074        let keystroke = keystroke.with_simulated_ime();
4075        let result = self.dispatch_event(
4076            PlatformInput::KeyDown(KeyDownEvent {
4077                keystroke: keystroke.clone(),
4078                is_held: false,
4079                prefer_character_input: false,
4080            }),
4081            cx,
4082        );
4083        if !result.propagate {
4084            return true;
4085        }
4086
4087        if let Some(input) = keystroke.key_char
4088            && let Some(mut input_handler) = self.platform_window.take_input_handler()
4089        {
4090            input_handler.dispatch_input(&input, self, cx);
4091            self.platform_window.set_input_handler(input_handler);
4092            return true;
4093        }
4094
4095        false
4096    }
4097
4098    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
4099    /// binding for the action (last binding added to the keymap).
4100    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4101        self.highest_precedence_binding_for_action(action)
4102            .map(|binding| {
4103                binding
4104                    .keystrokes()
4105                    .iter()
4106                    .map(ToString::to_string)
4107                    .collect::<Vec<_>>()
4108                    .join(" ")
4109            })
4110            .unwrap_or_else(|| action.name().to_string())
4111    }
4112
4113    /// Dispatch a mouse or keyboard event on the window.
4114    #[profiling::function]
4115    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4116        // Track input modality for focus-visible styling and hover suppression.
4117        // Hover is suppressed during keyboard modality so that keyboard navigation
4118        // doesn't show hover highlights on the item under the mouse cursor.
4119        let old_modality = self.last_input_modality;
4120        self.last_input_modality = match &event {
4121            PlatformInput::KeyDown(_) => InputModality::Keyboard,
4122            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4123            _ => self.last_input_modality,
4124        };
4125        if self.last_input_modality != old_modality {
4126            self.refresh();
4127        }
4128
4129        // Handlers may set this to false by calling `stop_propagation`.
4130        cx.propagate_event = true;
4131        // Handlers may set this to true by calling `prevent_default`.
4132        self.default_prevented = false;
4133
4134        let event = match event {
4135            // Track the mouse position with our own state, since accessing the platform
4136            // API for the mouse position can only occur on the main thread.
4137            PlatformInput::MouseMove(mouse_move) => {
4138                self.mouse_position = mouse_move.position;
4139                self.modifiers = mouse_move.modifiers;
4140                PlatformInput::MouseMove(mouse_move)
4141            }
4142            PlatformInput::MouseDown(mouse_down) => {
4143                self.mouse_position = mouse_down.position;
4144                self.modifiers = mouse_down.modifiers;
4145                PlatformInput::MouseDown(mouse_down)
4146            }
4147            PlatformInput::MouseUp(mouse_up) => {
4148                self.mouse_position = mouse_up.position;
4149                self.modifiers = mouse_up.modifiers;
4150                PlatformInput::MouseUp(mouse_up)
4151            }
4152            PlatformInput::MousePressure(mouse_pressure) => {
4153                PlatformInput::MousePressure(mouse_pressure)
4154            }
4155            PlatformInput::MouseExited(mouse_exited) => {
4156                self.modifiers = mouse_exited.modifiers;
4157                PlatformInput::MouseExited(mouse_exited)
4158            }
4159            PlatformInput::ModifiersChanged(modifiers_changed) => {
4160                self.modifiers = modifiers_changed.modifiers;
4161                self.capslock = modifiers_changed.capslock;
4162                PlatformInput::ModifiersChanged(modifiers_changed)
4163            }
4164            PlatformInput::ScrollWheel(scroll_wheel) => {
4165                self.mouse_position = scroll_wheel.position;
4166                self.modifiers = scroll_wheel.modifiers;
4167                PlatformInput::ScrollWheel(scroll_wheel)
4168            }
4169            PlatformInput::Pinch(pinch) => {
4170                self.mouse_position = pinch.position;
4171                self.modifiers = pinch.modifiers;
4172                PlatformInput::Pinch(pinch)
4173            }
4174            // Translate dragging and dropping of external files from the operating system
4175            // to internal drag and drop events.
4176            PlatformInput::FileDrop(file_drop) => match file_drop {
4177                FileDropEvent::Entered { position, paths } => {
4178                    self.mouse_position = position;
4179                    if cx.active_drag.is_none() {
4180                        cx.active_drag = Some(AnyDrag {
4181                            value: Arc::new(paths.clone()),
4182                            view: cx.new(|_| paths).into(),
4183                            cursor_offset: position,
4184                            cursor_style: None,
4185                        });
4186                    }
4187                    PlatformInput::MouseMove(MouseMoveEvent {
4188                        position,
4189                        pressed_button: Some(MouseButton::Left),
4190                        modifiers: Modifiers::default(),
4191                    })
4192                }
4193                FileDropEvent::Pending { position } => {
4194                    self.mouse_position = position;
4195                    PlatformInput::MouseMove(MouseMoveEvent {
4196                        position,
4197                        pressed_button: Some(MouseButton::Left),
4198                        modifiers: Modifiers::default(),
4199                    })
4200                }
4201                FileDropEvent::Submit { position } => {
4202                    cx.activate(true);
4203                    self.mouse_position = position;
4204                    PlatformInput::MouseUp(MouseUpEvent {
4205                        button: MouseButton::Left,
4206                        position,
4207                        modifiers: Modifiers::default(),
4208                        click_count: 1,
4209                    })
4210                }
4211                FileDropEvent::Exited => {
4212                    cx.active_drag.take();
4213                    PlatformInput::FileDrop(FileDropEvent::Exited)
4214                }
4215            },
4216            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4217        };
4218
4219        if let Some(any_mouse_event) = event.mouse_event() {
4220            self.dispatch_mouse_event(any_mouse_event, cx);
4221        } else if let Some(any_key_event) = event.keyboard_event() {
4222            self.dispatch_key_event(any_key_event, cx);
4223        }
4224
4225        if self.invalidator.is_dirty() {
4226            self.input_rate_tracker.borrow_mut().record_input();
4227        }
4228
4229        DispatchEventResult {
4230            propagate: cx.propagate_event,
4231            default_prevented: self.default_prevented,
4232        }
4233    }
4234
4235    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4236        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
4237        if hit_test != self.mouse_hit_test {
4238            self.mouse_hit_test = hit_test;
4239            self.reset_cursor_style(cx);
4240        }
4241
4242        #[cfg(any(feature = "inspector", debug_assertions))]
4243        if self.is_inspector_picking(cx) {
4244            self.handle_inspector_mouse_event(event, cx);
4245            // When inspector is picking, all other mouse handling is skipped.
4246            return;
4247        }
4248
4249        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4250
4251        // Capture phase, events bubble from back to front. Handlers for this phase are used for
4252        // special purposes, such as detecting events outside of a given Bounds.
4253        for listener in &mut mouse_listeners {
4254            let listener = listener.as_mut().unwrap();
4255            listener(event, DispatchPhase::Capture, self, cx);
4256            if !cx.propagate_event {
4257                break;
4258            }
4259        }
4260
4261        // Bubble phase, where most normal handlers do their work.
4262        if cx.propagate_event {
4263            for listener in mouse_listeners.iter_mut().rev() {
4264                let listener = listener.as_mut().unwrap();
4265                listener(event, DispatchPhase::Bubble, self, cx);
4266                if !cx.propagate_event {
4267                    break;
4268                }
4269            }
4270        }
4271
4272        self.rendered_frame.mouse_listeners = mouse_listeners;
4273
4274        if cx.has_active_drag() {
4275            if event.is::<MouseMoveEvent>() {
4276                // If this was a mouse move event, redraw the window so that the
4277                // active drag can follow the mouse cursor.
4278                self.refresh();
4279            } else if event.is::<MouseUpEvent>() {
4280                // If this was a mouse up event, cancel the active drag and redraw
4281                // the window.
4282                cx.active_drag = None;
4283                self.refresh();
4284            }
4285        }
4286
4287        // Auto-release pointer capture on mouse up
4288        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
4289            self.captured_hitbox = None;
4290        }
4291    }
4292
4293    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4294        if self.invalidator.is_dirty() {
4295            self.draw(cx).clear();
4296        }
4297
4298        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4299        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4300
4301        let mut keystroke: Option<Keystroke> = None;
4302
4303        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4304            if event.modifiers.number_of_modifiers() == 0
4305                && self.pending_modifier.modifiers.number_of_modifiers() == 1
4306                && !self.pending_modifier.saw_keystroke
4307            {
4308                let key = match self.pending_modifier.modifiers {
4309                    modifiers if modifiers.shift => Some("shift"),
4310                    modifiers if modifiers.control => Some("control"),
4311                    modifiers if modifiers.alt => Some("alt"),
4312                    modifiers if modifiers.platform => Some("platform"),
4313                    modifiers if modifiers.function => Some("function"),
4314                    _ => None,
4315                };
4316                if let Some(key) = key {
4317                    keystroke = Some(Keystroke {
4318                        key: key.to_string(),
4319                        key_char: None,
4320                        modifiers: Modifiers::default(),
4321                    });
4322                }
4323            }
4324
4325            if self.pending_modifier.modifiers.number_of_modifiers() == 0
4326                && event.modifiers.number_of_modifiers() == 1
4327            {
4328                self.pending_modifier.saw_keystroke = false
4329            }
4330            self.pending_modifier.modifiers = event.modifiers
4331        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4332            self.pending_modifier.saw_keystroke = true;
4333            keystroke = Some(key_down_event.keystroke.clone());
4334        }
4335
4336        let Some(keystroke) = keystroke else {
4337            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4338            return;
4339        };
4340
4341        cx.propagate_event = true;
4342        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4343        if !cx.propagate_event {
4344            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4345            return;
4346        }
4347
4348        let mut currently_pending = self.pending_input.take().unwrap_or_default();
4349        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4350            currently_pending = PendingInput::default();
4351        }
4352
4353        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4354            currently_pending.keystrokes,
4355            keystroke,
4356            &dispatch_path,
4357        );
4358
4359        if !match_result.to_replay.is_empty() {
4360            self.replay_pending_input(match_result.to_replay, cx);
4361            cx.propagate_event = true;
4362        }
4363
4364        if !match_result.pending.is_empty() {
4365            currently_pending.timer.take();
4366            currently_pending.keystrokes = match_result.pending;
4367            currently_pending.focus = self.focus;
4368
4369            let text_input_requires_timeout = event
4370                .downcast_ref::<KeyDownEvent>()
4371                .filter(|key_down| key_down.keystroke.key_char.is_some())
4372                .and_then(|_| self.platform_window.take_input_handler())
4373                .map_or(false, |mut input_handler| {
4374                    let accepts = input_handler.accepts_text_input(self, cx);
4375                    self.platform_window.set_input_handler(input_handler);
4376                    accepts
4377                });
4378
4379            currently_pending.needs_timeout |=
4380                match_result.pending_has_binding || text_input_requires_timeout;
4381
4382            if currently_pending.needs_timeout {
4383                currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4384                    cx.background_executor.timer(Duration::from_secs(1)).await;
4385                    cx.update(move |window, cx| {
4386                        let Some(currently_pending) = window
4387                            .pending_input
4388                            .take()
4389                            .filter(|pending| pending.focus == window.focus)
4390                        else {
4391                            return;
4392                        };
4393
4394                        let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4395                        let dispatch_path =
4396                            window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4397
4398                        let to_replay = window
4399                            .rendered_frame
4400                            .dispatch_tree
4401                            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4402
4403                        window.pending_input_changed(cx);
4404                        window.replay_pending_input(to_replay, cx)
4405                    })
4406                    .log_err();
4407                }));
4408            } else {
4409                currently_pending.timer = None;
4410            }
4411            self.pending_input = Some(currently_pending);
4412            self.pending_input_changed(cx);
4413            cx.propagate_event = false;
4414            return;
4415        }
4416
4417        let skip_bindings = event
4418            .downcast_ref::<KeyDownEvent>()
4419            .filter(|key_down_event| key_down_event.prefer_character_input)
4420            .map(|_| {
4421                self.platform_window
4422                    .take_input_handler()
4423                    .map_or(false, |mut input_handler| {
4424                        let accepts = input_handler.accepts_text_input(self, cx);
4425                        self.platform_window.set_input_handler(input_handler);
4426                        // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
4427                        // we prefer the text input over bindings.
4428                        accepts
4429                    })
4430            })
4431            .unwrap_or(false);
4432
4433        if !skip_bindings {
4434            for binding in match_result.bindings {
4435                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4436                if !cx.propagate_event {
4437                    self.dispatch_keystroke_observers(
4438                        event,
4439                        Some(binding.action),
4440                        match_result.context_stack,
4441                        cx,
4442                    );
4443                    self.pending_input_changed(cx);
4444                    return;
4445                }
4446            }
4447        }
4448
4449        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4450        self.pending_input_changed(cx);
4451    }
4452
4453    fn finish_dispatch_key_event(
4454        &mut self,
4455        event: &dyn Any,
4456        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4457        context_stack: Vec<KeyContext>,
4458        cx: &mut App,
4459    ) {
4460        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4461        if !cx.propagate_event {
4462            return;
4463        }
4464
4465        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4466        if !cx.propagate_event {
4467            return;
4468        }
4469
4470        self.dispatch_keystroke_observers(event, None, context_stack, cx);
4471    }
4472
4473    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4474        self.pending_input_observers
4475            .clone()
4476            .retain(&(), |callback| callback(self, cx));
4477    }
4478
4479    fn dispatch_key_down_up_event(
4480        &mut self,
4481        event: &dyn Any,
4482        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4483        cx: &mut App,
4484    ) {
4485        // Capture phase
4486        for node_id in dispatch_path {
4487            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4488
4489            for key_listener in node.key_listeners.clone() {
4490                key_listener(event, DispatchPhase::Capture, self, cx);
4491                if !cx.propagate_event {
4492                    return;
4493                }
4494            }
4495        }
4496
4497        // Bubble phase
4498        for node_id in dispatch_path.iter().rev() {
4499            // Handle low level key events
4500            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4501            for key_listener in node.key_listeners.clone() {
4502                key_listener(event, DispatchPhase::Bubble, self, cx);
4503                if !cx.propagate_event {
4504                    return;
4505                }
4506            }
4507        }
4508    }
4509
4510    fn dispatch_modifiers_changed_event(
4511        &mut self,
4512        event: &dyn Any,
4513        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4514        cx: &mut App,
4515    ) {
4516        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4517            return;
4518        };
4519        for node_id in dispatch_path.iter().rev() {
4520            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4521            for listener in node.modifiers_changed_listeners.clone() {
4522                listener(event, self, cx);
4523                if !cx.propagate_event {
4524                    return;
4525                }
4526            }
4527        }
4528    }
4529
4530    /// Determine whether a potential multi-stroke key binding is in progress on this window.
4531    pub fn has_pending_keystrokes(&self) -> bool {
4532        self.pending_input.is_some()
4533    }
4534
4535    pub(crate) fn clear_pending_keystrokes(&mut self) {
4536        self.pending_input.take();
4537    }
4538
4539    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4540    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4541        self.pending_input
4542            .as_ref()
4543            .map(|pending_input| pending_input.keystrokes.as_slice())
4544    }
4545
4546    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4547        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4548        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4549
4550        'replay: for replay in replays {
4551            let event = KeyDownEvent {
4552                keystroke: replay.keystroke.clone(),
4553                is_held: false,
4554                prefer_character_input: true,
4555            };
4556
4557            cx.propagate_event = true;
4558            for binding in replay.bindings {
4559                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4560                if !cx.propagate_event {
4561                    self.dispatch_keystroke_observers(
4562                        &event,
4563                        Some(binding.action),
4564                        Vec::default(),
4565                        cx,
4566                    );
4567                    continue 'replay;
4568                }
4569            }
4570
4571            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4572            if !cx.propagate_event {
4573                continue 'replay;
4574            }
4575            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4576                && let Some(mut input_handler) = self.platform_window.take_input_handler()
4577            {
4578                input_handler.dispatch_input(&input, self, cx);
4579                self.platform_window.set_input_handler(input_handler)
4580            }
4581        }
4582    }
4583
4584    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4585        focus_id
4586            .and_then(|focus_id| {
4587                self.rendered_frame
4588                    .dispatch_tree
4589                    .focusable_node_id(focus_id)
4590            })
4591            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4592    }
4593
4594    fn dispatch_action_on_node(
4595        &mut self,
4596        node_id: DispatchNodeId,
4597        action: &dyn Action,
4598        cx: &mut App,
4599    ) {
4600        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4601
4602        // Capture phase for global actions.
4603        cx.propagate_event = true;
4604        if let Some(mut global_listeners) = cx
4605            .global_action_listeners
4606            .remove(&action.as_any().type_id())
4607        {
4608            for listener in &global_listeners {
4609                listener(action.as_any(), DispatchPhase::Capture, cx);
4610                if !cx.propagate_event {
4611                    break;
4612                }
4613            }
4614
4615            global_listeners.extend(
4616                cx.global_action_listeners
4617                    .remove(&action.as_any().type_id())
4618                    .unwrap_or_default(),
4619            );
4620
4621            cx.global_action_listeners
4622                .insert(action.as_any().type_id(), global_listeners);
4623        }
4624
4625        if !cx.propagate_event {
4626            return;
4627        }
4628
4629        // Capture phase for window actions.
4630        for node_id in &dispatch_path {
4631            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4632            for DispatchActionListener {
4633                action_type,
4634                listener,
4635            } in node.action_listeners.clone()
4636            {
4637                let any_action = action.as_any();
4638                if action_type == any_action.type_id() {
4639                    listener(any_action, DispatchPhase::Capture, self, cx);
4640
4641                    if !cx.propagate_event {
4642                        return;
4643                    }
4644                }
4645            }
4646        }
4647
4648        // Bubble phase for window actions.
4649        for node_id in dispatch_path.iter().rev() {
4650            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4651            for DispatchActionListener {
4652                action_type,
4653                listener,
4654            } in node.action_listeners.clone()
4655            {
4656                let any_action = action.as_any();
4657                if action_type == any_action.type_id() {
4658                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4659                    listener(any_action, DispatchPhase::Bubble, self, cx);
4660
4661                    if !cx.propagate_event {
4662                        return;
4663                    }
4664                }
4665            }
4666        }
4667
4668        // Bubble phase for global actions.
4669        if let Some(mut global_listeners) = cx
4670            .global_action_listeners
4671            .remove(&action.as_any().type_id())
4672        {
4673            for listener in global_listeners.iter().rev() {
4674                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4675
4676                listener(action.as_any(), DispatchPhase::Bubble, cx);
4677                if !cx.propagate_event {
4678                    break;
4679                }
4680            }
4681
4682            global_listeners.extend(
4683                cx.global_action_listeners
4684                    .remove(&action.as_any().type_id())
4685                    .unwrap_or_default(),
4686            );
4687
4688            cx.global_action_listeners
4689                .insert(action.as_any().type_id(), global_listeners);
4690        }
4691    }
4692
4693    /// Register the given handler to be invoked whenever the global of the given type
4694    /// is updated.
4695    pub fn observe_global<G: Global>(
4696        &mut self,
4697        cx: &mut App,
4698        f: impl Fn(&mut Window, &mut App) + 'static,
4699    ) -> Subscription {
4700        let window_handle = self.handle;
4701        let (subscription, activate) = cx.global_observers.insert(
4702            TypeId::of::<G>(),
4703            Box::new(move |cx| {
4704                window_handle
4705                    .update(cx, |_, window, cx| f(window, cx))
4706                    .is_ok()
4707            }),
4708        );
4709        cx.defer(move |_| activate());
4710        subscription
4711    }
4712
4713    /// Focus the current window and bring it to the foreground at the platform level.
4714    pub fn activate_window(&self) {
4715        self.platform_window.activate();
4716    }
4717
4718    /// Minimize the current window at the platform level.
4719    pub fn minimize_window(&self) {
4720        self.platform_window.minimize();
4721    }
4722
4723    /// Toggle full screen status on the current window at the platform level.
4724    pub fn toggle_fullscreen(&self) {
4725        self.platform_window.toggle_fullscreen();
4726    }
4727
4728    /// Updates the IME panel position suggestions for languages like japanese, chinese.
4729    pub fn invalidate_character_coordinates(&self) {
4730        self.on_next_frame(|window, cx| {
4731            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4732                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4733                    window.platform_window.update_ime_position(bounds);
4734                }
4735                window.platform_window.set_input_handler(input_handler);
4736            }
4737        });
4738    }
4739
4740    /// Present a platform dialog.
4741    /// The provided message will be presented, along with buttons for each answer.
4742    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4743    pub fn prompt<T>(
4744        &mut self,
4745        level: PromptLevel,
4746        message: &str,
4747        detail: Option<&str>,
4748        answers: &[T],
4749        cx: &mut App,
4750    ) -> oneshot::Receiver<usize>
4751    where
4752        T: Clone + Into<PromptButton>,
4753    {
4754        let prompt_builder = cx.prompt_builder.take();
4755        let Some(prompt_builder) = prompt_builder else {
4756            unreachable!("Re-entrant window prompting is not supported by GPUI");
4757        };
4758
4759        let answers = answers
4760            .iter()
4761            .map(|answer| answer.clone().into())
4762            .collect::<Vec<_>>();
4763
4764        let receiver = match &prompt_builder {
4765            PromptBuilder::Default => self
4766                .platform_window
4767                .prompt(level, message, detail, &answers)
4768                .unwrap_or_else(|| {
4769                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4770                }),
4771            PromptBuilder::Custom(_) => {
4772                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4773            }
4774        };
4775
4776        cx.prompt_builder = Some(prompt_builder);
4777
4778        receiver
4779    }
4780
4781    fn build_custom_prompt(
4782        &mut self,
4783        prompt_builder: &PromptBuilder,
4784        level: PromptLevel,
4785        message: &str,
4786        detail: Option<&str>,
4787        answers: &[PromptButton],
4788        cx: &mut App,
4789    ) -> oneshot::Receiver<usize> {
4790        let (sender, receiver) = oneshot::channel();
4791        let handle = PromptHandle::new(sender);
4792        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4793        self.prompt = Some(handle);
4794        receiver
4795    }
4796
4797    /// Returns the current context stack.
4798    pub fn context_stack(&self) -> Vec<KeyContext> {
4799        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4800        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4801        dispatch_tree
4802            .dispatch_path(node_id)
4803            .iter()
4804            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4805            .collect()
4806    }
4807
4808    /// Returns all available actions for the focused element.
4809    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4810        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4811        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4812        for action_type in cx.global_action_listeners.keys() {
4813            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4814                let action = cx.actions.build_action_type(action_type).ok();
4815                if let Some(action) = action {
4816                    actions.insert(ix, action);
4817                }
4818            }
4819        }
4820        actions
4821    }
4822
4823    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4824    /// returned in the order they were added. For display, the last binding should take precedence.
4825    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4826        self.rendered_frame
4827            .dispatch_tree
4828            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4829    }
4830
4831    /// Returns the highest precedence key binding that invokes an action on the currently focused
4832    /// element. This is more efficient than getting the last result of `bindings_for_action`.
4833    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4834        self.rendered_frame
4835            .dispatch_tree
4836            .highest_precedence_binding_for_action(
4837                action,
4838                &self.rendered_frame.dispatch_tree.context_stack,
4839            )
4840    }
4841
4842    /// Returns the key bindings for an action in a context.
4843    pub fn bindings_for_action_in_context(
4844        &self,
4845        action: &dyn Action,
4846        context: KeyContext,
4847    ) -> Vec<KeyBinding> {
4848        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4849        dispatch_tree.bindings_for_action(action, &[context])
4850    }
4851
4852    /// Returns the highest precedence key binding for an action in a context. This is more
4853    /// efficient than getting the last result of `bindings_for_action_in_context`.
4854    pub fn highest_precedence_binding_for_action_in_context(
4855        &self,
4856        action: &dyn Action,
4857        context: KeyContext,
4858    ) -> Option<KeyBinding> {
4859        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4860        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4861    }
4862
4863    /// Returns any bindings that would invoke an action on the given focus handle if it were
4864    /// focused. Bindings are returned in the order they were added. For display, the last binding
4865    /// should take precedence.
4866    pub fn bindings_for_action_in(
4867        &self,
4868        action: &dyn Action,
4869        focus_handle: &FocusHandle,
4870    ) -> Vec<KeyBinding> {
4871        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4872        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4873            return vec![];
4874        };
4875        dispatch_tree.bindings_for_action(action, &context_stack)
4876    }
4877
4878    /// Returns the highest precedence key binding that would invoke an action on the given focus
4879    /// handle if it were focused. This is more efficient than getting the last result of
4880    /// `bindings_for_action_in`.
4881    pub fn highest_precedence_binding_for_action_in(
4882        &self,
4883        action: &dyn Action,
4884        focus_handle: &FocusHandle,
4885    ) -> Option<KeyBinding> {
4886        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4887        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4888        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4889    }
4890
4891    /// Find the bindings that can follow the current input sequence for the current context stack.
4892    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
4893        self.rendered_frame
4894            .dispatch_tree
4895            .possible_next_bindings_for_input(input, &self.context_stack())
4896    }
4897
4898    fn context_stack_for_focus_handle(
4899        &self,
4900        focus_handle: &FocusHandle,
4901    ) -> Option<Vec<KeyContext>> {
4902        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4903        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4904        let context_stack: Vec<_> = dispatch_tree
4905            .dispatch_path(node_id)
4906            .into_iter()
4907            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4908            .collect();
4909        Some(context_stack)
4910    }
4911
4912    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4913    pub fn listener_for<T: 'static, E>(
4914        &self,
4915        view: &Entity<T>,
4916        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
4917    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4918        let view = view.downgrade();
4919        move |e: &E, window: &mut Window, cx: &mut App| {
4920            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4921        }
4922    }
4923
4924    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4925    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
4926        &self,
4927        entity: &Entity<E>,
4928        f: Callback,
4929    ) -> impl Fn(&mut Window, &mut App) + 'static {
4930        let entity = entity.downgrade();
4931        move |window: &mut Window, cx: &mut App| {
4932            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
4933        }
4934    }
4935
4936    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4937    /// If the callback returns false, the window won't be closed.
4938    pub fn on_window_should_close(
4939        &self,
4940        cx: &App,
4941        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4942    ) {
4943        let mut cx = self.to_async(cx);
4944        self.platform_window.on_should_close(Box::new(move || {
4945            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4946        }))
4947    }
4948
4949    /// Register an action listener on this node for the next frame. The type of action
4950    /// is determined by the first parameter of the given listener. When the next frame is rendered
4951    /// the listener will be cleared.
4952    ///
4953    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4954    /// a specific need to register a listener yourself.
4955    ///
4956    /// This method should only be called as part of the paint phase of element drawing.
4957    pub fn on_action(
4958        &mut self,
4959        action_type: TypeId,
4960        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4961    ) {
4962        self.invalidator.debug_assert_paint();
4963
4964        self.next_frame
4965            .dispatch_tree
4966            .on_action(action_type, Rc::new(listener));
4967    }
4968
4969    /// Register a capturing action listener on this node for the next frame if the condition is true.
4970    /// The type of action is determined by the first parameter of the given listener. When the next
4971    /// frame is rendered the listener will be cleared.
4972    ///
4973    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4974    /// a specific need to register a listener yourself.
4975    ///
4976    /// This method should only be called as part of the paint phase of element drawing.
4977    pub fn on_action_when(
4978        &mut self,
4979        condition: bool,
4980        action_type: TypeId,
4981        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4982    ) {
4983        self.invalidator.debug_assert_paint();
4984
4985        if condition {
4986            self.next_frame
4987                .dispatch_tree
4988                .on_action(action_type, Rc::new(listener));
4989        }
4990    }
4991
4992    /// Read information about the GPU backing this window.
4993    /// Currently returns None on Mac and Windows.
4994    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4995        self.platform_window.gpu_specs()
4996    }
4997
4998    /// Perform titlebar double-click action.
4999    /// This is macOS specific.
5000    pub fn titlebar_double_click(&self) {
5001        self.platform_window.titlebar_double_click();
5002    }
5003
5004    /// Gets the window's title at the platform level.
5005    /// This is macOS specific.
5006    pub fn window_title(&self) -> String {
5007        self.platform_window.get_title()
5008    }
5009
5010    /// Returns a list of all tabbed windows and their titles.
5011    /// This is macOS specific.
5012    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5013        self.platform_window.tabbed_windows()
5014    }
5015
5016    /// Returns the tab bar visibility.
5017    /// This is macOS specific.
5018    pub fn tab_bar_visible(&self) -> bool {
5019        self.platform_window.tab_bar_visible()
5020    }
5021
5022    /// Merges all open windows into a single tabbed window.
5023    /// This is macOS specific.
5024    pub fn merge_all_windows(&self) {
5025        self.platform_window.merge_all_windows()
5026    }
5027
5028    /// Moves the tab to a new containing window.
5029    /// This is macOS specific.
5030    pub fn move_tab_to_new_window(&self) {
5031        self.platform_window.move_tab_to_new_window()
5032    }
5033
5034    /// Shows or hides the window tab overview.
5035    /// This is macOS specific.
5036    pub fn toggle_window_tab_overview(&self) {
5037        self.platform_window.toggle_window_tab_overview()
5038    }
5039
5040    /// Sets the tabbing identifier for the window.
5041    /// This is macOS specific.
5042    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5043        self.platform_window
5044            .set_tabbing_identifier(tabbing_identifier)
5045    }
5046
5047    /// Request the OS to play an alert sound. On some platforms this is associated
5048    /// with the window, for others it's just a simple global function call.
5049    pub fn play_system_bell(&self) {
5050        self.platform_window.play_system_bell()
5051    }
5052
5053    /// Toggles the inspector mode on this window.
5054    #[cfg(any(feature = "inspector", debug_assertions))]
5055    pub fn toggle_inspector(&mut self, cx: &mut App) {
5056        self.inspector = match self.inspector {
5057            None => Some(cx.new(|_| Inspector::new())),
5058            Some(_) => None,
5059        };
5060        self.refresh();
5061    }
5062
5063    /// Returns true if the window is in inspector mode.
5064    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
5065        #[cfg(any(feature = "inspector", debug_assertions))]
5066        {
5067            if let Some(inspector) = &self.inspector {
5068                return inspector.read(_cx).is_picking();
5069            }
5070        }
5071        false
5072    }
5073
5074    /// Executes the provided function with mutable access to an inspector state.
5075    #[cfg(any(feature = "inspector", debug_assertions))]
5076    pub fn with_inspector_state<T: 'static, R>(
5077        &mut self,
5078        _inspector_id: Option<&crate::InspectorElementId>,
5079        cx: &mut App,
5080        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
5081    ) -> R {
5082        if let Some(inspector_id) = _inspector_id
5083            && let Some(inspector) = &self.inspector
5084        {
5085            let inspector = inspector.clone();
5086            let active_element_id = inspector.read(cx).active_element_id();
5087            if Some(inspector_id) == active_element_id {
5088                return inspector.update(cx, |inspector, _cx| {
5089                    inspector.with_active_element_state(self, f)
5090                });
5091            }
5092        }
5093        f(&mut None, self)
5094    }
5095
5096    #[cfg(any(feature = "inspector", debug_assertions))]
5097    pub(crate) fn build_inspector_element_id(
5098        &mut self,
5099        path: crate::InspectorElementPath,
5100    ) -> crate::InspectorElementId {
5101        self.invalidator.debug_assert_paint_or_prepaint();
5102        let path = Rc::new(path);
5103        let next_instance_id = self
5104            .next_frame
5105            .next_inspector_instance_ids
5106            .entry(path.clone())
5107            .or_insert(0);
5108        let instance_id = *next_instance_id;
5109        *next_instance_id += 1;
5110        crate::InspectorElementId { path, instance_id }
5111    }
5112
5113    #[cfg(any(feature = "inspector", debug_assertions))]
5114    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5115        if let Some(inspector) = self.inspector.take() {
5116            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5117            inspector_element.prepaint_as_root(
5118                point(self.viewport_size.width - inspector_width, px(0.0)),
5119                size(inspector_width, self.viewport_size.height).into(),
5120                self,
5121                cx,
5122            );
5123            self.inspector = Some(inspector);
5124            Some(inspector_element)
5125        } else {
5126            None
5127        }
5128    }
5129
5130    #[cfg(any(feature = "inspector", debug_assertions))]
5131    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5132        if let Some(mut inspector_element) = inspector_element {
5133            inspector_element.paint(self, cx);
5134        };
5135    }
5136
5137    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
5138    /// inspect UI elements by clicking on them.
5139    #[cfg(any(feature = "inspector", debug_assertions))]
5140    pub fn insert_inspector_hitbox(
5141        &mut self,
5142        hitbox_id: HitboxId,
5143        inspector_id: Option<&crate::InspectorElementId>,
5144        cx: &App,
5145    ) {
5146        self.invalidator.debug_assert_paint_or_prepaint();
5147        if !self.is_inspector_picking(cx) {
5148            return;
5149        }
5150        if let Some(inspector_id) = inspector_id {
5151            self.next_frame
5152                .inspector_hitboxes
5153                .insert(hitbox_id, inspector_id.clone());
5154        }
5155    }
5156
5157    #[cfg(any(feature = "inspector", debug_assertions))]
5158    fn paint_inspector_hitbox(&mut self, cx: &App) {
5159        if let Some(inspector) = self.inspector.as_ref() {
5160            let inspector = inspector.read(cx);
5161            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5162                && let Some(hitbox) = self
5163                    .next_frame
5164                    .hitboxes
5165                    .iter()
5166                    .find(|hitbox| hitbox.id == hitbox_id)
5167            {
5168                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5169            }
5170        }
5171    }
5172
5173    #[cfg(any(feature = "inspector", debug_assertions))]
5174    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5175        let Some(inspector) = self.inspector.clone() else {
5176            return;
5177        };
5178        if event.downcast_ref::<MouseMoveEvent>().is_some() {
5179            inspector.update(cx, |inspector, _cx| {
5180                if let Some((_, inspector_id)) =
5181                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5182                {
5183                    inspector.hover(inspector_id, self);
5184                }
5185            });
5186        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5187            inspector.update(cx, |inspector, _cx| {
5188                if let Some((_, inspector_id)) =
5189                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5190                {
5191                    inspector.select(inspector_id, self);
5192                }
5193            });
5194        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5195            // This should be kept in sync with SCROLL_LINES in x11 platform.
5196            const SCROLL_LINES: f32 = 3.0;
5197            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5198            let delta_y = event
5199                .delta
5200                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5201                .y;
5202            if let Some(inspector) = self.inspector.clone() {
5203                inspector.update(cx, |inspector, _cx| {
5204                    if let Some(depth) = inspector.pick_depth.as_mut() {
5205                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5206                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5207                        if *depth < 0.0 {
5208                            *depth = 0.0;
5209                        } else if *depth > max_depth {
5210                            *depth = max_depth;
5211                        }
5212                        if let Some((_, inspector_id)) =
5213                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5214                        {
5215                            inspector.set_active_element_id(inspector_id, self);
5216                        }
5217                    }
5218                });
5219            }
5220        }
5221    }
5222
5223    #[cfg(any(feature = "inspector", debug_assertions))]
5224    fn hovered_inspector_hitbox(
5225        &self,
5226        inspector: &Inspector,
5227        frame: &Frame,
5228    ) -> Option<(HitboxId, crate::InspectorElementId)> {
5229        if let Some(pick_depth) = inspector.pick_depth {
5230            let depth = (pick_depth as i64).try_into().unwrap_or(0);
5231            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5232            let skip_count = (depth as usize).min(max_skipped);
5233            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5234                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5235                    return Some((*hitbox_id, inspector_id.clone()));
5236                }
5237            }
5238        }
5239        None
5240    }
5241
5242    /// For testing: set the current modifier keys state.
5243    /// This does not generate any events.
5244    #[cfg(any(test, feature = "test-support"))]
5245    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5246        self.modifiers = modifiers;
5247    }
5248
5249    /// For testing: simulate a mouse move event to the given position.
5250    /// This dispatches the event through the normal event handling path,
5251    /// which will trigger hover states and tooltips.
5252    #[cfg(any(test, feature = "test-support"))]
5253    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
5254        let event = PlatformInput::MouseMove(MouseMoveEvent {
5255            position,
5256            modifiers: self.modifiers,
5257            pressed_button: None,
5258        });
5259        let _ = self.dispatch_event(event, cx);
5260    }
5261}
5262
5263// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
5264slotmap::new_key_type! {
5265    /// A unique identifier for a window.
5266    pub struct WindowId;
5267}
5268
5269impl WindowId {
5270    /// Converts this window ID to a `u64`.
5271    pub fn as_u64(&self) -> u64 {
5272        self.0.as_ffi()
5273    }
5274}
5275
5276impl From<u64> for WindowId {
5277    fn from(value: u64) -> Self {
5278        WindowId(slotmap::KeyData::from_ffi(value))
5279    }
5280}
5281
5282/// A handle to a window with a specific root view type.
5283/// Note that this does not keep the window alive on its own.
5284#[derive(Deref, DerefMut)]
5285pub struct WindowHandle<V> {
5286    #[deref]
5287    #[deref_mut]
5288    pub(crate) any_handle: AnyWindowHandle,
5289    state_type: PhantomData<fn(V) -> V>,
5290}
5291
5292impl<V> Debug for WindowHandle<V> {
5293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5294        f.debug_struct("WindowHandle")
5295            .field("any_handle", &self.any_handle.id.as_u64())
5296            .finish()
5297    }
5298}
5299
5300impl<V: 'static + Render> WindowHandle<V> {
5301    /// Creates a new handle from a window ID.
5302    /// This does not check if the root type of the window is `V`.
5303    pub fn new(id: WindowId) -> Self {
5304        WindowHandle {
5305            any_handle: AnyWindowHandle {
5306                id,
5307                state_type: TypeId::of::<V>(),
5308            },
5309            state_type: PhantomData,
5310        }
5311    }
5312
5313    /// Get the root view out of this window.
5314    ///
5315    /// This will fail if the window is closed or if the root view's type does not match `V`.
5316    #[cfg(any(test, feature = "test-support"))]
5317    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5318    where
5319        C: AppContext,
5320    {
5321        cx.update_window(self.any_handle, |root_view, _, _| {
5322            root_view
5323                .downcast::<V>()
5324                .map_err(|_| anyhow!("the type of the window's root view has changed"))
5325        })?
5326    }
5327
5328    /// Updates the root view of this window.
5329    ///
5330    /// This will fail if the window has been closed or if the root view's type does not match
5331    pub fn update<C, R>(
5332        &self,
5333        cx: &mut C,
5334        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5335    ) -> Result<R>
5336    where
5337        C: AppContext,
5338    {
5339        cx.update_window(self.any_handle, |root_view, window, cx| {
5340            let view = root_view
5341                .downcast::<V>()
5342                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5343
5344            Ok(view.update(cx, |view, cx| update(view, window, cx)))
5345        })?
5346    }
5347
5348    /// Read the root view out of this window.
5349    ///
5350    /// This will fail if the window is closed or if the root view's type does not match `V`.
5351    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5352        let x = cx
5353            .windows
5354            .get(self.id)
5355            .and_then(|window| {
5356                window
5357                    .as_deref()
5358                    .and_then(|window| window.root.clone())
5359                    .map(|root_view| root_view.downcast::<V>())
5360            })
5361            .context("window not found")?
5362            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5363
5364        Ok(x.read(cx))
5365    }
5366
5367    /// Read the root view out of this window, with a callback
5368    ///
5369    /// This will fail if the window is closed or if the root view's type does not match `V`.
5370    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5371    where
5372        C: AppContext,
5373    {
5374        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5375    }
5376
5377    /// Read the root view pointer off of this window.
5378    ///
5379    /// This will fail if the window is closed or if the root view's type does not match `V`.
5380    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5381    where
5382        C: AppContext,
5383    {
5384        cx.read_window(self, |root_view, _cx| root_view)
5385    }
5386
5387    /// Check if this window is 'active'.
5388    ///
5389    /// Will return `None` if the window is closed or currently
5390    /// borrowed.
5391    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5392        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5393            .ok()
5394    }
5395}
5396
5397impl<V> Copy for WindowHandle<V> {}
5398
5399impl<V> Clone for WindowHandle<V> {
5400    fn clone(&self) -> Self {
5401        *self
5402    }
5403}
5404
5405impl<V> PartialEq for WindowHandle<V> {
5406    fn eq(&self, other: &Self) -> bool {
5407        self.any_handle == other.any_handle
5408    }
5409}
5410
5411impl<V> Eq for WindowHandle<V> {}
5412
5413impl<V> Hash for WindowHandle<V> {
5414    fn hash<H: Hasher>(&self, state: &mut H) {
5415        self.any_handle.hash(state);
5416    }
5417}
5418
5419impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5420    fn from(val: WindowHandle<V>) -> Self {
5421        val.any_handle
5422    }
5423}
5424
5425/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
5426#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5427pub struct AnyWindowHandle {
5428    pub(crate) id: WindowId,
5429    state_type: TypeId,
5430}
5431
5432impl AnyWindowHandle {
5433    /// Get the ID of this window.
5434    pub fn window_id(&self) -> WindowId {
5435        self.id
5436    }
5437
5438    /// Attempt to convert this handle to a window handle with a specific root view type.
5439    /// If the types do not match, this will return `None`.
5440    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5441        if TypeId::of::<T>() == self.state_type {
5442            Some(WindowHandle {
5443                any_handle: *self,
5444                state_type: PhantomData,
5445            })
5446        } else {
5447            None
5448        }
5449    }
5450
5451    /// Updates the state of the root view of this window.
5452    ///
5453    /// This will fail if the window has been closed.
5454    pub fn update<C, R>(
5455        self,
5456        cx: &mut C,
5457        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5458    ) -> Result<R>
5459    where
5460        C: AppContext,
5461    {
5462        cx.update_window(self, update)
5463    }
5464
5465    /// Read the state of the root view of this window.
5466    ///
5467    /// This will fail if the window has been closed.
5468    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5469    where
5470        C: AppContext,
5471        T: 'static,
5472    {
5473        let view = self
5474            .downcast::<T>()
5475            .context("the type of the window's root view has changed")?;
5476
5477        cx.read_window(&view, read)
5478    }
5479}
5480
5481impl HasWindowHandle for Window {
5482    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5483        self.platform_window.window_handle()
5484    }
5485}
5486
5487impl HasDisplayHandle for Window {
5488    fn display_handle(
5489        &self,
5490    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5491        self.platform_window.display_handle()
5492    }
5493}
5494
5495/// An identifier for an [`Element`].
5496///
5497/// Can be constructed with a string, a number, or both, as well
5498/// as other internal representations.
5499#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5500pub enum ElementId {
5501    /// The ID of a View element
5502    View(EntityId),
5503    /// An integer ID.
5504    Integer(u64),
5505    /// A string based ID.
5506    Name(SharedString),
5507    /// A UUID.
5508    Uuid(Uuid),
5509    /// An ID that's equated with a focus handle.
5510    FocusHandle(FocusId),
5511    /// A combination of a name and an integer.
5512    NamedInteger(SharedString, u64),
5513    /// A path.
5514    Path(Arc<std::path::Path>),
5515    /// A code location.
5516    CodeLocation(core::panic::Location<'static>),
5517    /// A labeled child of an element.
5518    NamedChild(Arc<ElementId>, SharedString),
5519    /// A byte array ID (used for text-anchors)
5520    OpaqueId([u8; 20]),
5521}
5522
5523impl ElementId {
5524    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5525    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5526        Self::NamedInteger(name.into(), integer as u64)
5527    }
5528}
5529
5530impl Display for ElementId {
5531    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5532        match self {
5533            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5534            ElementId::Integer(ix) => write!(f, "{}", ix)?,
5535            ElementId::Name(name) => write!(f, "{}", name)?,
5536            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5537            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5538            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5539            ElementId::Path(path) => write!(f, "{}", path.display())?,
5540            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5541            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5542            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
5543        }
5544
5545        Ok(())
5546    }
5547}
5548
5549impl TryInto<SharedString> for ElementId {
5550    type Error = anyhow::Error;
5551
5552    fn try_into(self) -> anyhow::Result<SharedString> {
5553        if let ElementId::Name(name) = self {
5554            Ok(name)
5555        } else {
5556            anyhow::bail!("element id is not string")
5557        }
5558    }
5559}
5560
5561impl From<usize> for ElementId {
5562    fn from(id: usize) -> Self {
5563        ElementId::Integer(id as u64)
5564    }
5565}
5566
5567impl From<i32> for ElementId {
5568    fn from(id: i32) -> Self {
5569        Self::Integer(id as u64)
5570    }
5571}
5572
5573impl From<SharedString> for ElementId {
5574    fn from(name: SharedString) -> Self {
5575        ElementId::Name(name)
5576    }
5577}
5578
5579impl From<String> for ElementId {
5580    fn from(name: String) -> Self {
5581        ElementId::Name(name.into())
5582    }
5583}
5584
5585impl From<Arc<str>> for ElementId {
5586    fn from(name: Arc<str>) -> Self {
5587        ElementId::Name(name.into())
5588    }
5589}
5590
5591impl From<Arc<std::path::Path>> for ElementId {
5592    fn from(path: Arc<std::path::Path>) -> Self {
5593        ElementId::Path(path)
5594    }
5595}
5596
5597impl From<&'static str> for ElementId {
5598    fn from(name: &'static str) -> Self {
5599        ElementId::Name(name.into())
5600    }
5601}
5602
5603impl<'a> From<&'a FocusHandle> for ElementId {
5604    fn from(handle: &'a FocusHandle) -> Self {
5605        ElementId::FocusHandle(handle.id)
5606    }
5607}
5608
5609impl From<(&'static str, EntityId)> for ElementId {
5610    fn from((name, id): (&'static str, EntityId)) -> Self {
5611        ElementId::NamedInteger(name.into(), id.as_u64())
5612    }
5613}
5614
5615impl From<(&'static str, usize)> for ElementId {
5616    fn from((name, id): (&'static str, usize)) -> Self {
5617        ElementId::NamedInteger(name.into(), id as u64)
5618    }
5619}
5620
5621impl From<(SharedString, usize)> for ElementId {
5622    fn from((name, id): (SharedString, usize)) -> Self {
5623        ElementId::NamedInteger(name, id as u64)
5624    }
5625}
5626
5627impl From<(&'static str, u64)> for ElementId {
5628    fn from((name, id): (&'static str, u64)) -> Self {
5629        ElementId::NamedInteger(name.into(), id)
5630    }
5631}
5632
5633impl From<Uuid> for ElementId {
5634    fn from(value: Uuid) -> Self {
5635        Self::Uuid(value)
5636    }
5637}
5638
5639impl From<(&'static str, u32)> for ElementId {
5640    fn from((name, id): (&'static str, u32)) -> Self {
5641        ElementId::NamedInteger(name.into(), id.into())
5642    }
5643}
5644
5645impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5646    fn from((id, name): (ElementId, T)) -> Self {
5647        ElementId::NamedChild(Arc::new(id), name.into())
5648    }
5649}
5650
5651impl From<&'static core::panic::Location<'static>> for ElementId {
5652    fn from(location: &'static core::panic::Location<'static>) -> Self {
5653        ElementId::CodeLocation(*location)
5654    }
5655}
5656
5657impl From<[u8; 20]> for ElementId {
5658    fn from(opaque_id: [u8; 20]) -> Self {
5659        ElementId::OpaqueId(opaque_id)
5660    }
5661}
5662
5663/// A rectangle to be rendered in the window at the given position and size.
5664/// Passed as an argument [`Window::paint_quad`].
5665#[derive(Clone)]
5666pub struct PaintQuad {
5667    /// The bounds of the quad within the window.
5668    pub bounds: Bounds<Pixels>,
5669    /// The radii of the quad's corners.
5670    pub corner_radii: Corners<Pixels>,
5671    /// The background color of the quad.
5672    pub background: Background,
5673    /// The widths of the quad's borders.
5674    pub border_widths: Edges<Pixels>,
5675    /// The color of the quad's borders.
5676    pub border_color: Hsla,
5677    /// The style of the quad's borders.
5678    pub border_style: BorderStyle,
5679}
5680
5681impl PaintQuad {
5682    /// Sets the corner radii of the quad.
5683    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5684        PaintQuad {
5685            corner_radii: corner_radii.into(),
5686            ..self
5687        }
5688    }
5689
5690    /// Sets the border widths of the quad.
5691    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5692        PaintQuad {
5693            border_widths: border_widths.into(),
5694            ..self
5695        }
5696    }
5697
5698    /// Sets the border color of the quad.
5699    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5700        PaintQuad {
5701            border_color: border_color.into(),
5702            ..self
5703        }
5704    }
5705
5706    /// Sets the background color of the quad.
5707    pub fn background(self, background: impl Into<Background>) -> Self {
5708        PaintQuad {
5709            background: background.into(),
5710            ..self
5711        }
5712    }
5713}
5714
5715/// Creates a quad with the given parameters.
5716pub fn quad(
5717    bounds: Bounds<Pixels>,
5718    corner_radii: impl Into<Corners<Pixels>>,
5719    background: impl Into<Background>,
5720    border_widths: impl Into<Edges<Pixels>>,
5721    border_color: impl Into<Hsla>,
5722    border_style: BorderStyle,
5723) -> PaintQuad {
5724    PaintQuad {
5725        bounds,
5726        corner_radii: corner_radii.into(),
5727        background: background.into(),
5728        border_widths: border_widths.into(),
5729        border_color: border_color.into(),
5730        border_style,
5731    }
5732}
5733
5734/// Creates a filled quad with the given bounds and background color.
5735pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5736    PaintQuad {
5737        bounds: bounds.into(),
5738        corner_radii: (0.).into(),
5739        background: background.into(),
5740        border_widths: (0.).into(),
5741        border_color: transparent_black(),
5742        border_style: BorderStyle::default(),
5743    }
5744}
5745
5746/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5747pub fn outline(
5748    bounds: impl Into<Bounds<Pixels>>,
5749    border_color: impl Into<Hsla>,
5750    border_style: BorderStyle,
5751) -> PaintQuad {
5752    PaintQuad {
5753        bounds: bounds.into(),
5754        corner_radii: (0.).into(),
5755        background: transparent_black().into(),
5756        border_widths: (1.).into(),
5757        border_color: border_color.into(),
5758        border_style,
5759    }
5760}