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, cx: &mut App) {
 349        window.focus(self, cx)
 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, cx: &mut App) {
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
1447        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
1448        // current effect cycle, and only for this window.
1449        let window_handle = self.handle;
1450        cx.defer(move |cx| {
1451            window_handle
1452                .update(cx, |_, window, cx| {
1453                    window.pending_input_changed(cx);
1454                })
1455                .ok();
1456        });
1457
1458        self.refresh();
1459    }
1460
1461    /// Remove focus from all elements within this context's window.
1462    pub fn blur(&mut self) {
1463        if !self.focus_enabled {
1464            return;
1465        }
1466
1467        self.focus = None;
1468        self.refresh();
1469    }
1470
1471    /// Blur the window and don't allow anything in it to be focused again.
1472    pub fn disable_focus(&mut self) {
1473        self.blur();
1474        self.focus_enabled = false;
1475    }
1476
1477    /// Move focus to next tab stop.
1478    pub fn focus_next(&mut self, cx: &mut App) {
1479        if !self.focus_enabled {
1480            return;
1481        }
1482
1483        if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
1484            self.focus(&handle, cx)
1485        }
1486    }
1487
1488    /// Move focus to previous tab stop.
1489    pub fn focus_prev(&mut self, cx: &mut App) {
1490        if !self.focus_enabled {
1491            return;
1492        }
1493
1494        if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
1495            self.focus(&handle, cx)
1496        }
1497    }
1498
1499    /// Accessor for the text system.
1500    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1501        &self.text_system
1502    }
1503
1504    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1505    pub fn text_style(&self) -> TextStyle {
1506        let mut style = TextStyle::default();
1507        for refinement in &self.text_style_stack {
1508            style.refine(refinement);
1509        }
1510        style
1511    }
1512
1513    /// Check if the platform window is maximized.
1514    ///
1515    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1516    pub fn is_maximized(&self) -> bool {
1517        self.platform_window.is_maximized()
1518    }
1519
1520    /// request a certain window decoration (Wayland)
1521    pub fn request_decorations(&self, decorations: WindowDecorations) {
1522        self.platform_window.request_decorations(decorations);
1523    }
1524
1525    /// Start a window resize operation (Wayland)
1526    pub fn start_window_resize(&self, edge: ResizeEdge) {
1527        self.platform_window.start_window_resize(edge);
1528    }
1529
1530    /// Return the `WindowBounds` to indicate that how a window should be opened
1531    /// after it has been closed
1532    pub fn window_bounds(&self) -> WindowBounds {
1533        self.platform_window.window_bounds()
1534    }
1535
1536    /// Return the `WindowBounds` excluding insets (Wayland and X11)
1537    pub fn inner_window_bounds(&self) -> WindowBounds {
1538        self.platform_window.inner_window_bounds()
1539    }
1540
1541    /// Dispatch the given action on the currently focused element.
1542    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1543        let focus_id = self.focused(cx).map(|handle| handle.id);
1544
1545        let window = self.handle;
1546        cx.defer(move |cx| {
1547            window
1548                .update(cx, |_, window, cx| {
1549                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1550                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1551                })
1552                .log_err();
1553        })
1554    }
1555
1556    pub(crate) fn dispatch_keystroke_observers(
1557        &mut self,
1558        event: &dyn Any,
1559        action: Option<Box<dyn Action>>,
1560        context_stack: Vec<KeyContext>,
1561        cx: &mut App,
1562    ) {
1563        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1564            return;
1565        };
1566
1567        cx.keystroke_observers.clone().retain(&(), move |callback| {
1568            (callback)(
1569                &KeystrokeEvent {
1570                    keystroke: key_down_event.keystroke.clone(),
1571                    action: action.as_ref().map(|action| action.boxed_clone()),
1572                    context_stack: context_stack.clone(),
1573                },
1574                self,
1575                cx,
1576            )
1577        });
1578    }
1579
1580    pub(crate) fn dispatch_keystroke_interceptors(
1581        &mut self,
1582        event: &dyn Any,
1583        context_stack: Vec<KeyContext>,
1584        cx: &mut App,
1585    ) {
1586        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1587            return;
1588        };
1589
1590        cx.keystroke_interceptors
1591            .clone()
1592            .retain(&(), move |callback| {
1593                (callback)(
1594                    &KeystrokeEvent {
1595                        keystroke: key_down_event.keystroke.clone(),
1596                        action: None,
1597                        context_stack: context_stack.clone(),
1598                    },
1599                    self,
1600                    cx,
1601                )
1602            });
1603    }
1604
1605    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1606    /// that are currently on the stack to be returned to the app.
1607    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1608        let handle = self.handle;
1609        cx.defer(move |cx| {
1610            handle.update(cx, |_, window, cx| f(window, cx)).ok();
1611        });
1612    }
1613
1614    /// Subscribe to events emitted by a entity.
1615    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1616    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1617    pub fn observe<T: 'static>(
1618        &mut self,
1619        observed: &Entity<T>,
1620        cx: &mut App,
1621        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1622    ) -> Subscription {
1623        let entity_id = observed.entity_id();
1624        let observed = observed.downgrade();
1625        let window_handle = self.handle;
1626        cx.new_observer(
1627            entity_id,
1628            Box::new(move |cx| {
1629                window_handle
1630                    .update(cx, |_, window, cx| {
1631                        if let Some(handle) = observed.upgrade() {
1632                            on_notify(handle, window, cx);
1633                            true
1634                        } else {
1635                            false
1636                        }
1637                    })
1638                    .unwrap_or(false)
1639            }),
1640        )
1641    }
1642
1643    /// Subscribe to events emitted by a entity.
1644    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1645    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1646    pub fn subscribe<Emitter, Evt>(
1647        &mut self,
1648        entity: &Entity<Emitter>,
1649        cx: &mut App,
1650        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1651    ) -> Subscription
1652    where
1653        Emitter: EventEmitter<Evt>,
1654        Evt: 'static,
1655    {
1656        let entity_id = entity.entity_id();
1657        let handle = entity.downgrade();
1658        let window_handle = self.handle;
1659        cx.new_subscription(
1660            entity_id,
1661            (
1662                TypeId::of::<Evt>(),
1663                Box::new(move |event, cx| {
1664                    window_handle
1665                        .update(cx, |_, window, cx| {
1666                            if let Some(entity) = handle.upgrade() {
1667                                let event = event.downcast_ref().expect("invalid event type");
1668                                on_event(entity, event, window, cx);
1669                                true
1670                            } else {
1671                                false
1672                            }
1673                        })
1674                        .unwrap_or(false)
1675                }),
1676            ),
1677        )
1678    }
1679
1680    /// Register a callback to be invoked when the given `Entity` is released.
1681    pub fn observe_release<T>(
1682        &self,
1683        entity: &Entity<T>,
1684        cx: &mut App,
1685        mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1686    ) -> Subscription
1687    where
1688        T: 'static,
1689    {
1690        let entity_id = entity.entity_id();
1691        let window_handle = self.handle;
1692        let (subscription, activate) = cx.release_listeners.insert(
1693            entity_id,
1694            Box::new(move |entity, cx| {
1695                let entity = entity.downcast_mut().expect("invalid entity type");
1696                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1697            }),
1698        );
1699        activate();
1700        subscription
1701    }
1702
1703    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1704    /// await points in async code.
1705    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1706        AsyncWindowContext::new_context(cx.to_async(), self.handle)
1707    }
1708
1709    /// Schedule the given closure to be run directly after the current frame is rendered.
1710    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1711        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1712    }
1713
1714    /// Schedule a frame to be drawn on the next animation frame.
1715    ///
1716    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
1717    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
1718    ///
1719    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
1720    pub fn request_animation_frame(&self) {
1721        let entity = self.current_view();
1722        self.on_next_frame(move |_, cx| cx.notify(entity));
1723    }
1724
1725    /// Spawn the future returned by the given closure on the application thread pool.
1726    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1727    /// use within your future.
1728    #[track_caller]
1729    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
1730    where
1731        R: 'static,
1732        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1733    {
1734        let handle = self.handle;
1735        cx.spawn(async move |app| {
1736            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1737            f(&mut async_window_cx).await
1738        })
1739    }
1740
1741    /// Spawn the future returned by the given closure on the application thread
1742    /// pool, with the given priority. The closure is provided a handle to the
1743    /// current window and an `AsyncWindowContext` for use within your future.
1744    #[track_caller]
1745    pub fn spawn_with_priority<AsyncFn, R>(
1746        &self,
1747        priority: Priority,
1748        cx: &App,
1749        f: AsyncFn,
1750    ) -> Task<R>
1751    where
1752        R: 'static,
1753        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1754    {
1755        let handle = self.handle;
1756        cx.spawn_with_priority(priority, async move |app| {
1757            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1758            f(&mut async_window_cx).await
1759        })
1760    }
1761
1762    fn bounds_changed(&mut self, cx: &mut App) {
1763        self.scale_factor = self.platform_window.scale_factor();
1764        self.viewport_size = self.platform_window.content_size();
1765        self.display_id = self.platform_window.display().map(|display| display.id());
1766
1767        self.refresh();
1768
1769        self.bounds_observers
1770            .clone()
1771            .retain(&(), |callback| callback(self, cx));
1772    }
1773
1774    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1775    pub fn bounds(&self) -> Bounds<Pixels> {
1776        self.platform_window.bounds()
1777    }
1778
1779    /// Returns the native window ID (CGWindowID on macOS) for window capture.
1780    /// This is used by visual testing infrastructure to capture window screenshots.
1781    /// Returns None on platforms that don't support this or in non-test builds.
1782    #[cfg(any(test, feature = "test-support"))]
1783    pub fn native_window_id(&self) -> Option<u32> {
1784        self.platform_window.native_window_id()
1785    }
1786
1787    /// Set the content size of the window.
1788    pub fn resize(&mut self, size: Size<Pixels>) {
1789        self.platform_window.resize(size);
1790    }
1791
1792    /// Returns whether or not the window is currently fullscreen
1793    pub fn is_fullscreen(&self) -> bool {
1794        self.platform_window.is_fullscreen()
1795    }
1796
1797    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1798        self.appearance = self.platform_window.appearance();
1799
1800        self.appearance_observers
1801            .clone()
1802            .retain(&(), |callback| callback(self, cx));
1803    }
1804
1805    /// Returns the appearance of the current window.
1806    pub fn appearance(&self) -> WindowAppearance {
1807        self.appearance
1808    }
1809
1810    /// Returns the size of the drawable area within the window.
1811    pub fn viewport_size(&self) -> Size<Pixels> {
1812        self.viewport_size
1813    }
1814
1815    /// Returns whether this window is focused by the operating system (receiving key events).
1816    pub fn is_window_active(&self) -> bool {
1817        self.active.get()
1818    }
1819
1820    /// Returns whether this window is considered to be the window
1821    /// that currently owns the mouse cursor.
1822    /// On mac, this is equivalent to `is_window_active`.
1823    pub fn is_window_hovered(&self) -> bool {
1824        if cfg!(any(
1825            target_os = "windows",
1826            target_os = "linux",
1827            target_os = "freebsd"
1828        )) {
1829            self.hovered.get()
1830        } else {
1831            self.is_window_active()
1832        }
1833    }
1834
1835    /// Toggle zoom on the window.
1836    pub fn zoom_window(&self) {
1837        self.platform_window.zoom();
1838    }
1839
1840    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1841    pub fn show_window_menu(&self, position: Point<Pixels>) {
1842        self.platform_window.show_window_menu(position)
1843    }
1844
1845    /// Handle window movement for Linux and macOS.
1846    /// Tells the compositor to take control of window movement (Wayland and X11)
1847    ///
1848    /// Events may not be received during a move operation.
1849    pub fn start_window_move(&self) {
1850        self.platform_window.start_window_move()
1851    }
1852
1853    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
1854    pub fn set_client_inset(&mut self, inset: Pixels) {
1855        self.client_inset = Some(inset);
1856        self.platform_window.set_client_inset(inset);
1857    }
1858
1859    /// Returns the client_inset value by [`Self::set_client_inset`].
1860    pub fn client_inset(&self) -> Option<Pixels> {
1861        self.client_inset
1862    }
1863
1864    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1865    pub fn window_decorations(&self) -> Decorations {
1866        self.platform_window.window_decorations()
1867    }
1868
1869    /// Returns which window controls are currently visible (Wayland)
1870    pub fn window_controls(&self) -> WindowControls {
1871        self.platform_window.window_controls()
1872    }
1873
1874    /// Updates the window's title at the platform level.
1875    pub fn set_window_title(&mut self, title: &str) {
1876        self.platform_window.set_title(title);
1877    }
1878
1879    /// Sets the application identifier.
1880    pub fn set_app_id(&mut self, app_id: &str) {
1881        self.platform_window.set_app_id(app_id);
1882    }
1883
1884    /// Sets the window background appearance.
1885    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1886        self.platform_window
1887            .set_background_appearance(background_appearance);
1888    }
1889
1890    /// Mark the window as dirty at the platform level.
1891    pub fn set_window_edited(&mut self, edited: bool) {
1892        self.platform_window.set_edited(edited);
1893    }
1894
1895    /// Determine the display on which the window is visible.
1896    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
1897        cx.platform
1898            .displays()
1899            .into_iter()
1900            .find(|display| Some(display.id()) == self.display_id)
1901    }
1902
1903    /// Show the platform character palette.
1904    pub fn show_character_palette(&self) {
1905        self.platform_window.show_character_palette();
1906    }
1907
1908    /// The scale factor of the display associated with the window. For example, it could
1909    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1910    /// be rendered as two pixels on screen.
1911    pub fn scale_factor(&self) -> f32 {
1912        self.scale_factor
1913    }
1914
1915    /// The size of an em for the base font of the application. Adjusting this value allows the
1916    /// UI to scale, just like zooming a web page.
1917    pub fn rem_size(&self) -> Pixels {
1918        self.rem_size_override_stack
1919            .last()
1920            .copied()
1921            .unwrap_or(self.rem_size)
1922    }
1923
1924    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1925    /// UI to scale, just like zooming a web page.
1926    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1927        self.rem_size = rem_size.into();
1928    }
1929
1930    /// Acquire a globally unique identifier for the given ElementId.
1931    /// Only valid for the duration of the provided closure.
1932    pub fn with_global_id<R>(
1933        &mut self,
1934        element_id: ElementId,
1935        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
1936    ) -> R {
1937        self.element_id_stack.push(element_id);
1938        let global_id = GlobalElementId(Arc::from(&*self.element_id_stack));
1939
1940        let result = f(&global_id, self);
1941        self.element_id_stack.pop();
1942        result
1943    }
1944
1945    /// Executes the provided function with the specified rem size.
1946    ///
1947    /// This method must only be called as part of element drawing.
1948    // This function is called in a highly recursive manner in editor
1949    // prepainting, make sure its inlined to reduce the stack burden
1950    #[inline]
1951    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1952    where
1953        F: FnOnce(&mut Self) -> R,
1954    {
1955        self.invalidator.debug_assert_paint_or_prepaint();
1956
1957        if let Some(rem_size) = rem_size {
1958            self.rem_size_override_stack.push(rem_size.into());
1959            let result = f(self);
1960            self.rem_size_override_stack.pop();
1961            result
1962        } else {
1963            f(self)
1964        }
1965    }
1966
1967    /// The line height associated with the current text style.
1968    pub fn line_height(&self) -> Pixels {
1969        self.text_style().line_height_in_pixels(self.rem_size())
1970    }
1971
1972    /// Call to prevent the default action of an event. Currently only used to prevent
1973    /// parent elements from becoming focused on mouse down.
1974    pub fn prevent_default(&mut self) {
1975        self.default_prevented = true;
1976    }
1977
1978    /// Obtain whether default has been prevented for the event currently being dispatched.
1979    pub fn default_prevented(&self) -> bool {
1980        self.default_prevented
1981    }
1982
1983    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1984    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
1985        let node_id =
1986            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
1987        self.rendered_frame
1988            .dispatch_tree
1989            .is_action_available(action, node_id)
1990    }
1991
1992    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
1993    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
1994        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
1995        self.rendered_frame
1996            .dispatch_tree
1997            .is_action_available(action, node_id)
1998    }
1999
2000    /// The position of the mouse relative to the window.
2001    pub fn mouse_position(&self) -> Point<Pixels> {
2002        self.mouse_position
2003    }
2004
2005    /// The current state of the keyboard's modifiers
2006    pub fn modifiers(&self) -> Modifiers {
2007        self.modifiers
2008    }
2009
2010    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
2011    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
2012    pub fn last_input_was_keyboard(&self) -> bool {
2013        self.last_input_modality == InputModality::Keyboard
2014    }
2015
2016    /// The current state of the keyboard's capslock
2017    pub fn capslock(&self) -> Capslock {
2018        self.capslock
2019    }
2020
2021    fn complete_frame(&self) {
2022        self.platform_window.completed_frame();
2023    }
2024
2025    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
2026    /// the contents of the new [`Scene`], use [`Self::present`].
2027    #[profiling::function]
2028    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2029        self.invalidate_entities();
2030        cx.entities.clear_accessed();
2031        debug_assert!(self.rendered_entity_stack.is_empty());
2032        self.invalidator.set_dirty(false);
2033        self.requested_autoscroll = None;
2034
2035        // Restore the previously-used input handler.
2036        if let Some(input_handler) = self.platform_window.take_input_handler() {
2037            self.rendered_frame.input_handlers.push(Some(input_handler));
2038        }
2039        if !cx.mode.skip_drawing() {
2040            self.draw_roots(cx);
2041        }
2042        self.dirty_views.clear();
2043        self.next_frame.window_active = self.active.get();
2044
2045        // Register requested input handler with the platform window.
2046        if let Some(input_handler) = self.next_frame.input_handlers.pop() {
2047            self.platform_window
2048                .set_input_handler(input_handler.unwrap());
2049        }
2050
2051        self.layout_engine.as_mut().unwrap().clear();
2052        self.text_system().finish_frame();
2053        self.next_frame.finish(&mut self.rendered_frame);
2054
2055        self.invalidator.set_phase(DrawPhase::Focus);
2056        let previous_focus_path = self.rendered_frame.focus_path();
2057        let previous_window_active = self.rendered_frame.window_active;
2058        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2059        self.next_frame.clear();
2060        let current_focus_path = self.rendered_frame.focus_path();
2061        let current_window_active = self.rendered_frame.window_active;
2062
2063        if previous_focus_path != current_focus_path
2064            || previous_window_active != current_window_active
2065        {
2066            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2067                self.focus_lost_listeners
2068                    .clone()
2069                    .retain(&(), |listener| listener(self, cx));
2070            }
2071
2072            let event = WindowFocusEvent {
2073                previous_focus_path: if previous_window_active {
2074                    previous_focus_path
2075                } else {
2076                    Default::default()
2077                },
2078                current_focus_path: if current_window_active {
2079                    current_focus_path
2080                } else {
2081                    Default::default()
2082                },
2083            };
2084            self.focus_listeners
2085                .clone()
2086                .retain(&(), |listener| listener(&event, self, cx));
2087        }
2088
2089        debug_assert!(self.rendered_entity_stack.is_empty());
2090        self.record_entities_accessed(cx);
2091        self.reset_cursor_style(cx);
2092        self.refreshing = false;
2093        self.invalidator.set_phase(DrawPhase::None);
2094        self.needs_present.set(true);
2095
2096        ArenaClearNeeded
2097    }
2098
2099    fn record_entities_accessed(&mut self, cx: &mut App) {
2100        let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
2101        let mut entities = mem::take(entities_ref.deref_mut());
2102        drop(entities_ref);
2103        let handle = self.handle;
2104        cx.record_entities_accessed(
2105            handle,
2106            // Try moving window invalidator into the Window
2107            self.invalidator.clone(),
2108            &entities,
2109        );
2110        let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
2111        mem::swap(&mut entities, entities_ref.deref_mut());
2112    }
2113
2114    fn invalidate_entities(&mut self) {
2115        let mut views = self.invalidator.take_views();
2116        for entity in views.drain() {
2117            self.mark_view_dirty(entity);
2118        }
2119        self.invalidator.replace_views(views);
2120    }
2121
2122    #[profiling::function]
2123    fn present(&self) {
2124        self.platform_window.draw(&self.rendered_frame.scene);
2125        self.needs_present.set(false);
2126        profiling::finish_frame!();
2127    }
2128
2129    fn draw_roots(&mut self, cx: &mut App) {
2130        self.invalidator.set_phase(DrawPhase::Prepaint);
2131        self.tooltip_bounds.take();
2132
2133        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2134        let root_size = {
2135            #[cfg(any(feature = "inspector", debug_assertions))]
2136            {
2137                if self.inspector.is_some() {
2138                    let mut size = self.viewport_size;
2139                    size.width = (size.width - _inspector_width).max(px(0.0));
2140                    size
2141                } else {
2142                    self.viewport_size
2143                }
2144            }
2145            #[cfg(not(any(feature = "inspector", debug_assertions)))]
2146            {
2147                self.viewport_size
2148            }
2149        };
2150
2151        // Layout all root elements.
2152        let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2153        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2154
2155        #[cfg(any(feature = "inspector", debug_assertions))]
2156        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2157
2158        let mut sorted_deferred_draws =
2159            (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
2160        sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2161        self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
2162
2163        let mut prompt_element = None;
2164        let mut active_drag_element = None;
2165        let mut tooltip_element = None;
2166        if let Some(prompt) = self.prompt.take() {
2167            let mut element = prompt.view.any_view().into_any();
2168            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2169            prompt_element = Some(element);
2170            self.prompt = Some(prompt);
2171        } else if let Some(active_drag) = cx.active_drag.take() {
2172            let mut element = active_drag.view.clone().into_any();
2173            let offset = self.mouse_position() - active_drag.cursor_offset;
2174            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2175            active_drag_element = Some(element);
2176            cx.active_drag = Some(active_drag);
2177        } else {
2178            tooltip_element = self.prepaint_tooltip(cx);
2179        }
2180
2181        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2182
2183        // Now actually paint the elements.
2184        self.invalidator.set_phase(DrawPhase::Paint);
2185        root_element.paint(self, cx);
2186
2187        #[cfg(any(feature = "inspector", debug_assertions))]
2188        self.paint_inspector(inspector_element, cx);
2189
2190        self.paint_deferred_draws(&sorted_deferred_draws, cx);
2191
2192        if let Some(mut prompt_element) = prompt_element {
2193            prompt_element.paint(self, cx);
2194        } else if let Some(mut drag_element) = active_drag_element {
2195            drag_element.paint(self, cx);
2196        } else if let Some(mut tooltip_element) = tooltip_element {
2197            tooltip_element.paint(self, cx);
2198        }
2199
2200        #[cfg(any(feature = "inspector", debug_assertions))]
2201        self.paint_inspector_hitbox(cx);
2202    }
2203
2204    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2205        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2206        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2207            let Some(Some(tooltip_request)) = self
2208                .next_frame
2209                .tooltip_requests
2210                .get(tooltip_request_index)
2211                .cloned()
2212            else {
2213                log::error!("Unexpectedly absent TooltipRequest");
2214                continue;
2215            };
2216            let mut element = tooltip_request.tooltip.view.clone().into_any();
2217            let mouse_position = tooltip_request.tooltip.mouse_position;
2218            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2219
2220            let mut tooltip_bounds =
2221                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2222            let window_bounds = Bounds {
2223                origin: Point::default(),
2224                size: self.viewport_size(),
2225            };
2226
2227            if tooltip_bounds.right() > window_bounds.right() {
2228                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2229                if new_x >= Pixels::ZERO {
2230                    tooltip_bounds.origin.x = new_x;
2231                } else {
2232                    tooltip_bounds.origin.x = cmp::max(
2233                        Pixels::ZERO,
2234                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2235                    );
2236                }
2237            }
2238
2239            if tooltip_bounds.bottom() > window_bounds.bottom() {
2240                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2241                if new_y >= Pixels::ZERO {
2242                    tooltip_bounds.origin.y = new_y;
2243                } else {
2244                    tooltip_bounds.origin.y = cmp::max(
2245                        Pixels::ZERO,
2246                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2247                    );
2248                }
2249            }
2250
2251            // It's possible for an element to have an active tooltip while not being painted (e.g.
2252            // via the `visible_on_hover` method). Since mouse listeners are not active in this
2253            // case, instead update the tooltip's visibility here.
2254            let is_visible =
2255                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2256            if !is_visible {
2257                continue;
2258            }
2259
2260            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2261                element.prepaint(window, cx)
2262            });
2263
2264            self.tooltip_bounds = Some(TooltipBounds {
2265                id: tooltip_request.id,
2266                bounds: tooltip_bounds,
2267            });
2268            return Some(element);
2269        }
2270        None
2271    }
2272
2273    fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2274        assert_eq!(self.element_id_stack.len(), 0);
2275
2276        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2277        for deferred_draw_ix in deferred_draw_indices {
2278            let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2279            self.element_id_stack
2280                .clone_from(&deferred_draw.element_id_stack);
2281            self.text_style_stack
2282                .clone_from(&deferred_draw.text_style_stack);
2283            self.next_frame
2284                .dispatch_tree
2285                .set_active_node(deferred_draw.parent_node);
2286
2287            let prepaint_start = self.prepaint_index();
2288            if let Some(element) = deferred_draw.element.as_mut() {
2289                self.with_rendered_view(deferred_draw.current_view, |window| {
2290                    window.with_absolute_element_offset(deferred_draw.absolute_offset, |window| {
2291                        element.prepaint(window, cx)
2292                    });
2293                })
2294            } else {
2295                self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2296            }
2297            let prepaint_end = self.prepaint_index();
2298            deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2299        }
2300        assert_eq!(
2301            self.next_frame.deferred_draws.len(),
2302            0,
2303            "cannot call defer_draw during deferred drawing"
2304        );
2305        self.next_frame.deferred_draws = deferred_draws;
2306        self.element_id_stack.clear();
2307        self.text_style_stack.clear();
2308    }
2309
2310    fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2311        assert_eq!(self.element_id_stack.len(), 0);
2312
2313        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2314        for deferred_draw_ix in deferred_draw_indices {
2315            let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2316            self.element_id_stack
2317                .clone_from(&deferred_draw.element_id_stack);
2318            self.next_frame
2319                .dispatch_tree
2320                .set_active_node(deferred_draw.parent_node);
2321
2322            let paint_start = self.paint_index();
2323            if let Some(element) = deferred_draw.element.as_mut() {
2324                self.with_rendered_view(deferred_draw.current_view, |window| {
2325                    element.paint(window, cx);
2326                })
2327            } else {
2328                self.reuse_paint(deferred_draw.paint_range.clone());
2329            }
2330            let paint_end = self.paint_index();
2331            deferred_draw.paint_range = paint_start..paint_end;
2332        }
2333        self.next_frame.deferred_draws = deferred_draws;
2334        self.element_id_stack.clear();
2335    }
2336
2337    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2338        PrepaintStateIndex {
2339            hitboxes_index: self.next_frame.hitboxes.len(),
2340            tooltips_index: self.next_frame.tooltip_requests.len(),
2341            deferred_draws_index: self.next_frame.deferred_draws.len(),
2342            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2343            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2344            line_layout_index: self.text_system.layout_index(),
2345        }
2346    }
2347
2348    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2349        self.next_frame.hitboxes.extend(
2350            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2351                .iter()
2352                .cloned(),
2353        );
2354        self.next_frame.tooltip_requests.extend(
2355            self.rendered_frame.tooltip_requests
2356                [range.start.tooltips_index..range.end.tooltips_index]
2357                .iter_mut()
2358                .map(|request| request.take()),
2359        );
2360        self.next_frame.accessed_element_states.extend(
2361            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2362                ..range.end.accessed_element_states_index]
2363                .iter()
2364                .map(|(id, type_id)| (id.clone(), *type_id)),
2365        );
2366        self.text_system
2367            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2368
2369        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2370            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2371            &mut self.rendered_frame.dispatch_tree,
2372            self.focus,
2373        );
2374
2375        if reused_subtree.contains_focus() {
2376            self.next_frame.focus = self.focus;
2377        }
2378
2379        self.next_frame.deferred_draws.extend(
2380            self.rendered_frame.deferred_draws
2381                [range.start.deferred_draws_index..range.end.deferred_draws_index]
2382                .iter()
2383                .map(|deferred_draw| DeferredDraw {
2384                    current_view: deferred_draw.current_view,
2385                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2386                    element_id_stack: deferred_draw.element_id_stack.clone(),
2387                    text_style_stack: deferred_draw.text_style_stack.clone(),
2388                    priority: deferred_draw.priority,
2389                    element: None,
2390                    absolute_offset: deferred_draw.absolute_offset,
2391                    prepaint_range: deferred_draw.prepaint_range.clone(),
2392                    paint_range: deferred_draw.paint_range.clone(),
2393                }),
2394        );
2395    }
2396
2397    pub(crate) fn paint_index(&self) -> PaintIndex {
2398        PaintIndex {
2399            scene_index: self.next_frame.scene.len(),
2400            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2401            input_handlers_index: self.next_frame.input_handlers.len(),
2402            cursor_styles_index: self.next_frame.cursor_styles.len(),
2403            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2404            tab_handle_index: self.next_frame.tab_stops.paint_index(),
2405            line_layout_index: self.text_system.layout_index(),
2406        }
2407    }
2408
2409    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2410        self.next_frame.cursor_styles.extend(
2411            self.rendered_frame.cursor_styles
2412                [range.start.cursor_styles_index..range.end.cursor_styles_index]
2413                .iter()
2414                .cloned(),
2415        );
2416        self.next_frame.input_handlers.extend(
2417            self.rendered_frame.input_handlers
2418                [range.start.input_handlers_index..range.end.input_handlers_index]
2419                .iter_mut()
2420                .map(|handler| handler.take()),
2421        );
2422        self.next_frame.mouse_listeners.extend(
2423            self.rendered_frame.mouse_listeners
2424                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2425                .iter_mut()
2426                .map(|listener| listener.take()),
2427        );
2428        self.next_frame.accessed_element_states.extend(
2429            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2430                ..range.end.accessed_element_states_index]
2431                .iter()
2432                .map(|(id, type_id)| (id.clone(), *type_id)),
2433        );
2434        self.next_frame.tab_stops.replay(
2435            &self.rendered_frame.tab_stops.insertion_history
2436                [range.start.tab_handle_index..range.end.tab_handle_index],
2437        );
2438
2439        self.text_system
2440            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2441        self.next_frame.scene.replay(
2442            range.start.scene_index..range.end.scene_index,
2443            &self.rendered_frame.scene,
2444        );
2445    }
2446
2447    /// Push a text style onto the stack, and call a function with that style active.
2448    /// Use [`Window::text_style`] to get the current, combined text style. This method
2449    /// should only be called as part of element drawing.
2450    // This function is called in a highly recursive manner in editor
2451    // prepainting, make sure its inlined to reduce the stack burden
2452    #[inline]
2453    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2454    where
2455        F: FnOnce(&mut Self) -> R,
2456    {
2457        self.invalidator.debug_assert_paint_or_prepaint();
2458        if let Some(style) = style {
2459            self.text_style_stack.push(style);
2460            let result = f(self);
2461            self.text_style_stack.pop();
2462            result
2463        } else {
2464            f(self)
2465        }
2466    }
2467
2468    /// Updates the cursor style at the platform level. This method should only be called
2469    /// during the paint phase of element drawing.
2470    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2471        self.invalidator.debug_assert_paint();
2472        self.next_frame.cursor_styles.push(CursorStyleRequest {
2473            hitbox_id: Some(hitbox.id),
2474            style,
2475        });
2476    }
2477
2478    /// Updates the cursor style for the entire window at the platform level. A cursor
2479    /// style using this method will have precedence over any cursor style set using
2480    /// `set_cursor_style`. This method should only be called during the paint
2481    /// phase of element drawing.
2482    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2483        self.invalidator.debug_assert_paint();
2484        self.next_frame.cursor_styles.push(CursorStyleRequest {
2485            hitbox_id: None,
2486            style,
2487        })
2488    }
2489
2490    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2491    /// during the paint phase of element drawing.
2492    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2493        self.invalidator.debug_assert_prepaint();
2494        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2495        self.next_frame
2496            .tooltip_requests
2497            .push(Some(TooltipRequest { id, tooltip }));
2498        id
2499    }
2500
2501    /// Invoke the given function with the given content mask after intersecting it
2502    /// with the current mask. This method should only be called during element drawing.
2503    // This function is called in a highly recursive manner in editor
2504    // prepainting, make sure its inlined to reduce the stack burden
2505    #[inline]
2506    pub fn with_content_mask<R>(
2507        &mut self,
2508        mask: Option<ContentMask<Pixels>>,
2509        f: impl FnOnce(&mut Self) -> R,
2510    ) -> R {
2511        self.invalidator.debug_assert_paint_or_prepaint();
2512        if let Some(mask) = mask {
2513            let mask = mask.intersect(&self.content_mask());
2514            self.content_mask_stack.push(mask);
2515            let result = f(self);
2516            self.content_mask_stack.pop();
2517            result
2518        } else {
2519            f(self)
2520        }
2521    }
2522
2523    /// Updates the global element offset relative to the current offset. This is used to implement
2524    /// scrolling. This method should only be called during the prepaint phase of element drawing.
2525    pub fn with_element_offset<R>(
2526        &mut self,
2527        offset: Point<Pixels>,
2528        f: impl FnOnce(&mut Self) -> R,
2529    ) -> R {
2530        self.invalidator.debug_assert_prepaint();
2531
2532        if offset.is_zero() {
2533            return f(self);
2534        };
2535
2536        let abs_offset = self.element_offset() + offset;
2537        self.with_absolute_element_offset(abs_offset, f)
2538    }
2539
2540    /// Updates the global element offset based on the given offset. This is used to implement
2541    /// drag handles and other manual painting of elements. This method should only be called during
2542    /// the prepaint phase of element drawing.
2543    pub fn with_absolute_element_offset<R>(
2544        &mut self,
2545        offset: Point<Pixels>,
2546        f: impl FnOnce(&mut Self) -> R,
2547    ) -> R {
2548        self.invalidator.debug_assert_prepaint();
2549        self.element_offset_stack.push(offset);
2550        let result = f(self);
2551        self.element_offset_stack.pop();
2552        result
2553    }
2554
2555    pub(crate) fn with_element_opacity<R>(
2556        &mut self,
2557        opacity: Option<f32>,
2558        f: impl FnOnce(&mut Self) -> R,
2559    ) -> R {
2560        self.invalidator.debug_assert_paint_or_prepaint();
2561
2562        let Some(opacity) = opacity else {
2563            return f(self);
2564        };
2565
2566        let previous_opacity = self.element_opacity;
2567        self.element_opacity = previous_opacity * opacity;
2568        let result = f(self);
2569        self.element_opacity = previous_opacity;
2570        result
2571    }
2572
2573    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2574    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2575    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2576    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
2577    /// called during the prepaint phase of element drawing.
2578    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2579        self.invalidator.debug_assert_prepaint();
2580        let index = self.prepaint_index();
2581        let result = f(self);
2582        if result.is_err() {
2583            self.next_frame.hitboxes.truncate(index.hitboxes_index);
2584            self.next_frame
2585                .tooltip_requests
2586                .truncate(index.tooltips_index);
2587            self.next_frame
2588                .deferred_draws
2589                .truncate(index.deferred_draws_index);
2590            self.next_frame
2591                .dispatch_tree
2592                .truncate(index.dispatch_tree_index);
2593            self.next_frame
2594                .accessed_element_states
2595                .truncate(index.accessed_element_states_index);
2596            self.text_system.truncate_layouts(index.line_layout_index);
2597        }
2598        result
2599    }
2600
2601    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
2602    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2603    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
2604    /// that supports this method being called on the elements it contains. This method should only be
2605    /// called during the prepaint phase of element drawing.
2606    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2607        self.invalidator.debug_assert_prepaint();
2608        self.requested_autoscroll = Some(bounds);
2609    }
2610
2611    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
2612    /// described in [`Self::request_autoscroll`].
2613    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2614        self.invalidator.debug_assert_prepaint();
2615        self.requested_autoscroll.take()
2616    }
2617
2618    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2619    /// Your view will be re-drawn once the asset has finished loading.
2620    ///
2621    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2622    /// time.
2623    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2624        let (task, is_first) = cx.fetch_asset::<A>(source);
2625        task.clone().now_or_never().or_else(|| {
2626            if is_first {
2627                let entity_id = self.current_view();
2628                self.spawn(cx, {
2629                    let task = task.clone();
2630                    async move |cx| {
2631                        task.await;
2632
2633                        cx.on_next_frame(move |_, cx| {
2634                            cx.notify(entity_id);
2635                        });
2636                    }
2637                })
2638                .detach();
2639            }
2640
2641            None
2642        })
2643    }
2644
2645    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
2646    /// Your view will not be re-drawn once the asset has finished loading.
2647    ///
2648    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2649    /// time.
2650    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2651        let (task, _) = cx.fetch_asset::<A>(source);
2652        task.now_or_never()
2653    }
2654    /// Obtain the current element offset. This method should only be called during the
2655    /// prepaint phase of element drawing.
2656    pub fn element_offset(&self) -> Point<Pixels> {
2657        self.invalidator.debug_assert_prepaint();
2658        self.element_offset_stack
2659            .last()
2660            .copied()
2661            .unwrap_or_default()
2662    }
2663
2664    /// Obtain the current element opacity. This method should only be called during the
2665    /// prepaint phase of element drawing.
2666    #[inline]
2667    pub(crate) fn element_opacity(&self) -> f32 {
2668        self.invalidator.debug_assert_paint_or_prepaint();
2669        self.element_opacity
2670    }
2671
2672    /// Obtain the current content mask. This method should only be called during element drawing.
2673    pub fn content_mask(&self) -> ContentMask<Pixels> {
2674        self.invalidator.debug_assert_paint_or_prepaint();
2675        self.content_mask_stack
2676            .last()
2677            .cloned()
2678            .unwrap_or_else(|| ContentMask {
2679                bounds: Bounds {
2680                    origin: Point::default(),
2681                    size: self.viewport_size,
2682                },
2683            })
2684    }
2685
2686    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2687    /// This can be used within a custom element to distinguish multiple sets of child elements.
2688    pub fn with_element_namespace<R>(
2689        &mut self,
2690        element_id: impl Into<ElementId>,
2691        f: impl FnOnce(&mut Self) -> R,
2692    ) -> R {
2693        self.element_id_stack.push(element_id.into());
2694        let result = f(self);
2695        self.element_id_stack.pop();
2696        result
2697    }
2698
2699    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
2700    pub fn use_keyed_state<S: 'static>(
2701        &mut self,
2702        key: impl Into<ElementId>,
2703        cx: &mut App,
2704        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2705    ) -> Entity<S> {
2706        let current_view = self.current_view();
2707        self.with_global_id(key.into(), |global_id, window| {
2708            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
2709                if let Some(state) = state {
2710                    (state.clone(), state)
2711                } else {
2712                    let new_state = cx.new(|cx| init(window, cx));
2713                    cx.observe(&new_state, move |_, cx| {
2714                        cx.notify(current_view);
2715                    })
2716                    .detach();
2717                    (new_state.clone(), new_state)
2718                }
2719            })
2720        })
2721    }
2722
2723    /// Immediately push an element ID onto the stack. Useful for simplifying IDs in lists
2724    pub fn with_id<R>(&mut self, id: impl Into<ElementId>, f: impl FnOnce(&mut Self) -> R) -> R {
2725        self.with_global_id(id.into(), |_, window| f(window))
2726    }
2727
2728    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
2729    ///
2730    /// NOTE: This method uses the location of the caller to generate an ID for this state.
2731    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
2732    ///       you can provide a custom ElementID using the `use_keyed_state` method.
2733    #[track_caller]
2734    pub fn use_state<S: 'static>(
2735        &mut self,
2736        cx: &mut App,
2737        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2738    ) -> Entity<S> {
2739        self.use_keyed_state(
2740            ElementId::CodeLocation(*core::panic::Location::caller()),
2741            cx,
2742            init,
2743        )
2744    }
2745
2746    /// Updates or initializes state for an element with the given id that lives across multiple
2747    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2748    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2749    /// when drawing the next frame. This method should only be called as part of element drawing.
2750    pub fn with_element_state<S, R>(
2751        &mut self,
2752        global_id: &GlobalElementId,
2753        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2754    ) -> R
2755    where
2756        S: 'static,
2757    {
2758        self.invalidator.debug_assert_paint_or_prepaint();
2759
2760        let key = (global_id.clone(), TypeId::of::<S>());
2761        self.next_frame.accessed_element_states.push(key.clone());
2762
2763        if let Some(any) = self
2764            .next_frame
2765            .element_states
2766            .remove(&key)
2767            .or_else(|| self.rendered_frame.element_states.remove(&key))
2768        {
2769            let ElementStateBox {
2770                inner,
2771                #[cfg(debug_assertions)]
2772                type_name,
2773            } = any;
2774            // Using the extra inner option to avoid needing to reallocate a new box.
2775            let mut state_box = inner
2776                .downcast::<Option<S>>()
2777                .map_err(|_| {
2778                    #[cfg(debug_assertions)]
2779                    {
2780                        anyhow::anyhow!(
2781                            "invalid element state type for id, requested {:?}, actual: {:?}",
2782                            std::any::type_name::<S>(),
2783                            type_name
2784                        )
2785                    }
2786
2787                    #[cfg(not(debug_assertions))]
2788                    {
2789                        anyhow::anyhow!(
2790                            "invalid element state type for id, requested {:?}",
2791                            std::any::type_name::<S>(),
2792                        )
2793                    }
2794                })
2795                .unwrap();
2796
2797            let state = state_box.take().expect(
2798                "reentrant call to with_element_state for the same state type and element id",
2799            );
2800            let (result, state) = f(Some(state), self);
2801            state_box.replace(state);
2802            self.next_frame.element_states.insert(
2803                key,
2804                ElementStateBox {
2805                    inner: state_box,
2806                    #[cfg(debug_assertions)]
2807                    type_name,
2808                },
2809            );
2810            result
2811        } else {
2812            let (result, state) = f(None, self);
2813            self.next_frame.element_states.insert(
2814                key,
2815                ElementStateBox {
2816                    inner: Box::new(Some(state)),
2817                    #[cfg(debug_assertions)]
2818                    type_name: std::any::type_name::<S>(),
2819                },
2820            );
2821            result
2822        }
2823    }
2824
2825    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2826    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2827    /// when the element is guaranteed to have an id.
2828    ///
2829    /// The first option means 'no ID provided'
2830    /// The second option means 'not yet initialized'
2831    pub fn with_optional_element_state<S, R>(
2832        &mut self,
2833        global_id: Option<&GlobalElementId>,
2834        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2835    ) -> R
2836    where
2837        S: 'static,
2838    {
2839        self.invalidator.debug_assert_paint_or_prepaint();
2840
2841        if let Some(global_id) = global_id {
2842            self.with_element_state(global_id, |state, cx| {
2843                let (result, state) = f(Some(state), cx);
2844                let state =
2845                    state.expect("you must return some state when you pass some element id");
2846                (result, state)
2847            })
2848        } else {
2849            let (result, state) = f(None, self);
2850            debug_assert!(
2851                state.is_none(),
2852                "you must not return an element state when passing None for the global id"
2853            );
2854            result
2855        }
2856    }
2857
2858    /// Executes the given closure within the context of a tab group.
2859    #[inline]
2860    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
2861        if let Some(index) = index {
2862            self.next_frame.tab_stops.begin_group(index);
2863            let result = f(self);
2864            self.next_frame.tab_stops.end_group();
2865            result
2866        } else {
2867            f(self)
2868        }
2869    }
2870
2871    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2872    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2873    /// with higher values being drawn on top.
2874    ///
2875    /// This method should only be called as part of the prepaint phase of element drawing.
2876    pub fn defer_draw(
2877        &mut self,
2878        element: AnyElement,
2879        absolute_offset: Point<Pixels>,
2880        priority: usize,
2881    ) {
2882        self.invalidator.debug_assert_prepaint();
2883        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
2884        self.next_frame.deferred_draws.push(DeferredDraw {
2885            current_view: self.current_view(),
2886            parent_node,
2887            element_id_stack: self.element_id_stack.clone(),
2888            text_style_stack: self.text_style_stack.clone(),
2889            priority,
2890            element: Some(element),
2891            absolute_offset,
2892            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2893            paint_range: PaintIndex::default()..PaintIndex::default(),
2894        });
2895    }
2896
2897    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2898    /// of geometry that are non-overlapping and have the same draw order. This is typically used
2899    /// for performance reasons.
2900    ///
2901    /// This method should only be called as part of the paint phase of element drawing.
2902    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2903        self.invalidator.debug_assert_paint();
2904
2905        let scale_factor = self.scale_factor();
2906        let content_mask = self.content_mask();
2907        let clipped_bounds = bounds.intersect(&content_mask.bounds);
2908        if !clipped_bounds.is_empty() {
2909            self.next_frame
2910                .scene
2911                .push_layer(clipped_bounds.scale(scale_factor));
2912        }
2913
2914        let result = f(self);
2915
2916        if !clipped_bounds.is_empty() {
2917            self.next_frame.scene.pop_layer();
2918        }
2919
2920        result
2921    }
2922
2923    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2924    ///
2925    /// This method should only be called as part of the paint phase of element drawing.
2926    pub fn paint_shadows(
2927        &mut self,
2928        bounds: Bounds<Pixels>,
2929        corner_radii: Corners<Pixels>,
2930        shadows: &[BoxShadow],
2931    ) {
2932        self.invalidator.debug_assert_paint();
2933
2934        let scale_factor = self.scale_factor();
2935        let content_mask = self.content_mask();
2936        let opacity = self.element_opacity();
2937        for shadow in shadows {
2938            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
2939            self.next_frame.scene.insert_primitive(Shadow {
2940                order: 0,
2941                blur_radius: shadow.blur_radius.scale(scale_factor),
2942                bounds: shadow_bounds.scale(scale_factor),
2943                content_mask: content_mask.scale(scale_factor),
2944                corner_radii: corner_radii.scale(scale_factor),
2945                color: shadow.color.opacity(opacity),
2946            });
2947        }
2948    }
2949
2950    /// Paint one or more quads into the scene for the next frame at the current stacking context.
2951    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2952    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
2953    ///
2954    /// This method should only be called as part of the paint phase of element drawing.
2955    ///
2956    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
2957    /// where the circular arcs meet. This will not display well when combined with dashed borders.
2958    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
2959    pub fn paint_quad(&mut self, quad: PaintQuad) {
2960        self.invalidator.debug_assert_paint();
2961
2962        let scale_factor = self.scale_factor();
2963        let content_mask = self.content_mask();
2964        let opacity = self.element_opacity();
2965        self.next_frame.scene.insert_primitive(Quad {
2966            order: 0,
2967            bounds: quad.bounds.scale(scale_factor),
2968            content_mask: content_mask.scale(scale_factor),
2969            background: quad.background.opacity(opacity),
2970            border_color: quad.border_color.opacity(opacity),
2971            corner_radii: quad.corner_radii.scale(scale_factor),
2972            border_widths: quad.border_widths.scale(scale_factor),
2973            border_style: quad.border_style,
2974        });
2975    }
2976
2977    /// Paint the given `Path` into the scene for the next frame at the current z-index.
2978    ///
2979    /// This method should only be called as part of the paint phase of element drawing.
2980    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
2981        self.invalidator.debug_assert_paint();
2982
2983        let scale_factor = self.scale_factor();
2984        let content_mask = self.content_mask();
2985        let opacity = self.element_opacity();
2986        path.content_mask = content_mask;
2987        let color: Background = color.into();
2988        path.color = color.opacity(opacity);
2989        self.next_frame
2990            .scene
2991            .insert_primitive(path.scale(scale_factor));
2992    }
2993
2994    /// Paint an underline into the scene for the next frame at the current z-index.
2995    ///
2996    /// This method should only be called as part of the paint phase of element drawing.
2997    pub fn paint_underline(
2998        &mut self,
2999        origin: Point<Pixels>,
3000        width: Pixels,
3001        style: &UnderlineStyle,
3002    ) {
3003        self.invalidator.debug_assert_paint();
3004
3005        let scale_factor = self.scale_factor();
3006        let height = if style.wavy {
3007            style.thickness * 3.
3008        } else {
3009            style.thickness
3010        };
3011        let bounds = Bounds {
3012            origin,
3013            size: size(width, height),
3014        };
3015        let content_mask = self.content_mask();
3016        let element_opacity = self.element_opacity();
3017
3018        self.next_frame.scene.insert_primitive(Underline {
3019            order: 0,
3020            pad: 0,
3021            bounds: bounds.scale(scale_factor),
3022            content_mask: content_mask.scale(scale_factor),
3023            color: style.color.unwrap_or_default().opacity(element_opacity),
3024            thickness: style.thickness.scale(scale_factor),
3025            wavy: if style.wavy { 1 } else { 0 },
3026        });
3027    }
3028
3029    /// Paint a strikethrough into the scene for the next frame at the current z-index.
3030    ///
3031    /// This method should only be called as part of the paint phase of element drawing.
3032    pub fn paint_strikethrough(
3033        &mut self,
3034        origin: Point<Pixels>,
3035        width: Pixels,
3036        style: &StrikethroughStyle,
3037    ) {
3038        self.invalidator.debug_assert_paint();
3039
3040        let scale_factor = self.scale_factor();
3041        let height = style.thickness;
3042        let bounds = Bounds {
3043            origin,
3044            size: size(width, height),
3045        };
3046        let content_mask = self.content_mask();
3047        let opacity = self.element_opacity();
3048
3049        self.next_frame.scene.insert_primitive(Underline {
3050            order: 0,
3051            pad: 0,
3052            bounds: bounds.scale(scale_factor),
3053            content_mask: content_mask.scale(scale_factor),
3054            thickness: style.thickness.scale(scale_factor),
3055            color: style.color.unwrap_or_default().opacity(opacity),
3056            wavy: 0,
3057        });
3058    }
3059
3060    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3061    ///
3062    /// The y component of the origin is the baseline of the glyph.
3063    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3064    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3065    /// This method is only useful if you need to paint a single glyph that has already been shaped.
3066    ///
3067    /// This method should only be called as part of the paint phase of element drawing.
3068    pub fn paint_glyph(
3069        &mut self,
3070        origin: Point<Pixels>,
3071        font_id: FontId,
3072        glyph_id: GlyphId,
3073        font_size: Pixels,
3074        color: Hsla,
3075    ) -> Result<()> {
3076        self.invalidator.debug_assert_paint();
3077
3078        let element_opacity = self.element_opacity();
3079        let scale_factor = self.scale_factor();
3080        let glyph_origin = origin.scale(scale_factor);
3081
3082        let subpixel_variant = Point {
3083            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS_X as f32).floor() as u8,
3084            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS_Y as f32).floor() as u8,
3085        };
3086        let params = RenderGlyphParams {
3087            font_id,
3088            glyph_id,
3089            font_size,
3090            subpixel_variant,
3091            scale_factor,
3092            is_emoji: false,
3093        };
3094
3095        let raster_bounds = self.text_system().raster_bounds(&params)?;
3096        if !raster_bounds.is_zero() {
3097            let tile = self
3098                .sprite_atlas
3099                .get_or_insert_with(&params.clone().into(), &mut || {
3100                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3101                    Ok(Some((size, Cow::Owned(bytes))))
3102                })?
3103                .expect("Callback above only errors or returns Some");
3104            let bounds = Bounds {
3105                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3106                size: tile.bounds.size.map(Into::into),
3107            };
3108            let content_mask = self.content_mask().scale(scale_factor);
3109            self.next_frame.scene.insert_primitive(MonochromeSprite {
3110                order: 0,
3111                pad: 0,
3112                bounds,
3113                content_mask,
3114                color: color.opacity(element_opacity),
3115                tile,
3116                transformation: TransformationMatrix::unit(),
3117            });
3118        }
3119        Ok(())
3120    }
3121
3122    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3123    ///
3124    /// The y component of the origin is the baseline of the glyph.
3125    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3126    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3127    /// This method is only useful if you need to paint a single emoji that has already been shaped.
3128    ///
3129    /// This method should only be called as part of the paint phase of element drawing.
3130    pub fn paint_emoji(
3131        &mut self,
3132        origin: Point<Pixels>,
3133        font_id: FontId,
3134        glyph_id: GlyphId,
3135        font_size: Pixels,
3136    ) -> Result<()> {
3137        self.invalidator.debug_assert_paint();
3138
3139        let scale_factor = self.scale_factor();
3140        let glyph_origin = origin.scale(scale_factor);
3141        let params = RenderGlyphParams {
3142            font_id,
3143            glyph_id,
3144            font_size,
3145            // We don't render emojis with subpixel variants.
3146            subpixel_variant: Default::default(),
3147            scale_factor,
3148            is_emoji: true,
3149        };
3150
3151        let raster_bounds = self.text_system().raster_bounds(&params)?;
3152        if !raster_bounds.is_zero() {
3153            let tile = self
3154                .sprite_atlas
3155                .get_or_insert_with(&params.clone().into(), &mut || {
3156                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3157                    Ok(Some((size, Cow::Owned(bytes))))
3158                })?
3159                .expect("Callback above only errors or returns Some");
3160
3161            let bounds = Bounds {
3162                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3163                size: tile.bounds.size.map(Into::into),
3164            };
3165            let content_mask = self.content_mask().scale(scale_factor);
3166            let opacity = self.element_opacity();
3167
3168            self.next_frame.scene.insert_primitive(PolychromeSprite {
3169                order: 0,
3170                pad: 0,
3171                grayscale: false,
3172                bounds,
3173                corner_radii: Default::default(),
3174                content_mask,
3175                tile,
3176                opacity,
3177            });
3178        }
3179        Ok(())
3180    }
3181
3182    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3183    ///
3184    /// This method should only be called as part of the paint phase of element drawing.
3185    pub fn paint_svg(
3186        &mut self,
3187        bounds: Bounds<Pixels>,
3188        path: SharedString,
3189        mut data: Option<&[u8]>,
3190        transformation: TransformationMatrix,
3191        color: Hsla,
3192        cx: &App,
3193    ) -> Result<()> {
3194        self.invalidator.debug_assert_paint();
3195
3196        let element_opacity = self.element_opacity();
3197        let scale_factor = self.scale_factor();
3198
3199        let bounds = bounds.scale(scale_factor);
3200        let params = RenderSvgParams {
3201            path,
3202            size: bounds.size.map(|pixels| {
3203                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3204            }),
3205        };
3206
3207        let Some(tile) =
3208            self.sprite_atlas
3209                .get_or_insert_with(&params.clone().into(), &mut || {
3210                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
3211                    else {
3212                        return Ok(None);
3213                    };
3214                    Ok(Some((size, Cow::Owned(bytes))))
3215                })?
3216        else {
3217            return Ok(());
3218        };
3219        let content_mask = self.content_mask().scale(scale_factor);
3220        let svg_bounds = Bounds {
3221            origin: bounds.center()
3222                - Point::new(
3223                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3224                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3225                ),
3226            size: tile
3227                .bounds
3228                .size
3229                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3230        };
3231
3232        self.next_frame.scene.insert_primitive(MonochromeSprite {
3233            order: 0,
3234            pad: 0,
3235            bounds: svg_bounds
3236                .map_origin(|origin| origin.round())
3237                .map_size(|size| size.ceil()),
3238            content_mask,
3239            color: color.opacity(element_opacity),
3240            tile,
3241            transformation,
3242        });
3243
3244        Ok(())
3245    }
3246
3247    /// Paint an image into the scene for the next frame at the current z-index.
3248    /// This method will panic if the frame_index is not valid
3249    ///
3250    /// This method should only be called as part of the paint phase of element drawing.
3251    pub fn paint_image(
3252        &mut self,
3253        bounds: Bounds<Pixels>,
3254        corner_radii: Corners<Pixels>,
3255        data: Arc<RenderImage>,
3256        frame_index: usize,
3257        grayscale: bool,
3258    ) -> Result<()> {
3259        self.invalidator.debug_assert_paint();
3260
3261        let scale_factor = self.scale_factor();
3262        let bounds = bounds.scale(scale_factor);
3263        let params = RenderImageParams {
3264            image_id: data.id,
3265            frame_index,
3266        };
3267
3268        let tile = self
3269            .sprite_atlas
3270            .get_or_insert_with(&params.into(), &mut || {
3271                Ok(Some((
3272                    data.size(frame_index),
3273                    Cow::Borrowed(
3274                        data.as_bytes(frame_index)
3275                            .expect("It's the caller's job to pass a valid frame index"),
3276                    ),
3277                )))
3278            })?
3279            .expect("Callback above only returns Some");
3280        let content_mask = self.content_mask().scale(scale_factor);
3281        let corner_radii = corner_radii.scale(scale_factor);
3282        let opacity = self.element_opacity();
3283
3284        self.next_frame.scene.insert_primitive(PolychromeSprite {
3285            order: 0,
3286            pad: 0,
3287            grayscale,
3288            bounds: bounds
3289                .map_origin(|origin| origin.floor())
3290                .map_size(|size| size.ceil()),
3291            content_mask,
3292            corner_radii,
3293            tile,
3294            opacity,
3295        });
3296        Ok(())
3297    }
3298
3299    /// Paint a surface into the scene for the next frame at the current z-index.
3300    ///
3301    /// This method should only be called as part of the paint phase of element drawing.
3302    #[cfg(target_os = "macos")]
3303    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3304        use crate::PaintSurface;
3305
3306        self.invalidator.debug_assert_paint();
3307
3308        let scale_factor = self.scale_factor();
3309        let bounds = bounds.scale(scale_factor);
3310        let content_mask = self.content_mask().scale(scale_factor);
3311        self.next_frame.scene.insert_primitive(PaintSurface {
3312            order: 0,
3313            bounds,
3314            content_mask,
3315            image_buffer,
3316        });
3317    }
3318
3319    /// Removes an image from the sprite atlas.
3320    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3321        for frame_index in 0..data.frame_count() {
3322            let params = RenderImageParams {
3323                image_id: data.id,
3324                frame_index,
3325            };
3326
3327            self.sprite_atlas.remove(&params.clone().into());
3328        }
3329
3330        Ok(())
3331    }
3332
3333    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3334    /// layout is being requested, along with the layout ids of any children. This method is called during
3335    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3336    ///
3337    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3338    #[must_use]
3339    pub fn request_layout(
3340        &mut self,
3341        style: Style,
3342        children: impl IntoIterator<Item = LayoutId>,
3343        cx: &mut App,
3344    ) -> LayoutId {
3345        self.invalidator.debug_assert_prepaint();
3346
3347        cx.layout_id_buffer.clear();
3348        cx.layout_id_buffer.extend(children);
3349        let rem_size = self.rem_size();
3350        let scale_factor = self.scale_factor();
3351
3352        self.layout_engine.as_mut().unwrap().request_layout(
3353            style,
3354            rem_size,
3355            scale_factor,
3356            &cx.layout_id_buffer,
3357        )
3358    }
3359
3360    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3361    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3362    /// determine the element's size. One place this is used internally is when measuring text.
3363    ///
3364    /// The given closure is invoked at layout time with the known dimensions and available space and
3365    /// returns a `Size`.
3366    ///
3367    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3368    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3369    where
3370        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3371            + 'static,
3372    {
3373        self.invalidator.debug_assert_prepaint();
3374
3375        let rem_size = self.rem_size();
3376        let scale_factor = self.scale_factor();
3377        self.layout_engine
3378            .as_mut()
3379            .unwrap()
3380            .request_measured_layout(style, rem_size, scale_factor, measure)
3381    }
3382
3383    /// Compute the layout for the given id within the given available space.
3384    /// This method is called for its side effect, typically by the framework prior to painting.
3385    /// After calling it, you can request the bounds of the given layout node id or any descendant.
3386    ///
3387    /// This method should only be called as part of the prepaint phase of element drawing.
3388    pub fn compute_layout(
3389        &mut self,
3390        layout_id: LayoutId,
3391        available_space: Size<AvailableSpace>,
3392        cx: &mut App,
3393    ) {
3394        self.invalidator.debug_assert_prepaint();
3395
3396        let mut layout_engine = self.layout_engine.take().unwrap();
3397        layout_engine.compute_layout(layout_id, available_space, self, cx);
3398        self.layout_engine = Some(layout_engine);
3399    }
3400
3401    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3402    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3403    ///
3404    /// This method should only be called as part of element drawing.
3405    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3406        self.invalidator.debug_assert_prepaint();
3407
3408        let scale_factor = self.scale_factor();
3409        let mut bounds = self
3410            .layout_engine
3411            .as_mut()
3412            .unwrap()
3413            .layout_bounds(layout_id, scale_factor)
3414            .map(Into::into);
3415        bounds.origin += self.element_offset();
3416        bounds
3417    }
3418
3419    /// This method should be called during `prepaint`. You can use
3420    /// the returned [Hitbox] during `paint` or in an event handler
3421    /// to determine whether the inserted hitbox was the topmost.
3422    ///
3423    /// This method should only be called as part of the prepaint phase of element drawing.
3424    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3425        self.invalidator.debug_assert_prepaint();
3426
3427        let content_mask = self.content_mask();
3428        let mut id = self.next_hitbox_id;
3429        self.next_hitbox_id = self.next_hitbox_id.next();
3430        let hitbox = Hitbox {
3431            id,
3432            bounds,
3433            content_mask,
3434            behavior,
3435        };
3436        self.next_frame.hitboxes.push(hitbox.clone());
3437        hitbox
3438    }
3439
3440    /// Set a hitbox which will act as a control area of the platform window.
3441    ///
3442    /// This method should only be called as part of the paint phase of element drawing.
3443    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3444        self.invalidator.debug_assert_paint();
3445        self.next_frame.window_control_hitboxes.push((area, hitbox));
3446    }
3447
3448    /// Sets the key context for the current element. This context will be used to translate
3449    /// keybindings into actions.
3450    ///
3451    /// This method should only be called as part of the paint phase of element drawing.
3452    pub fn set_key_context(&mut self, context: KeyContext) {
3453        self.invalidator.debug_assert_paint();
3454        self.next_frame.dispatch_tree.set_key_context(context);
3455    }
3456
3457    /// Sets the focus handle for the current element. This handle will be used to manage focus state
3458    /// and keyboard event dispatch for the element.
3459    ///
3460    /// This method should only be called as part of the prepaint phase of element drawing.
3461    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3462        self.invalidator.debug_assert_prepaint();
3463        if focus_handle.is_focused(self) {
3464            self.next_frame.focus = Some(focus_handle.id);
3465        }
3466        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3467    }
3468
3469    /// Sets the view id for the current element, which will be used to manage view caching.
3470    ///
3471    /// This method should only be called as part of element prepaint. We plan on removing this
3472    /// method eventually when we solve some issues that require us to construct editor elements
3473    /// directly instead of always using editors via views.
3474    pub fn set_view_id(&mut self, view_id: EntityId) {
3475        self.invalidator.debug_assert_prepaint();
3476        self.next_frame.dispatch_tree.set_view_id(view_id);
3477    }
3478
3479    /// Get the entity ID for the currently rendering view
3480    pub fn current_view(&self) -> EntityId {
3481        self.invalidator.debug_assert_paint_or_prepaint();
3482        self.rendered_entity_stack.last().copied().unwrap()
3483    }
3484
3485    pub(crate) fn with_rendered_view<R>(
3486        &mut self,
3487        id: EntityId,
3488        f: impl FnOnce(&mut Self) -> R,
3489    ) -> R {
3490        self.rendered_entity_stack.push(id);
3491        let result = f(self);
3492        self.rendered_entity_stack.pop();
3493        result
3494    }
3495
3496    /// Executes the provided function with the specified image cache.
3497    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3498    where
3499        F: FnOnce(&mut Self) -> R,
3500    {
3501        if let Some(image_cache) = image_cache {
3502            self.image_cache_stack.push(image_cache);
3503            let result = f(self);
3504            self.image_cache_stack.pop();
3505            result
3506        } else {
3507            f(self)
3508        }
3509    }
3510
3511    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
3512    /// platform to receive textual input with proper integration with concerns such
3513    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
3514    /// rendered.
3515    ///
3516    /// This method should only be called as part of the paint phase of element drawing.
3517    ///
3518    /// [element_input_handler]: crate::ElementInputHandler
3519    pub fn handle_input(
3520        &mut self,
3521        focus_handle: &FocusHandle,
3522        input_handler: impl InputHandler,
3523        cx: &App,
3524    ) {
3525        self.invalidator.debug_assert_paint();
3526
3527        if focus_handle.is_focused(self) {
3528            let cx = self.to_async(cx);
3529            self.next_frame
3530                .input_handlers
3531                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3532        }
3533    }
3534
3535    /// Register a mouse event listener on the window 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 method should only be called as part of the paint phase of element drawing.
3540    pub fn on_mouse_event<Event: MouseEvent>(
3541        &mut self,
3542        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3543    ) {
3544        self.invalidator.debug_assert_paint();
3545
3546        self.next_frame.mouse_listeners.push(Some(Box::new(
3547            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3548                if let Some(event) = event.downcast_ref() {
3549                    listener(event, phase, window, cx)
3550                }
3551            },
3552        )));
3553    }
3554
3555    /// Register a key event listener on this node for the next frame. The type of event
3556    /// is determined by the first parameter of the given listener. When the next frame is rendered
3557    /// the listener will be cleared.
3558    ///
3559    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3560    /// a specific need to register a listener yourself.
3561    ///
3562    /// This method should only be called as part of the paint phase of element drawing.
3563    pub fn on_key_event<Event: KeyEvent>(
3564        &mut self,
3565        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3566    ) {
3567        self.invalidator.debug_assert_paint();
3568
3569        self.next_frame.dispatch_tree.on_key_event(Rc::new(
3570            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
3571                if let Some(event) = event.downcast_ref::<Event>() {
3572                    listener(event, phase, window, cx)
3573                }
3574            },
3575        ));
3576    }
3577
3578    /// Register a modifiers changed event listener on the window for the next frame.
3579    ///
3580    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3581    /// a specific need to register a global listener.
3582    ///
3583    /// This method should only be called as part of the paint phase of element drawing.
3584    pub fn on_modifiers_changed(
3585        &mut self,
3586        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
3587    ) {
3588        self.invalidator.debug_assert_paint();
3589
3590        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
3591            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
3592                listener(event, window, cx)
3593            },
3594        ));
3595    }
3596
3597    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
3598    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
3599    /// Returns a subscription and persists until the subscription is dropped.
3600    pub fn on_focus_in(
3601        &mut self,
3602        handle: &FocusHandle,
3603        cx: &mut App,
3604        mut listener: impl FnMut(&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 event.is_focus_in(focus_id) {
3610                    listener(window, cx);
3611                }
3612                true
3613            }));
3614        cx.defer(move |_| activate());
3615        subscription
3616    }
3617
3618    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
3619    /// Returns a subscription and persists until the subscription is dropped.
3620    pub fn on_focus_out(
3621        &mut self,
3622        handle: &FocusHandle,
3623        cx: &mut App,
3624        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
3625    ) -> Subscription {
3626        let focus_id = handle.id;
3627        let (subscription, activate) =
3628            self.new_focus_listener(Box::new(move |event, window, cx| {
3629                if let Some(blurred_id) = event.previous_focus_path.last().copied()
3630                    && event.is_focus_out(focus_id)
3631                {
3632                    let event = FocusOutEvent {
3633                        blurred: WeakFocusHandle {
3634                            id: blurred_id,
3635                            handles: Arc::downgrade(&cx.focus_handles),
3636                        },
3637                    };
3638                    listener(event, window, cx)
3639                }
3640                true
3641            }));
3642        cx.defer(move |_| activate());
3643        subscription
3644    }
3645
3646    fn reset_cursor_style(&self, cx: &mut App) {
3647        // Set the cursor only if we're the active window.
3648        if self.is_window_hovered() {
3649            let style = self
3650                .rendered_frame
3651                .cursor_style(self)
3652                .unwrap_or(CursorStyle::Arrow);
3653            cx.platform.set_cursor_style(style);
3654        }
3655    }
3656
3657    /// Dispatch a given keystroke as though the user had typed it.
3658    /// You can create a keystroke with Keystroke::parse("").
3659    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
3660        let keystroke = keystroke.with_simulated_ime();
3661        let result = self.dispatch_event(
3662            PlatformInput::KeyDown(KeyDownEvent {
3663                keystroke: keystroke.clone(),
3664                is_held: false,
3665                prefer_character_input: false,
3666            }),
3667            cx,
3668        );
3669        if !result.propagate {
3670            return true;
3671        }
3672
3673        if let Some(input) = keystroke.key_char
3674            && let Some(mut input_handler) = self.platform_window.take_input_handler()
3675        {
3676            input_handler.dispatch_input(&input, self, cx);
3677            self.platform_window.set_input_handler(input_handler);
3678            return true;
3679        }
3680
3681        false
3682    }
3683
3684    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3685    /// binding for the action (last binding added to the keymap).
3686    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3687        self.highest_precedence_binding_for_action(action)
3688            .map(|binding| {
3689                binding
3690                    .keystrokes()
3691                    .iter()
3692                    .map(ToString::to_string)
3693                    .collect::<Vec<_>>()
3694                    .join(" ")
3695            })
3696            .unwrap_or_else(|| action.name().to_string())
3697    }
3698
3699    /// Dispatch a mouse or keyboard event on the window.
3700    #[profiling::function]
3701    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3702        self.last_input_timestamp.set(Instant::now());
3703
3704        // Track whether this input was keyboard-based for focus-visible styling
3705        self.last_input_modality = match &event {
3706            PlatformInput::KeyDown(_) | PlatformInput::ModifiersChanged(_) => {
3707                InputModality::Keyboard
3708            }
3709            PlatformInput::MouseDown(e) if e.is_focusing() => InputModality::Mouse,
3710            _ => self.last_input_modality,
3711        };
3712
3713        // Handlers may set this to false by calling `stop_propagation`.
3714        cx.propagate_event = true;
3715        // Handlers may set this to true by calling `prevent_default`.
3716        self.default_prevented = false;
3717
3718        let event = match event {
3719            // Track the mouse position with our own state, since accessing the platform
3720            // API for the mouse position can only occur on the main thread.
3721            PlatformInput::MouseMove(mouse_move) => {
3722                self.mouse_position = mouse_move.position;
3723                self.modifiers = mouse_move.modifiers;
3724                PlatformInput::MouseMove(mouse_move)
3725            }
3726            PlatformInput::MouseDown(mouse_down) => {
3727                self.mouse_position = mouse_down.position;
3728                self.modifiers = mouse_down.modifiers;
3729                PlatformInput::MouseDown(mouse_down)
3730            }
3731            PlatformInput::MouseUp(mouse_up) => {
3732                self.mouse_position = mouse_up.position;
3733                self.modifiers = mouse_up.modifiers;
3734                PlatformInput::MouseUp(mouse_up)
3735            }
3736            PlatformInput::MousePressure(mouse_pressure) => {
3737                PlatformInput::MousePressure(mouse_pressure)
3738            }
3739            PlatformInput::MouseExited(mouse_exited) => {
3740                self.modifiers = mouse_exited.modifiers;
3741                PlatformInput::MouseExited(mouse_exited)
3742            }
3743            PlatformInput::ModifiersChanged(modifiers_changed) => {
3744                self.modifiers = modifiers_changed.modifiers;
3745                self.capslock = modifiers_changed.capslock;
3746                PlatformInput::ModifiersChanged(modifiers_changed)
3747            }
3748            PlatformInput::ScrollWheel(scroll_wheel) => {
3749                self.mouse_position = scroll_wheel.position;
3750                self.modifiers = scroll_wheel.modifiers;
3751                PlatformInput::ScrollWheel(scroll_wheel)
3752            }
3753            // Translate dragging and dropping of external files from the operating system
3754            // to internal drag and drop events.
3755            PlatformInput::FileDrop(file_drop) => match file_drop {
3756                FileDropEvent::Entered { position, paths } => {
3757                    self.mouse_position = position;
3758                    if cx.active_drag.is_none() {
3759                        cx.active_drag = Some(AnyDrag {
3760                            value: Arc::new(paths.clone()),
3761                            view: cx.new(|_| paths).into(),
3762                            cursor_offset: position,
3763                            cursor_style: None,
3764                        });
3765                    }
3766                    PlatformInput::MouseMove(MouseMoveEvent {
3767                        position,
3768                        pressed_button: Some(MouseButton::Left),
3769                        modifiers: Modifiers::default(),
3770                    })
3771                }
3772                FileDropEvent::Pending { position } => {
3773                    self.mouse_position = position;
3774                    PlatformInput::MouseMove(MouseMoveEvent {
3775                        position,
3776                        pressed_button: Some(MouseButton::Left),
3777                        modifiers: Modifiers::default(),
3778                    })
3779                }
3780                FileDropEvent::Submit { position } => {
3781                    cx.activate(true);
3782                    self.mouse_position = position;
3783                    PlatformInput::MouseUp(MouseUpEvent {
3784                        button: MouseButton::Left,
3785                        position,
3786                        modifiers: Modifiers::default(),
3787                        click_count: 1,
3788                    })
3789                }
3790                FileDropEvent::Exited => {
3791                    cx.active_drag.take();
3792                    PlatformInput::FileDrop(FileDropEvent::Exited)
3793                }
3794            },
3795            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3796        };
3797
3798        if let Some(any_mouse_event) = event.mouse_event() {
3799            self.dispatch_mouse_event(any_mouse_event, cx);
3800        } else if let Some(any_key_event) = event.keyboard_event() {
3801            self.dispatch_key_event(any_key_event, cx);
3802        }
3803
3804        DispatchEventResult {
3805            propagate: cx.propagate_event,
3806            default_prevented: self.default_prevented,
3807        }
3808    }
3809
3810    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3811        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3812        if hit_test != self.mouse_hit_test {
3813            self.mouse_hit_test = hit_test;
3814            self.reset_cursor_style(cx);
3815        }
3816
3817        #[cfg(any(feature = "inspector", debug_assertions))]
3818        if self.is_inspector_picking(cx) {
3819            self.handle_inspector_mouse_event(event, cx);
3820            // When inspector is picking, all other mouse handling is skipped.
3821            return;
3822        }
3823
3824        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3825
3826        // Capture phase, events bubble from back to front. Handlers for this phase are used for
3827        // special purposes, such as detecting events outside of a given Bounds.
3828        for listener in &mut mouse_listeners {
3829            let listener = listener.as_mut().unwrap();
3830            listener(event, DispatchPhase::Capture, self, cx);
3831            if !cx.propagate_event {
3832                break;
3833            }
3834        }
3835
3836        // Bubble phase, where most normal handlers do their work.
3837        if cx.propagate_event {
3838            for listener in mouse_listeners.iter_mut().rev() {
3839                let listener = listener.as_mut().unwrap();
3840                listener(event, DispatchPhase::Bubble, self, cx);
3841                if !cx.propagate_event {
3842                    break;
3843                }
3844            }
3845        }
3846
3847        self.rendered_frame.mouse_listeners = mouse_listeners;
3848
3849        if cx.has_active_drag() {
3850            if event.is::<MouseMoveEvent>() {
3851                // If this was a mouse move event, redraw the window so that the
3852                // active drag can follow the mouse cursor.
3853                self.refresh();
3854            } else if event.is::<MouseUpEvent>() {
3855                // If this was a mouse up event, cancel the active drag and redraw
3856                // the window.
3857                cx.active_drag = None;
3858                self.refresh();
3859            }
3860        }
3861    }
3862
3863    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3864        if self.invalidator.is_dirty() {
3865            self.draw(cx).clear();
3866        }
3867
3868        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3869        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3870
3871        let mut keystroke: Option<Keystroke> = None;
3872
3873        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3874            if event.modifiers.number_of_modifiers() == 0
3875                && self.pending_modifier.modifiers.number_of_modifiers() == 1
3876                && !self.pending_modifier.saw_keystroke
3877            {
3878                let key = match self.pending_modifier.modifiers {
3879                    modifiers if modifiers.shift => Some("shift"),
3880                    modifiers if modifiers.control => Some("control"),
3881                    modifiers if modifiers.alt => Some("alt"),
3882                    modifiers if modifiers.platform => Some("platform"),
3883                    modifiers if modifiers.function => Some("function"),
3884                    _ => None,
3885                };
3886                if let Some(key) = key {
3887                    keystroke = Some(Keystroke {
3888                        key: key.to_string(),
3889                        key_char: None,
3890                        modifiers: Modifiers::default(),
3891                    });
3892                }
3893            }
3894
3895            if self.pending_modifier.modifiers.number_of_modifiers() == 0
3896                && event.modifiers.number_of_modifiers() == 1
3897            {
3898                self.pending_modifier.saw_keystroke = false
3899            }
3900            self.pending_modifier.modifiers = event.modifiers
3901        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3902            self.pending_modifier.saw_keystroke = true;
3903            keystroke = Some(key_down_event.keystroke.clone());
3904        }
3905
3906        let Some(keystroke) = keystroke else {
3907            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3908            return;
3909        };
3910
3911        cx.propagate_event = true;
3912        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
3913        if !cx.propagate_event {
3914            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3915            return;
3916        }
3917
3918        let mut currently_pending = self.pending_input.take().unwrap_or_default();
3919        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3920            currently_pending = PendingInput::default();
3921        }
3922
3923        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3924            currently_pending.keystrokes,
3925            keystroke,
3926            &dispatch_path,
3927        );
3928
3929        if !match_result.to_replay.is_empty() {
3930            self.replay_pending_input(match_result.to_replay, cx);
3931            cx.propagate_event = true;
3932        }
3933
3934        if !match_result.pending.is_empty() {
3935            currently_pending.timer.take();
3936            currently_pending.keystrokes = match_result.pending;
3937            currently_pending.focus = self.focus;
3938
3939            let text_input_requires_timeout = event
3940                .downcast_ref::<KeyDownEvent>()
3941                .filter(|key_down| key_down.keystroke.key_char.is_some())
3942                .and_then(|_| self.platform_window.take_input_handler())
3943                .map_or(false, |mut input_handler| {
3944                    let accepts = input_handler.accepts_text_input(self, cx);
3945                    self.platform_window.set_input_handler(input_handler);
3946                    accepts
3947                });
3948
3949            currently_pending.needs_timeout |=
3950                match_result.pending_has_binding || text_input_requires_timeout;
3951
3952            if currently_pending.needs_timeout {
3953                currently_pending.timer = Some(self.spawn(cx, async move |cx| {
3954                    cx.background_executor.timer(Duration::from_secs(1)).await;
3955                    cx.update(move |window, cx| {
3956                        let Some(currently_pending) = window
3957                            .pending_input
3958                            .take()
3959                            .filter(|pending| pending.focus == window.focus)
3960                        else {
3961                            return;
3962                        };
3963
3964                        let node_id = window.focus_node_id_in_rendered_frame(window.focus);
3965                        let dispatch_path =
3966                            window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3967
3968                        let to_replay = window
3969                            .rendered_frame
3970                            .dispatch_tree
3971                            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3972
3973                        window.pending_input_changed(cx);
3974                        window.replay_pending_input(to_replay, cx)
3975                    })
3976                    .log_err();
3977                }));
3978            } else {
3979                currently_pending.timer = None;
3980            }
3981            self.pending_input = Some(currently_pending);
3982            self.pending_input_changed(cx);
3983            cx.propagate_event = false;
3984            return;
3985        }
3986
3987        let skip_bindings = event
3988            .downcast_ref::<KeyDownEvent>()
3989            .filter(|key_down_event| key_down_event.prefer_character_input)
3990            .map(|_| {
3991                self.platform_window
3992                    .take_input_handler()
3993                    .map_or(false, |mut input_handler| {
3994                        let accepts = input_handler.accepts_text_input(self, cx);
3995                        self.platform_window.set_input_handler(input_handler);
3996                        // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
3997                        // we prefer the text input over bindings.
3998                        accepts
3999                    })
4000            })
4001            .unwrap_or(false);
4002
4003        if !skip_bindings {
4004            for binding in match_result.bindings {
4005                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4006                if !cx.propagate_event {
4007                    self.dispatch_keystroke_observers(
4008                        event,
4009                        Some(binding.action),
4010                        match_result.context_stack,
4011                        cx,
4012                    );
4013                    self.pending_input_changed(cx);
4014                    return;
4015                }
4016            }
4017        }
4018
4019        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4020        self.pending_input_changed(cx);
4021    }
4022
4023    fn finish_dispatch_key_event(
4024        &mut self,
4025        event: &dyn Any,
4026        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4027        context_stack: Vec<KeyContext>,
4028        cx: &mut App,
4029    ) {
4030        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4031        if !cx.propagate_event {
4032            return;
4033        }
4034
4035        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4036        if !cx.propagate_event {
4037            return;
4038        }
4039
4040        self.dispatch_keystroke_observers(event, None, context_stack, cx);
4041    }
4042
4043    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4044        self.pending_input_observers
4045            .clone()
4046            .retain(&(), |callback| callback(self, cx));
4047    }
4048
4049    fn dispatch_key_down_up_event(
4050        &mut self,
4051        event: &dyn Any,
4052        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4053        cx: &mut App,
4054    ) {
4055        // Capture phase
4056        for node_id in dispatch_path {
4057            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4058
4059            for key_listener in node.key_listeners.clone() {
4060                key_listener(event, DispatchPhase::Capture, self, cx);
4061                if !cx.propagate_event {
4062                    return;
4063                }
4064            }
4065        }
4066
4067        // Bubble phase
4068        for node_id in dispatch_path.iter().rev() {
4069            // Handle low level key events
4070            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4071            for key_listener in node.key_listeners.clone() {
4072                key_listener(event, DispatchPhase::Bubble, self, cx);
4073                if !cx.propagate_event {
4074                    return;
4075                }
4076            }
4077        }
4078    }
4079
4080    fn dispatch_modifiers_changed_event(
4081        &mut self,
4082        event: &dyn Any,
4083        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4084        cx: &mut App,
4085    ) {
4086        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4087            return;
4088        };
4089        for node_id in dispatch_path.iter().rev() {
4090            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4091            for listener in node.modifiers_changed_listeners.clone() {
4092                listener(event, self, cx);
4093                if !cx.propagate_event {
4094                    return;
4095                }
4096            }
4097        }
4098    }
4099
4100    /// Determine whether a potential multi-stroke key binding is in progress on this window.
4101    pub fn has_pending_keystrokes(&self) -> bool {
4102        self.pending_input.is_some()
4103    }
4104
4105    pub(crate) fn clear_pending_keystrokes(&mut self) {
4106        self.pending_input.take();
4107    }
4108
4109    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4110    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4111        self.pending_input
4112            .as_ref()
4113            .map(|pending_input| pending_input.keystrokes.as_slice())
4114    }
4115
4116    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4117        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4118        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4119
4120        'replay: for replay in replays {
4121            let event = KeyDownEvent {
4122                keystroke: replay.keystroke.clone(),
4123                is_held: false,
4124                prefer_character_input: true,
4125            };
4126
4127            cx.propagate_event = true;
4128            for binding in replay.bindings {
4129                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4130                if !cx.propagate_event {
4131                    self.dispatch_keystroke_observers(
4132                        &event,
4133                        Some(binding.action),
4134                        Vec::default(),
4135                        cx,
4136                    );
4137                    continue 'replay;
4138                }
4139            }
4140
4141            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4142            if !cx.propagate_event {
4143                continue 'replay;
4144            }
4145            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4146                && let Some(mut input_handler) = self.platform_window.take_input_handler()
4147            {
4148                input_handler.dispatch_input(&input, self, cx);
4149                self.platform_window.set_input_handler(input_handler)
4150            }
4151        }
4152    }
4153
4154    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4155        focus_id
4156            .and_then(|focus_id| {
4157                self.rendered_frame
4158                    .dispatch_tree
4159                    .focusable_node_id(focus_id)
4160            })
4161            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4162    }
4163
4164    fn dispatch_action_on_node(
4165        &mut self,
4166        node_id: DispatchNodeId,
4167        action: &dyn Action,
4168        cx: &mut App,
4169    ) {
4170        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4171
4172        // Capture phase for global actions.
4173        cx.propagate_event = true;
4174        if let Some(mut global_listeners) = cx
4175            .global_action_listeners
4176            .remove(&action.as_any().type_id())
4177        {
4178            for listener in &global_listeners {
4179                listener(action.as_any(), DispatchPhase::Capture, cx);
4180                if !cx.propagate_event {
4181                    break;
4182                }
4183            }
4184
4185            global_listeners.extend(
4186                cx.global_action_listeners
4187                    .remove(&action.as_any().type_id())
4188                    .unwrap_or_default(),
4189            );
4190
4191            cx.global_action_listeners
4192                .insert(action.as_any().type_id(), global_listeners);
4193        }
4194
4195        if !cx.propagate_event {
4196            return;
4197        }
4198
4199        // Capture phase for window actions.
4200        for node_id in &dispatch_path {
4201            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4202            for DispatchActionListener {
4203                action_type,
4204                listener,
4205            } in node.action_listeners.clone()
4206            {
4207                let any_action = action.as_any();
4208                if action_type == any_action.type_id() {
4209                    listener(any_action, DispatchPhase::Capture, self, cx);
4210
4211                    if !cx.propagate_event {
4212                        return;
4213                    }
4214                }
4215            }
4216        }
4217
4218        // Bubble phase for window actions.
4219        for node_id in dispatch_path.iter().rev() {
4220            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4221            for DispatchActionListener {
4222                action_type,
4223                listener,
4224            } in node.action_listeners.clone()
4225            {
4226                let any_action = action.as_any();
4227                if action_type == any_action.type_id() {
4228                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4229                    listener(any_action, DispatchPhase::Bubble, self, cx);
4230
4231                    if !cx.propagate_event {
4232                        return;
4233                    }
4234                }
4235            }
4236        }
4237
4238        // Bubble phase for global actions.
4239        if let Some(mut global_listeners) = cx
4240            .global_action_listeners
4241            .remove(&action.as_any().type_id())
4242        {
4243            for listener in global_listeners.iter().rev() {
4244                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4245
4246                listener(action.as_any(), DispatchPhase::Bubble, cx);
4247                if !cx.propagate_event {
4248                    break;
4249                }
4250            }
4251
4252            global_listeners.extend(
4253                cx.global_action_listeners
4254                    .remove(&action.as_any().type_id())
4255                    .unwrap_or_default(),
4256            );
4257
4258            cx.global_action_listeners
4259                .insert(action.as_any().type_id(), global_listeners);
4260        }
4261    }
4262
4263    /// Register the given handler to be invoked whenever the global of the given type
4264    /// is updated.
4265    pub fn observe_global<G: Global>(
4266        &mut self,
4267        cx: &mut App,
4268        f: impl Fn(&mut Window, &mut App) + 'static,
4269    ) -> Subscription {
4270        let window_handle = self.handle;
4271        let (subscription, activate) = cx.global_observers.insert(
4272            TypeId::of::<G>(),
4273            Box::new(move |cx| {
4274                window_handle
4275                    .update(cx, |_, window, cx| f(window, cx))
4276                    .is_ok()
4277            }),
4278        );
4279        cx.defer(move |_| activate());
4280        subscription
4281    }
4282
4283    /// Focus the current window and bring it to the foreground at the platform level.
4284    pub fn activate_window(&self) {
4285        self.platform_window.activate();
4286    }
4287
4288    /// Minimize the current window at the platform level.
4289    pub fn minimize_window(&self) {
4290        self.platform_window.minimize();
4291    }
4292
4293    /// Toggle full screen status on the current window at the platform level.
4294    pub fn toggle_fullscreen(&self) {
4295        self.platform_window.toggle_fullscreen();
4296    }
4297
4298    /// Updates the IME panel position suggestions for languages like japanese, chinese.
4299    pub fn invalidate_character_coordinates(&self) {
4300        self.on_next_frame(|window, cx| {
4301            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4302                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4303                    window.platform_window.update_ime_position(bounds);
4304                }
4305                window.platform_window.set_input_handler(input_handler);
4306            }
4307        });
4308    }
4309
4310    /// Present a platform dialog.
4311    /// The provided message will be presented, along with buttons for each answer.
4312    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4313    pub fn prompt<T>(
4314        &mut self,
4315        level: PromptLevel,
4316        message: &str,
4317        detail: Option<&str>,
4318        answers: &[T],
4319        cx: &mut App,
4320    ) -> oneshot::Receiver<usize>
4321    where
4322        T: Clone + Into<PromptButton>,
4323    {
4324        let prompt_builder = cx.prompt_builder.take();
4325        let Some(prompt_builder) = prompt_builder else {
4326            unreachable!("Re-entrant window prompting is not supported by GPUI");
4327        };
4328
4329        let answers = answers
4330            .iter()
4331            .map(|answer| answer.clone().into())
4332            .collect::<Vec<_>>();
4333
4334        let receiver = match &prompt_builder {
4335            PromptBuilder::Default => self
4336                .platform_window
4337                .prompt(level, message, detail, &answers)
4338                .unwrap_or_else(|| {
4339                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4340                }),
4341            PromptBuilder::Custom(_) => {
4342                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4343            }
4344        };
4345
4346        cx.prompt_builder = Some(prompt_builder);
4347
4348        receiver
4349    }
4350
4351    fn build_custom_prompt(
4352        &mut self,
4353        prompt_builder: &PromptBuilder,
4354        level: PromptLevel,
4355        message: &str,
4356        detail: Option<&str>,
4357        answers: &[PromptButton],
4358        cx: &mut App,
4359    ) -> oneshot::Receiver<usize> {
4360        let (sender, receiver) = oneshot::channel();
4361        let handle = PromptHandle::new(sender);
4362        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4363        self.prompt = Some(handle);
4364        receiver
4365    }
4366
4367    /// Returns the current context stack.
4368    pub fn context_stack(&self) -> Vec<KeyContext> {
4369        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4370        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4371        dispatch_tree
4372            .dispatch_path(node_id)
4373            .iter()
4374            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4375            .collect()
4376    }
4377
4378    /// Returns all available actions for the focused element.
4379    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4380        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4381        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4382        for action_type in cx.global_action_listeners.keys() {
4383            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4384                let action = cx.actions.build_action_type(action_type).ok();
4385                if let Some(action) = action {
4386                    actions.insert(ix, action);
4387                }
4388            }
4389        }
4390        actions
4391    }
4392
4393    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4394    /// returned in the order they were added. For display, the last binding should take precedence.
4395    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4396        self.rendered_frame
4397            .dispatch_tree
4398            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4399    }
4400
4401    /// Returns the highest precedence key binding that invokes an action on the currently focused
4402    /// element. This is more efficient than getting the last result of `bindings_for_action`.
4403    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4404        self.rendered_frame
4405            .dispatch_tree
4406            .highest_precedence_binding_for_action(
4407                action,
4408                &self.rendered_frame.dispatch_tree.context_stack,
4409            )
4410    }
4411
4412    /// Returns the key bindings for an action in a context.
4413    pub fn bindings_for_action_in_context(
4414        &self,
4415        action: &dyn Action,
4416        context: KeyContext,
4417    ) -> Vec<KeyBinding> {
4418        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4419        dispatch_tree.bindings_for_action(action, &[context])
4420    }
4421
4422    /// Returns the highest precedence key binding for an action in a context. This is more
4423    /// efficient than getting the last result of `bindings_for_action_in_context`.
4424    pub fn highest_precedence_binding_for_action_in_context(
4425        &self,
4426        action: &dyn Action,
4427        context: KeyContext,
4428    ) -> Option<KeyBinding> {
4429        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4430        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4431    }
4432
4433    /// Returns any bindings that would invoke an action on the given focus handle if it were
4434    /// focused. Bindings are returned in the order they were added. For display, the last binding
4435    /// should take precedence.
4436    pub fn bindings_for_action_in(
4437        &self,
4438        action: &dyn Action,
4439        focus_handle: &FocusHandle,
4440    ) -> Vec<KeyBinding> {
4441        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4442        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4443            return vec![];
4444        };
4445        dispatch_tree.bindings_for_action(action, &context_stack)
4446    }
4447
4448    /// Returns the highest precedence key binding that would invoke an action on the given focus
4449    /// handle if it were focused. This is more efficient than getting the last result of
4450    /// `bindings_for_action_in`.
4451    pub fn highest_precedence_binding_for_action_in(
4452        &self,
4453        action: &dyn Action,
4454        focus_handle: &FocusHandle,
4455    ) -> Option<KeyBinding> {
4456        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4457        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4458        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4459    }
4460
4461    /// Find the bindings that can follow the current input sequence for the current context stack.
4462    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
4463        self.rendered_frame
4464            .dispatch_tree
4465            .possible_next_bindings_for_input(input, &self.context_stack())
4466    }
4467
4468    fn context_stack_for_focus_handle(
4469        &self,
4470        focus_handle: &FocusHandle,
4471    ) -> Option<Vec<KeyContext>> {
4472        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4473        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4474        let context_stack: Vec<_> = dispatch_tree
4475            .dispatch_path(node_id)
4476            .into_iter()
4477            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4478            .collect();
4479        Some(context_stack)
4480    }
4481
4482    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4483    pub fn listener_for<T: 'static, E>(
4484        &self,
4485        view: &Entity<T>,
4486        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
4487    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4488        let view = view.downgrade();
4489        move |e: &E, window: &mut Window, cx: &mut App| {
4490            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4491        }
4492    }
4493
4494    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4495    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
4496        &self,
4497        entity: &Entity<E>,
4498        f: Callback,
4499    ) -> impl Fn(&mut Window, &mut App) + 'static {
4500        let entity = entity.downgrade();
4501        move |window: &mut Window, cx: &mut App| {
4502            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
4503        }
4504    }
4505
4506    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4507    /// If the callback returns false, the window won't be closed.
4508    pub fn on_window_should_close(
4509        &self,
4510        cx: &App,
4511        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4512    ) {
4513        let mut cx = self.to_async(cx);
4514        self.platform_window.on_should_close(Box::new(move || {
4515            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4516        }))
4517    }
4518
4519    /// Register an action listener on this node for the next frame. The type of action
4520    /// is determined by the first parameter of the given listener. When the next frame is rendered
4521    /// the listener will be cleared.
4522    ///
4523    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4524    /// a specific need to register a listener yourself.
4525    ///
4526    /// This method should only be called as part of the paint phase of element drawing.
4527    pub fn on_action(
4528        &mut self,
4529        action_type: TypeId,
4530        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4531    ) {
4532        self.invalidator.debug_assert_paint();
4533
4534        self.next_frame
4535            .dispatch_tree
4536            .on_action(action_type, Rc::new(listener));
4537    }
4538
4539    /// Register a capturing action listener on this node for the next frame if the condition is true.
4540    /// The type of action is determined by the first parameter of the given listener. When the next
4541    /// frame is rendered the listener will be cleared.
4542    ///
4543    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4544    /// a specific need to register a listener yourself.
4545    ///
4546    /// This method should only be called as part of the paint phase of element drawing.
4547    pub fn on_action_when(
4548        &mut self,
4549        condition: bool,
4550        action_type: TypeId,
4551        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4552    ) {
4553        self.invalidator.debug_assert_paint();
4554
4555        if condition {
4556            self.next_frame
4557                .dispatch_tree
4558                .on_action(action_type, Rc::new(listener));
4559        }
4560    }
4561
4562    /// Read information about the GPU backing this window.
4563    /// Currently returns None on Mac and Windows.
4564    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4565        self.platform_window.gpu_specs()
4566    }
4567
4568    /// Perform titlebar double-click action.
4569    /// This is macOS specific.
4570    pub fn titlebar_double_click(&self) {
4571        self.platform_window.titlebar_double_click();
4572    }
4573
4574    /// Gets the window's title at the platform level.
4575    /// This is macOS specific.
4576    pub fn window_title(&self) -> String {
4577        self.platform_window.get_title()
4578    }
4579
4580    /// Returns a list of all tabbed windows and their titles.
4581    /// This is macOS specific.
4582    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
4583        self.platform_window.tabbed_windows()
4584    }
4585
4586    /// Returns the tab bar visibility.
4587    /// This is macOS specific.
4588    pub fn tab_bar_visible(&self) -> bool {
4589        self.platform_window.tab_bar_visible()
4590    }
4591
4592    /// Merges all open windows into a single tabbed window.
4593    /// This is macOS specific.
4594    pub fn merge_all_windows(&self) {
4595        self.platform_window.merge_all_windows()
4596    }
4597
4598    /// Moves the tab to a new containing window.
4599    /// This is macOS specific.
4600    pub fn move_tab_to_new_window(&self) {
4601        self.platform_window.move_tab_to_new_window()
4602    }
4603
4604    /// Shows or hides the window tab overview.
4605    /// This is macOS specific.
4606    pub fn toggle_window_tab_overview(&self) {
4607        self.platform_window.toggle_window_tab_overview()
4608    }
4609
4610    /// Sets the tabbing identifier for the window.
4611    /// This is macOS specific.
4612    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
4613        self.platform_window
4614            .set_tabbing_identifier(tabbing_identifier)
4615    }
4616
4617    /// Toggles the inspector mode on this window.
4618    #[cfg(any(feature = "inspector", debug_assertions))]
4619    pub fn toggle_inspector(&mut self, cx: &mut App) {
4620        self.inspector = match self.inspector {
4621            None => Some(cx.new(|_| Inspector::new())),
4622            Some(_) => None,
4623        };
4624        self.refresh();
4625    }
4626
4627    /// Returns true if the window is in inspector mode.
4628    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
4629        #[cfg(any(feature = "inspector", debug_assertions))]
4630        {
4631            if let Some(inspector) = &self.inspector {
4632                return inspector.read(_cx).is_picking();
4633            }
4634        }
4635        false
4636    }
4637
4638    /// Executes the provided function with mutable access to an inspector state.
4639    #[cfg(any(feature = "inspector", debug_assertions))]
4640    pub fn with_inspector_state<T: 'static, R>(
4641        &mut self,
4642        _inspector_id: Option<&crate::InspectorElementId>,
4643        cx: &mut App,
4644        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
4645    ) -> R {
4646        if let Some(inspector_id) = _inspector_id
4647            && let Some(inspector) = &self.inspector
4648        {
4649            let inspector = inspector.clone();
4650            let active_element_id = inspector.read(cx).active_element_id();
4651            if Some(inspector_id) == active_element_id {
4652                return inspector.update(cx, |inspector, _cx| {
4653                    inspector.with_active_element_state(self, f)
4654                });
4655            }
4656        }
4657        f(&mut None, self)
4658    }
4659
4660    #[cfg(any(feature = "inspector", debug_assertions))]
4661    pub(crate) fn build_inspector_element_id(
4662        &mut self,
4663        path: crate::InspectorElementPath,
4664    ) -> crate::InspectorElementId {
4665        self.invalidator.debug_assert_paint_or_prepaint();
4666        let path = Rc::new(path);
4667        let next_instance_id = self
4668            .next_frame
4669            .next_inspector_instance_ids
4670            .entry(path.clone())
4671            .or_insert(0);
4672        let instance_id = *next_instance_id;
4673        *next_instance_id += 1;
4674        crate::InspectorElementId { path, instance_id }
4675    }
4676
4677    #[cfg(any(feature = "inspector", debug_assertions))]
4678    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
4679        if let Some(inspector) = self.inspector.take() {
4680            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
4681            inspector_element.prepaint_as_root(
4682                point(self.viewport_size.width - inspector_width, px(0.0)),
4683                size(inspector_width, self.viewport_size.height).into(),
4684                self,
4685                cx,
4686            );
4687            self.inspector = Some(inspector);
4688            Some(inspector_element)
4689        } else {
4690            None
4691        }
4692    }
4693
4694    #[cfg(any(feature = "inspector", debug_assertions))]
4695    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
4696        if let Some(mut inspector_element) = inspector_element {
4697            inspector_element.paint(self, cx);
4698        };
4699    }
4700
4701    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
4702    /// inspect UI elements by clicking on them.
4703    #[cfg(any(feature = "inspector", debug_assertions))]
4704    pub fn insert_inspector_hitbox(
4705        &mut self,
4706        hitbox_id: HitboxId,
4707        inspector_id: Option<&crate::InspectorElementId>,
4708        cx: &App,
4709    ) {
4710        self.invalidator.debug_assert_paint_or_prepaint();
4711        if !self.is_inspector_picking(cx) {
4712            return;
4713        }
4714        if let Some(inspector_id) = inspector_id {
4715            self.next_frame
4716                .inspector_hitboxes
4717                .insert(hitbox_id, inspector_id.clone());
4718        }
4719    }
4720
4721    #[cfg(any(feature = "inspector", debug_assertions))]
4722    fn paint_inspector_hitbox(&mut self, cx: &App) {
4723        if let Some(inspector) = self.inspector.as_ref() {
4724            let inspector = inspector.read(cx);
4725            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
4726                && let Some(hitbox) = self
4727                    .next_frame
4728                    .hitboxes
4729                    .iter()
4730                    .find(|hitbox| hitbox.id == hitbox_id)
4731            {
4732                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
4733            }
4734        }
4735    }
4736
4737    #[cfg(any(feature = "inspector", debug_assertions))]
4738    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4739        let Some(inspector) = self.inspector.clone() else {
4740            return;
4741        };
4742        if event.downcast_ref::<MouseMoveEvent>().is_some() {
4743            inspector.update(cx, |inspector, _cx| {
4744                if let Some((_, inspector_id)) =
4745                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4746                {
4747                    inspector.hover(inspector_id, self);
4748                }
4749            });
4750        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
4751            inspector.update(cx, |inspector, _cx| {
4752                if let Some((_, inspector_id)) =
4753                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4754                {
4755                    inspector.select(inspector_id, self);
4756                }
4757            });
4758        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
4759            // This should be kept in sync with SCROLL_LINES in x11 platform.
4760            const SCROLL_LINES: f32 = 3.0;
4761            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
4762            let delta_y = event
4763                .delta
4764                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
4765                .y;
4766            if let Some(inspector) = self.inspector.clone() {
4767                inspector.update(cx, |inspector, _cx| {
4768                    if let Some(depth) = inspector.pick_depth.as_mut() {
4769                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
4770                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
4771                        if *depth < 0.0 {
4772                            *depth = 0.0;
4773                        } else if *depth > max_depth {
4774                            *depth = max_depth;
4775                        }
4776                        if let Some((_, inspector_id)) =
4777                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4778                        {
4779                            inspector.set_active_element_id(inspector_id, self);
4780                        }
4781                    }
4782                });
4783            }
4784        }
4785    }
4786
4787    #[cfg(any(feature = "inspector", debug_assertions))]
4788    fn hovered_inspector_hitbox(
4789        &self,
4790        inspector: &Inspector,
4791        frame: &Frame,
4792    ) -> Option<(HitboxId, crate::InspectorElementId)> {
4793        if let Some(pick_depth) = inspector.pick_depth {
4794            let depth = (pick_depth as i64).try_into().unwrap_or(0);
4795            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
4796            let skip_count = (depth as usize).min(max_skipped);
4797            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
4798                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
4799                    return Some((*hitbox_id, inspector_id.clone()));
4800                }
4801            }
4802        }
4803        None
4804    }
4805
4806    /// For testing: set the current modifier keys state.
4807    /// This does not generate any events.
4808    #[cfg(any(test, feature = "test-support"))]
4809    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
4810        self.modifiers = modifiers;
4811    }
4812}
4813
4814// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4815slotmap::new_key_type! {
4816    /// A unique identifier for a window.
4817    pub struct WindowId;
4818}
4819
4820impl WindowId {
4821    /// Converts this window ID to a `u64`.
4822    pub fn as_u64(&self) -> u64 {
4823        self.0.as_ffi()
4824    }
4825}
4826
4827impl From<u64> for WindowId {
4828    fn from(value: u64) -> Self {
4829        WindowId(slotmap::KeyData::from_ffi(value))
4830    }
4831}
4832
4833/// A handle to a window with a specific root view type.
4834/// Note that this does not keep the window alive on its own.
4835#[derive(Deref, DerefMut)]
4836pub struct WindowHandle<V> {
4837    #[deref]
4838    #[deref_mut]
4839    pub(crate) any_handle: AnyWindowHandle,
4840    state_type: PhantomData<fn(V) -> V>,
4841}
4842
4843impl<V> Debug for WindowHandle<V> {
4844    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4845        f.debug_struct("WindowHandle")
4846            .field("any_handle", &self.any_handle.id.as_u64())
4847            .finish()
4848    }
4849}
4850
4851impl<V: 'static + Render> WindowHandle<V> {
4852    /// Creates a new handle from a window ID.
4853    /// This does not check if the root type of the window is `V`.
4854    pub fn new(id: WindowId) -> Self {
4855        WindowHandle {
4856            any_handle: AnyWindowHandle {
4857                id,
4858                state_type: TypeId::of::<V>(),
4859            },
4860            state_type: PhantomData,
4861        }
4862    }
4863
4864    /// Get the root view out of this window.
4865    ///
4866    /// This will fail if the window is closed or if the root view's type does not match `V`.
4867    #[cfg(any(test, feature = "test-support"))]
4868    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
4869    where
4870        C: AppContext,
4871    {
4872        crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
4873            root_view
4874                .downcast::<V>()
4875                .map_err(|_| anyhow!("the type of the window's root view has changed"))
4876        }))
4877    }
4878
4879    /// Updates the root view of this window.
4880    ///
4881    /// This will fail if the window has been closed or if the root view's type does not match
4882    pub fn update<C, R>(
4883        &self,
4884        cx: &mut C,
4885        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
4886    ) -> Result<R>
4887    where
4888        C: AppContext,
4889    {
4890        cx.update_window(self.any_handle, |root_view, window, cx| {
4891            let view = root_view
4892                .downcast::<V>()
4893                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4894
4895            Ok(view.update(cx, |view, cx| update(view, window, cx)))
4896        })?
4897    }
4898
4899    /// Read the root view out of this window.
4900    ///
4901    /// This will fail if the window is closed or if the root view's type does not match `V`.
4902    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
4903        let x = cx
4904            .windows
4905            .get(self.id)
4906            .and_then(|window| {
4907                window
4908                    .as_deref()
4909                    .and_then(|window| window.root.clone())
4910                    .map(|root_view| root_view.downcast::<V>())
4911            })
4912            .context("window not found")?
4913            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4914
4915        Ok(x.read(cx))
4916    }
4917
4918    /// Read the root view out of this window, with a callback
4919    ///
4920    /// This will fail if the window is closed or if the root view's type does not match `V`.
4921    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
4922    where
4923        C: AppContext,
4924    {
4925        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4926    }
4927
4928    /// Read the root view pointer off of this window.
4929    ///
4930    /// This will fail if the window is closed or if the root view's type does not match `V`.
4931    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
4932    where
4933        C: AppContext,
4934    {
4935        cx.read_window(self, |root_view, _cx| root_view)
4936    }
4937
4938    /// Check if this window is 'active'.
4939    ///
4940    /// Will return `None` if the window is closed or currently
4941    /// borrowed.
4942    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
4943        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
4944            .ok()
4945    }
4946}
4947
4948impl<V> Copy for WindowHandle<V> {}
4949
4950impl<V> Clone for WindowHandle<V> {
4951    fn clone(&self) -> Self {
4952        *self
4953    }
4954}
4955
4956impl<V> PartialEq for WindowHandle<V> {
4957    fn eq(&self, other: &Self) -> bool {
4958        self.any_handle == other.any_handle
4959    }
4960}
4961
4962impl<V> Eq for WindowHandle<V> {}
4963
4964impl<V> Hash for WindowHandle<V> {
4965    fn hash<H: Hasher>(&self, state: &mut H) {
4966        self.any_handle.hash(state);
4967    }
4968}
4969
4970impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4971    fn from(val: WindowHandle<V>) -> Self {
4972        val.any_handle
4973    }
4974}
4975
4976/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4977#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
4978pub struct AnyWindowHandle {
4979    pub(crate) id: WindowId,
4980    state_type: TypeId,
4981}
4982
4983impl AnyWindowHandle {
4984    /// Get the ID of this window.
4985    pub fn window_id(&self) -> WindowId {
4986        self.id
4987    }
4988
4989    /// Attempt to convert this handle to a window handle with a specific root view type.
4990    /// If the types do not match, this will return `None`.
4991    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4992        if TypeId::of::<T>() == self.state_type {
4993            Some(WindowHandle {
4994                any_handle: *self,
4995                state_type: PhantomData,
4996            })
4997        } else {
4998            None
4999        }
5000    }
5001
5002    /// Updates the state of the root view of this window.
5003    ///
5004    /// This will fail if the window has been closed.
5005    pub fn update<C, R>(
5006        self,
5007        cx: &mut C,
5008        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5009    ) -> Result<R>
5010    where
5011        C: AppContext,
5012    {
5013        cx.update_window(self, update)
5014    }
5015
5016    /// Read the state of the root view of this window.
5017    ///
5018    /// This will fail if the window has been closed.
5019    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5020    where
5021        C: AppContext,
5022        T: 'static,
5023    {
5024        let view = self
5025            .downcast::<T>()
5026            .context("the type of the window's root view has changed")?;
5027
5028        cx.read_window(&view, read)
5029    }
5030}
5031
5032impl HasWindowHandle for Window {
5033    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5034        self.platform_window.window_handle()
5035    }
5036}
5037
5038impl HasDisplayHandle for Window {
5039    fn display_handle(
5040        &self,
5041    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5042        self.platform_window.display_handle()
5043    }
5044}
5045
5046/// An identifier for an [`Element`].
5047///
5048/// Can be constructed with a string, a number, or both, as well
5049/// as other internal representations.
5050#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5051pub enum ElementId {
5052    /// The ID of a View element
5053    View(EntityId),
5054    /// An integer ID.
5055    Integer(u64),
5056    /// A string based ID.
5057    Name(SharedString),
5058    /// A UUID.
5059    Uuid(Uuid),
5060    /// An ID that's equated with a focus handle.
5061    FocusHandle(FocusId),
5062    /// A combination of a name and an integer.
5063    NamedInteger(SharedString, u64),
5064    /// A path.
5065    Path(Arc<std::path::Path>),
5066    /// A code location.
5067    CodeLocation(core::panic::Location<'static>),
5068    /// A labeled child of an element.
5069    NamedChild(Arc<ElementId>, SharedString),
5070}
5071
5072impl ElementId {
5073    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5074    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5075        Self::NamedInteger(name.into(), integer as u64)
5076    }
5077}
5078
5079impl Display for ElementId {
5080    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5081        match self {
5082            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5083            ElementId::Integer(ix) => write!(f, "{}", ix)?,
5084            ElementId::Name(name) => write!(f, "{}", name)?,
5085            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5086            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5087            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5088            ElementId::Path(path) => write!(f, "{}", path.display())?,
5089            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5090            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5091        }
5092
5093        Ok(())
5094    }
5095}
5096
5097impl TryInto<SharedString> for ElementId {
5098    type Error = anyhow::Error;
5099
5100    fn try_into(self) -> anyhow::Result<SharedString> {
5101        if let ElementId::Name(name) = self {
5102            Ok(name)
5103        } else {
5104            anyhow::bail!("element id is not string")
5105        }
5106    }
5107}
5108
5109impl From<usize> for ElementId {
5110    fn from(id: usize) -> Self {
5111        ElementId::Integer(id as u64)
5112    }
5113}
5114
5115impl From<i32> for ElementId {
5116    fn from(id: i32) -> Self {
5117        Self::Integer(id as u64)
5118    }
5119}
5120
5121impl From<SharedString> for ElementId {
5122    fn from(name: SharedString) -> Self {
5123        ElementId::Name(name)
5124    }
5125}
5126
5127impl From<String> for ElementId {
5128    fn from(name: String) -> Self {
5129        ElementId::Name(name.into())
5130    }
5131}
5132
5133impl From<Arc<str>> for ElementId {
5134    fn from(name: Arc<str>) -> Self {
5135        ElementId::Name(name.into())
5136    }
5137}
5138
5139impl From<Arc<std::path::Path>> for ElementId {
5140    fn from(path: Arc<std::path::Path>) -> Self {
5141        ElementId::Path(path)
5142    }
5143}
5144
5145impl From<&'static str> for ElementId {
5146    fn from(name: &'static str) -> Self {
5147        ElementId::Name(name.into())
5148    }
5149}
5150
5151impl<'a> From<&'a FocusHandle> for ElementId {
5152    fn from(handle: &'a FocusHandle) -> Self {
5153        ElementId::FocusHandle(handle.id)
5154    }
5155}
5156
5157impl From<(&'static str, EntityId)> for ElementId {
5158    fn from((name, id): (&'static str, EntityId)) -> Self {
5159        ElementId::NamedInteger(name.into(), id.as_u64())
5160    }
5161}
5162
5163impl From<(&'static str, usize)> for ElementId {
5164    fn from((name, id): (&'static str, usize)) -> Self {
5165        ElementId::NamedInteger(name.into(), id as u64)
5166    }
5167}
5168
5169impl From<(SharedString, usize)> for ElementId {
5170    fn from((name, id): (SharedString, usize)) -> Self {
5171        ElementId::NamedInteger(name, id as u64)
5172    }
5173}
5174
5175impl From<(&'static str, u64)> for ElementId {
5176    fn from((name, id): (&'static str, u64)) -> Self {
5177        ElementId::NamedInteger(name.into(), id)
5178    }
5179}
5180
5181impl From<Uuid> for ElementId {
5182    fn from(value: Uuid) -> Self {
5183        Self::Uuid(value)
5184    }
5185}
5186
5187impl From<(&'static str, u32)> for ElementId {
5188    fn from((name, id): (&'static str, u32)) -> Self {
5189        ElementId::NamedInteger(name.into(), id.into())
5190    }
5191}
5192
5193impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5194    fn from((id, name): (ElementId, T)) -> Self {
5195        ElementId::NamedChild(Arc::new(id), name.into())
5196    }
5197}
5198
5199impl From<&'static core::panic::Location<'static>> for ElementId {
5200    fn from(location: &'static core::panic::Location<'static>) -> Self {
5201        ElementId::CodeLocation(*location)
5202    }
5203}
5204
5205/// A rectangle to be rendered in the window at the given position and size.
5206/// Passed as an argument [`Window::paint_quad`].
5207#[derive(Clone)]
5208pub struct PaintQuad {
5209    /// The bounds of the quad within the window.
5210    pub bounds: Bounds<Pixels>,
5211    /// The radii of the quad's corners.
5212    pub corner_radii: Corners<Pixels>,
5213    /// The background color of the quad.
5214    pub background: Background,
5215    /// The widths of the quad's borders.
5216    pub border_widths: Edges<Pixels>,
5217    /// The color of the quad's borders.
5218    pub border_color: Hsla,
5219    /// The style of the quad's borders.
5220    pub border_style: BorderStyle,
5221}
5222
5223impl PaintQuad {
5224    /// Sets the corner radii of the quad.
5225    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5226        PaintQuad {
5227            corner_radii: corner_radii.into(),
5228            ..self
5229        }
5230    }
5231
5232    /// Sets the border widths of the quad.
5233    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5234        PaintQuad {
5235            border_widths: border_widths.into(),
5236            ..self
5237        }
5238    }
5239
5240    /// Sets the border color of the quad.
5241    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5242        PaintQuad {
5243            border_color: border_color.into(),
5244            ..self
5245        }
5246    }
5247
5248    /// Sets the background color of the quad.
5249    pub fn background(self, background: impl Into<Background>) -> Self {
5250        PaintQuad {
5251            background: background.into(),
5252            ..self
5253        }
5254    }
5255}
5256
5257/// Creates a quad with the given parameters.
5258pub fn quad(
5259    bounds: Bounds<Pixels>,
5260    corner_radii: impl Into<Corners<Pixels>>,
5261    background: impl Into<Background>,
5262    border_widths: impl Into<Edges<Pixels>>,
5263    border_color: impl Into<Hsla>,
5264    border_style: BorderStyle,
5265) -> PaintQuad {
5266    PaintQuad {
5267        bounds,
5268        corner_radii: corner_radii.into(),
5269        background: background.into(),
5270        border_widths: border_widths.into(),
5271        border_color: border_color.into(),
5272        border_style,
5273    }
5274}
5275
5276/// Creates a filled quad with the given bounds and background color.
5277pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5278    PaintQuad {
5279        bounds: bounds.into(),
5280        corner_radii: (0.).into(),
5281        background: background.into(),
5282        border_widths: (0.).into(),
5283        border_color: transparent_black(),
5284        border_style: BorderStyle::default(),
5285    }
5286}
5287
5288/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5289pub fn outline(
5290    bounds: impl Into<Bounds<Pixels>>,
5291    border_color: impl Into<Hsla>,
5292    border_style: BorderStyle,
5293) -> PaintQuad {
5294    PaintQuad {
5295        bounds: bounds.into(),
5296        corner_radii: (0.).into(),
5297        background: transparent_black().into(),
5298        border_widths: (1.).into(),
5299        border_color: border_color.into(),
5300        border_style,
5301    }
5302}