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