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