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