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