window.rs

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