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