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
 213/// Returned when the element arena has been used and so must be cleared before the next draw.
 214#[must_use]
 215pub struct ArenaClearNeeded;
 216
 217impl ArenaClearNeeded {
 218    /// Clear the element arena.
 219    pub fn clear(self) {
 220        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
 221            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
 222            if percentage >= 80. {
 223                log::warn!("elevated element arena occupation: {}.", percentage);
 224            }
 225            element_arena.clear();
 226        })
 227    }
 228}
 229
 230pub(crate) type FocusMap = RwLock<SlotMap<FocusId, AtomicUsize>>;
 231
 232impl FocusId {
 233    /// Obtains whether the element associated with this handle is currently focused.
 234    pub fn is_focused(&self, window: &Window) -> bool {
 235        window.focus == Some(*self)
 236    }
 237
 238    /// Obtains whether the element associated with this handle contains the focused
 239    /// element or is itself focused.
 240    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
 241        window
 242            .focused(cx)
 243            .map_or(false, |focused| self.contains(focused.id, window))
 244    }
 245
 246    /// Obtains whether the element associated with this handle is contained within the
 247    /// focused element or is itself focused.
 248    pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
 249        let focused = window.focused(cx);
 250        focused.map_or(false, |focused| focused.id.contains(*self, window))
 251    }
 252
 253    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 254    pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
 255        window
 256            .rendered_frame
 257            .dispatch_tree
 258            .focus_contains(*self, other)
 259    }
 260}
 261
 262/// A handle which can be used to track and manipulate the focused element in a window.
 263pub struct FocusHandle {
 264    pub(crate) id: FocusId,
 265    handles: Arc<FocusMap>,
 266}
 267
 268impl std::fmt::Debug for FocusHandle {
 269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 270        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 271    }
 272}
 273
 274impl FocusHandle {
 275    pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
 276        let id = handles.write().insert(AtomicUsize::new(1));
 277        Self {
 278            id,
 279            handles: handles.clone(),
 280        }
 281    }
 282
 283    pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
 284        let lock = handles.read();
 285        let ref_count = lock.get(id)?;
 286        if atomic_incr_if_not_zero(ref_count) == 0 {
 287            return None;
 288        }
 289        Some(Self {
 290            id,
 291            handles: handles.clone(),
 292        })
 293    }
 294
 295    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
 296    pub fn downgrade(&self) -> WeakFocusHandle {
 297        WeakFocusHandle {
 298            id: self.id,
 299            handles: Arc::downgrade(&self.handles),
 300        }
 301    }
 302
 303    /// Moves the focus to the element associated with this handle.
 304    pub fn focus(&self, window: &mut Window) {
 305        window.focus(self)
 306    }
 307
 308    /// Obtains whether the element associated with this handle is currently focused.
 309    pub fn is_focused(&self, window: &Window) -> bool {
 310        self.id.is_focused(window)
 311    }
 312
 313    /// Obtains whether the element associated with this handle contains the focused
 314    /// element or is itself focused.
 315    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
 316        self.id.contains_focused(window, cx)
 317    }
 318
 319    /// Obtains whether the element associated with this handle is contained within the
 320    /// focused element or is itself focused.
 321    pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
 322        self.id.within_focused(window, cx)
 323    }
 324
 325    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 326    pub fn contains(&self, other: &Self, window: &Window) -> bool {
 327        self.id.contains(other.id, window)
 328    }
 329
 330    /// Dispatch an action on the element that rendered this focus handle
 331    pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
 332        if let Some(node_id) = window
 333            .rendered_frame
 334            .dispatch_tree
 335            .focusable_node_id(self.id)
 336        {
 337            window.dispatch_action_on_node(node_id, action, cx)
 338        }
 339    }
 340}
 341
 342impl Clone for FocusHandle {
 343    fn clone(&self) -> Self {
 344        Self::for_id(self.id, &self.handles).unwrap()
 345    }
 346}
 347
 348impl PartialEq for FocusHandle {
 349    fn eq(&self, other: &Self) -> bool {
 350        self.id == other.id
 351    }
 352}
 353
 354impl Eq for FocusHandle {}
 355
 356impl Drop for FocusHandle {
 357    fn drop(&mut self) {
 358        self.handles
 359            .read()
 360            .get(self.id)
 361            .unwrap()
 362            .fetch_sub(1, SeqCst);
 363    }
 364}
 365
 366/// A weak reference to a focus handle.
 367#[derive(Clone, Debug)]
 368pub struct WeakFocusHandle {
 369    pub(crate) id: FocusId,
 370    pub(crate) handles: Weak<FocusMap>,
 371}
 372
 373impl WeakFocusHandle {
 374    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
 375    pub fn upgrade(&self) -> Option<FocusHandle> {
 376        let handles = self.handles.upgrade()?;
 377        FocusHandle::for_id(self.id, &handles)
 378    }
 379}
 380
 381impl PartialEq for WeakFocusHandle {
 382    fn eq(&self, other: &WeakFocusHandle) -> bool {
 383        self.id == other.id
 384    }
 385}
 386
 387impl Eq for WeakFocusHandle {}
 388
 389impl PartialEq<FocusHandle> for WeakFocusHandle {
 390    fn eq(&self, other: &FocusHandle) -> bool {
 391        self.id == other.id
 392    }
 393}
 394
 395impl PartialEq<WeakFocusHandle> for FocusHandle {
 396    fn eq(&self, other: &WeakFocusHandle) -> bool {
 397        self.id == other.id
 398    }
 399}
 400
 401/// Focusable allows users of your view to easily
 402/// focus it (using window.focus_view(cx, view))
 403pub trait Focusable: 'static {
 404    /// Returns the focus handle associated with this view.
 405    fn focus_handle(&self, cx: &App) -> FocusHandle;
 406}
 407
 408impl<V: Focusable> Focusable for Entity<V> {
 409    fn focus_handle(&self, cx: &App) -> FocusHandle {
 410        self.read(cx).focus_handle(cx)
 411    }
 412}
 413
 414/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 415/// where the lifecycle of the view is handled by another view.
 416pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
 417
 418impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
 419
 420/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 421pub struct DismissEvent;
 422
 423type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
 424
 425pub(crate) type AnyMouseListener =
 426    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
 427
 428#[derive(Clone)]
 429pub(crate) struct CursorStyleRequest {
 430    pub(crate) hitbox_id: Option<HitboxId>,
 431    pub(crate) style: CursorStyle,
 432}
 433
 434#[derive(Default, Eq, PartialEq)]
 435pub(crate) struct HitTest {
 436    pub(crate) ids: SmallVec<[HitboxId; 8]>,
 437    pub(crate) hover_hitbox_count: usize,
 438}
 439
 440/// A type of window control area that corresponds to the platform window.
 441#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 442pub enum WindowControlArea {
 443    /// An area that allows dragging of the platform window.
 444    Drag,
 445    /// An area that allows closing of the platform window.
 446    Close,
 447    /// An area that allows maximizing of the platform window.
 448    Max,
 449    /// An area that allows minimizing of the platform window.
 450    Min,
 451}
 452
 453/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
 454#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
 455pub struct HitboxId(u64);
 456
 457impl HitboxId {
 458    /// Checks if the hitbox with this ID is currently hovered. Except when handling
 459    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
 460    /// events or paint hover styles.
 461    ///
 462    /// See [`Hitbox::is_hovered`] for details.
 463    pub fn is_hovered(self, window: &Window) -> bool {
 464        let hit_test = &window.mouse_hit_test;
 465        for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
 466            if self == *id {
 467                return true;
 468            }
 469        }
 470        return false;
 471    }
 472
 473    /// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
 474    /// Typically this should only be used when handling `ScrollWheelEvent`, and otherwise
 475    /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
 476    /// this distinction.
 477    pub fn should_handle_scroll(self, window: &Window) -> bool {
 478        window.mouse_hit_test.ids.contains(&self)
 479    }
 480
 481    fn next(mut self) -> HitboxId {
 482        HitboxId(self.0.wrapping_add(1))
 483    }
 484}
 485
 486/// A rectangular region that potentially blocks hitboxes inserted prior.
 487/// See [Window::insert_hitbox] for more details.
 488#[derive(Clone, Debug, Deref)]
 489pub struct Hitbox {
 490    /// A unique identifier for the hitbox.
 491    pub id: HitboxId,
 492    /// The bounds of the hitbox.
 493    #[deref]
 494    pub bounds: Bounds<Pixels>,
 495    /// The content mask when the hitbox was inserted.
 496    pub content_mask: ContentMask<Pixels>,
 497    /// Flags that specify hitbox behavior.
 498    pub behavior: HitboxBehavior,
 499}
 500
 501impl Hitbox {
 502    /// Checks if the hitbox is currently hovered. Except when handling `ScrollWheelEvent`, this is
 503    /// typically what you want when determining whether to handle mouse events or paint hover
 504    /// styles.
 505    ///
 506    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
 507    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
 508    /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`).
 509    ///
 510    /// Handling of `ScrollWheelEvent` should typically use `should_handle_scroll` instead.
 511    /// Concretely, this is due to use-cases like overlays that cause the elements under to be
 512    /// non-interactive while still allowing scrolling. More abstractly, this is because
 513    /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
 514    /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
 515    /// container.
 516    pub fn is_hovered(&self, window: &Window) -> bool {
 517        self.id.is_hovered(window)
 518    }
 519
 520    /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
 521    /// should only be used when handling `ScrollWheelEvent`, and otherwise `is_hovered` should be
 522    /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
 523    ///
 524    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
 525    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
 526    pub fn should_handle_scroll(&self, window: &Window) -> bool {
 527        self.id.should_handle_scroll(window)
 528    }
 529}
 530
 531/// How the hitbox affects mouse behavior.
 532#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
 533pub enum HitboxBehavior {
 534    /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
 535    #[default]
 536    Normal,
 537
 538    /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
 539    /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
 540    /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
 541    /// [`InteractiveElement::occlude`].
 542    ///
 543    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
 544    /// bubble-phase handler for every mouse event type:
 545    ///
 546    /// ```
 547    /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
 548    ///     if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
 549    ///         cx.stop_propagation();
 550    ///     }
 551    /// }
 552    /// ```
 553    ///
 554    /// This has effects beyond event handling - any use of hitbox checking, such as hover
 555    /// styles and tooltops. These other behaviors are the main point of this mechanism. An
 556    /// alternative might be to not affect mouse event handling - but this would allow
 557    /// inconsistent UI where clicks and moves interact with elements that are not considered to
 558    /// be hovered.
 559    BlockMouse,
 560
 561    /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
 562    /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
 563    /// interaction except scroll events to be ignored - see the documentation of
 564    /// [`Hitbox::is_hovered`] for details. This flag is set by
 565    /// [`InteractiveElement::block_mouse_except_scroll`].
 566    ///
 567    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
 568    /// bubble-phase handler for every mouse event type **except** `ScrollWheelEvent`:
 569    ///
 570    /// ```
 571    /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, _cx| {
 572    ///     if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 573    ///         cx.stop_propagation();
 574    ///     }
 575    /// }
 576    /// ```
 577    ///
 578    /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollWheelEvent` is
 579    /// handled differently than other mouse events. If also blocking these scroll events is
 580    /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
 581    ///
 582    /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
 583    /// hover styles and tooltops. These other behaviors are the main point of this mechanism.
 584    /// An alternative might be to not affect mouse event handling - but this would allow
 585    /// inconsistent UI where clicks and moves interact with elements that are not considered to
 586    /// be hovered.
 587    BlockMouseExceptScroll,
 588}
 589
 590/// An identifier for a tooltip.
 591#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 592pub struct TooltipId(usize);
 593
 594impl TooltipId {
 595    /// Checks if the tooltip is currently hovered.
 596    pub fn is_hovered(&self, window: &Window) -> bool {
 597        window
 598            .tooltip_bounds
 599            .as_ref()
 600            .map_or(false, |tooltip_bounds| {
 601                tooltip_bounds.id == *self
 602                    && tooltip_bounds.bounds.contains(&window.mouse_position())
 603            })
 604    }
 605}
 606
 607pub(crate) struct TooltipBounds {
 608    id: TooltipId,
 609    bounds: Bounds<Pixels>,
 610}
 611
 612#[derive(Clone)]
 613pub(crate) struct TooltipRequest {
 614    id: TooltipId,
 615    tooltip: AnyTooltip,
 616}
 617
 618pub(crate) struct DeferredDraw {
 619    current_view: EntityId,
 620    priority: usize,
 621    parent_node: DispatchNodeId,
 622    element_id_stack: SmallVec<[ElementId; 32]>,
 623    text_style_stack: Vec<TextStyleRefinement>,
 624    element: Option<AnyElement>,
 625    absolute_offset: Point<Pixels>,
 626    prepaint_range: Range<PrepaintStateIndex>,
 627    paint_range: Range<PaintIndex>,
 628}
 629
 630pub(crate) struct Frame {
 631    pub(crate) focus: Option<FocusId>,
 632    pub(crate) window_active: bool,
 633    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
 634    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
 635    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
 636    pub(crate) dispatch_tree: DispatchTree,
 637    pub(crate) scene: Scene,
 638    pub(crate) hitboxes: Vec<Hitbox>,
 639    pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
 640    pub(crate) deferred_draws: Vec<DeferredDraw>,
 641    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
 642    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
 643    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
 644    #[cfg(any(test, feature = "test-support"))]
 645    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
 646    #[cfg(any(feature = "inspector", debug_assertions))]
 647    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
 648    #[cfg(any(feature = "inspector", debug_assertions))]
 649    pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
 650}
 651
 652#[derive(Clone, Default)]
 653pub(crate) struct PrepaintStateIndex {
 654    hitboxes_index: usize,
 655    tooltips_index: usize,
 656    deferred_draws_index: usize,
 657    dispatch_tree_index: usize,
 658    accessed_element_states_index: usize,
 659    line_layout_index: LineLayoutIndex,
 660}
 661
 662#[derive(Clone, Default)]
 663pub(crate) struct PaintIndex {
 664    scene_index: usize,
 665    mouse_listeners_index: usize,
 666    input_handlers_index: usize,
 667    cursor_styles_index: usize,
 668    accessed_element_states_index: usize,
 669    line_layout_index: LineLayoutIndex,
 670}
 671
 672impl Frame {
 673    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
 674        Frame {
 675            focus: None,
 676            window_active: false,
 677            element_states: FxHashMap::default(),
 678            accessed_element_states: Vec::new(),
 679            mouse_listeners: Vec::new(),
 680            dispatch_tree,
 681            scene: Scene::default(),
 682            hitboxes: Vec::new(),
 683            window_control_hitboxes: Vec::new(),
 684            deferred_draws: Vec::new(),
 685            input_handlers: Vec::new(),
 686            tooltip_requests: Vec::new(),
 687            cursor_styles: Vec::new(),
 688
 689            #[cfg(any(test, feature = "test-support"))]
 690            debug_bounds: FxHashMap::default(),
 691
 692            #[cfg(any(feature = "inspector", debug_assertions))]
 693            next_inspector_instance_ids: FxHashMap::default(),
 694
 695            #[cfg(any(feature = "inspector", debug_assertions))]
 696            inspector_hitboxes: FxHashMap::default(),
 697        }
 698    }
 699
 700    pub(crate) fn clear(&mut self) {
 701        self.element_states.clear();
 702        self.accessed_element_states.clear();
 703        self.mouse_listeners.clear();
 704        self.dispatch_tree.clear();
 705        self.scene.clear();
 706        self.input_handlers.clear();
 707        self.tooltip_requests.clear();
 708        self.cursor_styles.clear();
 709        self.hitboxes.clear();
 710        self.window_control_hitboxes.clear();
 711        self.deferred_draws.clear();
 712        self.focus = None;
 713
 714        #[cfg(any(feature = "inspector", debug_assertions))]
 715        {
 716            self.next_inspector_instance_ids.clear();
 717            self.inspector_hitboxes.clear();
 718        }
 719    }
 720
 721    pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
 722        self.cursor_styles
 723            .iter()
 724            .rev()
 725            .fold_while(None, |style, request| match request.hitbox_id {
 726                None => Done(Some(request.style)),
 727                Some(hitbox_id) => Continue(
 728                    style.or_else(|| hitbox_id.is_hovered(window).then_some(request.style)),
 729                ),
 730            })
 731            .into_inner()
 732    }
 733
 734    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
 735        let mut set_hover_hitbox_count = false;
 736        let mut hit_test = HitTest::default();
 737        for hitbox in self.hitboxes.iter().rev() {
 738            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
 739            if bounds.contains(&position) {
 740                hit_test.ids.push(hitbox.id);
 741                if !set_hover_hitbox_count
 742                    && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
 743                {
 744                    hit_test.hover_hitbox_count = hit_test.ids.len();
 745                    set_hover_hitbox_count = true;
 746                }
 747                if hitbox.behavior == HitboxBehavior::BlockMouse {
 748                    break;
 749                }
 750            }
 751        }
 752        if !set_hover_hitbox_count {
 753            hit_test.hover_hitbox_count = hit_test.ids.len();
 754        }
 755        hit_test
 756    }
 757
 758    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 759        self.focus
 760            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 761            .unwrap_or_default()
 762    }
 763
 764    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
 765        for element_state_key in &self.accessed_element_states {
 766            if let Some((element_state_key, element_state)) =
 767                prev_frame.element_states.remove_entry(element_state_key)
 768            {
 769                self.element_states.insert(element_state_key, element_state);
 770            }
 771        }
 772
 773        self.scene.finish();
 774    }
 775}
 776
 777/// Holds the state for a specific window.
 778pub struct Window {
 779    pub(crate) handle: AnyWindowHandle,
 780    pub(crate) invalidator: WindowInvalidator,
 781    pub(crate) removed: bool,
 782    pub(crate) platform_window: Box<dyn PlatformWindow>,
 783    display_id: Option<DisplayId>,
 784    sprite_atlas: Arc<dyn PlatformAtlas>,
 785    text_system: Arc<WindowTextSystem>,
 786    rem_size: Pixels,
 787    /// The stack of override values for the window's rem size.
 788    ///
 789    /// This is used by `with_rem_size` to allow rendering an element tree with
 790    /// a given rem size.
 791    rem_size_override_stack: SmallVec<[Pixels; 8]>,
 792    pub(crate) viewport_size: Size<Pixels>,
 793    layout_engine: Option<TaffyLayoutEngine>,
 794    pub(crate) root: Option<AnyView>,
 795    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
 796    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
 797    pub(crate) rendered_entity_stack: Vec<EntityId>,
 798    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
 799    pub(crate) element_opacity: Option<f32>,
 800    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
 801    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
 802    pub(crate) image_cache_stack: Vec<AnyImageCache>,
 803    pub(crate) rendered_frame: Frame,
 804    pub(crate) next_frame: Frame,
 805    next_hitbox_id: HitboxId,
 806    pub(crate) next_tooltip_id: TooltipId,
 807    pub(crate) tooltip_bounds: Option<TooltipBounds>,
 808    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
 809    pub(crate) dirty_views: FxHashSet<EntityId>,
 810    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 811    pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 812    default_prevented: bool,
 813    mouse_position: Point<Pixels>,
 814    mouse_hit_test: HitTest,
 815    modifiers: Modifiers,
 816    capslock: Capslock,
 817    scale_factor: f32,
 818    pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
 819    appearance: WindowAppearance,
 820    pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
 821    active: Rc<Cell<bool>>,
 822    hovered: Rc<Cell<bool>>,
 823    pub(crate) needs_present: Rc<Cell<bool>>,
 824    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
 825    pub(crate) refreshing: bool,
 826    pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
 827    pub(crate) focus: Option<FocusId>,
 828    focus_enabled: bool,
 829    pending_input: Option<PendingInput>,
 830    pending_modifier: ModifierState,
 831    pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
 832    prompt: Option<RenderablePromptHandle>,
 833    pub(crate) client_inset: Option<Pixels>,
 834    #[cfg(any(feature = "inspector", debug_assertions))]
 835    inspector: Option<Entity<Inspector>>,
 836}
 837
 838#[derive(Clone, Debug, Default)]
 839struct ModifierState {
 840    modifiers: Modifiers,
 841    saw_keystroke: bool,
 842}
 843
 844#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 845pub(crate) enum DrawPhase {
 846    None,
 847    Prepaint,
 848    Paint,
 849    Focus,
 850}
 851
 852#[derive(Default, Debug)]
 853struct PendingInput {
 854    keystrokes: SmallVec<[Keystroke; 1]>,
 855    focus: Option<FocusId>,
 856    timer: Option<Task<()>>,
 857}
 858
 859pub(crate) struct ElementStateBox {
 860    pub(crate) inner: Box<dyn Any>,
 861    #[cfg(debug_assertions)]
 862    pub(crate) type_name: &'static str,
 863}
 864
 865fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> Bounds<Pixels> {
 866    const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
 867
 868    // TODO, BUG: if you open a window with the currently active window
 869    // on the stack, this will erroneously select the 'unwrap_or_else'
 870    // code path
 871    cx.active_window()
 872        .and_then(|w| w.update(cx, |_, window, _| window.bounds()).ok())
 873        .map(|mut bounds| {
 874            bounds.origin += DEFAULT_WINDOW_OFFSET;
 875            bounds
 876        })
 877        .unwrap_or_else(|| {
 878            let display = display_id
 879                .map(|id| cx.find_display(id))
 880                .unwrap_or_else(|| cx.primary_display());
 881
 882            display
 883                .map(|display| display.default_bounds())
 884                .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
 885        })
 886}
 887
 888impl Window {
 889    pub(crate) fn new(
 890        handle: AnyWindowHandle,
 891        options: WindowOptions,
 892        cx: &mut App,
 893    ) -> Result<Self> {
 894        let WindowOptions {
 895            window_bounds,
 896            titlebar,
 897            focus,
 898            show,
 899            kind,
 900            is_movable,
 901            display_id,
 902            window_background,
 903            app_id,
 904            window_min_size,
 905            window_decorations,
 906        } = options;
 907
 908        let bounds = window_bounds
 909            .map(|bounds| bounds.get_bounds())
 910            .unwrap_or_else(|| default_bounds(display_id, cx));
 911        let mut platform_window = cx.platform.open_window(
 912            handle,
 913            WindowParams {
 914                bounds,
 915                titlebar,
 916                kind,
 917                is_movable,
 918                focus,
 919                show,
 920                display_id,
 921                window_min_size,
 922            },
 923        )?;
 924        let display_id = platform_window.display().map(|display| display.id());
 925        let sprite_atlas = platform_window.sprite_atlas();
 926        let mouse_position = platform_window.mouse_position();
 927        let modifiers = platform_window.modifiers();
 928        let capslock = platform_window.capslock();
 929        let content_size = platform_window.content_size();
 930        let scale_factor = platform_window.scale_factor();
 931        let appearance = platform_window.appearance();
 932        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
 933        let invalidator = WindowInvalidator::new();
 934        let active = Rc::new(Cell::new(platform_window.is_active()));
 935        let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
 936        let needs_present = Rc::new(Cell::new(false));
 937        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
 938        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
 939
 940        platform_window
 941            .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
 942        platform_window.set_background_appearance(window_background);
 943
 944        if let Some(ref window_open_state) = window_bounds {
 945            match window_open_state {
 946                WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
 947                WindowBounds::Maximized(_) => platform_window.zoom(),
 948                WindowBounds::Windowed(_) => {}
 949            }
 950        }
 951
 952        platform_window.on_close(Box::new({
 953            let mut cx = cx.to_async();
 954            move || {
 955                let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
 956            }
 957        }));
 958        platform_window.on_request_frame(Box::new({
 959            let mut cx = cx.to_async();
 960            let invalidator = invalidator.clone();
 961            let active = active.clone();
 962            let needs_present = needs_present.clone();
 963            let next_frame_callbacks = next_frame_callbacks.clone();
 964            let last_input_timestamp = last_input_timestamp.clone();
 965            move |request_frame_options| {
 966                let next_frame_callbacks = next_frame_callbacks.take();
 967                if !next_frame_callbacks.is_empty() {
 968                    handle
 969                        .update(&mut cx, |_, window, cx| {
 970                            for callback in next_frame_callbacks {
 971                                callback(window, cx);
 972                            }
 973                        })
 974                        .log_err();
 975                }
 976
 977                // Keep presenting the current scene for 1 extra second since the
 978                // last input to prevent the display from underclocking the refresh rate.
 979                let needs_present = request_frame_options.require_presentation
 980                    || needs_present.get()
 981                    || (active.get()
 982                        && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
 983
 984                if invalidator.is_dirty() {
 985                    measure("frame duration", || {
 986                        handle
 987                            .update(&mut cx, |_, window, cx| {
 988                                let arena_clear_needed = window.draw(cx);
 989                                window.present();
 990                                // drop the arena elements after present to reduce latency
 991                                arena_clear_needed.clear();
 992                            })
 993                            .log_err();
 994                    })
 995                } else if needs_present {
 996                    handle
 997                        .update(&mut cx, |_, window, _| window.present())
 998                        .log_err();
 999                }
1000
1001                handle
1002                    .update(&mut cx, |_, window, _| {
1003                        window.complete_frame();
1004                    })
1005                    .log_err();
1006            }
1007        }));
1008        platform_window.on_resize(Box::new({
1009            let mut cx = cx.to_async();
1010            move |_, _| {
1011                handle
1012                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1013                    .log_err();
1014            }
1015        }));
1016        platform_window.on_moved(Box::new({
1017            let mut cx = cx.to_async();
1018            move || {
1019                handle
1020                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1021                    .log_err();
1022            }
1023        }));
1024        platform_window.on_appearance_changed(Box::new({
1025            let mut cx = cx.to_async();
1026            move || {
1027                handle
1028                    .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1029                    .log_err();
1030            }
1031        }));
1032        platform_window.on_active_status_change(Box::new({
1033            let mut cx = cx.to_async();
1034            move |active| {
1035                handle
1036                    .update(&mut cx, |_, window, cx| {
1037                        window.active.set(active);
1038                        window.modifiers = window.platform_window.modifiers();
1039                        window.capslock = window.platform_window.capslock();
1040                        window
1041                            .activation_observers
1042                            .clone()
1043                            .retain(&(), |callback| callback(window, cx));
1044                        window.refresh();
1045                    })
1046                    .log_err();
1047            }
1048        }));
1049        platform_window.on_hover_status_change(Box::new({
1050            let mut cx = cx.to_async();
1051            move |active| {
1052                handle
1053                    .update(&mut cx, |_, window, _| {
1054                        window.hovered.set(active);
1055                        window.refresh();
1056                    })
1057                    .log_err();
1058            }
1059        }));
1060        platform_window.on_input({
1061            let mut cx = cx.to_async();
1062            Box::new(move |event| {
1063                handle
1064                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1065                    .log_err()
1066                    .unwrap_or(DispatchEventResult::default())
1067            })
1068        });
1069        platform_window.on_hit_test_window_control({
1070            let mut cx = cx.to_async();
1071            Box::new(move || {
1072                handle
1073                    .update(&mut cx, |_, window, _cx| {
1074                        for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1075                            if window.mouse_hit_test.ids.contains(&hitbox.id) {
1076                                return Some(*area);
1077                            }
1078                        }
1079                        None
1080                    })
1081                    .log_err()
1082                    .unwrap_or(None)
1083            })
1084        });
1085
1086        if let Some(app_id) = app_id {
1087            platform_window.set_app_id(&app_id);
1088        }
1089
1090        platform_window.map_window().unwrap();
1091
1092        Ok(Window {
1093            handle,
1094            invalidator,
1095            removed: false,
1096            platform_window,
1097            display_id,
1098            sprite_atlas,
1099            text_system,
1100            rem_size: px(16.),
1101            rem_size_override_stack: SmallVec::new(),
1102            viewport_size: content_size,
1103            layout_engine: Some(TaffyLayoutEngine::new()),
1104            root: None,
1105            element_id_stack: SmallVec::default(),
1106            text_style_stack: Vec::new(),
1107            rendered_entity_stack: Vec::new(),
1108            element_offset_stack: Vec::new(),
1109            content_mask_stack: Vec::new(),
1110            element_opacity: None,
1111            requested_autoscroll: None,
1112            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1113            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1114            next_frame_callbacks,
1115            next_hitbox_id: HitboxId(0),
1116            next_tooltip_id: TooltipId::default(),
1117            tooltip_bounds: None,
1118            dirty_views: FxHashSet::default(),
1119            focus_listeners: SubscriberSet::new(),
1120            focus_lost_listeners: SubscriberSet::new(),
1121            default_prevented: true,
1122            mouse_position,
1123            mouse_hit_test: HitTest::default(),
1124            modifiers,
1125            capslock,
1126            scale_factor,
1127            bounds_observers: SubscriberSet::new(),
1128            appearance,
1129            appearance_observers: SubscriberSet::new(),
1130            active,
1131            hovered,
1132            needs_present,
1133            last_input_timestamp,
1134            refreshing: false,
1135            activation_observers: SubscriberSet::new(),
1136            focus: None,
1137            focus_enabled: true,
1138            pending_input: None,
1139            pending_modifier: ModifierState::default(),
1140            pending_input_observers: SubscriberSet::new(),
1141            prompt: None,
1142            client_inset: None,
1143            image_cache_stack: Vec::new(),
1144            #[cfg(any(feature = "inspector", debug_assertions))]
1145            inspector: None,
1146        })
1147    }
1148
1149    pub(crate) fn new_focus_listener(
1150        &self,
1151        value: AnyWindowFocusListener,
1152    ) -> (Subscription, impl FnOnce() + use<>) {
1153        self.focus_listeners.insert((), value)
1154    }
1155}
1156
1157#[derive(Clone, Debug, Default, PartialEq, Eq)]
1158pub(crate) struct DispatchEventResult {
1159    pub propagate: bool,
1160    pub default_prevented: bool,
1161}
1162
1163/// Indicates which region of the window is visible. Content falling outside of this mask will not be
1164/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
1165/// to leave room to support more complex shapes in the future.
1166#[derive(Clone, Debug, Default, PartialEq, Eq)]
1167#[repr(C)]
1168pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1169    /// The bounds
1170    pub bounds: Bounds<P>,
1171}
1172
1173impl ContentMask<Pixels> {
1174    /// Scale the content mask's pixel units by the given scaling factor.
1175    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1176        ContentMask {
1177            bounds: self.bounds.scale(factor),
1178        }
1179    }
1180
1181    /// Intersect the content mask with the given content mask.
1182    pub fn intersect(&self, other: &Self) -> Self {
1183        let bounds = self.bounds.intersect(&other.bounds);
1184        ContentMask { bounds }
1185    }
1186}
1187
1188impl Window {
1189    fn mark_view_dirty(&mut self, view_id: EntityId) {
1190        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
1191        // should already be dirty.
1192        for view_id in self
1193            .rendered_frame
1194            .dispatch_tree
1195            .view_path(view_id)
1196            .into_iter()
1197            .rev()
1198        {
1199            if !self.dirty_views.insert(view_id) {
1200                break;
1201            }
1202        }
1203    }
1204
1205    /// Registers a callback to be invoked when the window appearance changes.
1206    pub fn observe_window_appearance(
1207        &self,
1208        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1209    ) -> Subscription {
1210        let (subscription, activate) = self.appearance_observers.insert(
1211            (),
1212            Box::new(move |window, cx| {
1213                callback(window, cx);
1214                true
1215            }),
1216        );
1217        activate();
1218        subscription
1219    }
1220
1221    /// Replaces the root entity of the window with a new one.
1222    pub fn replace_root<E>(
1223        &mut self,
1224        cx: &mut App,
1225        build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1226    ) -> Entity<E>
1227    where
1228        E: 'static + Render,
1229    {
1230        let view = cx.new(|cx| build_view(self, cx));
1231        self.root = Some(view.clone().into());
1232        self.refresh();
1233        view
1234    }
1235
1236    /// Returns the root entity of the window, if it has one.
1237    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1238    where
1239        E: 'static + Render,
1240    {
1241        self.root
1242            .as_ref()
1243            .map(|view| view.clone().downcast::<E>().ok())
1244    }
1245
1246    /// Obtain a handle to the window that belongs to this context.
1247    pub fn window_handle(&self) -> AnyWindowHandle {
1248        self.handle
1249    }
1250
1251    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1252    pub fn refresh(&mut self) {
1253        if self.invalidator.not_drawing() {
1254            self.refreshing = true;
1255            self.invalidator.set_dirty(true);
1256        }
1257    }
1258
1259    /// Close this window.
1260    pub fn remove_window(&mut self) {
1261        self.removed = true;
1262    }
1263
1264    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1265    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1266        self.focus
1267            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1268    }
1269
1270    /// Move focus to the element associated with the given [`FocusHandle`].
1271    pub fn focus(&mut self, handle: &FocusHandle) {
1272        if !self.focus_enabled || self.focus == Some(handle.id) {
1273            return;
1274        }
1275
1276        self.focus = Some(handle.id);
1277        self.clear_pending_keystrokes();
1278        self.refresh();
1279    }
1280
1281    /// Remove focus from all elements within this context's window.
1282    pub fn blur(&mut self) {
1283        if !self.focus_enabled {
1284            return;
1285        }
1286
1287        self.focus = None;
1288        self.refresh();
1289    }
1290
1291    /// Blur the window and don't allow anything in it to be focused again.
1292    pub fn disable_focus(&mut self) {
1293        self.blur();
1294        self.focus_enabled = false;
1295    }
1296
1297    /// Accessor for the text system.
1298    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1299        &self.text_system
1300    }
1301
1302    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1303    pub fn text_style(&self) -> TextStyle {
1304        let mut style = TextStyle::default();
1305        for refinement in &self.text_style_stack {
1306            style.refine(refinement);
1307        }
1308        style
1309    }
1310
1311    /// Check if the platform window is maximized
1312    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1313    pub fn is_maximized(&self) -> bool {
1314        self.platform_window.is_maximized()
1315    }
1316
1317    /// request a certain window decoration (Wayland)
1318    pub fn request_decorations(&self, decorations: WindowDecorations) {
1319        self.platform_window.request_decorations(decorations);
1320    }
1321
1322    /// Start a window resize operation (Wayland)
1323    pub fn start_window_resize(&self, edge: ResizeEdge) {
1324        self.platform_window.start_window_resize(edge);
1325    }
1326
1327    /// Return the `WindowBounds` to indicate that how a window should be opened
1328    /// after it has been closed
1329    pub fn window_bounds(&self) -> WindowBounds {
1330        self.platform_window.window_bounds()
1331    }
1332
1333    /// Return the `WindowBounds` excluding insets (Wayland and X11)
1334    pub fn inner_window_bounds(&self) -> WindowBounds {
1335        self.platform_window.inner_window_bounds()
1336    }
1337
1338    /// Dispatch the given action on the currently focused element.
1339    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1340        let focus_id = self.focused(cx).map(|handle| handle.id);
1341
1342        let window = self.handle;
1343        cx.defer(move |cx| {
1344            window
1345                .update(cx, |_, window, cx| {
1346                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1347                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1348                })
1349                .log_err();
1350        })
1351    }
1352
1353    pub(crate) fn dispatch_keystroke_observers(
1354        &mut self,
1355        event: &dyn Any,
1356        action: Option<Box<dyn Action>>,
1357        context_stack: Vec<KeyContext>,
1358        cx: &mut App,
1359    ) {
1360        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1361            return;
1362        };
1363
1364        cx.keystroke_observers.clone().retain(&(), move |callback| {
1365            (callback)(
1366                &KeystrokeEvent {
1367                    keystroke: key_down_event.keystroke.clone(),
1368                    action: action.as_ref().map(|action| action.boxed_clone()),
1369                    context_stack: context_stack.clone(),
1370                },
1371                self,
1372                cx,
1373            )
1374        });
1375    }
1376
1377    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1378    /// that are currently on the stack to be returned to the app.
1379    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1380        let handle = self.handle;
1381        cx.defer(move |cx| {
1382            handle.update(cx, |_, window, cx| f(window, cx)).ok();
1383        });
1384    }
1385
1386    /// Subscribe to events emitted by a entity.
1387    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1388    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1389    pub fn observe<T: 'static>(
1390        &mut self,
1391        observed: &Entity<T>,
1392        cx: &mut App,
1393        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1394    ) -> Subscription {
1395        let entity_id = observed.entity_id();
1396        let observed = observed.downgrade();
1397        let window_handle = self.handle;
1398        cx.new_observer(
1399            entity_id,
1400            Box::new(move |cx| {
1401                window_handle
1402                    .update(cx, |_, window, cx| {
1403                        if let Some(handle) = observed.upgrade() {
1404                            on_notify(handle, window, cx);
1405                            true
1406                        } else {
1407                            false
1408                        }
1409                    })
1410                    .unwrap_or(false)
1411            }),
1412        )
1413    }
1414
1415    /// Subscribe to events emitted by a entity.
1416    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1417    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1418    pub fn subscribe<Emitter, Evt>(
1419        &mut self,
1420        entity: &Entity<Emitter>,
1421        cx: &mut App,
1422        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1423    ) -> Subscription
1424    where
1425        Emitter: EventEmitter<Evt>,
1426        Evt: 'static,
1427    {
1428        let entity_id = entity.entity_id();
1429        let handle = entity.downgrade();
1430        let window_handle = self.handle;
1431        cx.new_subscription(
1432            entity_id,
1433            (
1434                TypeId::of::<Evt>(),
1435                Box::new(move |event, cx| {
1436                    window_handle
1437                        .update(cx, |_, window, cx| {
1438                            if let Some(entity) = handle.upgrade() {
1439                                let event = event.downcast_ref().expect("invalid event type");
1440                                on_event(entity, event, window, cx);
1441                                true
1442                            } else {
1443                                false
1444                            }
1445                        })
1446                        .unwrap_or(false)
1447                }),
1448            ),
1449        )
1450    }
1451
1452    /// Register a callback to be invoked when the given `Entity` is released.
1453    pub fn observe_release<T>(
1454        &self,
1455        entity: &Entity<T>,
1456        cx: &mut App,
1457        mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1458    ) -> Subscription
1459    where
1460        T: 'static,
1461    {
1462        let entity_id = entity.entity_id();
1463        let window_handle = self.handle;
1464        let (subscription, activate) = cx.release_listeners.insert(
1465            entity_id,
1466            Box::new(move |entity, cx| {
1467                let entity = entity.downcast_mut().expect("invalid entity type");
1468                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1469            }),
1470        );
1471        activate();
1472        subscription
1473    }
1474
1475    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1476    /// await points in async code.
1477    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1478        AsyncWindowContext::new_context(cx.to_async(), self.handle)
1479    }
1480
1481    /// Schedule the given closure to be run directly after the current frame is rendered.
1482    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1483        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1484    }
1485
1486    /// Schedule a frame to be drawn on the next animation frame.
1487    ///
1488    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
1489    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
1490    ///
1491    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
1492    pub fn request_animation_frame(&self) {
1493        let entity = self.current_view();
1494        self.on_next_frame(move |_, cx| cx.notify(entity));
1495    }
1496
1497    /// Spawn the future returned by the given closure on the application thread pool.
1498    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1499    /// use within your future.
1500    #[track_caller]
1501    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
1502    where
1503        R: 'static,
1504        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1505    {
1506        let handle = self.handle;
1507        cx.spawn(async move |app| {
1508            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1509            f(&mut async_window_cx).await
1510        })
1511    }
1512
1513    fn bounds_changed(&mut self, cx: &mut App) {
1514        self.scale_factor = self.platform_window.scale_factor();
1515        self.viewport_size = self.platform_window.content_size();
1516        self.display_id = self.platform_window.display().map(|display| display.id());
1517
1518        self.refresh();
1519
1520        self.bounds_observers
1521            .clone()
1522            .retain(&(), |callback| callback(self, cx));
1523    }
1524
1525    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1526    pub fn bounds(&self) -> Bounds<Pixels> {
1527        self.platform_window.bounds()
1528    }
1529
1530    /// Set the content size of the window.
1531    pub fn resize(&mut self, size: Size<Pixels>) {
1532        self.platform_window.resize(size);
1533    }
1534
1535    /// Returns whether or not the window is currently fullscreen
1536    pub fn is_fullscreen(&self) -> bool {
1537        self.platform_window.is_fullscreen()
1538    }
1539
1540    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1541        self.appearance = self.platform_window.appearance();
1542
1543        self.appearance_observers
1544            .clone()
1545            .retain(&(), |callback| callback(self, cx));
1546    }
1547
1548    /// Returns the appearance of the current window.
1549    pub fn appearance(&self) -> WindowAppearance {
1550        self.appearance
1551    }
1552
1553    /// Returns the size of the drawable area within the window.
1554    pub fn viewport_size(&self) -> Size<Pixels> {
1555        self.viewport_size
1556    }
1557
1558    /// Returns whether this window is focused by the operating system (receiving key events).
1559    pub fn is_window_active(&self) -> bool {
1560        self.active.get()
1561    }
1562
1563    /// Returns whether this window is considered to be the window
1564    /// that currently owns the mouse cursor.
1565    /// On mac, this is equivalent to `is_window_active`.
1566    pub fn is_window_hovered(&self) -> bool {
1567        if cfg!(any(
1568            target_os = "windows",
1569            target_os = "linux",
1570            target_os = "freebsd"
1571        )) {
1572            self.hovered.get()
1573        } else {
1574            self.is_window_active()
1575        }
1576    }
1577
1578    /// Toggle zoom on the window.
1579    pub fn zoom_window(&self) {
1580        self.platform_window.zoom();
1581    }
1582
1583    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1584    pub fn show_window_menu(&self, position: Point<Pixels>) {
1585        self.platform_window.show_window_menu(position)
1586    }
1587
1588    /// Tells the compositor to take control of window movement (Wayland and X11)
1589    ///
1590    /// Events may not be received during a move operation.
1591    pub fn start_window_move(&self) {
1592        self.platform_window.start_window_move()
1593    }
1594
1595    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
1596    pub fn set_client_inset(&mut self, inset: Pixels) {
1597        self.client_inset = Some(inset);
1598        self.platform_window.set_client_inset(inset);
1599    }
1600
1601    /// Returns the client_inset value by [`Self::set_client_inset`].
1602    pub fn client_inset(&self) -> Option<Pixels> {
1603        self.client_inset
1604    }
1605
1606    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1607    pub fn window_decorations(&self) -> Decorations {
1608        self.platform_window.window_decorations()
1609    }
1610
1611    /// Returns which window controls are currently visible (Wayland)
1612    pub fn window_controls(&self) -> WindowControls {
1613        self.platform_window.window_controls()
1614    }
1615
1616    /// Updates the window's title at the platform level.
1617    pub fn set_window_title(&mut self, title: &str) {
1618        self.platform_window.set_title(title);
1619    }
1620
1621    /// Sets the application identifier.
1622    pub fn set_app_id(&mut self, app_id: &str) {
1623        self.platform_window.set_app_id(app_id);
1624    }
1625
1626    /// Sets the window background appearance.
1627    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1628        self.platform_window
1629            .set_background_appearance(background_appearance);
1630    }
1631
1632    /// Mark the window as dirty at the platform level.
1633    pub fn set_window_edited(&mut self, edited: bool) {
1634        self.platform_window.set_edited(edited);
1635    }
1636
1637    /// Determine the display on which the window is visible.
1638    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
1639        cx.platform
1640            .displays()
1641            .into_iter()
1642            .find(|display| Some(display.id()) == self.display_id)
1643    }
1644
1645    /// Show the platform character palette.
1646    pub fn show_character_palette(&self) {
1647        self.platform_window.show_character_palette();
1648    }
1649
1650    /// The scale factor of the display associated with the window. For example, it could
1651    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1652    /// be rendered as two pixels on screen.
1653    pub fn scale_factor(&self) -> f32 {
1654        self.scale_factor
1655    }
1656
1657    /// The size of an em for the base font of the application. Adjusting this value allows the
1658    /// UI to scale, just like zooming a web page.
1659    pub fn rem_size(&self) -> Pixels {
1660        self.rem_size_override_stack
1661            .last()
1662            .copied()
1663            .unwrap_or(self.rem_size)
1664    }
1665
1666    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1667    /// UI to scale, just like zooming a web page.
1668    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1669        self.rem_size = rem_size.into();
1670    }
1671
1672    /// Acquire a globally unique identifier for the given ElementId.
1673    /// Only valid for the duration of the provided closure.
1674    pub fn with_global_id<R>(
1675        &mut self,
1676        element_id: ElementId,
1677        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
1678    ) -> R {
1679        self.element_id_stack.push(element_id);
1680        let global_id = GlobalElementId(self.element_id_stack.clone());
1681        let result = f(&global_id, self);
1682        self.element_id_stack.pop();
1683        result
1684    }
1685
1686    /// Executes the provided function with the specified rem size.
1687    ///
1688    /// This method must only be called as part of element drawing.
1689    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1690    where
1691        F: FnOnce(&mut Self) -> R,
1692    {
1693        self.invalidator.debug_assert_paint_or_prepaint();
1694
1695        if let Some(rem_size) = rem_size {
1696            self.rem_size_override_stack.push(rem_size.into());
1697            let result = f(self);
1698            self.rem_size_override_stack.pop();
1699            result
1700        } else {
1701            f(self)
1702        }
1703    }
1704
1705    /// The line height associated with the current text style.
1706    pub fn line_height(&self) -> Pixels {
1707        self.text_style().line_height_in_pixels(self.rem_size())
1708    }
1709
1710    /// Call to prevent the default action of an event. Currently only used to prevent
1711    /// parent elements from becoming focused on mouse down.
1712    pub fn prevent_default(&mut self) {
1713        self.default_prevented = true;
1714    }
1715
1716    /// Obtain whether default has been prevented for the event currently being dispatched.
1717    pub fn default_prevented(&self) -> bool {
1718        self.default_prevented
1719    }
1720
1721    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1722    pub fn is_action_available(&self, action: &dyn Action, cx: &mut App) -> bool {
1723        let node_id =
1724            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
1725        self.rendered_frame
1726            .dispatch_tree
1727            .is_action_available(action, node_id)
1728    }
1729
1730    /// The position of the mouse relative to the window.
1731    pub fn mouse_position(&self) -> Point<Pixels> {
1732        self.mouse_position
1733    }
1734
1735    /// The current state of the keyboard's modifiers
1736    pub fn modifiers(&self) -> Modifiers {
1737        self.modifiers
1738    }
1739
1740    /// The current state of the keyboard's capslock
1741    pub fn capslock(&self) -> Capslock {
1742        self.capslock
1743    }
1744
1745    fn complete_frame(&self) {
1746        self.platform_window.completed_frame();
1747    }
1748
1749    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1750    /// the contents of the new [Scene], use [present].
1751    #[profiling::function]
1752    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
1753        self.invalidate_entities();
1754        cx.entities.clear_accessed();
1755        debug_assert!(self.rendered_entity_stack.is_empty());
1756        self.invalidator.set_dirty(false);
1757        self.requested_autoscroll = None;
1758
1759        // Restore the previously-used input handler.
1760        if let Some(input_handler) = self.platform_window.take_input_handler() {
1761            self.rendered_frame.input_handlers.push(Some(input_handler));
1762        }
1763        self.draw_roots(cx);
1764        self.dirty_views.clear();
1765        self.next_frame.window_active = self.active.get();
1766
1767        // Register requested input handler with the platform window.
1768        if let Some(input_handler) = self.next_frame.input_handlers.pop() {
1769            self.platform_window
1770                .set_input_handler(input_handler.unwrap());
1771        }
1772
1773        self.layout_engine.as_mut().unwrap().clear();
1774        self.text_system().finish_frame();
1775        self.next_frame.finish(&mut self.rendered_frame);
1776
1777        self.invalidator.set_phase(DrawPhase::Focus);
1778        let previous_focus_path = self.rendered_frame.focus_path();
1779        let previous_window_active = self.rendered_frame.window_active;
1780        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
1781        self.next_frame.clear();
1782        let current_focus_path = self.rendered_frame.focus_path();
1783        let current_window_active = self.rendered_frame.window_active;
1784
1785        if previous_focus_path != current_focus_path
1786            || previous_window_active != current_window_active
1787        {
1788            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1789                self.focus_lost_listeners
1790                    .clone()
1791                    .retain(&(), |listener| listener(self, cx));
1792            }
1793
1794            let event = WindowFocusEvent {
1795                previous_focus_path: if previous_window_active {
1796                    previous_focus_path
1797                } else {
1798                    Default::default()
1799                },
1800                current_focus_path: if current_window_active {
1801                    current_focus_path
1802                } else {
1803                    Default::default()
1804                },
1805            };
1806            self.focus_listeners
1807                .clone()
1808                .retain(&(), |listener| listener(&event, self, cx));
1809        }
1810
1811        debug_assert!(self.rendered_entity_stack.is_empty());
1812        self.record_entities_accessed(cx);
1813        self.reset_cursor_style(cx);
1814        self.refreshing = false;
1815        self.invalidator.set_phase(DrawPhase::None);
1816        self.needs_present.set(true);
1817
1818        ArenaClearNeeded
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).clear();
3485        }
3486
3487        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3488        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3489
3490        let mut keystroke: Option<Keystroke> = None;
3491
3492        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3493            if event.modifiers.number_of_modifiers() == 0
3494                && self.pending_modifier.modifiers.number_of_modifiers() == 1
3495                && !self.pending_modifier.saw_keystroke
3496            {
3497                let key = match self.pending_modifier.modifiers {
3498                    modifiers if modifiers.shift => Some("shift"),
3499                    modifiers if modifiers.control => Some("control"),
3500                    modifiers if modifiers.alt => Some("alt"),
3501                    modifiers if modifiers.platform => Some("platform"),
3502                    modifiers if modifiers.function => Some("function"),
3503                    _ => None,
3504                };
3505                if let Some(key) = key {
3506                    keystroke = Some(Keystroke {
3507                        key: key.to_string(),
3508                        key_char: None,
3509                        modifiers: Modifiers::default(),
3510                    });
3511                }
3512            }
3513
3514            if self.pending_modifier.modifiers.number_of_modifiers() == 0
3515                && event.modifiers.number_of_modifiers() == 1
3516            {
3517                self.pending_modifier.saw_keystroke = false
3518            }
3519            self.pending_modifier.modifiers = event.modifiers
3520        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3521            self.pending_modifier.saw_keystroke = true;
3522            keystroke = Some(key_down_event.keystroke.clone());
3523        }
3524
3525        let Some(keystroke) = keystroke else {
3526            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3527            return;
3528        };
3529
3530        let mut currently_pending = self.pending_input.take().unwrap_or_default();
3531        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3532            currently_pending = PendingInput::default();
3533        }
3534
3535        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3536            currently_pending.keystrokes,
3537            keystroke,
3538            &dispatch_path,
3539        );
3540
3541        if !match_result.to_replay.is_empty() {
3542            self.replay_pending_input(match_result.to_replay, cx)
3543        }
3544
3545        if !match_result.pending.is_empty() {
3546            currently_pending.keystrokes = match_result.pending;
3547            currently_pending.focus = self.focus;
3548            currently_pending.timer = Some(self.spawn(cx, async move |cx| {
3549                cx.background_executor.timer(Duration::from_secs(1)).await;
3550                cx.update(move |window, cx| {
3551                    let Some(currently_pending) = window
3552                        .pending_input
3553                        .take()
3554                        .filter(|pending| pending.focus == window.focus)
3555                    else {
3556                        return;
3557                    };
3558
3559                    let node_id = window.focus_node_id_in_rendered_frame(window.focus);
3560                    let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3561
3562                    let to_replay = window
3563                        .rendered_frame
3564                        .dispatch_tree
3565                        .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3566
3567                    window.pending_input_changed(cx);
3568                    window.replay_pending_input(to_replay, cx)
3569                })
3570                .log_err();
3571            }));
3572            self.pending_input = Some(currently_pending);
3573            self.pending_input_changed(cx);
3574            cx.propagate_event = false;
3575            return;
3576        }
3577
3578        cx.propagate_event = true;
3579        for binding in match_result.bindings {
3580            self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3581            if !cx.propagate_event {
3582                self.dispatch_keystroke_observers(
3583                    event,
3584                    Some(binding.action),
3585                    match_result.context_stack.clone(),
3586                    cx,
3587                );
3588                self.pending_input_changed(cx);
3589                return;
3590            }
3591        }
3592
3593        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
3594        self.pending_input_changed(cx);
3595    }
3596
3597    fn finish_dispatch_key_event(
3598        &mut self,
3599        event: &dyn Any,
3600        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3601        context_stack: Vec<KeyContext>,
3602        cx: &mut App,
3603    ) {
3604        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
3605        if !cx.propagate_event {
3606            return;
3607        }
3608
3609        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
3610        if !cx.propagate_event {
3611            return;
3612        }
3613
3614        self.dispatch_keystroke_observers(event, None, context_stack, cx);
3615    }
3616
3617    fn pending_input_changed(&mut self, cx: &mut App) {
3618        self.pending_input_observers
3619            .clone()
3620            .retain(&(), |callback| callback(self, cx));
3621    }
3622
3623    fn dispatch_key_down_up_event(
3624        &mut self,
3625        event: &dyn Any,
3626        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3627        cx: &mut App,
3628    ) {
3629        // Capture phase
3630        for node_id in dispatch_path {
3631            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3632
3633            for key_listener in node.key_listeners.clone() {
3634                key_listener(event, DispatchPhase::Capture, self, cx);
3635                if !cx.propagate_event {
3636                    return;
3637                }
3638            }
3639        }
3640
3641        // Bubble phase
3642        for node_id in dispatch_path.iter().rev() {
3643            // Handle low level key events
3644            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3645            for key_listener in node.key_listeners.clone() {
3646                key_listener(event, DispatchPhase::Bubble, self, cx);
3647                if !cx.propagate_event {
3648                    return;
3649                }
3650            }
3651        }
3652    }
3653
3654    fn dispatch_modifiers_changed_event(
3655        &mut self,
3656        event: &dyn Any,
3657        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3658        cx: &mut App,
3659    ) {
3660        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3661            return;
3662        };
3663        for node_id in dispatch_path.iter().rev() {
3664            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3665            for listener in node.modifiers_changed_listeners.clone() {
3666                listener(event, self, cx);
3667                if !cx.propagate_event {
3668                    return;
3669                }
3670            }
3671        }
3672    }
3673
3674    /// Determine whether a potential multi-stroke key binding is in progress on this window.
3675    pub fn has_pending_keystrokes(&self) -> bool {
3676        self.pending_input.is_some()
3677    }
3678
3679    pub(crate) fn clear_pending_keystrokes(&mut self) {
3680        self.pending_input.take();
3681    }
3682
3683    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3684    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3685        self.pending_input
3686            .as_ref()
3687            .map(|pending_input| pending_input.keystrokes.as_slice())
3688    }
3689
3690    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
3691        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3692        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3693
3694        'replay: for replay in replays {
3695            let event = KeyDownEvent {
3696                keystroke: replay.keystroke.clone(),
3697                is_held: false,
3698            };
3699
3700            cx.propagate_event = true;
3701            for binding in replay.bindings {
3702                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3703                if !cx.propagate_event {
3704                    self.dispatch_keystroke_observers(
3705                        &event,
3706                        Some(binding.action),
3707                        Vec::default(),
3708                        cx,
3709                    );
3710                    continue 'replay;
3711                }
3712            }
3713
3714            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
3715            if !cx.propagate_event {
3716                continue 'replay;
3717            }
3718            if let Some(input) = replay.keystroke.key_char.as_ref().cloned() {
3719                if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3720                    input_handler.dispatch_input(&input, self, cx);
3721                    self.platform_window.set_input_handler(input_handler)
3722                }
3723            }
3724        }
3725    }
3726
3727    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
3728        focus_id
3729            .and_then(|focus_id| {
3730                self.rendered_frame
3731                    .dispatch_tree
3732                    .focusable_node_id(focus_id)
3733            })
3734            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
3735    }
3736
3737    fn dispatch_action_on_node(
3738        &mut self,
3739        node_id: DispatchNodeId,
3740        action: &dyn Action,
3741        cx: &mut App,
3742    ) {
3743        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3744
3745        // Capture phase for global actions.
3746        cx.propagate_event = true;
3747        if let Some(mut global_listeners) = cx
3748            .global_action_listeners
3749            .remove(&action.as_any().type_id())
3750        {
3751            for listener in &global_listeners {
3752                listener(action.as_any(), DispatchPhase::Capture, cx);
3753                if !cx.propagate_event {
3754                    break;
3755                }
3756            }
3757
3758            global_listeners.extend(
3759                cx.global_action_listeners
3760                    .remove(&action.as_any().type_id())
3761                    .unwrap_or_default(),
3762            );
3763
3764            cx.global_action_listeners
3765                .insert(action.as_any().type_id(), global_listeners);
3766        }
3767
3768        if !cx.propagate_event {
3769            return;
3770        }
3771
3772        // Capture phase for window actions.
3773        for node_id in &dispatch_path {
3774            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3775            for DispatchActionListener {
3776                action_type,
3777                listener,
3778            } in node.action_listeners.clone()
3779            {
3780                let any_action = action.as_any();
3781                if action_type == any_action.type_id() {
3782                    listener(any_action, DispatchPhase::Capture, self, cx);
3783
3784                    if !cx.propagate_event {
3785                        return;
3786                    }
3787                }
3788            }
3789        }
3790
3791        // Bubble phase for window actions.
3792        for node_id in dispatch_path.iter().rev() {
3793            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3794            for DispatchActionListener {
3795                action_type,
3796                listener,
3797            } in node.action_listeners.clone()
3798            {
3799                let any_action = action.as_any();
3800                if action_type == any_action.type_id() {
3801                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3802                    listener(any_action, DispatchPhase::Bubble, self, cx);
3803
3804                    if !cx.propagate_event {
3805                        return;
3806                    }
3807                }
3808            }
3809        }
3810
3811        // Bubble phase for global actions.
3812        if let Some(mut global_listeners) = cx
3813            .global_action_listeners
3814            .remove(&action.as_any().type_id())
3815        {
3816            for listener in global_listeners.iter().rev() {
3817                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3818
3819                listener(action.as_any(), DispatchPhase::Bubble, cx);
3820                if !cx.propagate_event {
3821                    break;
3822                }
3823            }
3824
3825            global_listeners.extend(
3826                cx.global_action_listeners
3827                    .remove(&action.as_any().type_id())
3828                    .unwrap_or_default(),
3829            );
3830
3831            cx.global_action_listeners
3832                .insert(action.as_any().type_id(), global_listeners);
3833        }
3834    }
3835
3836    /// Register the given handler to be invoked whenever the global of the given type
3837    /// is updated.
3838    pub fn observe_global<G: Global>(
3839        &mut self,
3840        cx: &mut App,
3841        f: impl Fn(&mut Window, &mut App) + 'static,
3842    ) -> Subscription {
3843        let window_handle = self.handle;
3844        let (subscription, activate) = cx.global_observers.insert(
3845            TypeId::of::<G>(),
3846            Box::new(move |cx| {
3847                window_handle
3848                    .update(cx, |_, window, cx| f(window, cx))
3849                    .is_ok()
3850            }),
3851        );
3852        cx.defer(move |_| activate());
3853        subscription
3854    }
3855
3856    /// Focus the current window and bring it to the foreground at the platform level.
3857    pub fn activate_window(&self) {
3858        self.platform_window.activate();
3859    }
3860
3861    /// Minimize the current window at the platform level.
3862    pub fn minimize_window(&self) {
3863        self.platform_window.minimize();
3864    }
3865
3866    /// Toggle full screen status on the current window at the platform level.
3867    pub fn toggle_fullscreen(&self) {
3868        self.platform_window.toggle_fullscreen();
3869    }
3870
3871    /// Updates the IME panel position suggestions for languages like japanese, chinese.
3872    pub fn invalidate_character_coordinates(&self) {
3873        self.on_next_frame(|window, cx| {
3874            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
3875                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
3876                    window
3877                        .platform_window
3878                        .update_ime_position(bounds.scale(window.scale_factor()));
3879                }
3880                window.platform_window.set_input_handler(input_handler);
3881            }
3882        });
3883    }
3884
3885    /// Present a platform dialog.
3886    /// The provided message will be presented, along with buttons for each answer.
3887    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3888    pub fn prompt<T>(
3889        &mut self,
3890        level: PromptLevel,
3891        message: &str,
3892        detail: Option<&str>,
3893        answers: &[T],
3894        cx: &mut App,
3895    ) -> oneshot::Receiver<usize>
3896    where
3897        T: Clone + Into<PromptButton>,
3898    {
3899        let prompt_builder = cx.prompt_builder.take();
3900        let Some(prompt_builder) = prompt_builder else {
3901            unreachable!("Re-entrant window prompting is not supported by GPUI");
3902        };
3903
3904        let answers = answers
3905            .iter()
3906            .map(|answer| answer.clone().into())
3907            .collect::<Vec<_>>();
3908
3909        let receiver = match &prompt_builder {
3910            PromptBuilder::Default => self
3911                .platform_window
3912                .prompt(level, message, detail, &answers)
3913                .unwrap_or_else(|| {
3914                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
3915                }),
3916            PromptBuilder::Custom(_) => {
3917                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
3918            }
3919        };
3920
3921        cx.prompt_builder = Some(prompt_builder);
3922
3923        receiver
3924    }
3925
3926    fn build_custom_prompt(
3927        &mut self,
3928        prompt_builder: &PromptBuilder,
3929        level: PromptLevel,
3930        message: &str,
3931        detail: Option<&str>,
3932        answers: &[PromptButton],
3933        cx: &mut App,
3934    ) -> oneshot::Receiver<usize> {
3935        let (sender, receiver) = oneshot::channel();
3936        let handle = PromptHandle::new(sender);
3937        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
3938        self.prompt = Some(handle);
3939        receiver
3940    }
3941
3942    /// Returns the current context stack.
3943    pub fn context_stack(&self) -> Vec<KeyContext> {
3944        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3945        let dispatch_tree = &self.rendered_frame.dispatch_tree;
3946        dispatch_tree
3947            .dispatch_path(node_id)
3948            .iter()
3949            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
3950            .collect()
3951    }
3952
3953    /// Returns all available actions for the focused element.
3954    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
3955        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3956        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
3957        for action_type in cx.global_action_listeners.keys() {
3958            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3959                let action = cx.actions.build_action_type(action_type).ok();
3960                if let Some(action) = action {
3961                    actions.insert(ix, action);
3962                }
3963            }
3964        }
3965        actions
3966    }
3967
3968    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
3969    /// returned in the order they were added. For display, the last binding should take precedence.
3970    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3971        self.rendered_frame
3972            .dispatch_tree
3973            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
3974    }
3975
3976    /// Returns the highest precedence key binding that invokes an action on the currently focused
3977    /// element. This is more efficient than getting the last result of `bindings_for_action`.
3978    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
3979        self.rendered_frame
3980            .dispatch_tree
3981            .highest_precedence_binding_for_action(
3982                action,
3983                &self.rendered_frame.dispatch_tree.context_stack,
3984            )
3985    }
3986
3987    /// Returns the key bindings for an action in a context.
3988    pub fn bindings_for_action_in_context(
3989        &self,
3990        action: &dyn Action,
3991        context: KeyContext,
3992    ) -> Vec<KeyBinding> {
3993        let dispatch_tree = &self.rendered_frame.dispatch_tree;
3994        dispatch_tree.bindings_for_action(action, &[context])
3995    }
3996
3997    /// Returns the highest precedence key binding for an action in a context. This is more
3998    /// efficient than getting the last result of `bindings_for_action_in_context`.
3999    pub fn highest_precedence_binding_for_action_in_context(
4000        &self,
4001        action: &dyn Action,
4002        context: KeyContext,
4003    ) -> Option<KeyBinding> {
4004        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4005        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4006    }
4007
4008    /// Returns any bindings that would invoke an action on the given focus handle if it were
4009    /// focused. Bindings are returned in the order they were added. For display, the last binding
4010    /// should take precedence.
4011    pub fn bindings_for_action_in(
4012        &self,
4013        action: &dyn Action,
4014        focus_handle: &FocusHandle,
4015    ) -> Vec<KeyBinding> {
4016        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4017        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4018            return vec![];
4019        };
4020        dispatch_tree.bindings_for_action(action, &context_stack)
4021    }
4022
4023    /// Returns the highest precedence key binding that would invoke an action on the given focus
4024    /// handle if it were focused. This is more efficient than getting the last result of
4025    /// `bindings_for_action_in`.
4026    pub fn highest_precedence_binding_for_action_in(
4027        &self,
4028        action: &dyn Action,
4029        focus_handle: &FocusHandle,
4030    ) -> Option<KeyBinding> {
4031        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4032        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4033        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4034    }
4035
4036    fn context_stack_for_focus_handle(
4037        &self,
4038        focus_handle: &FocusHandle,
4039    ) -> Option<Vec<KeyContext>> {
4040        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4041        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4042        let context_stack: Vec<_> = dispatch_tree
4043            .dispatch_path(node_id)
4044            .into_iter()
4045            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4046            .collect();
4047        Some(context_stack)
4048    }
4049
4050    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4051    pub fn listener_for<V: Render, E>(
4052        &self,
4053        view: &Entity<V>,
4054        f: impl Fn(&mut V, &E, &mut Window, &mut Context<V>) + 'static,
4055    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4056        let view = view.downgrade();
4057        move |e: &E, window: &mut Window, cx: &mut App| {
4058            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4059        }
4060    }
4061
4062    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4063    pub fn handler_for<V: Render, Callback: Fn(&mut V, &mut Window, &mut Context<V>) + 'static>(
4064        &self,
4065        view: &Entity<V>,
4066        f: Callback,
4067    ) -> impl Fn(&mut Window, &mut App) + use<V, Callback> {
4068        let view = view.downgrade();
4069        move |window: &mut Window, cx: &mut App| {
4070            view.update(cx, |view, cx| f(view, window, cx)).ok();
4071        }
4072    }
4073
4074    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4075    /// If the callback returns false, the window won't be closed.
4076    pub fn on_window_should_close(
4077        &self,
4078        cx: &App,
4079        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4080    ) {
4081        let mut cx = self.to_async(cx);
4082        self.platform_window.on_should_close(Box::new(move || {
4083            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4084        }))
4085    }
4086
4087    /// Register an action listener on the window for the next frame. The type of action
4088    /// is determined by the first parameter of the given listener. When the next frame is rendered
4089    /// the listener will be cleared.
4090    ///
4091    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4092    /// a specific need to register a global listener.
4093    pub fn on_action(
4094        &mut self,
4095        action_type: TypeId,
4096        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4097    ) {
4098        self.next_frame
4099            .dispatch_tree
4100            .on_action(action_type, Rc::new(listener));
4101    }
4102
4103    /// Read information about the GPU backing this window.
4104    /// Currently returns None on Mac and Windows.
4105    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4106        self.platform_window.gpu_specs()
4107    }
4108
4109    /// Perform titlebar double-click action.
4110    /// This is MacOS specific.
4111    pub fn titlebar_double_click(&self) {
4112        self.platform_window.titlebar_double_click();
4113    }
4114
4115    /// Toggles the inspector mode on this window.
4116    #[cfg(any(feature = "inspector", debug_assertions))]
4117    pub fn toggle_inspector(&mut self, cx: &mut App) {
4118        self.inspector = match self.inspector {
4119            None => Some(cx.new(|_| Inspector::new())),
4120            Some(_) => None,
4121        };
4122        self.refresh();
4123    }
4124
4125    /// Returns true if the window is in inspector mode.
4126    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
4127        #[cfg(any(feature = "inspector", debug_assertions))]
4128        {
4129            if let Some(inspector) = &self.inspector {
4130                return inspector.read(_cx).is_picking();
4131            }
4132        }
4133        false
4134    }
4135
4136    /// Executes the provided function with mutable access to an inspector state.
4137    #[cfg(any(feature = "inspector", debug_assertions))]
4138    pub fn with_inspector_state<T: 'static, R>(
4139        &mut self,
4140        _inspector_id: Option<&crate::InspectorElementId>,
4141        cx: &mut App,
4142        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
4143    ) -> R {
4144        if let Some(inspector_id) = _inspector_id {
4145            if let Some(inspector) = &self.inspector {
4146                let inspector = inspector.clone();
4147                let active_element_id = inspector.read(cx).active_element_id();
4148                if Some(inspector_id) == active_element_id {
4149                    return inspector.update(cx, |inspector, _cx| {
4150                        inspector.with_active_element_state(self, f)
4151                    });
4152                }
4153            }
4154        }
4155        f(&mut None, self)
4156    }
4157
4158    #[cfg(any(feature = "inspector", debug_assertions))]
4159    pub(crate) fn build_inspector_element_id(
4160        &mut self,
4161        path: crate::InspectorElementPath,
4162    ) -> crate::InspectorElementId {
4163        self.invalidator.debug_assert_paint_or_prepaint();
4164        let path = Rc::new(path);
4165        let next_instance_id = self
4166            .next_frame
4167            .next_inspector_instance_ids
4168            .entry(path.clone())
4169            .or_insert(0);
4170        let instance_id = *next_instance_id;
4171        *next_instance_id += 1;
4172        crate::InspectorElementId { path, instance_id }
4173    }
4174
4175    #[cfg(any(feature = "inspector", debug_assertions))]
4176    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
4177        if let Some(inspector) = self.inspector.take() {
4178            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
4179            inspector_element.prepaint_as_root(
4180                point(self.viewport_size.width - inspector_width, px(0.0)),
4181                size(inspector_width, self.viewport_size.height).into(),
4182                self,
4183                cx,
4184            );
4185            self.inspector = Some(inspector);
4186            Some(inspector_element)
4187        } else {
4188            None
4189        }
4190    }
4191
4192    #[cfg(any(feature = "inspector", debug_assertions))]
4193    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
4194        if let Some(mut inspector_element) = inspector_element {
4195            inspector_element.paint(self, cx);
4196        };
4197    }
4198
4199    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
4200    /// inspect UI elements by clicking on them.
4201    #[cfg(any(feature = "inspector", debug_assertions))]
4202    pub fn insert_inspector_hitbox(
4203        &mut self,
4204        hitbox_id: HitboxId,
4205        inspector_id: Option<&crate::InspectorElementId>,
4206        cx: &App,
4207    ) {
4208        self.invalidator.debug_assert_paint_or_prepaint();
4209        if !self.is_inspector_picking(cx) {
4210            return;
4211        }
4212        if let Some(inspector_id) = inspector_id {
4213            self.next_frame
4214                .inspector_hitboxes
4215                .insert(hitbox_id, inspector_id.clone());
4216        }
4217    }
4218
4219    #[cfg(any(feature = "inspector", debug_assertions))]
4220    fn paint_inspector_hitbox(&mut self, cx: &App) {
4221        if let Some(inspector) = self.inspector.as_ref() {
4222            let inspector = inspector.read(cx);
4223            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
4224            {
4225                if let Some(hitbox) = self
4226                    .next_frame
4227                    .hitboxes
4228                    .iter()
4229                    .find(|hitbox| hitbox.id == hitbox_id)
4230                {
4231                    self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
4232                }
4233            }
4234        }
4235    }
4236
4237    #[cfg(any(feature = "inspector", debug_assertions))]
4238    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4239        let Some(inspector) = self.inspector.clone() else {
4240            return;
4241        };
4242        if event.downcast_ref::<MouseMoveEvent>().is_some() {
4243            inspector.update(cx, |inspector, _cx| {
4244                if let Some((_, inspector_id)) =
4245                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4246                {
4247                    inspector.hover(inspector_id, self);
4248                }
4249            });
4250        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
4251            inspector.update(cx, |inspector, _cx| {
4252                if let Some((_, inspector_id)) =
4253                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4254                {
4255                    inspector.select(inspector_id, self);
4256                }
4257            });
4258        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
4259            // This should be kept in sync with SCROLL_LINES in x11 platform.
4260            const SCROLL_LINES: f32 = 3.0;
4261            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
4262            let delta_y = event
4263                .delta
4264                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
4265                .y;
4266            if let Some(inspector) = self.inspector.clone() {
4267                inspector.update(cx, |inspector, _cx| {
4268                    if let Some(depth) = inspector.pick_depth.as_mut() {
4269                        *depth += delta_y.0 / SCROLL_PIXELS_PER_LAYER;
4270                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
4271                        if *depth < 0.0 {
4272                            *depth = 0.0;
4273                        } else if *depth > max_depth {
4274                            *depth = max_depth;
4275                        }
4276                        if let Some((_, inspector_id)) =
4277                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4278                        {
4279                            inspector.set_active_element_id(inspector_id.clone(), self);
4280                        }
4281                    }
4282                });
4283            }
4284        }
4285    }
4286
4287    #[cfg(any(feature = "inspector", debug_assertions))]
4288    fn hovered_inspector_hitbox(
4289        &self,
4290        inspector: &Inspector,
4291        frame: &Frame,
4292    ) -> Option<(HitboxId, crate::InspectorElementId)> {
4293        if let Some(pick_depth) = inspector.pick_depth {
4294            let depth = (pick_depth as i64).try_into().unwrap_or(0);
4295            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
4296            let skip_count = (depth as usize).min(max_skipped);
4297            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
4298                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
4299                    return Some((*hitbox_id, inspector_id.clone()));
4300                }
4301            }
4302        }
4303        return None;
4304    }
4305}
4306
4307// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4308slotmap::new_key_type! {
4309    /// A unique identifier for a window.
4310    pub struct WindowId;
4311}
4312
4313impl WindowId {
4314    /// Converts this window ID to a `u64`.
4315    pub fn as_u64(&self) -> u64 {
4316        self.0.as_ffi()
4317    }
4318}
4319
4320impl From<u64> for WindowId {
4321    fn from(value: u64) -> Self {
4322        WindowId(slotmap::KeyData::from_ffi(value))
4323    }
4324}
4325
4326/// A handle to a window with a specific root view type.
4327/// Note that this does not keep the window alive on its own.
4328#[derive(Deref, DerefMut)]
4329pub struct WindowHandle<V> {
4330    #[deref]
4331    #[deref_mut]
4332    pub(crate) any_handle: AnyWindowHandle,
4333    state_type: PhantomData<V>,
4334}
4335
4336impl<V: 'static + Render> WindowHandle<V> {
4337    /// Creates a new handle from a window ID.
4338    /// This does not check if the root type of the window is `V`.
4339    pub fn new(id: WindowId) -> Self {
4340        WindowHandle {
4341            any_handle: AnyWindowHandle {
4342                id,
4343                state_type: TypeId::of::<V>(),
4344            },
4345            state_type: PhantomData,
4346        }
4347    }
4348
4349    /// Get the root view out of this window.
4350    ///
4351    /// This will fail if the window is closed or if the root view's type does not match `V`.
4352    #[cfg(any(test, feature = "test-support"))]
4353    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
4354    where
4355        C: AppContext,
4356    {
4357        crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
4358            root_view
4359                .downcast::<V>()
4360                .map_err(|_| anyhow!("the type of the window's root view has changed"))
4361        }))
4362    }
4363
4364    /// Updates the root view of this window.
4365    ///
4366    /// This will fail if the window has been closed or if the root view's type does not match
4367    pub fn update<C, R>(
4368        &self,
4369        cx: &mut C,
4370        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
4371    ) -> Result<R>
4372    where
4373        C: AppContext,
4374    {
4375        cx.update_window(self.any_handle, |root_view, window, cx| {
4376            let view = root_view
4377                .downcast::<V>()
4378                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4379
4380            Ok(view.update(cx, |view, cx| update(view, window, cx)))
4381        })?
4382    }
4383
4384    /// Read the root view out of this window.
4385    ///
4386    /// This will fail if the window is closed or if the root view's type does not match `V`.
4387    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
4388        let x = cx
4389            .windows
4390            .get(self.id)
4391            .and_then(|window| {
4392                window
4393                    .as_ref()
4394                    .and_then(|window| window.root.clone())
4395                    .map(|root_view| root_view.downcast::<V>())
4396            })
4397            .context("window not found")?
4398            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4399
4400        Ok(x.read(cx))
4401    }
4402
4403    /// Read the root view out of this window, with a callback
4404    ///
4405    /// This will fail if the window is closed or if the root view's type does not match `V`.
4406    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
4407    where
4408        C: AppContext,
4409    {
4410        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4411    }
4412
4413    /// Read the root view pointer off of this window.
4414    ///
4415    /// This will fail if the window is closed or if the root view's type does not match `V`.
4416    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
4417    where
4418        C: AppContext,
4419    {
4420        cx.read_window(self, |root_view, _cx| root_view.clone())
4421    }
4422
4423    /// Check if this window is 'active'.
4424    ///
4425    /// Will return `None` if the window is closed or currently
4426    /// borrowed.
4427    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
4428        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
4429            .ok()
4430    }
4431}
4432
4433impl<V> Copy for WindowHandle<V> {}
4434
4435impl<V> Clone for WindowHandle<V> {
4436    fn clone(&self) -> Self {
4437        *self
4438    }
4439}
4440
4441impl<V> PartialEq for WindowHandle<V> {
4442    fn eq(&self, other: &Self) -> bool {
4443        self.any_handle == other.any_handle
4444    }
4445}
4446
4447impl<V> Eq for WindowHandle<V> {}
4448
4449impl<V> Hash for WindowHandle<V> {
4450    fn hash<H: Hasher>(&self, state: &mut H) {
4451        self.any_handle.hash(state);
4452    }
4453}
4454
4455impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4456    fn from(val: WindowHandle<V>) -> Self {
4457        val.any_handle
4458    }
4459}
4460
4461unsafe impl<V> Send for WindowHandle<V> {}
4462unsafe impl<V> Sync for WindowHandle<V> {}
4463
4464/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4465#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4466pub struct AnyWindowHandle {
4467    pub(crate) id: WindowId,
4468    state_type: TypeId,
4469}
4470
4471impl AnyWindowHandle {
4472    /// Get the ID of this window.
4473    pub fn window_id(&self) -> WindowId {
4474        self.id
4475    }
4476
4477    /// Attempt to convert this handle to a window handle with a specific root view type.
4478    /// If the types do not match, this will return `None`.
4479    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4480        if TypeId::of::<T>() == self.state_type {
4481            Some(WindowHandle {
4482                any_handle: *self,
4483                state_type: PhantomData,
4484            })
4485        } else {
4486            None
4487        }
4488    }
4489
4490    /// Updates the state of the root view of this window.
4491    ///
4492    /// This will fail if the window has been closed.
4493    pub fn update<C, R>(
4494        self,
4495        cx: &mut C,
4496        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
4497    ) -> Result<R>
4498    where
4499        C: AppContext,
4500    {
4501        cx.update_window(self, update)
4502    }
4503
4504    /// Read the state of the root view of this window.
4505    ///
4506    /// This will fail if the window has been closed.
4507    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
4508    where
4509        C: AppContext,
4510        T: 'static,
4511    {
4512        let view = self
4513            .downcast::<T>()
4514            .context("the type of the window's root view has changed")?;
4515
4516        cx.read_window(&view, read)
4517    }
4518}
4519
4520impl HasWindowHandle for Window {
4521    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
4522        self.platform_window.window_handle()
4523    }
4524}
4525
4526impl HasDisplayHandle for Window {
4527    fn display_handle(
4528        &self,
4529    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
4530        self.platform_window.display_handle()
4531    }
4532}
4533
4534/// An identifier for an [`Element`](crate::Element).
4535///
4536/// Can be constructed with a string, a number, or both, as well
4537/// as other internal representations.
4538#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4539pub enum ElementId {
4540    /// The ID of a View element
4541    View(EntityId),
4542    /// An integer ID.
4543    Integer(u64),
4544    /// A string based ID.
4545    Name(SharedString),
4546    /// A UUID.
4547    Uuid(Uuid),
4548    /// An ID that's equated with a focus handle.
4549    FocusHandle(FocusId),
4550    /// A combination of a name and an integer.
4551    NamedInteger(SharedString, u64),
4552    /// A path.
4553    Path(Arc<std::path::Path>),
4554}
4555
4556impl ElementId {
4557    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
4558    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
4559        Self::NamedInteger(name.into(), integer as u64)
4560    }
4561}
4562
4563impl Display for ElementId {
4564    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4565        match self {
4566            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4567            ElementId::Integer(ix) => write!(f, "{}", ix)?,
4568            ElementId::Name(name) => write!(f, "{}", name)?,
4569            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4570            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4571            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4572            ElementId::Path(path) => write!(f, "{}", path.display())?,
4573        }
4574
4575        Ok(())
4576    }
4577}
4578
4579impl TryInto<SharedString> for ElementId {
4580    type Error = anyhow::Error;
4581
4582    fn try_into(self) -> anyhow::Result<SharedString> {
4583        if let ElementId::Name(name) = self {
4584            Ok(name)
4585        } else {
4586            anyhow::bail!("element id is not string")
4587        }
4588    }
4589}
4590
4591impl From<usize> for ElementId {
4592    fn from(id: usize) -> Self {
4593        ElementId::Integer(id as u64)
4594    }
4595}
4596
4597impl From<i32> for ElementId {
4598    fn from(id: i32) -> Self {
4599        Self::Integer(id as u64)
4600    }
4601}
4602
4603impl From<SharedString> for ElementId {
4604    fn from(name: SharedString) -> Self {
4605        ElementId::Name(name)
4606    }
4607}
4608
4609impl From<Arc<std::path::Path>> for ElementId {
4610    fn from(path: Arc<std::path::Path>) -> Self {
4611        ElementId::Path(path)
4612    }
4613}
4614
4615impl From<&'static str> for ElementId {
4616    fn from(name: &'static str) -> Self {
4617        ElementId::Name(name.into())
4618    }
4619}
4620
4621impl<'a> From<&'a FocusHandle> for ElementId {
4622    fn from(handle: &'a FocusHandle) -> Self {
4623        ElementId::FocusHandle(handle.id)
4624    }
4625}
4626
4627impl From<(&'static str, EntityId)> for ElementId {
4628    fn from((name, id): (&'static str, EntityId)) -> Self {
4629        ElementId::NamedInteger(name.into(), id.as_u64())
4630    }
4631}
4632
4633impl From<(&'static str, usize)> for ElementId {
4634    fn from((name, id): (&'static str, usize)) -> Self {
4635        ElementId::NamedInteger(name.into(), id as u64)
4636    }
4637}
4638
4639impl From<(SharedString, usize)> for ElementId {
4640    fn from((name, id): (SharedString, usize)) -> Self {
4641        ElementId::NamedInteger(name, id as u64)
4642    }
4643}
4644
4645impl From<(&'static str, u64)> for ElementId {
4646    fn from((name, id): (&'static str, u64)) -> Self {
4647        ElementId::NamedInteger(name.into(), id)
4648    }
4649}
4650
4651impl From<Uuid> for ElementId {
4652    fn from(value: Uuid) -> Self {
4653        Self::Uuid(value)
4654    }
4655}
4656
4657impl From<(&'static str, u32)> for ElementId {
4658    fn from((name, id): (&'static str, u32)) -> Self {
4659        ElementId::NamedInteger(name.into(), id.into())
4660    }
4661}
4662
4663/// A rectangle to be rendered in the window at the given position and size.
4664/// Passed as an argument [`Window::paint_quad`].
4665#[derive(Clone)]
4666pub struct PaintQuad {
4667    /// The bounds of the quad within the window.
4668    pub bounds: Bounds<Pixels>,
4669    /// The radii of the quad's corners.
4670    pub corner_radii: Corners<Pixels>,
4671    /// The background color of the quad.
4672    pub background: Background,
4673    /// The widths of the quad's borders.
4674    pub border_widths: Edges<Pixels>,
4675    /// The color of the quad's borders.
4676    pub border_color: Hsla,
4677    /// The style of the quad's borders.
4678    pub border_style: BorderStyle,
4679}
4680
4681impl PaintQuad {
4682    /// Sets the corner radii of the quad.
4683    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4684        PaintQuad {
4685            corner_radii: corner_radii.into(),
4686            ..self
4687        }
4688    }
4689
4690    /// Sets the border widths of the quad.
4691    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4692        PaintQuad {
4693            border_widths: border_widths.into(),
4694            ..self
4695        }
4696    }
4697
4698    /// Sets the border color of the quad.
4699    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4700        PaintQuad {
4701            border_color: border_color.into(),
4702            ..self
4703        }
4704    }
4705
4706    /// Sets the background color of the quad.
4707    pub fn background(self, background: impl Into<Background>) -> Self {
4708        PaintQuad {
4709            background: background.into(),
4710            ..self
4711        }
4712    }
4713}
4714
4715/// Creates a quad with the given parameters.
4716pub fn quad(
4717    bounds: Bounds<Pixels>,
4718    corner_radii: impl Into<Corners<Pixels>>,
4719    background: impl Into<Background>,
4720    border_widths: impl Into<Edges<Pixels>>,
4721    border_color: impl Into<Hsla>,
4722    border_style: BorderStyle,
4723) -> PaintQuad {
4724    PaintQuad {
4725        bounds,
4726        corner_radii: corner_radii.into(),
4727        background: background.into(),
4728        border_widths: border_widths.into(),
4729        border_color: border_color.into(),
4730        border_style,
4731    }
4732}
4733
4734/// Creates a filled quad with the given bounds and background color.
4735pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
4736    PaintQuad {
4737        bounds: bounds.into(),
4738        corner_radii: (0.).into(),
4739        background: background.into(),
4740        border_widths: (0.).into(),
4741        border_color: transparent_black(),
4742        border_style: BorderStyle::default(),
4743    }
4744}
4745
4746/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4747pub fn outline(
4748    bounds: impl Into<Bounds<Pixels>>,
4749    border_color: impl Into<Hsla>,
4750    border_style: BorderStyle,
4751) -> PaintQuad {
4752    PaintQuad {
4753        bounds: bounds.into(),
4754        corner_radii: (0.).into(),
4755        background: transparent_black().into(),
4756        border_widths: (1.).into(),
4757        border_color: border_color.into(),
4758        border_style,
4759    }
4760}