window.rs

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