window.rs

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