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