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