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