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