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