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