window.rs

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