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