window.rs

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