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