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