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