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