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