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            println!("setting focus for next frame");
2137            self.next_frame.focus = self.focus;
2138        }
2139
2140        self.next_frame.deferred_draws.extend(
2141            self.rendered_frame.deferred_draws
2142                [range.start.deferred_draws_index..range.end.deferred_draws_index]
2143                .iter()
2144                .map(|deferred_draw| DeferredDraw {
2145                    current_view: deferred_draw.current_view,
2146                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2147                    element_id_stack: deferred_draw.element_id_stack.clone(),
2148                    text_style_stack: deferred_draw.text_style_stack.clone(),
2149                    priority: deferred_draw.priority,
2150                    element: None,
2151                    absolute_offset: deferred_draw.absolute_offset,
2152                    prepaint_range: deferred_draw.prepaint_range.clone(),
2153                    paint_range: deferred_draw.paint_range.clone(),
2154                }),
2155        );
2156    }
2157
2158    pub(crate) fn paint_index(&self) -> PaintIndex {
2159        PaintIndex {
2160            scene_index: self.next_frame.scene.len(),
2161            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2162            input_handlers_index: self.next_frame.input_handlers.len(),
2163            cursor_styles_index: self.next_frame.cursor_styles.len(),
2164            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2165            line_layout_index: self.text_system.layout_index(),
2166        }
2167    }
2168
2169    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2170        self.next_frame.cursor_styles.extend(
2171            self.rendered_frame.cursor_styles
2172                [range.start.cursor_styles_index..range.end.cursor_styles_index]
2173                .iter()
2174                .cloned(),
2175        );
2176        self.next_frame.input_handlers.extend(
2177            self.rendered_frame.input_handlers
2178                [range.start.input_handlers_index..range.end.input_handlers_index]
2179                .iter_mut()
2180                .map(|handler| handler.take()),
2181        );
2182        self.next_frame.mouse_listeners.extend(
2183            self.rendered_frame.mouse_listeners
2184                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2185                .iter_mut()
2186                .map(|listener| listener.take()),
2187        );
2188        self.next_frame.accessed_element_states.extend(
2189            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2190                ..range.end.accessed_element_states_index]
2191                .iter()
2192                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
2193        );
2194
2195        self.text_system
2196            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2197        self.next_frame.scene.replay(
2198            range.start.scene_index..range.end.scene_index,
2199            &self.rendered_frame.scene,
2200        );
2201    }
2202
2203    /// Push a text style onto the stack, and call a function with that style active.
2204    /// Use [`Window::text_style`] to get the current, combined text style. This method
2205    /// should only be called as part of element drawing.
2206    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2207    where
2208        F: FnOnce(&mut Self) -> R,
2209    {
2210        self.invalidator.debug_assert_paint_or_prepaint();
2211        if let Some(style) = style {
2212            self.text_style_stack.push(style);
2213            let result = f(self);
2214            self.text_style_stack.pop();
2215            result
2216        } else {
2217            f(self)
2218        }
2219    }
2220
2221    /// Updates the cursor style at the platform level. This method should only be called
2222    /// during the prepaint phase of element drawing.
2223    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2224        self.invalidator.debug_assert_paint();
2225        self.next_frame.cursor_styles.push(CursorStyleRequest {
2226            hitbox_id: Some(hitbox.id),
2227            style,
2228        });
2229    }
2230
2231    /// Updates the cursor style for the entire window at the platform level. A cursor
2232    /// style using this method will have precedence over any cursor style set using
2233    /// `set_cursor_style`. This method should only be called during the prepaint
2234    /// phase of element drawing.
2235    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2236        self.invalidator.debug_assert_paint();
2237        self.next_frame.cursor_styles.push(CursorStyleRequest {
2238            hitbox_id: None,
2239            style,
2240        })
2241    }
2242
2243    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2244    /// during the paint phase of element drawing.
2245    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2246        self.invalidator.debug_assert_prepaint();
2247        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2248        self.next_frame
2249            .tooltip_requests
2250            .push(Some(TooltipRequest { id, tooltip }));
2251        id
2252    }
2253
2254    /// Invoke the given function with the given content mask after intersecting it
2255    /// with the current mask. This method should only be called during element drawing.
2256    pub fn with_content_mask<R>(
2257        &mut self,
2258        mask: Option<ContentMask<Pixels>>,
2259        f: impl FnOnce(&mut Self) -> R,
2260    ) -> R {
2261        self.invalidator.debug_assert_paint_or_prepaint();
2262        if let Some(mask) = mask {
2263            let mask = mask.intersect(&self.content_mask());
2264            self.content_mask_stack.push(mask);
2265            let result = f(self);
2266            self.content_mask_stack.pop();
2267            result
2268        } else {
2269            f(self)
2270        }
2271    }
2272
2273    /// Updates the global element offset relative to the current offset. This is used to implement
2274    /// scrolling. This method should only be called during the prepaint phase of element drawing.
2275    pub fn with_element_offset<R>(
2276        &mut self,
2277        offset: Point<Pixels>,
2278        f: impl FnOnce(&mut Self) -> R,
2279    ) -> R {
2280        self.invalidator.debug_assert_prepaint();
2281
2282        if offset.is_zero() {
2283            return f(self);
2284        };
2285
2286        let abs_offset = self.element_offset() + offset;
2287        self.with_absolute_element_offset(abs_offset, f)
2288    }
2289
2290    /// Updates the global element offset based on the given offset. This is used to implement
2291    /// drag handles and other manual painting of elements. This method should only be called during
2292    /// the prepaint phase of element drawing.
2293    pub fn with_absolute_element_offset<R>(
2294        &mut self,
2295        offset: Point<Pixels>,
2296        f: impl FnOnce(&mut Self) -> R,
2297    ) -> R {
2298        self.invalidator.debug_assert_prepaint();
2299        self.element_offset_stack.push(offset);
2300        let result = f(self);
2301        self.element_offset_stack.pop();
2302        result
2303    }
2304
2305    pub(crate) fn with_element_opacity<R>(
2306        &mut self,
2307        opacity: Option<f32>,
2308        f: impl FnOnce(&mut Self) -> R,
2309    ) -> R {
2310        if opacity.is_none() {
2311            return f(self);
2312        }
2313
2314        self.invalidator.debug_assert_paint_or_prepaint();
2315        self.element_opacity = opacity;
2316        let result = f(self);
2317        self.element_opacity = None;
2318        result
2319    }
2320
2321    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2322    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2323    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2324    /// element offset and prepaint again. See [`List`] for an example. This method should only be
2325    /// called during the prepaint phase of element drawing.
2326    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2327        self.invalidator.debug_assert_prepaint();
2328        let index = self.prepaint_index();
2329        let result = f(self);
2330        if result.is_err() {
2331            self.next_frame.hitboxes.truncate(index.hitboxes_index);
2332            self.next_frame
2333                .tooltip_requests
2334                .truncate(index.tooltips_index);
2335            self.next_frame
2336                .deferred_draws
2337                .truncate(index.deferred_draws_index);
2338            self.next_frame
2339                .dispatch_tree
2340                .truncate(index.dispatch_tree_index);
2341            self.next_frame
2342                .accessed_element_states
2343                .truncate(index.accessed_element_states_index);
2344            self.text_system.truncate_layouts(index.line_layout_index);
2345        }
2346        result
2347    }
2348
2349    /// When you call this method during [`prepaint`], containing elements will attempt to
2350    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2351    /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
2352    /// that supports this method being called on the elements it contains. This method should only be
2353    /// called during the prepaint phase of element drawing.
2354    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2355        self.invalidator.debug_assert_prepaint();
2356        self.requested_autoscroll = Some(bounds);
2357    }
2358
2359    /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
2360    /// described in [`request_autoscroll`].
2361    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2362        self.invalidator.debug_assert_prepaint();
2363        self.requested_autoscroll.take()
2364    }
2365
2366    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2367    /// Your view will be re-drawn once the asset has finished loading.
2368    ///
2369    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2370    /// time.
2371    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2372        let (task, is_first) = cx.fetch_asset::<A>(source);
2373        task.clone().now_or_never().or_else(|| {
2374            if is_first {
2375                let entity_id = self.current_view();
2376                self.spawn(cx, {
2377                    let task = task.clone();
2378                    async move |cx| {
2379                        task.await;
2380
2381                        cx.on_next_frame(move |_, cx| {
2382                            cx.notify(entity_id);
2383                        });
2384                    }
2385                })
2386                .detach();
2387            }
2388
2389            None
2390        })
2391    }
2392
2393    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
2394    /// Your view will not be re-drawn once the asset has finished loading.
2395    ///
2396    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2397    /// time.
2398    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2399        let (task, _) = cx.fetch_asset::<A>(source);
2400        task.clone().now_or_never()
2401    }
2402    /// Obtain the current element offset. This method should only be called during the
2403    /// prepaint phase of element drawing.
2404    pub fn element_offset(&self) -> Point<Pixels> {
2405        self.invalidator.debug_assert_prepaint();
2406        self.element_offset_stack
2407            .last()
2408            .copied()
2409            .unwrap_or_default()
2410    }
2411
2412    /// Obtain the current element opacity. This method should only be called during the
2413    /// prepaint phase of element drawing.
2414    pub(crate) fn element_opacity(&self) -> f32 {
2415        self.invalidator.debug_assert_paint_or_prepaint();
2416        self.element_opacity.unwrap_or(1.0)
2417    }
2418
2419    /// Obtain the current content mask. This method should only be called during element drawing.
2420    pub fn content_mask(&self) -> ContentMask<Pixels> {
2421        self.invalidator.debug_assert_paint_or_prepaint();
2422        self.content_mask_stack
2423            .last()
2424            .cloned()
2425            .unwrap_or_else(|| ContentMask {
2426                bounds: Bounds {
2427                    origin: Point::default(),
2428                    size: self.viewport_size,
2429                },
2430            })
2431    }
2432
2433    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2434    /// This can be used within a custom element to distinguish multiple sets of child elements.
2435    pub fn with_element_namespace<R>(
2436        &mut self,
2437        element_id: impl Into<ElementId>,
2438        f: impl FnOnce(&mut Self) -> R,
2439    ) -> R {
2440        self.element_id_stack.push(element_id.into());
2441        let result = f(self);
2442        self.element_id_stack.pop();
2443        result
2444    }
2445
2446    /// Updates or initializes state for an element with the given id that lives across multiple
2447    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2448    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2449    /// when drawing the next frame. This method should only be called as part of element drawing.
2450    pub fn with_element_state<S, R>(
2451        &mut self,
2452        global_id: &GlobalElementId,
2453        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2454    ) -> R
2455    where
2456        S: 'static,
2457    {
2458        self.invalidator.debug_assert_paint_or_prepaint();
2459
2460        let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
2461        self.next_frame
2462            .accessed_element_states
2463            .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2464
2465        if let Some(any) = self
2466            .next_frame
2467            .element_states
2468            .remove(&key)
2469            .or_else(|| self.rendered_frame.element_states.remove(&key))
2470        {
2471            let ElementStateBox {
2472                inner,
2473                #[cfg(debug_assertions)]
2474                type_name,
2475            } = any;
2476            // Using the extra inner option to avoid needing to reallocate a new box.
2477            let mut state_box = inner
2478                .downcast::<Option<S>>()
2479                .map_err(|_| {
2480                    #[cfg(debug_assertions)]
2481                    {
2482                        anyhow::anyhow!(
2483                            "invalid element state type for id, requested {:?}, actual: {:?}",
2484                            std::any::type_name::<S>(),
2485                            type_name
2486                        )
2487                    }
2488
2489                    #[cfg(not(debug_assertions))]
2490                    {
2491                        anyhow::anyhow!(
2492                            "invalid element state type for id, requested {:?}",
2493                            std::any::type_name::<S>(),
2494                        )
2495                    }
2496                })
2497                .unwrap();
2498
2499            let state = state_box.take().expect(
2500                "reentrant call to with_element_state for the same state type and element id",
2501            );
2502            let (result, state) = f(Some(state), self);
2503            state_box.replace(state);
2504            self.next_frame.element_states.insert(
2505                key,
2506                ElementStateBox {
2507                    inner: state_box,
2508                    #[cfg(debug_assertions)]
2509                    type_name,
2510                },
2511            );
2512            result
2513        } else {
2514            let (result, state) = f(None, self);
2515            self.next_frame.element_states.insert(
2516                key,
2517                ElementStateBox {
2518                    inner: Box::new(Some(state)),
2519                    #[cfg(debug_assertions)]
2520                    type_name: std::any::type_name::<S>(),
2521                },
2522            );
2523            result
2524        }
2525    }
2526
2527    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2528    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2529    /// when the element is guaranteed to have an id.
2530    ///
2531    /// The first option means 'no ID provided'
2532    /// The second option means 'not yet initialized'
2533    pub fn with_optional_element_state<S, R>(
2534        &mut self,
2535        global_id: Option<&GlobalElementId>,
2536        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2537    ) -> R
2538    where
2539        S: 'static,
2540    {
2541        self.invalidator.debug_assert_paint_or_prepaint();
2542
2543        if let Some(global_id) = global_id {
2544            self.with_element_state(global_id, |state, cx| {
2545                let (result, state) = f(Some(state), cx);
2546                let state =
2547                    state.expect("you must return some state when you pass some element id");
2548                (result, state)
2549            })
2550        } else {
2551            let (result, state) = f(None, self);
2552            debug_assert!(
2553                state.is_none(),
2554                "you must not return an element state when passing None for the global id"
2555            );
2556            result
2557        }
2558    }
2559
2560    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2561    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2562    /// with higher values being drawn on top.
2563    ///
2564    /// This method should only be called as part of the prepaint phase of element drawing.
2565    pub fn defer_draw(
2566        &mut self,
2567        element: AnyElement,
2568        absolute_offset: Point<Pixels>,
2569        priority: usize,
2570    ) {
2571        self.invalidator.debug_assert_prepaint();
2572        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
2573        self.next_frame.deferred_draws.push(DeferredDraw {
2574            current_view: self.current_view(),
2575            parent_node,
2576            element_id_stack: self.element_id_stack.clone(),
2577            text_style_stack: self.text_style_stack.clone(),
2578            priority,
2579            element: Some(element),
2580            absolute_offset,
2581            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2582            paint_range: PaintIndex::default()..PaintIndex::default(),
2583        });
2584    }
2585
2586    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2587    /// of geometry that are non-overlapping and have the same draw order. This is typically used
2588    /// for performance reasons.
2589    ///
2590    /// This method should only be called as part of the paint phase of element drawing.
2591    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2592        self.invalidator.debug_assert_paint();
2593
2594        let scale_factor = self.scale_factor();
2595        let content_mask = self.content_mask();
2596        let clipped_bounds = bounds.intersect(&content_mask.bounds);
2597        if !clipped_bounds.is_empty() {
2598            self.next_frame
2599                .scene
2600                .push_layer(clipped_bounds.scale(scale_factor));
2601        }
2602
2603        let result = f(self);
2604
2605        if !clipped_bounds.is_empty() {
2606            self.next_frame.scene.pop_layer();
2607        }
2608
2609        result
2610    }
2611
2612    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2613    ///
2614    /// This method should only be called as part of the paint phase of element drawing.
2615    pub fn paint_shadows(
2616        &mut self,
2617        bounds: Bounds<Pixels>,
2618        corner_radii: Corners<Pixels>,
2619        shadows: &[BoxShadow],
2620    ) {
2621        self.invalidator.debug_assert_paint();
2622
2623        let scale_factor = self.scale_factor();
2624        let content_mask = self.content_mask();
2625        let opacity = self.element_opacity();
2626        for shadow in shadows {
2627            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
2628            self.next_frame.scene.insert_primitive(Shadow {
2629                order: 0,
2630                blur_radius: shadow.blur_radius.scale(scale_factor),
2631                bounds: shadow_bounds.scale(scale_factor),
2632                content_mask: content_mask.scale(scale_factor),
2633                corner_radii: corner_radii.scale(scale_factor),
2634                color: shadow.color.opacity(opacity),
2635            });
2636        }
2637    }
2638
2639    /// Paint one or more quads into the scene for the next frame at the current stacking context.
2640    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2641    /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2642    ///
2643    /// This method should only be called as part of the paint phase of element drawing.
2644    ///
2645    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
2646    /// where the circular arcs meet. This will not display well when combined with dashed borders.
2647    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
2648    pub fn paint_quad(&mut self, quad: PaintQuad) {
2649        self.invalidator.debug_assert_paint();
2650
2651        let scale_factor = self.scale_factor();
2652        let content_mask = self.content_mask();
2653        let opacity = self.element_opacity();
2654        self.next_frame.scene.insert_primitive(Quad {
2655            order: 0,
2656            bounds: quad.bounds.scale(scale_factor),
2657            content_mask: content_mask.scale(scale_factor),
2658            background: quad.background.opacity(opacity),
2659            border_color: quad.border_color.opacity(opacity),
2660            corner_radii: quad.corner_radii.scale(scale_factor),
2661            border_widths: quad.border_widths.scale(scale_factor),
2662            border_style: quad.border_style,
2663        });
2664    }
2665
2666    /// Paint the given `Path` into the scene for the next frame at the current z-index.
2667    ///
2668    /// This method should only be called as part of the paint phase of element drawing.
2669    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
2670        self.invalidator.debug_assert_paint();
2671
2672        let scale_factor = self.scale_factor();
2673        let content_mask = self.content_mask();
2674        let opacity = self.element_opacity();
2675        path.content_mask = content_mask;
2676        let color: Background = color.into();
2677        path.color = color.opacity(opacity);
2678        self.next_frame
2679            .scene
2680            .insert_primitive(path.apply_scale(scale_factor));
2681    }
2682
2683    /// Paint an underline into the scene for the next frame at the current z-index.
2684    ///
2685    /// This method should only be called as part of the paint phase of element drawing.
2686    pub fn paint_underline(
2687        &mut self,
2688        origin: Point<Pixels>,
2689        width: Pixels,
2690        style: &UnderlineStyle,
2691    ) {
2692        self.invalidator.debug_assert_paint();
2693
2694        let scale_factor = self.scale_factor();
2695        let height = if style.wavy {
2696            style.thickness * 3.
2697        } else {
2698            style.thickness
2699        };
2700        let bounds = Bounds {
2701            origin,
2702            size: size(width, height),
2703        };
2704        let content_mask = self.content_mask();
2705        let element_opacity = self.element_opacity();
2706
2707        self.next_frame.scene.insert_primitive(Underline {
2708            order: 0,
2709            pad: 0,
2710            bounds: bounds.scale(scale_factor),
2711            content_mask: content_mask.scale(scale_factor),
2712            color: style.color.unwrap_or_default().opacity(element_opacity),
2713            thickness: style.thickness.scale(scale_factor),
2714            wavy: style.wavy,
2715        });
2716    }
2717
2718    /// Paint a strikethrough into the scene for the next frame at the current z-index.
2719    ///
2720    /// This method should only be called as part of the paint phase of element drawing.
2721    pub fn paint_strikethrough(
2722        &mut self,
2723        origin: Point<Pixels>,
2724        width: Pixels,
2725        style: &StrikethroughStyle,
2726    ) {
2727        self.invalidator.debug_assert_paint();
2728
2729        let scale_factor = self.scale_factor();
2730        let height = style.thickness;
2731        let bounds = Bounds {
2732            origin,
2733            size: size(width, height),
2734        };
2735        let content_mask = self.content_mask();
2736        let opacity = self.element_opacity();
2737
2738        self.next_frame.scene.insert_primitive(Underline {
2739            order: 0,
2740            pad: 0,
2741            bounds: bounds.scale(scale_factor),
2742            content_mask: content_mask.scale(scale_factor),
2743            thickness: style.thickness.scale(scale_factor),
2744            color: style.color.unwrap_or_default().opacity(opacity),
2745            wavy: false,
2746        });
2747    }
2748
2749    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2750    ///
2751    /// The y component of the origin is the baseline of the glyph.
2752    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2753    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2754    /// This method is only useful if you need to paint a single glyph that has already been shaped.
2755    ///
2756    /// This method should only be called as part of the paint phase of element drawing.
2757    pub fn paint_glyph(
2758        &mut self,
2759        origin: Point<Pixels>,
2760        font_id: FontId,
2761        glyph_id: GlyphId,
2762        font_size: Pixels,
2763        color: Hsla,
2764    ) -> Result<()> {
2765        self.invalidator.debug_assert_paint();
2766
2767        let element_opacity = self.element_opacity();
2768        let scale_factor = self.scale_factor();
2769        let glyph_origin = origin.scale(scale_factor);
2770        let subpixel_variant = Point {
2771            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2772            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2773        };
2774        let params = RenderGlyphParams {
2775            font_id,
2776            glyph_id,
2777            font_size,
2778            subpixel_variant,
2779            scale_factor,
2780            is_emoji: false,
2781        };
2782
2783        let raster_bounds = self.text_system().raster_bounds(&params)?;
2784        if !raster_bounds.is_zero() {
2785            let tile = self
2786                .sprite_atlas
2787                .get_or_insert_with(&params.clone().into(), &mut || {
2788                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2789                    Ok(Some((size, Cow::Owned(bytes))))
2790                })?
2791                .expect("Callback above only errors or returns Some");
2792            let bounds = Bounds {
2793                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2794                size: tile.bounds.size.map(Into::into),
2795            };
2796            let content_mask = self.content_mask().scale(scale_factor);
2797            self.next_frame.scene.insert_primitive(MonochromeSprite {
2798                order: 0,
2799                pad: 0,
2800                bounds,
2801                content_mask,
2802                color: color.opacity(element_opacity),
2803                tile,
2804                transformation: TransformationMatrix::unit(),
2805            });
2806        }
2807        Ok(())
2808    }
2809
2810    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2811    ///
2812    /// The y component of the origin is the baseline of the glyph.
2813    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2814    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2815    /// This method is only useful if you need to paint a single emoji that has already been shaped.
2816    ///
2817    /// This method should only be called as part of the paint phase of element drawing.
2818    pub fn paint_emoji(
2819        &mut self,
2820        origin: Point<Pixels>,
2821        font_id: FontId,
2822        glyph_id: GlyphId,
2823        font_size: Pixels,
2824    ) -> Result<()> {
2825        self.invalidator.debug_assert_paint();
2826
2827        let scale_factor = self.scale_factor();
2828        let glyph_origin = origin.scale(scale_factor);
2829        let params = RenderGlyphParams {
2830            font_id,
2831            glyph_id,
2832            font_size,
2833            // We don't render emojis with subpixel variants.
2834            subpixel_variant: Default::default(),
2835            scale_factor,
2836            is_emoji: true,
2837        };
2838
2839        let raster_bounds = self.text_system().raster_bounds(&params)?;
2840        if !raster_bounds.is_zero() {
2841            let tile = self
2842                .sprite_atlas
2843                .get_or_insert_with(&params.clone().into(), &mut || {
2844                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2845                    Ok(Some((size, Cow::Owned(bytes))))
2846                })?
2847                .expect("Callback above only errors or returns Some");
2848
2849            let bounds = Bounds {
2850                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2851                size: tile.bounds.size.map(Into::into),
2852            };
2853            let content_mask = self.content_mask().scale(scale_factor);
2854            let opacity = self.element_opacity();
2855
2856            self.next_frame.scene.insert_primitive(PolychromeSprite {
2857                order: 0,
2858                pad: 0,
2859                grayscale: false,
2860                bounds,
2861                corner_radii: Default::default(),
2862                content_mask,
2863                tile,
2864                opacity,
2865            });
2866        }
2867        Ok(())
2868    }
2869
2870    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2871    ///
2872    /// This method should only be called as part of the paint phase of element drawing.
2873    pub fn paint_svg(
2874        &mut self,
2875        bounds: Bounds<Pixels>,
2876        path: SharedString,
2877        transformation: TransformationMatrix,
2878        color: Hsla,
2879        cx: &App,
2880    ) -> Result<()> {
2881        self.invalidator.debug_assert_paint();
2882
2883        let element_opacity = self.element_opacity();
2884        let scale_factor = self.scale_factor();
2885        let bounds = bounds.scale(scale_factor);
2886        let params = RenderSvgParams {
2887            path,
2888            size: bounds.size.map(|pixels| {
2889                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
2890            }),
2891        };
2892
2893        let Some(tile) =
2894            self.sprite_atlas
2895                .get_or_insert_with(&params.clone().into(), &mut || {
2896                    let Some(bytes) = cx.svg_renderer.render(&params)? else {
2897                        return Ok(None);
2898                    };
2899                    Ok(Some((params.size, Cow::Owned(bytes))))
2900                })?
2901        else {
2902            return Ok(());
2903        };
2904        let content_mask = self.content_mask().scale(scale_factor);
2905
2906        self.next_frame.scene.insert_primitive(MonochromeSprite {
2907            order: 0,
2908            pad: 0,
2909            bounds: bounds
2910                .map_origin(|origin| origin.floor())
2911                .map_size(|size| size.ceil()),
2912            content_mask,
2913            color: color.opacity(element_opacity),
2914            tile,
2915            transformation,
2916        });
2917
2918        Ok(())
2919    }
2920
2921    /// Paint an image into the scene for the next frame at the current z-index.
2922    /// This method will panic if the frame_index is not valid
2923    ///
2924    /// This method should only be called as part of the paint phase of element drawing.
2925    pub fn paint_image(
2926        &mut self,
2927        bounds: Bounds<Pixels>,
2928        corner_radii: Corners<Pixels>,
2929        data: Arc<RenderImage>,
2930        frame_index: usize,
2931        grayscale: bool,
2932    ) -> Result<()> {
2933        self.invalidator.debug_assert_paint();
2934
2935        let scale_factor = self.scale_factor();
2936        let bounds = bounds.scale(scale_factor);
2937        let params = RenderImageParams {
2938            image_id: data.id,
2939            frame_index,
2940        };
2941
2942        let tile = self
2943            .sprite_atlas
2944            .get_or_insert_with(&params.clone().into(), &mut || {
2945                Ok(Some((
2946                    data.size(frame_index),
2947                    Cow::Borrowed(
2948                        data.as_bytes(frame_index)
2949                            .expect("It's the caller's job to pass a valid frame index"),
2950                    ),
2951                )))
2952            })?
2953            .expect("Callback above only returns Some");
2954        let content_mask = self.content_mask().scale(scale_factor);
2955        let corner_radii = corner_radii.scale(scale_factor);
2956        let opacity = self.element_opacity();
2957
2958        self.next_frame.scene.insert_primitive(PolychromeSprite {
2959            order: 0,
2960            pad: 0,
2961            grayscale,
2962            bounds: bounds
2963                .map_origin(|origin| origin.floor())
2964                .map_size(|size| size.ceil()),
2965            content_mask,
2966            corner_radii,
2967            tile,
2968            opacity,
2969        });
2970        Ok(())
2971    }
2972
2973    /// Paint a surface into the scene for the next frame at the current z-index.
2974    ///
2975    /// This method should only be called as part of the paint phase of element drawing.
2976    #[cfg(target_os = "macos")]
2977    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
2978        use crate::PaintSurface;
2979
2980        self.invalidator.debug_assert_paint();
2981
2982        let scale_factor = self.scale_factor();
2983        let bounds = bounds.scale(scale_factor);
2984        let content_mask = self.content_mask().scale(scale_factor);
2985        self.next_frame.scene.insert_primitive(PaintSurface {
2986            order: 0,
2987            bounds,
2988            content_mask,
2989            image_buffer,
2990        });
2991    }
2992
2993    /// Removes an image from the sprite atlas.
2994    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
2995        for frame_index in 0..data.frame_count() {
2996            let params = RenderImageParams {
2997                image_id: data.id,
2998                frame_index,
2999            };
3000
3001            self.sprite_atlas.remove(&params.clone().into());
3002        }
3003
3004        Ok(())
3005    }
3006
3007    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3008    /// layout is being requested, along with the layout ids of any children. This method is called during
3009    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3010    ///
3011    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3012    #[must_use]
3013    pub fn request_layout(
3014        &mut self,
3015        style: Style,
3016        children: impl IntoIterator<Item = LayoutId>,
3017        cx: &mut App,
3018    ) -> LayoutId {
3019        self.invalidator.debug_assert_prepaint();
3020
3021        cx.layout_id_buffer.clear();
3022        cx.layout_id_buffer.extend(children);
3023        let rem_size = self.rem_size();
3024
3025        self.layout_engine
3026            .as_mut()
3027            .unwrap()
3028            .request_layout(style, rem_size, &cx.layout_id_buffer)
3029    }
3030
3031    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3032    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3033    /// determine the element's size. One place this is used internally is when measuring text.
3034    ///
3035    /// The given closure is invoked at layout time with the known dimensions and available space and
3036    /// returns a `Size`.
3037    ///
3038    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3039    pub fn request_measured_layout<
3040        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3041            + 'static,
3042    >(
3043        &mut self,
3044        style: Style,
3045        measure: F,
3046    ) -> LayoutId {
3047        self.invalidator.debug_assert_prepaint();
3048
3049        let rem_size = self.rem_size();
3050        self.layout_engine
3051            .as_mut()
3052            .unwrap()
3053            .request_measured_layout(style, rem_size, measure)
3054    }
3055
3056    /// Compute the layout for the given id within the given available space.
3057    /// This method is called for its side effect, typically by the framework prior to painting.
3058    /// After calling it, you can request the bounds of the given layout node id or any descendant.
3059    ///
3060    /// This method should only be called as part of the prepaint phase of element drawing.
3061    pub fn compute_layout(
3062        &mut self,
3063        layout_id: LayoutId,
3064        available_space: Size<AvailableSpace>,
3065        cx: &mut App,
3066    ) {
3067        self.invalidator.debug_assert_prepaint();
3068
3069        let mut layout_engine = self.layout_engine.take().unwrap();
3070        layout_engine.compute_layout(layout_id, available_space, self, cx);
3071        self.layout_engine = Some(layout_engine);
3072    }
3073
3074    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3075    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3076    ///
3077    /// This method should only be called as part of element drawing.
3078    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3079        self.invalidator.debug_assert_prepaint();
3080
3081        let mut bounds = self
3082            .layout_engine
3083            .as_mut()
3084            .unwrap()
3085            .layout_bounds(layout_id)
3086            .map(Into::into);
3087        bounds.origin += self.element_offset();
3088        bounds
3089    }
3090
3091    /// This method should be called during `prepaint`. You can use
3092    /// the returned [Hitbox] during `paint` or in an event handler
3093    /// to determine whether the inserted hitbox was the topmost.
3094    ///
3095    /// This method should only be called as part of the prepaint phase of element drawing.
3096    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3097        self.invalidator.debug_assert_prepaint();
3098
3099        let content_mask = self.content_mask();
3100        let mut id = self.next_hitbox_id;
3101        self.next_hitbox_id = self.next_hitbox_id.next();
3102        let hitbox = Hitbox {
3103            id,
3104            bounds,
3105            content_mask,
3106            behavior,
3107        };
3108        self.next_frame.hitboxes.push(hitbox.clone());
3109        hitbox
3110    }
3111
3112    /// Set a hitbox which will act as a control area of the platform window.
3113    ///
3114    /// This method should only be called as part of the paint phase of element drawing.
3115    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3116        self.invalidator.debug_assert_paint();
3117        self.next_frame.window_control_hitboxes.push((area, hitbox));
3118    }
3119
3120    /// Sets the key context for the current element. This context will be used to translate
3121    /// keybindings into actions.
3122    ///
3123    /// This method should only be called as part of the paint phase of element drawing.
3124    pub fn set_key_context(&mut self, context: KeyContext) {
3125        self.invalidator.debug_assert_paint();
3126        self.next_frame.dispatch_tree.set_key_context(context);
3127    }
3128
3129    /// Sets the focus handle for the current element. This handle will be used to manage focus state
3130    /// and keyboard event dispatch for the element.
3131    ///
3132    /// This method should only be called as part of the prepaint phase of element drawing.
3133    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3134        self.invalidator.debug_assert_prepaint();
3135        if focus_handle.is_focused(self) {
3136            println!("setting focus for next frame");
3137            self.next_frame.focus = Some(focus_handle.id);
3138        }
3139        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3140    }
3141
3142    /// Sets the view id for the current element, which will be used to manage view caching.
3143    ///
3144    /// This method should only be called as part of element prepaint. We plan on removing this
3145    /// method eventually when we solve some issues that require us to construct editor elements
3146    /// directly instead of always using editors via views.
3147    pub fn set_view_id(&mut self, view_id: EntityId) {
3148        self.invalidator.debug_assert_prepaint();
3149        self.next_frame.dispatch_tree.set_view_id(view_id);
3150    }
3151
3152    /// Get the entity ID for the currently rendering view
3153    pub fn current_view(&self) -> EntityId {
3154        self.invalidator.debug_assert_paint_or_prepaint();
3155        self.rendered_entity_stack.last().copied().unwrap()
3156    }
3157
3158    pub(crate) fn with_rendered_view<R>(
3159        &mut self,
3160        id: EntityId,
3161        f: impl FnOnce(&mut Self) -> R,
3162    ) -> R {
3163        self.rendered_entity_stack.push(id);
3164        let result = f(self);
3165        self.rendered_entity_stack.pop();
3166        result
3167    }
3168
3169    /// Executes the provided function with the specified image cache.
3170    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3171    where
3172        F: FnOnce(&mut Self) -> R,
3173    {
3174        if let Some(image_cache) = image_cache {
3175            self.image_cache_stack.push(image_cache);
3176            let result = f(self);
3177            self.image_cache_stack.pop();
3178            result
3179        } else {
3180            f(self)
3181        }
3182    }
3183
3184    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
3185    /// platform to receive textual input with proper integration with concerns such
3186    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
3187    /// rendered.
3188    ///
3189    /// This method should only be called as part of the paint phase of element drawing.
3190    ///
3191    /// [element_input_handler]: crate::ElementInputHandler
3192    pub fn handle_input(
3193        &mut self,
3194        focus_handle: &FocusHandle,
3195        input_handler: impl InputHandler,
3196        cx: &App,
3197    ) {
3198        self.invalidator.debug_assert_paint();
3199
3200        if focus_handle.is_focused(self) {
3201            let cx = self.to_async(cx);
3202            self.next_frame
3203                .input_handlers
3204                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3205        }
3206    }
3207
3208    /// Register a mouse event listener on the window for the next frame. The type of event
3209    /// is determined by the first parameter of the given listener. When the next frame is rendered
3210    /// the listener will be cleared.
3211    ///
3212    /// This method should only be called as part of the paint phase of element drawing.
3213    pub fn on_mouse_event<Event: MouseEvent>(
3214        &mut self,
3215        mut handler: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3216    ) {
3217        self.invalidator.debug_assert_paint();
3218
3219        self.next_frame.mouse_listeners.push(Some(Box::new(
3220            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3221                if let Some(event) = event.downcast_ref() {
3222                    handler(event, phase, window, cx)
3223                }
3224            },
3225        )));
3226    }
3227
3228    /// Register a key event listener on the window for the next frame. The type of event
3229    /// is determined by the first parameter of the given listener. When the next frame is rendered
3230    /// the listener will be cleared.
3231    ///
3232    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3233    /// a specific need to register a global listener.
3234    ///
3235    /// This method should only be called as part of the paint phase of element drawing.
3236    pub fn on_key_event<Event: KeyEvent>(
3237        &mut self,
3238        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3239    ) {
3240        self.invalidator.debug_assert_paint();
3241
3242        self.next_frame.dispatch_tree.on_key_event(Rc::new(
3243            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
3244                if let Some(event) = event.downcast_ref::<Event>() {
3245                    listener(event, phase, window, cx)
3246                }
3247            },
3248        ));
3249    }
3250
3251    /// Register a modifiers changed event listener on the window for the next frame.
3252    ///
3253    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3254    /// a specific need to register a global listener.
3255    ///
3256    /// This method should only be called as part of the paint phase of element drawing.
3257    pub fn on_modifiers_changed(
3258        &mut self,
3259        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
3260    ) {
3261        self.invalidator.debug_assert_paint();
3262
3263        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
3264            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
3265                listener(event, window, cx)
3266            },
3267        ));
3268    }
3269
3270    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
3271    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
3272    /// Returns a subscription and persists until the subscription is dropped.
3273    pub fn on_focus_in(
3274        &mut self,
3275        handle: &FocusHandle,
3276        cx: &mut App,
3277        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
3278    ) -> Subscription {
3279        let focus_id = handle.id;
3280        let (subscription, activate) =
3281            self.new_focus_listener(Box::new(move |event, window, cx| {
3282                if event.is_focus_in(focus_id) {
3283                    listener(window, cx);
3284                }
3285                true
3286            }));
3287        cx.defer(move |_| activate());
3288        subscription
3289    }
3290
3291    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
3292    /// Returns a subscription and persists until the subscription is dropped.
3293    pub fn on_focus_out(
3294        &mut self,
3295        handle: &FocusHandle,
3296        cx: &mut App,
3297        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
3298    ) -> Subscription {
3299        let focus_id = handle.id;
3300        let (subscription, activate) =
3301            self.new_focus_listener(Box::new(move |event, window, cx| {
3302                if let Some(blurred_id) = event.previous_focus_path.last().copied() {
3303                    if event.is_focus_out(focus_id) {
3304                        let event = FocusOutEvent {
3305                            blurred: WeakFocusHandle {
3306                                id: blurred_id,
3307                                handles: Arc::downgrade(&cx.focus_handles),
3308                            },
3309                        };
3310                        listener(event, window, cx)
3311                    }
3312                }
3313                true
3314            }));
3315        cx.defer(move |_| activate());
3316        subscription
3317    }
3318
3319    fn reset_cursor_style(&self, cx: &mut App) {
3320        // Set the cursor only if we're the active window.
3321        if self.is_window_hovered() {
3322            let style = self
3323                .rendered_frame
3324                .cursor_style(self)
3325                .unwrap_or(CursorStyle::Arrow);
3326            cx.platform.set_cursor_style(style);
3327        }
3328    }
3329
3330    /// Dispatch a given keystroke as though the user had typed it.
3331    /// You can create a keystroke with Keystroke::parse("").
3332    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
3333        let keystroke = keystroke.with_simulated_ime();
3334        let result = self.dispatch_event(
3335            PlatformInput::KeyDown(KeyDownEvent {
3336                keystroke: keystroke.clone(),
3337                is_held: false,
3338            }),
3339            cx,
3340        );
3341        if !result.propagate {
3342            return true;
3343        }
3344
3345        if let Some(input) = keystroke.key_char {
3346            if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3347                input_handler.dispatch_input(&input, self, cx);
3348                self.platform_window.set_input_handler(input_handler);
3349                return true;
3350            }
3351        }
3352
3353        false
3354    }
3355
3356    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3357    /// binding for the action (last binding added to the keymap).
3358    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3359        self.highest_precedence_binding_for_action(action)
3360            .map(|binding| {
3361                binding
3362                    .keystrokes()
3363                    .iter()
3364                    .map(ToString::to_string)
3365                    .collect::<Vec<_>>()
3366                    .join(" ")
3367            })
3368            .unwrap_or_else(|| action.name().to_string())
3369    }
3370
3371    /// Dispatch a mouse or keyboard event on the window.
3372    #[profiling::function]
3373    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3374        self.last_input_timestamp.set(Instant::now());
3375        // Handlers may set this to false by calling `stop_propagation`.
3376        cx.propagate_event = true;
3377        // Handlers may set this to true by calling `prevent_default`.
3378        self.default_prevented = false;
3379
3380        let event = match event {
3381            // Track the mouse position with our own state, since accessing the platform
3382            // API for the mouse position can only occur on the main thread.
3383            PlatformInput::MouseMove(mouse_move) => {
3384                self.mouse_position = mouse_move.position;
3385                self.modifiers = mouse_move.modifiers;
3386                PlatformInput::MouseMove(mouse_move)
3387            }
3388            PlatformInput::MouseDown(mouse_down) => {
3389                self.mouse_position = mouse_down.position;
3390                self.modifiers = mouse_down.modifiers;
3391                PlatformInput::MouseDown(mouse_down)
3392            }
3393            PlatformInput::MouseUp(mouse_up) => {
3394                self.mouse_position = mouse_up.position;
3395                self.modifiers = mouse_up.modifiers;
3396                PlatformInput::MouseUp(mouse_up)
3397            }
3398            PlatformInput::MouseExited(mouse_exited) => {
3399                self.modifiers = mouse_exited.modifiers;
3400                PlatformInput::MouseExited(mouse_exited)
3401            }
3402            PlatformInput::ModifiersChanged(modifiers_changed) => {
3403                self.modifiers = modifiers_changed.modifiers;
3404                self.capslock = modifiers_changed.capslock;
3405                PlatformInput::ModifiersChanged(modifiers_changed)
3406            }
3407            PlatformInput::ScrollWheel(scroll_wheel) => {
3408                self.mouse_position = scroll_wheel.position;
3409                self.modifiers = scroll_wheel.modifiers;
3410                PlatformInput::ScrollWheel(scroll_wheel)
3411            }
3412            // Translate dragging and dropping of external files from the operating system
3413            // to internal drag and drop events.
3414            PlatformInput::FileDrop(file_drop) => match file_drop {
3415                FileDropEvent::Entered { position, paths } => {
3416                    self.mouse_position = position;
3417                    if cx.active_drag.is_none() {
3418                        cx.active_drag = Some(AnyDrag {
3419                            value: Arc::new(paths.clone()),
3420                            view: cx.new(|_| paths).into(),
3421                            cursor_offset: position,
3422                            cursor_style: None,
3423                        });
3424                    }
3425                    PlatformInput::MouseMove(MouseMoveEvent {
3426                        position,
3427                        pressed_button: Some(MouseButton::Left),
3428                        modifiers: Modifiers::default(),
3429                    })
3430                }
3431                FileDropEvent::Pending { position } => {
3432                    self.mouse_position = position;
3433                    PlatformInput::MouseMove(MouseMoveEvent {
3434                        position,
3435                        pressed_button: Some(MouseButton::Left),
3436                        modifiers: Modifiers::default(),
3437                    })
3438                }
3439                FileDropEvent::Submit { position } => {
3440                    cx.activate(true);
3441                    self.mouse_position = position;
3442                    PlatformInput::MouseUp(MouseUpEvent {
3443                        button: MouseButton::Left,
3444                        position,
3445                        modifiers: Modifiers::default(),
3446                        click_count: 1,
3447                    })
3448                }
3449                FileDropEvent::Exited => {
3450                    cx.active_drag.take();
3451                    PlatformInput::FileDrop(FileDropEvent::Exited)
3452                }
3453            },
3454            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3455        };
3456
3457        if let Some(any_mouse_event) = event.mouse_event() {
3458            self.dispatch_mouse_event(any_mouse_event, cx);
3459        } else if let Some(any_key_event) = event.keyboard_event() {
3460            self.dispatch_key_event(any_key_event, cx);
3461        }
3462
3463        DispatchEventResult {
3464            propagate: cx.propagate_event,
3465            default_prevented: self.default_prevented,
3466        }
3467    }
3468
3469    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3470        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3471        if hit_test != self.mouse_hit_test {
3472            self.mouse_hit_test = hit_test;
3473            self.reset_cursor_style(cx);
3474        }
3475
3476        #[cfg(any(feature = "inspector", debug_assertions))]
3477        if self.is_inspector_picking(cx) {
3478            self.handle_inspector_mouse_event(event, cx);
3479            // When inspector is picking, all other mouse handling is skipped.
3480            return;
3481        }
3482
3483        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3484
3485        // Capture phase, events bubble from back to front. Handlers for this phase are used for
3486        // special purposes, such as detecting events outside of a given Bounds.
3487        for listener in &mut mouse_listeners {
3488            let listener = listener.as_mut().unwrap();
3489            listener(event, DispatchPhase::Capture, self, cx);
3490            if !cx.propagate_event {
3491                break;
3492            }
3493        }
3494
3495        // Bubble phase, where most normal handlers do their work.
3496        if cx.propagate_event {
3497            for listener in mouse_listeners.iter_mut().rev() {
3498                let listener = listener.as_mut().unwrap();
3499                listener(event, DispatchPhase::Bubble, self, cx);
3500                if !cx.propagate_event {
3501                    break;
3502                }
3503            }
3504        }
3505
3506        self.rendered_frame.mouse_listeners = mouse_listeners;
3507
3508        if cx.has_active_drag() {
3509            if event.is::<MouseMoveEvent>() {
3510                // If this was a mouse move event, redraw the window so that the
3511                // active drag can follow the mouse cursor.
3512                self.refresh();
3513            } else if event.is::<MouseUpEvent>() {
3514                // If this was a mouse up event, cancel the active drag and redraw
3515                // the window.
3516                cx.active_drag = None;
3517                self.refresh();
3518            }
3519        }
3520    }
3521
3522    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3523        if self.invalidator.is_dirty() {
3524            self.draw(cx).clear();
3525        }
3526
3527        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3528        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3529
3530        let mut keystroke: Option<Keystroke> = None;
3531
3532        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3533            if event.modifiers.number_of_modifiers() == 0
3534                && self.pending_modifier.modifiers.number_of_modifiers() == 1
3535                && !self.pending_modifier.saw_keystroke
3536            {
3537                let key = match self.pending_modifier.modifiers {
3538                    modifiers if modifiers.shift => Some("shift"),
3539                    modifiers if modifiers.control => Some("control"),
3540                    modifiers if modifiers.alt => Some("alt"),
3541                    modifiers if modifiers.platform => Some("platform"),
3542                    modifiers if modifiers.function => Some("function"),
3543                    _ => None,
3544                };
3545                if let Some(key) = key {
3546                    keystroke = Some(Keystroke {
3547                        key: key.to_string(),
3548                        key_char: None,
3549                        modifiers: Modifiers::default(),
3550                    });
3551                }
3552            }
3553
3554            if self.pending_modifier.modifiers.number_of_modifiers() == 0
3555                && event.modifiers.number_of_modifiers() == 1
3556            {
3557                self.pending_modifier.saw_keystroke = false
3558            }
3559            self.pending_modifier.modifiers = event.modifiers
3560        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3561            self.pending_modifier.saw_keystroke = true;
3562            keystroke = Some(key_down_event.keystroke.clone());
3563        }
3564
3565        let Some(keystroke) = keystroke else {
3566            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3567            return;
3568        };
3569
3570        cx.propagate_event = true;
3571        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
3572        if !cx.propagate_event {
3573            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3574            return;
3575        }
3576
3577        let mut currently_pending = self.pending_input.take().unwrap_or_default();
3578        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3579            currently_pending = PendingInput::default();
3580        }
3581
3582        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3583            currently_pending.keystrokes,
3584            keystroke,
3585            &dispatch_path,
3586        );
3587
3588        if !match_result.to_replay.is_empty() {
3589            self.replay_pending_input(match_result.to_replay, cx)
3590        }
3591
3592        if !match_result.pending.is_empty() {
3593            currently_pending.keystrokes = match_result.pending;
3594            currently_pending.focus = self.focus;
3595            currently_pending.timer = Some(self.spawn(cx, async move |cx| {
3596                cx.background_executor.timer(Duration::from_secs(1)).await;
3597                cx.update(move |window, cx| {
3598                    let Some(currently_pending) = window
3599                        .pending_input
3600                        .take()
3601                        .filter(|pending| pending.focus == window.focus)
3602                    else {
3603                        return;
3604                    };
3605
3606                    let node_id = window.focus_node_id_in_rendered_frame(window.focus);
3607                    let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3608
3609                    let to_replay = window
3610                        .rendered_frame
3611                        .dispatch_tree
3612                        .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3613
3614                    window.pending_input_changed(cx);
3615                    window.replay_pending_input(to_replay, cx)
3616                })
3617                .log_err();
3618            }));
3619            self.pending_input = Some(currently_pending);
3620            self.pending_input_changed(cx);
3621            cx.propagate_event = false;
3622            return;
3623        }
3624
3625        for binding in match_result.bindings {
3626            self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3627            if !cx.propagate_event {
3628                self.dispatch_keystroke_observers(
3629                    event,
3630                    Some(binding.action),
3631                    match_result.context_stack.clone(),
3632                    cx,
3633                );
3634                self.pending_input_changed(cx);
3635                return;
3636            }
3637        }
3638
3639        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
3640        self.pending_input_changed(cx);
3641    }
3642
3643    fn finish_dispatch_key_event(
3644        &mut self,
3645        event: &dyn Any,
3646        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3647        context_stack: Vec<KeyContext>,
3648        cx: &mut App,
3649    ) {
3650        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
3651        if !cx.propagate_event {
3652            return;
3653        }
3654
3655        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
3656        if !cx.propagate_event {
3657            return;
3658        }
3659
3660        self.dispatch_keystroke_observers(event, None, context_stack, cx);
3661    }
3662
3663    fn pending_input_changed(&mut self, cx: &mut App) {
3664        self.pending_input_observers
3665            .clone()
3666            .retain(&(), |callback| callback(self, cx));
3667    }
3668
3669    fn dispatch_key_down_up_event(
3670        &mut self,
3671        event: &dyn Any,
3672        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3673        cx: &mut App,
3674    ) {
3675        // Capture phase
3676        for node_id in dispatch_path {
3677            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3678
3679            for key_listener in node.key_listeners.clone() {
3680                key_listener(event, DispatchPhase::Capture, self, cx);
3681                if !cx.propagate_event {
3682                    return;
3683                }
3684            }
3685        }
3686
3687        // Bubble phase
3688        for node_id in dispatch_path.iter().rev() {
3689            // Handle low level key events
3690            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3691            for key_listener in node.key_listeners.clone() {
3692                key_listener(event, DispatchPhase::Bubble, self, cx);
3693                if !cx.propagate_event {
3694                    return;
3695                }
3696            }
3697        }
3698    }
3699
3700    fn dispatch_modifiers_changed_event(
3701        &mut self,
3702        event: &dyn Any,
3703        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3704        cx: &mut App,
3705    ) {
3706        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3707            return;
3708        };
3709        for node_id in dispatch_path.iter().rev() {
3710            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3711            for listener in node.modifiers_changed_listeners.clone() {
3712                listener(event, self, cx);
3713                if !cx.propagate_event {
3714                    return;
3715                }
3716            }
3717        }
3718    }
3719
3720    /// Determine whether a potential multi-stroke key binding is in progress on this window.
3721    pub fn has_pending_keystrokes(&self) -> bool {
3722        self.pending_input.is_some()
3723    }
3724
3725    pub(crate) fn clear_pending_keystrokes(&mut self) {
3726        self.pending_input.take();
3727    }
3728
3729    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3730    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3731        self.pending_input
3732            .as_ref()
3733            .map(|pending_input| pending_input.keystrokes.as_slice())
3734    }
3735
3736    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
3737        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3738        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3739
3740        'replay: for replay in replays {
3741            let event = KeyDownEvent {
3742                keystroke: replay.keystroke.clone(),
3743                is_held: false,
3744            };
3745
3746            cx.propagate_event = true;
3747            for binding in replay.bindings {
3748                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3749                if !cx.propagate_event {
3750                    self.dispatch_keystroke_observers(
3751                        &event,
3752                        Some(binding.action),
3753                        Vec::default(),
3754                        cx,
3755                    );
3756                    continue 'replay;
3757                }
3758            }
3759
3760            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
3761            if !cx.propagate_event {
3762                continue 'replay;
3763            }
3764            if let Some(input) = replay.keystroke.key_char.as_ref().cloned() {
3765                if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3766                    input_handler.dispatch_input(&input, self, cx);
3767                    self.platform_window.set_input_handler(input_handler)
3768                }
3769            }
3770        }
3771    }
3772
3773    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
3774        focus_id
3775            .and_then(|focus_id| {
3776                self.rendered_frame
3777                    .dispatch_tree
3778                    .focusable_node_id(focus_id)
3779            })
3780            .unwrap_or_else(|| {
3781                println!("root node id");
3782                self.rendered_frame.dispatch_tree.root_node_id()
3783            })
3784    }
3785
3786    fn dispatch_action_on_node(
3787        &mut self,
3788        node_id: DispatchNodeId,
3789        action: &dyn Action,
3790        cx: &mut App,
3791    ) {
3792        dbg!("dispatch_action_on_node");
3793        dbg!(action.name());
3794        dbg!(action.as_any().type_id());
3795        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3796        dbg!(&dispatch_path);
3797
3798        // Capture phase for global actions.
3799        cx.propagate_event = true;
3800        if let Some(mut global_listeners) = cx
3801            .global_action_listeners
3802            .remove(&action.as_any().type_id())
3803        {
3804            dbg!(
3805                "Found global listeners for capture phase",
3806                global_listeners.len()
3807            );
3808            for listener in &global_listeners {
3809                dbg!("Executing global listener in capture phase");
3810                listener(action.as_any(), DispatchPhase::Capture, cx);
3811                if !cx.propagate_event {
3812                    dbg!("Event propagation stopped in global capture phase");
3813                    break;
3814                }
3815            }
3816
3817            global_listeners.extend(
3818                cx.global_action_listeners
3819                    .remove(&action.as_any().type_id())
3820                    .unwrap_or_default(),
3821            );
3822
3823            cx.global_action_listeners
3824                .insert(action.as_any().type_id(), global_listeners);
3825        }
3826
3827        if !cx.propagate_event {
3828            return;
3829        }
3830
3831        // Capture phase for window actions.
3832        for node_id in &dispatch_path {
3833            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3834            for DispatchActionListener {
3835                action_type,
3836                listener,
3837            } in node.action_listeners.clone()
3838            {
3839                let any_action = action.as_any();
3840                if action_type == any_action.type_id() {
3841                    dbg!("Found window action listener in capture phase", node_id);
3842                    listener(any_action, DispatchPhase::Capture, self, cx);
3843
3844                    if !cx.propagate_event {
3845                        dbg!("Event propagation stopped in window capture phase");
3846                        return;
3847                    }
3848                }
3849            }
3850        }
3851
3852        // Bubble phase for window actions.
3853        for node_id in dispatch_path.iter().rev() {
3854            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3855            for DispatchActionListener {
3856                action_type,
3857                listener,
3858            } in node.action_listeners.clone()
3859            {
3860                let any_action = action.as_any();
3861                if action_type == any_action.type_id() {
3862                    dbg!("Found window action listener in bubble phase", node_id);
3863                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3864                    listener(any_action, DispatchPhase::Bubble, self, cx);
3865
3866                    if !cx.propagate_event {
3867                        dbg!("Event propagation stopped in window bubble phase");
3868                        return;
3869                    }
3870                }
3871            }
3872        }
3873
3874        // Bubble phase for global actions.
3875        if let Some(mut global_listeners) = cx
3876            .global_action_listeners
3877            .remove(&action.as_any().type_id())
3878        {
3879            dbg!(
3880                "Found global listeners for bubble phase",
3881                global_listeners.len()
3882            );
3883            for listener in global_listeners.iter().rev() {
3884                dbg!("Executing global listener in bubble phase");
3885                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3886
3887                listener(action.as_any(), DispatchPhase::Bubble, cx);
3888                if !cx.propagate_event {
3889                    dbg!("Event propagation stopped in global bubble phase");
3890                    break;
3891                }
3892            }
3893
3894            global_listeners.extend(
3895                cx.global_action_listeners
3896                    .remove(&action.as_any().type_id())
3897                    .unwrap_or_default(),
3898            );
3899
3900            cx.global_action_listeners
3901                .insert(action.as_any().type_id(), global_listeners);
3902        }
3903    }
3904
3905    /// Register the given handler to be invoked whenever the global of the given type
3906    /// is updated.
3907    pub fn observe_global<G: Global>(
3908        &mut self,
3909        cx: &mut App,
3910        f: impl Fn(&mut Window, &mut App) + 'static,
3911    ) -> Subscription {
3912        let window_handle = self.handle;
3913        let (subscription, activate) = cx.global_observers.insert(
3914            TypeId::of::<G>(),
3915            Box::new(move |cx| {
3916                window_handle
3917                    .update(cx, |_, window, cx| f(window, cx))
3918                    .is_ok()
3919            }),
3920        );
3921        cx.defer(move |_| activate());
3922        subscription
3923    }
3924
3925    /// Focus the current window and bring it to the foreground at the platform level.
3926    pub fn activate_window(&self) {
3927        self.platform_window.activate();
3928    }
3929
3930    /// Minimize the current window at the platform level.
3931    pub fn minimize_window(&self) {
3932        self.platform_window.minimize();
3933    }
3934
3935    /// Toggle full screen status on the current window at the platform level.
3936    pub fn toggle_fullscreen(&self) {
3937        self.platform_window.toggle_fullscreen();
3938    }
3939
3940    /// Updates the IME panel position suggestions for languages like japanese, chinese.
3941    pub fn invalidate_character_coordinates(&self) {
3942        self.on_next_frame(|window, cx| {
3943            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
3944                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
3945                    window
3946                        .platform_window
3947                        .update_ime_position(bounds.scale(window.scale_factor()));
3948                }
3949                window.platform_window.set_input_handler(input_handler);
3950            }
3951        });
3952    }
3953
3954    /// Present a platform dialog.
3955    /// The provided message will be presented, along with buttons for each answer.
3956    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3957    pub fn prompt<T>(
3958        &mut self,
3959        level: PromptLevel,
3960        message: &str,
3961        detail: Option<&str>,
3962        answers: &[T],
3963        cx: &mut App,
3964    ) -> oneshot::Receiver<usize>
3965    where
3966        T: Clone + Into<PromptButton>,
3967    {
3968        let prompt_builder = cx.prompt_builder.take();
3969        let Some(prompt_builder) = prompt_builder else {
3970            unreachable!("Re-entrant window prompting is not supported by GPUI");
3971        };
3972
3973        let answers = answers
3974            .iter()
3975            .map(|answer| answer.clone().into())
3976            .collect::<Vec<_>>();
3977
3978        let receiver = match &prompt_builder {
3979            PromptBuilder::Default => self
3980                .platform_window
3981                .prompt(level, message, detail, &answers)
3982                .unwrap_or_else(|| {
3983                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
3984                }),
3985            PromptBuilder::Custom(_) => {
3986                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
3987            }
3988        };
3989
3990        cx.prompt_builder = Some(prompt_builder);
3991
3992        receiver
3993    }
3994
3995    fn build_custom_prompt(
3996        &mut self,
3997        prompt_builder: &PromptBuilder,
3998        level: PromptLevel,
3999        message: &str,
4000        detail: Option<&str>,
4001        answers: &[PromptButton],
4002        cx: &mut App,
4003    ) -> oneshot::Receiver<usize> {
4004        let (sender, receiver) = oneshot::channel();
4005        let handle = PromptHandle::new(sender);
4006        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4007        self.prompt = Some(handle);
4008        receiver
4009    }
4010
4011    /// Returns the current context stack.
4012    pub fn context_stack(&self) -> Vec<KeyContext> {
4013        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4014        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4015        dispatch_tree
4016            .dispatch_path(node_id)
4017            .iter()
4018            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4019            .collect()
4020    }
4021
4022    /// Returns all available actions for the focused element.
4023    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4024        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4025        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4026        for action_type in cx.global_action_listeners.keys() {
4027            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4028                let action = cx.actions.build_action_type(action_type).ok();
4029                if let Some(action) = action {
4030                    actions.insert(ix, action);
4031                }
4032            }
4033        }
4034        actions
4035    }
4036
4037    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4038    /// returned in the order they were added. For display, the last binding should take precedence.
4039    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4040        self.rendered_frame
4041            .dispatch_tree
4042            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4043    }
4044
4045    /// Returns the highest precedence key binding that invokes an action on the currently focused
4046    /// element. This is more efficient than getting the last result of `bindings_for_action`.
4047    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4048        self.rendered_frame
4049            .dispatch_tree
4050            .highest_precedence_binding_for_action(
4051                action,
4052                &self.rendered_frame.dispatch_tree.context_stack,
4053            )
4054    }
4055
4056    /// Returns the key bindings for an action in a context.
4057    pub fn bindings_for_action_in_context(
4058        &self,
4059        action: &dyn Action,
4060        context: KeyContext,
4061    ) -> Vec<KeyBinding> {
4062        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4063        dispatch_tree.bindings_for_action(action, &[context])
4064    }
4065
4066    /// Returns the highest precedence key binding for an action in a context. This is more
4067    /// efficient than getting the last result of `bindings_for_action_in_context`.
4068    pub fn highest_precedence_binding_for_action_in_context(
4069        &self,
4070        action: &dyn Action,
4071        context: KeyContext,
4072    ) -> Option<KeyBinding> {
4073        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4074        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4075    }
4076
4077    /// Returns any bindings that would invoke an action on the given focus handle if it were
4078    /// focused. Bindings are returned in the order they were added. For display, the last binding
4079    /// should take precedence.
4080    pub fn bindings_for_action_in(
4081        &self,
4082        action: &dyn Action,
4083        focus_handle: &FocusHandle,
4084    ) -> Vec<KeyBinding> {
4085        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4086        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4087            return vec![];
4088        };
4089        dispatch_tree.bindings_for_action(action, &context_stack)
4090    }
4091
4092    /// Returns the highest precedence key binding that would invoke an action on the given focus
4093    /// handle if it were focused. This is more efficient than getting the last result of
4094    /// `bindings_for_action_in`.
4095    pub fn highest_precedence_binding_for_action_in(
4096        &self,
4097        action: &dyn Action,
4098        focus_handle: &FocusHandle,
4099    ) -> Option<KeyBinding> {
4100        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4101        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4102        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4103    }
4104
4105    fn context_stack_for_focus_handle(
4106        &self,
4107        focus_handle: &FocusHandle,
4108    ) -> Option<Vec<KeyContext>> {
4109        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4110        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4111        let context_stack: Vec<_> = dispatch_tree
4112            .dispatch_path(node_id)
4113            .into_iter()
4114            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4115            .collect();
4116        Some(context_stack)
4117    }
4118
4119    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4120    pub fn listener_for<V: Render, E>(
4121        &self,
4122        view: &Entity<V>,
4123        f: impl Fn(&mut V, &E, &mut Window, &mut Context<V>) + 'static,
4124    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4125        let view = view.downgrade();
4126        move |e: &E, window: &mut Window, cx: &mut App| {
4127            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4128        }
4129    }
4130
4131    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4132    pub fn handler_for<V: Render, Callback: Fn(&mut V, &mut Window, &mut Context<V>) + 'static>(
4133        &self,
4134        view: &Entity<V>,
4135        f: Callback,
4136    ) -> impl Fn(&mut Window, &mut App) + use<V, Callback> {
4137        let view = view.downgrade();
4138        move |window: &mut Window, cx: &mut App| {
4139            view.update(cx, |view, cx| f(view, window, cx)).ok();
4140        }
4141    }
4142
4143    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4144    /// If the callback returns false, the window won't be closed.
4145    pub fn on_window_should_close(
4146        &self,
4147        cx: &App,
4148        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4149    ) {
4150        let mut cx = self.to_async(cx);
4151        self.platform_window.on_should_close(Box::new(move || {
4152            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4153        }))
4154    }
4155
4156    /// Register an action listener on the window for the next frame. The type of action
4157    /// is determined by the first parameter of the given listener. When the next frame is rendered
4158    /// the listener will be cleared.
4159    ///
4160    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4161    /// a specific need to register a global listener.
4162    pub fn on_action(
4163        &mut self,
4164        action_type: TypeId,
4165        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4166    ) {
4167        self.next_frame
4168            .dispatch_tree
4169            .on_action(action_type, Rc::new(listener));
4170    }
4171
4172    /// Read information about the GPU backing this window.
4173    /// Currently returns None on Mac and Windows.
4174    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4175        self.platform_window.gpu_specs()
4176    }
4177
4178    /// Perform titlebar double-click action.
4179    /// This is MacOS specific.
4180    pub fn titlebar_double_click(&self) {
4181        self.platform_window.titlebar_double_click();
4182    }
4183
4184    /// Toggles the inspector mode on this window.
4185    #[cfg(any(feature = "inspector", debug_assertions))]
4186    pub fn toggle_inspector(&mut self, cx: &mut App) {
4187        self.inspector = match self.inspector {
4188            None => Some(cx.new(|_| Inspector::new())),
4189            Some(_) => None,
4190        };
4191        self.refresh();
4192    }
4193
4194    /// Returns true if the window is in inspector mode.
4195    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
4196        #[cfg(any(feature = "inspector", debug_assertions))]
4197        {
4198            if let Some(inspector) = &self.inspector {
4199                return inspector.read(_cx).is_picking();
4200            }
4201        }
4202        false
4203    }
4204
4205    /// Executes the provided function with mutable access to an inspector state.
4206    #[cfg(any(feature = "inspector", debug_assertions))]
4207    pub fn with_inspector_state<T: 'static, R>(
4208        &mut self,
4209        _inspector_id: Option<&crate::InspectorElementId>,
4210        cx: &mut App,
4211        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
4212    ) -> R {
4213        if let Some(inspector_id) = _inspector_id {
4214            if let Some(inspector) = &self.inspector {
4215                let inspector = inspector.clone();
4216                let active_element_id = inspector.read(cx).active_element_id();
4217                if Some(inspector_id) == active_element_id {
4218                    return inspector.update(cx, |inspector, _cx| {
4219                        inspector.with_active_element_state(self, f)
4220                    });
4221                }
4222            }
4223        }
4224        f(&mut None, self)
4225    }
4226
4227    #[cfg(any(feature = "inspector", debug_assertions))]
4228    pub(crate) fn build_inspector_element_id(
4229        &mut self,
4230        path: crate::InspectorElementPath,
4231    ) -> crate::InspectorElementId {
4232        self.invalidator.debug_assert_paint_or_prepaint();
4233        let path = Rc::new(path);
4234        let next_instance_id = self
4235            .next_frame
4236            .next_inspector_instance_ids
4237            .entry(path.clone())
4238            .or_insert(0);
4239        let instance_id = *next_instance_id;
4240        *next_instance_id += 1;
4241        crate::InspectorElementId { path, instance_id }
4242    }
4243
4244    #[cfg(any(feature = "inspector", debug_assertions))]
4245    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
4246        if let Some(inspector) = self.inspector.take() {
4247            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
4248            inspector_element.prepaint_as_root(
4249                point(self.viewport_size.width - inspector_width, px(0.0)),
4250                size(inspector_width, self.viewport_size.height).into(),
4251                self,
4252                cx,
4253            );
4254            self.inspector = Some(inspector);
4255            Some(inspector_element)
4256        } else {
4257            None
4258        }
4259    }
4260
4261    #[cfg(any(feature = "inspector", debug_assertions))]
4262    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
4263        if let Some(mut inspector_element) = inspector_element {
4264            inspector_element.paint(self, cx);
4265        };
4266    }
4267
4268    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
4269    /// inspect UI elements by clicking on them.
4270    #[cfg(any(feature = "inspector", debug_assertions))]
4271    pub fn insert_inspector_hitbox(
4272        &mut self,
4273        hitbox_id: HitboxId,
4274        inspector_id: Option<&crate::InspectorElementId>,
4275        cx: &App,
4276    ) {
4277        self.invalidator.debug_assert_paint_or_prepaint();
4278        if !self.is_inspector_picking(cx) {
4279            return;
4280        }
4281        if let Some(inspector_id) = inspector_id {
4282            self.next_frame
4283                .inspector_hitboxes
4284                .insert(hitbox_id, inspector_id.clone());
4285        }
4286    }
4287
4288    #[cfg(any(feature = "inspector", debug_assertions))]
4289    fn paint_inspector_hitbox(&mut self, cx: &App) {
4290        if let Some(inspector) = self.inspector.as_ref() {
4291            let inspector = inspector.read(cx);
4292            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
4293            {
4294                if let Some(hitbox) = self
4295                    .next_frame
4296                    .hitboxes
4297                    .iter()
4298                    .find(|hitbox| hitbox.id == hitbox_id)
4299                {
4300                    self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
4301                }
4302            }
4303        }
4304    }
4305
4306    #[cfg(any(feature = "inspector", debug_assertions))]
4307    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4308        let Some(inspector) = self.inspector.clone() else {
4309            return;
4310        };
4311        if event.downcast_ref::<MouseMoveEvent>().is_some() {
4312            inspector.update(cx, |inspector, _cx| {
4313                if let Some((_, inspector_id)) =
4314                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4315                {
4316                    inspector.hover(inspector_id, self);
4317                }
4318            });
4319        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
4320            inspector.update(cx, |inspector, _cx| {
4321                if let Some((_, inspector_id)) =
4322                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4323                {
4324                    inspector.select(inspector_id, self);
4325                }
4326            });
4327        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
4328            // This should be kept in sync with SCROLL_LINES in x11 platform.
4329            const SCROLL_LINES: f32 = 3.0;
4330            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
4331            let delta_y = event
4332                .delta
4333                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
4334                .y;
4335            if let Some(inspector) = self.inspector.clone() {
4336                inspector.update(cx, |inspector, _cx| {
4337                    if let Some(depth) = inspector.pick_depth.as_mut() {
4338                        *depth += delta_y.0 / SCROLL_PIXELS_PER_LAYER;
4339                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
4340                        if *depth < 0.0 {
4341                            *depth = 0.0;
4342                        } else if *depth > max_depth {
4343                            *depth = max_depth;
4344                        }
4345                        if let Some((_, inspector_id)) =
4346                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4347                        {
4348                            inspector.set_active_element_id(inspector_id.clone(), self);
4349                        }
4350                    }
4351                });
4352            }
4353        }
4354    }
4355
4356    #[cfg(any(feature = "inspector", debug_assertions))]
4357    fn hovered_inspector_hitbox(
4358        &self,
4359        inspector: &Inspector,
4360        frame: &Frame,
4361    ) -> Option<(HitboxId, crate::InspectorElementId)> {
4362        if let Some(pick_depth) = inspector.pick_depth {
4363            let depth = (pick_depth as i64).try_into().unwrap_or(0);
4364            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
4365            let skip_count = (depth as usize).min(max_skipped);
4366            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
4367                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
4368                    return Some((*hitbox_id, inspector_id.clone()));
4369                }
4370            }
4371        }
4372        return None;
4373    }
4374}
4375
4376// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4377slotmap::new_key_type! {
4378    /// A unique identifier for a window.
4379    pub struct WindowId;
4380}
4381
4382impl WindowId {
4383    /// Converts this window ID to a `u64`.
4384    pub fn as_u64(&self) -> u64 {
4385        self.0.as_ffi()
4386    }
4387}
4388
4389impl From<u64> for WindowId {
4390    fn from(value: u64) -> Self {
4391        WindowId(slotmap::KeyData::from_ffi(value))
4392    }
4393}
4394
4395/// A handle to a window with a specific root view type.
4396/// Note that this does not keep the window alive on its own.
4397#[derive(Deref, DerefMut)]
4398pub struct WindowHandle<V> {
4399    #[deref]
4400    #[deref_mut]
4401    pub(crate) any_handle: AnyWindowHandle,
4402    state_type: PhantomData<V>,
4403}
4404
4405impl<V: 'static + Render> WindowHandle<V> {
4406    /// Creates a new handle from a window ID.
4407    /// This does not check if the root type of the window is `V`.
4408    pub fn new(id: WindowId) -> Self {
4409        WindowHandle {
4410            any_handle: AnyWindowHandle {
4411                id,
4412                state_type: TypeId::of::<V>(),
4413            },
4414            state_type: PhantomData,
4415        }
4416    }
4417
4418    /// Get the root view out of this window.
4419    ///
4420    /// This will fail if the window is closed or if the root view's type does not match `V`.
4421    #[cfg(any(test, feature = "test-support"))]
4422    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
4423    where
4424        C: AppContext,
4425    {
4426        crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
4427            root_view
4428                .downcast::<V>()
4429                .map_err(|_| anyhow!("the type of the window's root view has changed"))
4430        }))
4431    }
4432
4433    /// Updates the root view of this window.
4434    ///
4435    /// This will fail if the window has been closed or if the root view's type does not match
4436    pub fn update<C, R>(
4437        &self,
4438        cx: &mut C,
4439        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
4440    ) -> Result<R>
4441    where
4442        C: AppContext,
4443    {
4444        cx.update_window(self.any_handle, |root_view, window, cx| {
4445            let view = root_view
4446                .downcast::<V>()
4447                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4448
4449            Ok(view.update(cx, |view, cx| update(view, window, cx)))
4450        })?
4451    }
4452
4453    /// Read the root view out of this window.
4454    ///
4455    /// This will fail if the window is closed or if the root view's type does not match `V`.
4456    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
4457        let x = cx
4458            .windows
4459            .get(self.id)
4460            .and_then(|window| {
4461                window
4462                    .as_ref()
4463                    .and_then(|window| window.root.clone())
4464                    .map(|root_view| root_view.downcast::<V>())
4465            })
4466            .context("window not found")?
4467            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4468
4469        Ok(x.read(cx))
4470    }
4471
4472    /// Read the root view out of this window, with a callback
4473    ///
4474    /// This will fail if the window is closed or if the root view's type does not match `V`.
4475    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
4476    where
4477        C: AppContext,
4478    {
4479        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4480    }
4481
4482    /// Read the root view pointer off of this window.
4483    ///
4484    /// This will fail if the window is closed or if the root view's type does not match `V`.
4485    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
4486    where
4487        C: AppContext,
4488    {
4489        cx.read_window(self, |root_view, _cx| root_view.clone())
4490    }
4491
4492    /// Check if this window is 'active'.
4493    ///
4494    /// Will return `None` if the window is closed or currently
4495    /// borrowed.
4496    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
4497        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
4498            .ok()
4499    }
4500}
4501
4502impl<V> Copy for WindowHandle<V> {}
4503
4504impl<V> Clone for WindowHandle<V> {
4505    fn clone(&self) -> Self {
4506        *self
4507    }
4508}
4509
4510impl<V> PartialEq for WindowHandle<V> {
4511    fn eq(&self, other: &Self) -> bool {
4512        self.any_handle == other.any_handle
4513    }
4514}
4515
4516impl<V> Eq for WindowHandle<V> {}
4517
4518impl<V> Hash for WindowHandle<V> {
4519    fn hash<H: Hasher>(&self, state: &mut H) {
4520        self.any_handle.hash(state);
4521    }
4522}
4523
4524impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4525    fn from(val: WindowHandle<V>) -> Self {
4526        val.any_handle
4527    }
4528}
4529
4530unsafe impl<V> Send for WindowHandle<V> {}
4531unsafe impl<V> Sync for WindowHandle<V> {}
4532
4533/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4534#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4535pub struct AnyWindowHandle {
4536    pub(crate) id: WindowId,
4537    state_type: TypeId,
4538}
4539
4540impl AnyWindowHandle {
4541    /// Get the ID of this window.
4542    pub fn window_id(&self) -> WindowId {
4543        self.id
4544    }
4545
4546    /// Attempt to convert this handle to a window handle with a specific root view type.
4547    /// If the types do not match, this will return `None`.
4548    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4549        if TypeId::of::<T>() == self.state_type {
4550            Some(WindowHandle {
4551                any_handle: *self,
4552                state_type: PhantomData,
4553            })
4554        } else {
4555            None
4556        }
4557    }
4558
4559    /// Updates the state of the root view of this window.
4560    ///
4561    /// This will fail if the window has been closed.
4562    pub fn update<C, R>(
4563        self,
4564        cx: &mut C,
4565        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
4566    ) -> Result<R>
4567    where
4568        C: AppContext,
4569    {
4570        cx.update_window(self, update)
4571    }
4572
4573    /// Read the state of the root view of this window.
4574    ///
4575    /// This will fail if the window has been closed.
4576    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
4577    where
4578        C: AppContext,
4579        T: 'static,
4580    {
4581        let view = self
4582            .downcast::<T>()
4583            .context("the type of the window's root view has changed")?;
4584
4585        cx.read_window(&view, read)
4586    }
4587}
4588
4589impl HasWindowHandle for Window {
4590    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
4591        self.platform_window.window_handle()
4592    }
4593}
4594
4595impl HasDisplayHandle for Window {
4596    fn display_handle(
4597        &self,
4598    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
4599        self.platform_window.display_handle()
4600    }
4601}
4602
4603/// An identifier for an [`Element`](crate::Element).
4604///
4605/// Can be constructed with a string, a number, or both, as well
4606/// as other internal representations.
4607#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4608pub enum ElementId {
4609    /// The ID of a View element
4610    View(EntityId),
4611    /// An integer ID.
4612    Integer(u64),
4613    /// A string based ID.
4614    Name(SharedString),
4615    /// A UUID.
4616    Uuid(Uuid),
4617    /// An ID that's equated with a focus handle.
4618    FocusHandle(FocusId),
4619    /// A combination of a name and an integer.
4620    NamedInteger(SharedString, u64),
4621    /// A path.
4622    Path(Arc<std::path::Path>),
4623}
4624
4625impl ElementId {
4626    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
4627    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
4628        Self::NamedInteger(name.into(), integer as u64)
4629    }
4630}
4631
4632impl Display for ElementId {
4633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4634        match self {
4635            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4636            ElementId::Integer(ix) => write!(f, "{}", ix)?,
4637            ElementId::Name(name) => write!(f, "{}", name)?,
4638            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4639            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4640            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4641            ElementId::Path(path) => write!(f, "{}", path.display())?,
4642        }
4643
4644        Ok(())
4645    }
4646}
4647
4648impl TryInto<SharedString> for ElementId {
4649    type Error = anyhow::Error;
4650
4651    fn try_into(self) -> anyhow::Result<SharedString> {
4652        if let ElementId::Name(name) = self {
4653            Ok(name)
4654        } else {
4655            anyhow::bail!("element id is not string")
4656        }
4657    }
4658}
4659
4660impl From<usize> for ElementId {
4661    fn from(id: usize) -> Self {
4662        ElementId::Integer(id as u64)
4663    }
4664}
4665
4666impl From<i32> for ElementId {
4667    fn from(id: i32) -> Self {
4668        Self::Integer(id as u64)
4669    }
4670}
4671
4672impl From<SharedString> for ElementId {
4673    fn from(name: SharedString) -> Self {
4674        ElementId::Name(name)
4675    }
4676}
4677
4678impl From<Arc<std::path::Path>> for ElementId {
4679    fn from(path: Arc<std::path::Path>) -> Self {
4680        ElementId::Path(path)
4681    }
4682}
4683
4684impl From<&'static str> for ElementId {
4685    fn from(name: &'static str) -> Self {
4686        ElementId::Name(name.into())
4687    }
4688}
4689
4690impl<'a> From<&'a FocusHandle> for ElementId {
4691    fn from(handle: &'a FocusHandle) -> Self {
4692        ElementId::FocusHandle(handle.id)
4693    }
4694}
4695
4696impl From<(&'static str, EntityId)> for ElementId {
4697    fn from((name, id): (&'static str, EntityId)) -> Self {
4698        ElementId::NamedInteger(name.into(), id.as_u64())
4699    }
4700}
4701
4702impl From<(&'static str, usize)> for ElementId {
4703    fn from((name, id): (&'static str, usize)) -> Self {
4704        ElementId::NamedInteger(name.into(), id as u64)
4705    }
4706}
4707
4708impl From<(SharedString, usize)> for ElementId {
4709    fn from((name, id): (SharedString, usize)) -> Self {
4710        ElementId::NamedInteger(name, id as u64)
4711    }
4712}
4713
4714impl From<(&'static str, u64)> for ElementId {
4715    fn from((name, id): (&'static str, u64)) -> Self {
4716        ElementId::NamedInteger(name.into(), id)
4717    }
4718}
4719
4720impl From<Uuid> for ElementId {
4721    fn from(value: Uuid) -> Self {
4722        Self::Uuid(value)
4723    }
4724}
4725
4726impl From<(&'static str, u32)> for ElementId {
4727    fn from((name, id): (&'static str, u32)) -> Self {
4728        ElementId::NamedInteger(name.into(), id.into())
4729    }
4730}
4731
4732/// A rectangle to be rendered in the window at the given position and size.
4733/// Passed as an argument [`Window::paint_quad`].
4734#[derive(Clone)]
4735pub struct PaintQuad {
4736    /// The bounds of the quad within the window.
4737    pub bounds: Bounds<Pixels>,
4738    /// The radii of the quad's corners.
4739    pub corner_radii: Corners<Pixels>,
4740    /// The background color of the quad.
4741    pub background: Background,
4742    /// The widths of the quad's borders.
4743    pub border_widths: Edges<Pixels>,
4744    /// The color of the quad's borders.
4745    pub border_color: Hsla,
4746    /// The style of the quad's borders.
4747    pub border_style: BorderStyle,
4748}
4749
4750impl PaintQuad {
4751    /// Sets the corner radii of the quad.
4752    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4753        PaintQuad {
4754            corner_radii: corner_radii.into(),
4755            ..self
4756        }
4757    }
4758
4759    /// Sets the border widths of the quad.
4760    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4761        PaintQuad {
4762            border_widths: border_widths.into(),
4763            ..self
4764        }
4765    }
4766
4767    /// Sets the border color of the quad.
4768    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4769        PaintQuad {
4770            border_color: border_color.into(),
4771            ..self
4772        }
4773    }
4774
4775    /// Sets the background color of the quad.
4776    pub fn background(self, background: impl Into<Background>) -> Self {
4777        PaintQuad {
4778            background: background.into(),
4779            ..self
4780        }
4781    }
4782}
4783
4784/// Creates a quad with the given parameters.
4785pub fn quad(
4786    bounds: Bounds<Pixels>,
4787    corner_radii: impl Into<Corners<Pixels>>,
4788    background: impl Into<Background>,
4789    border_widths: impl Into<Edges<Pixels>>,
4790    border_color: impl Into<Hsla>,
4791    border_style: BorderStyle,
4792) -> PaintQuad {
4793    PaintQuad {
4794        bounds,
4795        corner_radii: corner_radii.into(),
4796        background: background.into(),
4797        border_widths: border_widths.into(),
4798        border_color: border_color.into(),
4799        border_style,
4800    }
4801}
4802
4803/// Creates a filled quad with the given bounds and background color.
4804pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
4805    PaintQuad {
4806        bounds: bounds.into(),
4807        corner_radii: (0.).into(),
4808        background: background.into(),
4809        border_widths: (0.).into(),
4810        border_color: transparent_black(),
4811        border_style: BorderStyle::default(),
4812    }
4813}
4814
4815/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4816pub fn outline(
4817    bounds: impl Into<Bounds<Pixels>>,
4818    border_color: impl Into<Hsla>,
4819    border_style: BorderStyle,
4820) -> PaintQuad {
4821    PaintQuad {
4822        bounds: bounds.into(),
4823        corner_radii: (0.).into(),
4824        background: transparent_black().into(),
4825        border_widths: (1.).into(),
4826        border_color: border_color.into(),
4827        border_style,
4828    }
4829}