window.rs

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