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