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