window.rs

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