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.with_id(element_id, |this| {
2046            let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2047
2048            f(&global_id, this)
2049        })
2050    }
2051
2052    /// Calls the provided closure with the element ID pushed on the stack.
2053    #[inline]
2054    pub fn with_id<R>(
2055        &mut self,
2056        element_id: impl Into<ElementId>,
2057        f: impl FnOnce(&mut Self) -> R,
2058    ) -> R {
2059        self.element_id_stack.push(element_id.into());
2060        let result = f(self);
2061        self.element_id_stack.pop();
2062        result
2063    }
2064
2065    /// Executes the provided function with the specified rem size.
2066    ///
2067    /// This method must only be called as part of element drawing.
2068    // This function is called in a highly recursive manner in editor
2069    // prepainting, make sure its inlined to reduce the stack burden
2070    #[inline]
2071    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2072    where
2073        F: FnOnce(&mut Self) -> R,
2074    {
2075        self.invalidator.debug_assert_paint_or_prepaint();
2076
2077        if let Some(rem_size) = rem_size {
2078            self.rem_size_override_stack.push(rem_size.into());
2079            let result = f(self);
2080            self.rem_size_override_stack.pop();
2081            result
2082        } else {
2083            f(self)
2084        }
2085    }
2086
2087    /// The line height associated with the current text style.
2088    pub fn line_height(&self) -> Pixels {
2089        self.text_style().line_height_in_pixels(self.rem_size())
2090    }
2091
2092    /// Call to prevent the default action of an event. Currently only used to prevent
2093    /// parent elements from becoming focused on mouse down.
2094    pub fn prevent_default(&mut self) {
2095        self.default_prevented = true;
2096    }
2097
2098    /// Obtain whether default has been prevented for the event currently being dispatched.
2099    pub fn default_prevented(&self) -> bool {
2100        self.default_prevented
2101    }
2102
2103    /// Determine whether the given action is available along the dispatch path to the currently focused element.
2104    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2105        let node_id =
2106            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2107        self.rendered_frame
2108            .dispatch_tree
2109            .is_action_available(action, node_id)
2110    }
2111
2112    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
2113    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2114        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2115        self.rendered_frame
2116            .dispatch_tree
2117            .is_action_available(action, node_id)
2118    }
2119
2120    /// The position of the mouse relative to the window.
2121    pub fn mouse_position(&self) -> Point<Pixels> {
2122        self.mouse_position
2123    }
2124
2125    /// The current state of the keyboard's modifiers
2126    pub fn modifiers(&self) -> Modifiers {
2127        self.modifiers
2128    }
2129
2130    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
2131    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
2132    pub fn last_input_was_keyboard(&self) -> bool {
2133        self.last_input_modality == InputModality::Keyboard
2134    }
2135
2136    /// The current state of the keyboard's capslock
2137    pub fn capslock(&self) -> Capslock {
2138        self.capslock
2139    }
2140
2141    fn complete_frame(&self) {
2142        self.platform_window.completed_frame();
2143    }
2144
2145    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
2146    /// the contents of the new [`Scene`], use [`Self::present`].
2147    #[profiling::function]
2148    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2149        // Set up the per-App arena for element allocation during this draw.
2150        // This ensures that multiple test Apps have isolated arenas.
2151        let _arena_scope = ElementArenaScope::enter(&cx.element_arena);
2152
2153        self.invalidate_entities();
2154        cx.entities.clear_accessed();
2155        debug_assert!(self.rendered_entity_stack.is_empty());
2156        self.invalidator.set_dirty(false);
2157        self.requested_autoscroll = None;
2158
2159        // Restore the previously-used input handler.
2160        if let Some(input_handler) = self.platform_window.take_input_handler() {
2161            self.rendered_frame.input_handlers.push(Some(input_handler));
2162        }
2163        if !cx.mode.skip_drawing() {
2164            self.draw_roots(cx);
2165        }
2166        self.dirty_views.clear();
2167        self.next_frame.window_active = self.active.get();
2168
2169        // Register requested input handler with the platform window.
2170        if let Some(input_handler) = self.next_frame.input_handlers.pop() {
2171            self.platform_window
2172                .set_input_handler(input_handler.unwrap());
2173        }
2174
2175        self.layout_engine.as_mut().unwrap().clear();
2176        self.text_system().finish_frame();
2177        self.next_frame.finish(&mut self.rendered_frame);
2178
2179        self.invalidator.set_phase(DrawPhase::Focus);
2180        let previous_focus_path = self.rendered_frame.focus_path();
2181        let previous_window_active = self.rendered_frame.window_active;
2182        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2183        self.next_frame.clear();
2184        let current_focus_path = self.rendered_frame.focus_path();
2185        let current_window_active = self.rendered_frame.window_active;
2186
2187        if previous_focus_path != current_focus_path
2188            || previous_window_active != current_window_active
2189        {
2190            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2191                self.focus_lost_listeners
2192                    .clone()
2193                    .retain(&(), |listener| listener(self, cx));
2194            }
2195
2196            let event = WindowFocusEvent {
2197                previous_focus_path: if previous_window_active {
2198                    previous_focus_path
2199                } else {
2200                    Default::default()
2201                },
2202                current_focus_path: if current_window_active {
2203                    current_focus_path
2204                } else {
2205                    Default::default()
2206                },
2207            };
2208            self.focus_listeners
2209                .clone()
2210                .retain(&(), |listener| listener(&event, self, cx));
2211        }
2212
2213        debug_assert!(self.rendered_entity_stack.is_empty());
2214        self.record_entities_accessed(cx);
2215        self.reset_cursor_style(cx);
2216        self.refreshing = false;
2217        self.invalidator.set_phase(DrawPhase::None);
2218        self.needs_present.set(true);
2219
2220        ArenaClearNeeded::new(&cx.element_arena)
2221    }
2222
2223    fn record_entities_accessed(&mut self, cx: &mut App) {
2224        let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
2225        let mut entities = mem::take(entities_ref.deref_mut());
2226        drop(entities_ref);
2227        let handle = self.handle;
2228        cx.record_entities_accessed(
2229            handle,
2230            // Try moving window invalidator into the Window
2231            self.invalidator.clone(),
2232            &entities,
2233        );
2234        let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
2235        mem::swap(&mut entities, entities_ref.deref_mut());
2236    }
2237
2238    fn invalidate_entities(&mut self) {
2239        let mut views = self.invalidator.take_views();
2240        for entity in views.drain() {
2241            self.mark_view_dirty(entity);
2242        }
2243        self.invalidator.replace_views(views);
2244    }
2245
2246    #[profiling::function]
2247    fn present(&self) {
2248        self.platform_window.draw(&self.rendered_frame.scene);
2249        self.needs_present.set(false);
2250        profiling::finish_frame!();
2251    }
2252
2253    fn draw_roots(&mut self, cx: &mut App) {
2254        self.invalidator.set_phase(DrawPhase::Prepaint);
2255        self.tooltip_bounds.take();
2256
2257        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2258        let root_size = {
2259            #[cfg(any(feature = "inspector", debug_assertions))]
2260            {
2261                if self.inspector.is_some() {
2262                    let mut size = self.viewport_size;
2263                    size.width = (size.width - _inspector_width).max(px(0.0));
2264                    size
2265                } else {
2266                    self.viewport_size
2267                }
2268            }
2269            #[cfg(not(any(feature = "inspector", debug_assertions)))]
2270            {
2271                self.viewport_size
2272            }
2273        };
2274
2275        // Layout all root elements.
2276        let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2277        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2278
2279        #[cfg(any(feature = "inspector", debug_assertions))]
2280        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2281
2282        let mut sorted_deferred_draws =
2283            (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
2284        sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2285        self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
2286
2287        let mut prompt_element = None;
2288        let mut active_drag_element = None;
2289        let mut tooltip_element = None;
2290        if let Some(prompt) = self.prompt.take() {
2291            let mut element = prompt.view.any_view().into_any();
2292            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2293            prompt_element = Some(element);
2294            self.prompt = Some(prompt);
2295        } else if let Some(active_drag) = cx.active_drag.take() {
2296            let mut element = active_drag.view.clone().into_any();
2297            let offset = self.mouse_position() - active_drag.cursor_offset;
2298            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2299            active_drag_element = Some(element);
2300            cx.active_drag = Some(active_drag);
2301        } else {
2302            tooltip_element = self.prepaint_tooltip(cx);
2303        }
2304
2305        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2306
2307        // Now actually paint the elements.
2308        self.invalidator.set_phase(DrawPhase::Paint);
2309        root_element.paint(self, cx);
2310
2311        #[cfg(any(feature = "inspector", debug_assertions))]
2312        self.paint_inspector(inspector_element, cx);
2313
2314        self.paint_deferred_draws(&sorted_deferred_draws, cx);
2315
2316        if let Some(mut prompt_element) = prompt_element {
2317            prompt_element.paint(self, cx);
2318        } else if let Some(mut drag_element) = active_drag_element {
2319            drag_element.paint(self, cx);
2320        } else if let Some(mut tooltip_element) = tooltip_element {
2321            tooltip_element.paint(self, cx);
2322        }
2323
2324        #[cfg(any(feature = "inspector", debug_assertions))]
2325        self.paint_inspector_hitbox(cx);
2326    }
2327
2328    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2329        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2330        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2331            let Some(Some(tooltip_request)) = self
2332                .next_frame
2333                .tooltip_requests
2334                .get(tooltip_request_index)
2335                .cloned()
2336            else {
2337                log::error!("Unexpectedly absent TooltipRequest");
2338                continue;
2339            };
2340            let mut element = tooltip_request.tooltip.view.clone().into_any();
2341            let mouse_position = tooltip_request.tooltip.mouse_position;
2342            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2343
2344            let mut tooltip_bounds =
2345                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2346            let window_bounds = Bounds {
2347                origin: Point::default(),
2348                size: self.viewport_size(),
2349            };
2350
2351            if tooltip_bounds.right() > window_bounds.right() {
2352                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2353                if new_x >= Pixels::ZERO {
2354                    tooltip_bounds.origin.x = new_x;
2355                } else {
2356                    tooltip_bounds.origin.x = cmp::max(
2357                        Pixels::ZERO,
2358                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2359                    );
2360                }
2361            }
2362
2363            if tooltip_bounds.bottom() > window_bounds.bottom() {
2364                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2365                if new_y >= Pixels::ZERO {
2366                    tooltip_bounds.origin.y = new_y;
2367                } else {
2368                    tooltip_bounds.origin.y = cmp::max(
2369                        Pixels::ZERO,
2370                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2371                    );
2372                }
2373            }
2374
2375            // It's possible for an element to have an active tooltip while not being painted (e.g.
2376            // via the `visible_on_hover` method). Since mouse listeners are not active in this
2377            // case, instead update the tooltip's visibility here.
2378            let is_visible =
2379                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2380            if !is_visible {
2381                continue;
2382            }
2383
2384            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2385                element.prepaint(window, cx)
2386            });
2387
2388            self.tooltip_bounds = Some(TooltipBounds {
2389                id: tooltip_request.id,
2390                bounds: tooltip_bounds,
2391            });
2392            return Some(element);
2393        }
2394        None
2395    }
2396
2397    fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2398        assert_eq!(self.element_id_stack.len(), 0);
2399
2400        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2401        for deferred_draw_ix in deferred_draw_indices {
2402            let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2403            self.element_id_stack
2404                .clone_from(&deferred_draw.element_id_stack);
2405            self.text_style_stack
2406                .clone_from(&deferred_draw.text_style_stack);
2407            self.next_frame
2408                .dispatch_tree
2409                .set_active_node(deferred_draw.parent_node);
2410
2411            let prepaint_start = self.prepaint_index();
2412            if let Some(element) = deferred_draw.element.as_mut() {
2413                self.with_rendered_view(deferred_draw.current_view, |window| {
2414                    window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2415                        window.with_absolute_element_offset(
2416                            deferred_draw.absolute_offset,
2417                            |window| {
2418                                element.prepaint(window, cx);
2419                            },
2420                        );
2421                    });
2422                })
2423            } else {
2424                self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2425            }
2426            let prepaint_end = self.prepaint_index();
2427            deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2428        }
2429        assert_eq!(
2430            self.next_frame.deferred_draws.len(),
2431            0,
2432            "cannot call defer_draw during deferred drawing"
2433        );
2434        self.next_frame.deferred_draws = deferred_draws;
2435        self.element_id_stack.clear();
2436        self.text_style_stack.clear();
2437    }
2438
2439    fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2440        assert_eq!(self.element_id_stack.len(), 0);
2441
2442        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2443        for deferred_draw_ix in deferred_draw_indices {
2444            let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2445            self.element_id_stack
2446                .clone_from(&deferred_draw.element_id_stack);
2447            self.next_frame
2448                .dispatch_tree
2449                .set_active_node(deferred_draw.parent_node);
2450
2451            let paint_start = self.paint_index();
2452            if let Some(element) = deferred_draw.element.as_mut() {
2453                self.with_rendered_view(deferred_draw.current_view, |window| {
2454                    window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2455                        element.paint(window, cx);
2456                    })
2457                })
2458            } else {
2459                self.reuse_paint(deferred_draw.paint_range.clone());
2460            }
2461            let paint_end = self.paint_index();
2462            deferred_draw.paint_range = paint_start..paint_end;
2463        }
2464        self.next_frame.deferred_draws = deferred_draws;
2465        self.element_id_stack.clear();
2466    }
2467
2468    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2469        PrepaintStateIndex {
2470            hitboxes_index: self.next_frame.hitboxes.len(),
2471            tooltips_index: self.next_frame.tooltip_requests.len(),
2472            deferred_draws_index: self.next_frame.deferred_draws.len(),
2473            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2474            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2475            line_layout_index: self.text_system.layout_index(),
2476        }
2477    }
2478
2479    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2480        self.next_frame.hitboxes.extend(
2481            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2482                .iter()
2483                .cloned(),
2484        );
2485        self.next_frame.tooltip_requests.extend(
2486            self.rendered_frame.tooltip_requests
2487                [range.start.tooltips_index..range.end.tooltips_index]
2488                .iter_mut()
2489                .map(|request| request.take()),
2490        );
2491        self.next_frame.accessed_element_states.extend(
2492            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2493                ..range.end.accessed_element_states_index]
2494                .iter()
2495                .map(|(id, type_id)| (id.clone(), *type_id)),
2496        );
2497        self.text_system
2498            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2499
2500        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2501            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2502            &mut self.rendered_frame.dispatch_tree,
2503            self.focus,
2504        );
2505
2506        if reused_subtree.contains_focus() {
2507            self.next_frame.focus = self.focus;
2508        }
2509
2510        self.next_frame.deferred_draws.extend(
2511            self.rendered_frame.deferred_draws
2512                [range.start.deferred_draws_index..range.end.deferred_draws_index]
2513                .iter()
2514                .map(|deferred_draw| DeferredDraw {
2515                    current_view: deferred_draw.current_view,
2516                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2517                    element_id_stack: deferred_draw.element_id_stack.clone(),
2518                    text_style_stack: deferred_draw.text_style_stack.clone(),
2519                    rem_size: deferred_draw.rem_size,
2520                    priority: deferred_draw.priority,
2521                    element: None,
2522                    absolute_offset: deferred_draw.absolute_offset,
2523                    prepaint_range: deferred_draw.prepaint_range.clone(),
2524                    paint_range: deferred_draw.paint_range.clone(),
2525                }),
2526        );
2527    }
2528
2529    pub(crate) fn paint_index(&self) -> PaintIndex {
2530        PaintIndex {
2531            scene_index: self.next_frame.scene.len(),
2532            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2533            input_handlers_index: self.next_frame.input_handlers.len(),
2534            cursor_styles_index: self.next_frame.cursor_styles.len(),
2535            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2536            tab_handle_index: self.next_frame.tab_stops.paint_index(),
2537            line_layout_index: self.text_system.layout_index(),
2538        }
2539    }
2540
2541    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2542        self.next_frame.cursor_styles.extend(
2543            self.rendered_frame.cursor_styles
2544                [range.start.cursor_styles_index..range.end.cursor_styles_index]
2545                .iter()
2546                .cloned(),
2547        );
2548        self.next_frame.input_handlers.extend(
2549            self.rendered_frame.input_handlers
2550                [range.start.input_handlers_index..range.end.input_handlers_index]
2551                .iter_mut()
2552                .map(|handler| handler.take()),
2553        );
2554        self.next_frame.mouse_listeners.extend(
2555            self.rendered_frame.mouse_listeners
2556                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2557                .iter_mut()
2558                .map(|listener| listener.take()),
2559        );
2560        self.next_frame.accessed_element_states.extend(
2561            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2562                ..range.end.accessed_element_states_index]
2563                .iter()
2564                .map(|(id, type_id)| (id.clone(), *type_id)),
2565        );
2566        self.next_frame.tab_stops.replay(
2567            &self.rendered_frame.tab_stops.insertion_history
2568                [range.start.tab_handle_index..range.end.tab_handle_index],
2569        );
2570
2571        self.text_system
2572            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2573        self.next_frame.scene.replay(
2574            range.start.scene_index..range.end.scene_index,
2575            &self.rendered_frame.scene,
2576        );
2577    }
2578
2579    /// Push a text style onto the stack, and call a function with that style active.
2580    /// Use [`Window::text_style`] to get the current, combined text style. This method
2581    /// should only be called as part of element drawing.
2582    // This function is called in a highly recursive manner in editor
2583    // prepainting, make sure its inlined to reduce the stack burden
2584    #[inline]
2585    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2586    where
2587        F: FnOnce(&mut Self) -> R,
2588    {
2589        self.invalidator.debug_assert_paint_or_prepaint();
2590        if let Some(style) = style {
2591            self.text_style_stack.push(style);
2592            let result = f(self);
2593            self.text_style_stack.pop();
2594            result
2595        } else {
2596            f(self)
2597        }
2598    }
2599
2600    /// Updates the cursor style at the platform level. This method should only be called
2601    /// during the paint phase of element drawing.
2602    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2603        self.invalidator.debug_assert_paint();
2604        self.next_frame.cursor_styles.push(CursorStyleRequest {
2605            hitbox_id: Some(hitbox.id),
2606            style,
2607        });
2608    }
2609
2610    /// Updates the cursor style for the entire window at the platform level. A cursor
2611    /// style using this method will have precedence over any cursor style set using
2612    /// `set_cursor_style`. This method should only be called during the paint
2613    /// phase of element drawing.
2614    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2615        self.invalidator.debug_assert_paint();
2616        self.next_frame.cursor_styles.push(CursorStyleRequest {
2617            hitbox_id: None,
2618            style,
2619        })
2620    }
2621
2622    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2623    /// during the paint phase of element drawing.
2624    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2625        self.invalidator.debug_assert_prepaint();
2626        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2627        self.next_frame
2628            .tooltip_requests
2629            .push(Some(TooltipRequest { id, tooltip }));
2630        id
2631    }
2632
2633    /// Invoke the given function with the given content mask after intersecting it
2634    /// with the current mask. This method should only be called during element drawing.
2635    // This function is called in a highly recursive manner in editor
2636    // prepainting, make sure its inlined to reduce the stack burden
2637    #[inline]
2638    pub fn with_content_mask<R>(
2639        &mut self,
2640        mask: Option<ContentMask<Pixels>>,
2641        f: impl FnOnce(&mut Self) -> R,
2642    ) -> R {
2643        self.invalidator.debug_assert_paint_or_prepaint();
2644        if let Some(mask) = mask {
2645            let mask = mask.intersect(&self.content_mask());
2646            self.content_mask_stack.push(mask);
2647            let result = f(self);
2648            self.content_mask_stack.pop();
2649            result
2650        } else {
2651            f(self)
2652        }
2653    }
2654
2655    /// Updates the global element offset relative to the current offset. This is used to implement
2656    /// scrolling. This method should only be called during the prepaint phase of element drawing.
2657    pub fn with_element_offset<R>(
2658        &mut self,
2659        offset: Point<Pixels>,
2660        f: impl FnOnce(&mut Self) -> R,
2661    ) -> R {
2662        self.invalidator.debug_assert_prepaint();
2663
2664        if offset.is_zero() {
2665            return f(self);
2666        };
2667
2668        let abs_offset = self.element_offset() + offset;
2669        self.with_absolute_element_offset(abs_offset, f)
2670    }
2671
2672    /// Updates the global element offset based on the given offset. This is used to implement
2673    /// drag handles and other manual painting of elements. This method should only be called during
2674    /// the prepaint phase of element drawing.
2675    pub fn with_absolute_element_offset<R>(
2676        &mut self,
2677        offset: Point<Pixels>,
2678        f: impl FnOnce(&mut Self) -> R,
2679    ) -> R {
2680        self.invalidator.debug_assert_prepaint();
2681        self.element_offset_stack.push(offset);
2682        let result = f(self);
2683        self.element_offset_stack.pop();
2684        result
2685    }
2686
2687    pub(crate) fn with_element_opacity<R>(
2688        &mut self,
2689        opacity: Option<f32>,
2690        f: impl FnOnce(&mut Self) -> R,
2691    ) -> R {
2692        self.invalidator.debug_assert_paint_or_prepaint();
2693
2694        let Some(opacity) = opacity else {
2695            return f(self);
2696        };
2697
2698        let previous_opacity = self.element_opacity;
2699        self.element_opacity = previous_opacity * opacity;
2700        let result = f(self);
2701        self.element_opacity = previous_opacity;
2702        result
2703    }
2704
2705    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2706    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2707    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2708    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
2709    /// called during the prepaint phase of element drawing.
2710    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2711        self.invalidator.debug_assert_prepaint();
2712        let index = self.prepaint_index();
2713        let result = f(self);
2714        if result.is_err() {
2715            self.next_frame.hitboxes.truncate(index.hitboxes_index);
2716            self.next_frame
2717                .tooltip_requests
2718                .truncate(index.tooltips_index);
2719            self.next_frame
2720                .deferred_draws
2721                .truncate(index.deferred_draws_index);
2722            self.next_frame
2723                .dispatch_tree
2724                .truncate(index.dispatch_tree_index);
2725            self.next_frame
2726                .accessed_element_states
2727                .truncate(index.accessed_element_states_index);
2728            self.text_system.truncate_layouts(index.line_layout_index);
2729        }
2730        result
2731    }
2732
2733    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
2734    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2735    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
2736    /// that supports this method being called on the elements it contains. This method should only be
2737    /// called during the prepaint phase of element drawing.
2738    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2739        self.invalidator.debug_assert_prepaint();
2740        self.requested_autoscroll = Some(bounds);
2741    }
2742
2743    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
2744    /// described in [`Self::request_autoscroll`].
2745    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2746        self.invalidator.debug_assert_prepaint();
2747        self.requested_autoscroll.take()
2748    }
2749
2750    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2751    /// Your view will be re-drawn once the asset has finished loading.
2752    ///
2753    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2754    /// time.
2755    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2756        let (task, is_first) = cx.fetch_asset::<A>(source);
2757        task.clone().now_or_never().or_else(|| {
2758            if is_first {
2759                let entity_id = self.current_view();
2760                self.spawn(cx, {
2761                    let task = task.clone();
2762                    async move |cx| {
2763                        task.await;
2764
2765                        cx.on_next_frame(move |_, cx| {
2766                            cx.notify(entity_id);
2767                        });
2768                    }
2769                })
2770                .detach();
2771            }
2772
2773            None
2774        })
2775    }
2776
2777    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
2778    /// Your view will not be re-drawn once the asset has finished loading.
2779    ///
2780    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2781    /// time.
2782    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2783        let (task, _) = cx.fetch_asset::<A>(source);
2784        task.now_or_never()
2785    }
2786    /// Obtain the current element offset. This method should only be called during the
2787    /// prepaint phase of element drawing.
2788    pub fn element_offset(&self) -> Point<Pixels> {
2789        self.invalidator.debug_assert_prepaint();
2790        self.element_offset_stack
2791            .last()
2792            .copied()
2793            .unwrap_or_default()
2794    }
2795
2796    /// Obtain the current element opacity. This method should only be called during the
2797    /// prepaint phase of element drawing.
2798    #[inline]
2799    pub(crate) fn element_opacity(&self) -> f32 {
2800        self.invalidator.debug_assert_paint_or_prepaint();
2801        self.element_opacity
2802    }
2803
2804    /// Obtain the current content mask. This method should only be called during element drawing.
2805    pub fn content_mask(&self) -> ContentMask<Pixels> {
2806        self.invalidator.debug_assert_paint_or_prepaint();
2807        self.content_mask_stack
2808            .last()
2809            .cloned()
2810            .unwrap_or_else(|| ContentMask {
2811                bounds: Bounds {
2812                    origin: Point::default(),
2813                    size: self.viewport_size,
2814                },
2815            })
2816    }
2817
2818    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2819    /// This can be used within a custom element to distinguish multiple sets of child elements.
2820    pub fn with_element_namespace<R>(
2821        &mut self,
2822        element_id: impl Into<ElementId>,
2823        f: impl FnOnce(&mut Self) -> R,
2824    ) -> R {
2825        self.element_id_stack.push(element_id.into());
2826        let result = f(self);
2827        self.element_id_stack.pop();
2828        result
2829    }
2830
2831    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
2832    pub fn use_keyed_state<S: 'static>(
2833        &mut self,
2834        key: impl Into<ElementId>,
2835        cx: &mut App,
2836        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2837    ) -> Entity<S> {
2838        let current_view = self.current_view();
2839        self.with_global_id(key.into(), |global_id, window| {
2840            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
2841                if let Some(state) = state {
2842                    (state.clone(), state)
2843                } else {
2844                    let new_state = cx.new(|cx| init(window, cx));
2845                    cx.observe(&new_state, move |_, cx| {
2846                        cx.notify(current_view);
2847                    })
2848                    .detach();
2849                    (new_state.clone(), new_state)
2850                }
2851            })
2852        })
2853    }
2854
2855    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
2856    ///
2857    /// NOTE: This method uses the location of the caller to generate an ID for this state.
2858    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
2859    ///       you can provide a custom ElementID using the `use_keyed_state` method.
2860    #[track_caller]
2861    pub fn use_state<S: 'static>(
2862        &mut self,
2863        cx: &mut App,
2864        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2865    ) -> Entity<S> {
2866        self.use_keyed_state(
2867            ElementId::CodeLocation(*core::panic::Location::caller()),
2868            cx,
2869            init,
2870        )
2871    }
2872
2873    /// Updates or initializes state for an element with the given id that lives across multiple
2874    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2875    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2876    /// when drawing the next frame. This method should only be called as part of element drawing.
2877    pub fn with_element_state<S, R>(
2878        &mut self,
2879        global_id: &GlobalElementId,
2880        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2881    ) -> R
2882    where
2883        S: 'static,
2884    {
2885        self.invalidator.debug_assert_paint_or_prepaint();
2886
2887        let key = (global_id.clone(), TypeId::of::<S>());
2888        self.next_frame.accessed_element_states.push(key.clone());
2889
2890        if let Some(any) = self
2891            .next_frame
2892            .element_states
2893            .remove(&key)
2894            .or_else(|| self.rendered_frame.element_states.remove(&key))
2895        {
2896            let ElementStateBox {
2897                inner,
2898                #[cfg(debug_assertions)]
2899                type_name,
2900            } = any;
2901            // Using the extra inner option to avoid needing to reallocate a new box.
2902            let mut state_box = inner
2903                .downcast::<Option<S>>()
2904                .map_err(|_| {
2905                    #[cfg(debug_assertions)]
2906                    {
2907                        anyhow::anyhow!(
2908                            "invalid element state type for id, requested {:?}, actual: {:?}",
2909                            std::any::type_name::<S>(),
2910                            type_name
2911                        )
2912                    }
2913
2914                    #[cfg(not(debug_assertions))]
2915                    {
2916                        anyhow::anyhow!(
2917                            "invalid element state type for id, requested {:?}",
2918                            std::any::type_name::<S>(),
2919                        )
2920                    }
2921                })
2922                .unwrap();
2923
2924            let state = state_box.take().expect(
2925                "reentrant call to with_element_state for the same state type and element id",
2926            );
2927            let (result, state) = f(Some(state), self);
2928            state_box.replace(state);
2929            self.next_frame.element_states.insert(
2930                key,
2931                ElementStateBox {
2932                    inner: state_box,
2933                    #[cfg(debug_assertions)]
2934                    type_name,
2935                },
2936            );
2937            result
2938        } else {
2939            let (result, state) = f(None, self);
2940            self.next_frame.element_states.insert(
2941                key,
2942                ElementStateBox {
2943                    inner: Box::new(Some(state)),
2944                    #[cfg(debug_assertions)]
2945                    type_name: std::any::type_name::<S>(),
2946                },
2947            );
2948            result
2949        }
2950    }
2951
2952    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2953    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2954    /// when the element is guaranteed to have an id.
2955    ///
2956    /// The first option means 'no ID provided'
2957    /// The second option means 'not yet initialized'
2958    pub fn with_optional_element_state<S, R>(
2959        &mut self,
2960        global_id: Option<&GlobalElementId>,
2961        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2962    ) -> R
2963    where
2964        S: 'static,
2965    {
2966        self.invalidator.debug_assert_paint_or_prepaint();
2967
2968        if let Some(global_id) = global_id {
2969            self.with_element_state(global_id, |state, cx| {
2970                let (result, state) = f(Some(state), cx);
2971                let state =
2972                    state.expect("you must return some state when you pass some element id");
2973                (result, state)
2974            })
2975        } else {
2976            let (result, state) = f(None, self);
2977            debug_assert!(
2978                state.is_none(),
2979                "you must not return an element state when passing None for the global id"
2980            );
2981            result
2982        }
2983    }
2984
2985    /// Executes the given closure within the context of a tab group.
2986    #[inline]
2987    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
2988        if let Some(index) = index {
2989            self.next_frame.tab_stops.begin_group(index);
2990            let result = f(self);
2991            self.next_frame.tab_stops.end_group();
2992            result
2993        } else {
2994            f(self)
2995        }
2996    }
2997
2998    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2999    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3000    /// with higher values being drawn on top.
3001    ///
3002    /// This method should only be called as part of the prepaint phase of element drawing.
3003    pub fn defer_draw(
3004        &mut self,
3005        element: AnyElement,
3006        absolute_offset: Point<Pixels>,
3007        priority: usize,
3008    ) {
3009        self.invalidator.debug_assert_prepaint();
3010        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3011        self.next_frame.deferred_draws.push(DeferredDraw {
3012            current_view: self.current_view(),
3013            parent_node,
3014            element_id_stack: self.element_id_stack.clone(),
3015            text_style_stack: self.text_style_stack.clone(),
3016            rem_size: self.rem_size(),
3017            priority,
3018            element: Some(element),
3019            absolute_offset,
3020            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3021            paint_range: PaintIndex::default()..PaintIndex::default(),
3022        });
3023    }
3024
3025    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3026    /// of geometry that are non-overlapping and have the same draw order. This is typically used
3027    /// for performance reasons.
3028    ///
3029    /// This method should only be called as part of the paint phase of element drawing.
3030    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3031        self.invalidator.debug_assert_paint();
3032
3033        let scale_factor = self.scale_factor();
3034        let content_mask = self.content_mask();
3035        let clipped_bounds = bounds.intersect(&content_mask.bounds);
3036        if !clipped_bounds.is_empty() {
3037            self.next_frame
3038                .scene
3039                .push_layer(clipped_bounds.scale(scale_factor));
3040        }
3041
3042        let result = f(self);
3043
3044        if !clipped_bounds.is_empty() {
3045            self.next_frame.scene.pop_layer();
3046        }
3047
3048        result
3049    }
3050
3051    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
3052    ///
3053    /// This method should only be called as part of the paint phase of element drawing.
3054    pub fn paint_shadows(
3055        &mut self,
3056        bounds: Bounds<Pixels>,
3057        corner_radii: Corners<Pixels>,
3058        shadows: &[BoxShadow],
3059    ) {
3060        self.invalidator.debug_assert_paint();
3061
3062        let scale_factor = self.scale_factor();
3063        let content_mask = self.content_mask();
3064        let opacity = self.element_opacity();
3065        for shadow in shadows {
3066            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3067            self.next_frame.scene.insert_primitive(Shadow {
3068                order: 0,
3069                blur_radius: shadow.blur_radius.scale(scale_factor),
3070                bounds: shadow_bounds.scale(scale_factor),
3071                content_mask: content_mask.scale(scale_factor),
3072                corner_radii: corner_radii.scale(scale_factor),
3073                color: shadow.color.opacity(opacity),
3074            });
3075        }
3076    }
3077
3078    /// Paint one or more quads into the scene for the next frame at the current stacking context.
3079    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3080    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3081    ///
3082    /// This method should only be called as part of the paint phase of element drawing.
3083    ///
3084    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3085    /// where the circular arcs meet. This will not display well when combined with dashed borders.
3086    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3087    pub fn paint_quad(&mut self, quad: PaintQuad) {
3088        self.invalidator.debug_assert_paint();
3089
3090        let scale_factor = self.scale_factor();
3091        let content_mask = self.content_mask();
3092        let opacity = self.element_opacity();
3093        self.next_frame.scene.insert_primitive(Quad {
3094            order: 0,
3095            bounds: quad.bounds.scale(scale_factor),
3096            content_mask: content_mask.scale(scale_factor),
3097            background: quad.background.opacity(opacity),
3098            border_color: quad.border_color.opacity(opacity),
3099            corner_radii: quad.corner_radii.scale(scale_factor),
3100            border_widths: quad.border_widths.scale(scale_factor),
3101            border_style: quad.border_style,
3102        });
3103    }
3104
3105    /// Paint the given `Path` into the scene for the next frame at the current z-index.
3106    ///
3107    /// This method should only be called as part of the paint phase of element drawing.
3108    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3109        self.invalidator.debug_assert_paint();
3110
3111        let scale_factor = self.scale_factor();
3112        let content_mask = self.content_mask();
3113        let opacity = self.element_opacity();
3114        path.content_mask = content_mask;
3115        let color: Background = color.into();
3116        path.color = color.opacity(opacity);
3117        self.next_frame
3118            .scene
3119            .insert_primitive(path.scale(scale_factor));
3120    }
3121
3122    /// Paint an underline into the scene for the next frame at the current z-index.
3123    ///
3124    /// This method should only be called as part of the paint phase of element drawing.
3125    pub fn paint_underline(
3126        &mut self,
3127        origin: Point<Pixels>,
3128        width: Pixels,
3129        style: &UnderlineStyle,
3130    ) {
3131        self.invalidator.debug_assert_paint();
3132
3133        let scale_factor = self.scale_factor();
3134        let height = if style.wavy {
3135            style.thickness * 3.
3136        } else {
3137            style.thickness
3138        };
3139        let bounds = Bounds {
3140            origin,
3141            size: size(width, height),
3142        };
3143        let content_mask = self.content_mask();
3144        let element_opacity = self.element_opacity();
3145
3146        self.next_frame.scene.insert_primitive(Underline {
3147            order: 0,
3148            pad: 0,
3149            bounds: bounds.scale(scale_factor),
3150            content_mask: content_mask.scale(scale_factor),
3151            color: style.color.unwrap_or_default().opacity(element_opacity),
3152            thickness: style.thickness.scale(scale_factor),
3153            wavy: if style.wavy { 1 } else { 0 },
3154        });
3155    }
3156
3157    /// Paint a strikethrough into the scene for the next frame at the current z-index.
3158    ///
3159    /// This method should only be called as part of the paint phase of element drawing.
3160    pub fn paint_strikethrough(
3161        &mut self,
3162        origin: Point<Pixels>,
3163        width: Pixels,
3164        style: &StrikethroughStyle,
3165    ) {
3166        self.invalidator.debug_assert_paint();
3167
3168        let scale_factor = self.scale_factor();
3169        let height = style.thickness;
3170        let bounds = Bounds {
3171            origin,
3172            size: size(width, height),
3173        };
3174        let content_mask = self.content_mask();
3175        let opacity = self.element_opacity();
3176
3177        self.next_frame.scene.insert_primitive(Underline {
3178            order: 0,
3179            pad: 0,
3180            bounds: bounds.scale(scale_factor),
3181            content_mask: content_mask.scale(scale_factor),
3182            thickness: style.thickness.scale(scale_factor),
3183            color: style.color.unwrap_or_default().opacity(opacity),
3184            wavy: 0,
3185        });
3186    }
3187
3188    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3189    ///
3190    /// The y component of the origin is the baseline of the glyph.
3191    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3192    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3193    /// This method is only useful if you need to paint a single glyph that has already been shaped.
3194    ///
3195    /// This method should only be called as part of the paint phase of element drawing.
3196    pub fn paint_glyph(
3197        &mut self,
3198        origin: Point<Pixels>,
3199        font_id: FontId,
3200        glyph_id: GlyphId,
3201        font_size: Pixels,
3202        color: Hsla,
3203    ) -> Result<()> {
3204        self.invalidator.debug_assert_paint();
3205
3206        let element_opacity = self.element_opacity();
3207        let scale_factor = self.scale_factor();
3208        let glyph_origin = origin.scale(scale_factor);
3209
3210        let subpixel_variant = Point {
3211            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS_X as f32).floor() as u8,
3212            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS_Y as f32).floor() as u8,
3213        };
3214        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3215        let params = RenderGlyphParams {
3216            font_id,
3217            glyph_id,
3218            font_size,
3219            subpixel_variant,
3220            scale_factor,
3221            is_emoji: false,
3222            subpixel_rendering,
3223        };
3224
3225        let raster_bounds = self.text_system().raster_bounds(&params)?;
3226        if !raster_bounds.is_zero() {
3227            let tile = self
3228                .sprite_atlas
3229                .get_or_insert_with(&params.clone().into(), &mut || {
3230                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3231                    Ok(Some((size, Cow::Owned(bytes))))
3232                })?
3233                .expect("Callback above only errors or returns Some");
3234            let bounds = Bounds {
3235                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3236                size: tile.bounds.size.map(Into::into),
3237            };
3238            let content_mask = self.content_mask().scale(scale_factor);
3239
3240            if subpixel_rendering {
3241                self.next_frame.scene.insert_primitive(SubpixelSprite {
3242                    order: 0,
3243                    pad: 0,
3244                    bounds,
3245                    content_mask,
3246                    color: color.opacity(element_opacity),
3247                    tile,
3248                    transformation: TransformationMatrix::unit(),
3249                });
3250            } else {
3251                self.next_frame.scene.insert_primitive(MonochromeSprite {
3252                    order: 0,
3253                    pad: 0,
3254                    bounds,
3255                    content_mask,
3256                    color: color.opacity(element_opacity),
3257                    tile,
3258                    transformation: TransformationMatrix::unit(),
3259                });
3260            }
3261        }
3262        Ok(())
3263    }
3264
3265    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3266        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3267            return false;
3268        }
3269
3270        if !self.platform_window.is_subpixel_rendering_supported() {
3271            return false;
3272        }
3273
3274        let mode = match self.text_rendering_mode.get() {
3275            TextRenderingMode::PlatformDefault => self
3276                .text_system()
3277                .recommended_rendering_mode(font_id, font_size),
3278            mode => mode,
3279        };
3280
3281        mode == TextRenderingMode::Subpixel
3282    }
3283
3284    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3285    ///
3286    /// The y component of the origin is the baseline of the glyph.
3287    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3288    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3289    /// This method is only useful if you need to paint a single emoji that has already been shaped.
3290    ///
3291    /// This method should only be called as part of the paint phase of element drawing.
3292    pub fn paint_emoji(
3293        &mut self,
3294        origin: Point<Pixels>,
3295        font_id: FontId,
3296        glyph_id: GlyphId,
3297        font_size: Pixels,
3298    ) -> Result<()> {
3299        self.invalidator.debug_assert_paint();
3300
3301        let scale_factor = self.scale_factor();
3302        let glyph_origin = origin.scale(scale_factor);
3303        let params = RenderGlyphParams {
3304            font_id,
3305            glyph_id,
3306            font_size,
3307            // We don't render emojis with subpixel variants.
3308            subpixel_variant: Default::default(),
3309            scale_factor,
3310            is_emoji: true,
3311            subpixel_rendering: false,
3312        };
3313
3314        let raster_bounds = self.text_system().raster_bounds(&params)?;
3315        if !raster_bounds.is_zero() {
3316            let tile = self
3317                .sprite_atlas
3318                .get_or_insert_with(&params.clone().into(), &mut || {
3319                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3320                    Ok(Some((size, Cow::Owned(bytes))))
3321                })?
3322                .expect("Callback above only errors or returns Some");
3323
3324            let bounds = Bounds {
3325                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3326                size: tile.bounds.size.map(Into::into),
3327            };
3328            let content_mask = self.content_mask().scale(scale_factor);
3329            let opacity = self.element_opacity();
3330
3331            self.next_frame.scene.insert_primitive(PolychromeSprite {
3332                order: 0,
3333                pad: 0,
3334                grayscale: false,
3335                bounds,
3336                corner_radii: Default::default(),
3337                content_mask,
3338                tile,
3339                opacity,
3340            });
3341        }
3342        Ok(())
3343    }
3344
3345    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3346    ///
3347    /// This method should only be called as part of the paint phase of element drawing.
3348    pub fn paint_svg(
3349        &mut self,
3350        bounds: Bounds<Pixels>,
3351        path: SharedString,
3352        mut data: Option<&[u8]>,
3353        transformation: TransformationMatrix,
3354        color: Hsla,
3355        cx: &App,
3356    ) -> Result<()> {
3357        self.invalidator.debug_assert_paint();
3358
3359        let element_opacity = self.element_opacity();
3360        let scale_factor = self.scale_factor();
3361
3362        let bounds = bounds.scale(scale_factor);
3363        let params = RenderSvgParams {
3364            path,
3365            size: bounds.size.map(|pixels| {
3366                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3367            }),
3368        };
3369
3370        let Some(tile) =
3371            self.sprite_atlas
3372                .get_or_insert_with(&params.clone().into(), &mut || {
3373                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
3374                    else {
3375                        return Ok(None);
3376                    };
3377                    Ok(Some((size, Cow::Owned(bytes))))
3378                })?
3379        else {
3380            return Ok(());
3381        };
3382        let content_mask = self.content_mask().scale(scale_factor);
3383        let svg_bounds = Bounds {
3384            origin: bounds.center()
3385                - Point::new(
3386                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3387                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3388                ),
3389            size: tile
3390                .bounds
3391                .size
3392                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3393        };
3394
3395        self.next_frame.scene.insert_primitive(MonochromeSprite {
3396            order: 0,
3397            pad: 0,
3398            bounds: svg_bounds
3399                .map_origin(|origin| origin.round())
3400                .map_size(|size| size.ceil()),
3401            content_mask,
3402            color: color.opacity(element_opacity),
3403            tile,
3404            transformation,
3405        });
3406
3407        Ok(())
3408    }
3409
3410    /// Paint an image into the scene for the next frame at the current z-index.
3411    /// This method will panic if the frame_index is not valid
3412    ///
3413    /// This method should only be called as part of the paint phase of element drawing.
3414    pub fn paint_image(
3415        &mut self,
3416        bounds: Bounds<Pixels>,
3417        corner_radii: Corners<Pixels>,
3418        data: Arc<RenderImage>,
3419        frame_index: usize,
3420        grayscale: bool,
3421    ) -> Result<()> {
3422        self.invalidator.debug_assert_paint();
3423
3424        let scale_factor = self.scale_factor();
3425        let bounds = bounds.scale(scale_factor);
3426        let params = RenderImageParams {
3427            image_id: data.id,
3428            frame_index,
3429        };
3430
3431        let tile = self
3432            .sprite_atlas
3433            .get_or_insert_with(&params.into(), &mut || {
3434                Ok(Some((
3435                    data.size(frame_index),
3436                    Cow::Borrowed(
3437                        data.as_bytes(frame_index)
3438                            .expect("It's the caller's job to pass a valid frame index"),
3439                    ),
3440                )))
3441            })?
3442            .expect("Callback above only returns Some");
3443        let content_mask = self.content_mask().scale(scale_factor);
3444        let corner_radii = corner_radii.scale(scale_factor);
3445        let opacity = self.element_opacity();
3446
3447        self.next_frame.scene.insert_primitive(PolychromeSprite {
3448            order: 0,
3449            pad: 0,
3450            grayscale,
3451            bounds: bounds
3452                .map_origin(|origin| origin.floor())
3453                .map_size(|size| size.ceil()),
3454            content_mask,
3455            corner_radii,
3456            tile,
3457            opacity,
3458        });
3459        Ok(())
3460    }
3461
3462    /// Paint a surface into the scene for the next frame at the current z-index.
3463    ///
3464    /// This method should only be called as part of the paint phase of element drawing.
3465    #[cfg(target_os = "macos")]
3466    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3467        use crate::PaintSurface;
3468
3469        self.invalidator.debug_assert_paint();
3470
3471        let scale_factor = self.scale_factor();
3472        let bounds = bounds.scale(scale_factor);
3473        let content_mask = self.content_mask().scale(scale_factor);
3474        self.next_frame.scene.insert_primitive(PaintSurface {
3475            order: 0,
3476            bounds,
3477            content_mask,
3478            image_buffer,
3479        });
3480    }
3481
3482    /// Removes an image from the sprite atlas.
3483    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3484        for frame_index in 0..data.frame_count() {
3485            let params = RenderImageParams {
3486                image_id: data.id,
3487                frame_index,
3488            };
3489
3490            self.sprite_atlas.remove(&params.clone().into());
3491        }
3492
3493        Ok(())
3494    }
3495
3496    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3497    /// layout is being requested, along with the layout ids of any children. This method is called during
3498    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3499    ///
3500    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3501    #[must_use]
3502    pub fn request_layout(
3503        &mut self,
3504        style: Style,
3505        children: impl IntoIterator<Item = LayoutId>,
3506        cx: &mut App,
3507    ) -> LayoutId {
3508        self.invalidator.debug_assert_prepaint();
3509
3510        cx.layout_id_buffer.clear();
3511        cx.layout_id_buffer.extend(children);
3512        let rem_size = self.rem_size();
3513        let scale_factor = self.scale_factor();
3514
3515        self.layout_engine.as_mut().unwrap().request_layout(
3516            style,
3517            rem_size,
3518            scale_factor,
3519            &cx.layout_id_buffer,
3520        )
3521    }
3522
3523    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3524    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3525    /// determine the element's size. One place this is used internally is when measuring text.
3526    ///
3527    /// The given closure is invoked at layout time with the known dimensions and available space and
3528    /// returns a `Size`.
3529    ///
3530    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3531    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3532    where
3533        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3534            + 'static,
3535    {
3536        self.invalidator.debug_assert_prepaint();
3537
3538        let rem_size = self.rem_size();
3539        let scale_factor = self.scale_factor();
3540        self.layout_engine
3541            .as_mut()
3542            .unwrap()
3543            .request_measured_layout(style, rem_size, scale_factor, measure)
3544    }
3545
3546    /// Compute the layout for the given id within the given available space.
3547    /// This method is called for its side effect, typically by the framework prior to painting.
3548    /// After calling it, you can request the bounds of the given layout node id or any descendant.
3549    ///
3550    /// This method should only be called as part of the prepaint phase of element drawing.
3551    pub fn compute_layout(
3552        &mut self,
3553        layout_id: LayoutId,
3554        available_space: Size<AvailableSpace>,
3555        cx: &mut App,
3556    ) {
3557        self.invalidator.debug_assert_prepaint();
3558
3559        let mut layout_engine = self.layout_engine.take().unwrap();
3560        layout_engine.compute_layout(layout_id, available_space, self, cx);
3561        self.layout_engine = Some(layout_engine);
3562    }
3563
3564    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3565    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3566    ///
3567    /// This method should only be called as part of element drawing.
3568    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3569        self.invalidator.debug_assert_prepaint();
3570
3571        let scale_factor = self.scale_factor();
3572        let mut bounds = self
3573            .layout_engine
3574            .as_mut()
3575            .unwrap()
3576            .layout_bounds(layout_id, scale_factor)
3577            .map(Into::into);
3578        bounds.origin += self.element_offset();
3579        bounds
3580    }
3581
3582    /// This method should be called during `prepaint`. You can use
3583    /// the returned [Hitbox] during `paint` or in an event handler
3584    /// to determine whether the inserted hitbox was the topmost.
3585    ///
3586    /// This method should only be called as part of the prepaint phase of element drawing.
3587    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3588        self.invalidator.debug_assert_prepaint();
3589
3590        let content_mask = self.content_mask();
3591        let mut id = self.next_hitbox_id;
3592        self.next_hitbox_id = self.next_hitbox_id.next();
3593        let hitbox = Hitbox {
3594            id,
3595            bounds,
3596            content_mask,
3597            behavior,
3598        };
3599        self.next_frame.hitboxes.push(hitbox.clone());
3600        hitbox
3601    }
3602
3603    /// Set a hitbox which will act as a control area of the platform window.
3604    ///
3605    /// This method should only be called as part of the paint phase of element drawing.
3606    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3607        self.invalidator.debug_assert_paint();
3608        self.next_frame.window_control_hitboxes.push((area, hitbox));
3609    }
3610
3611    /// Sets the key context for the current element. This context will be used to translate
3612    /// keybindings into actions.
3613    ///
3614    /// This method should only be called as part of the paint phase of element drawing.
3615    pub fn set_key_context(&mut self, context: KeyContext) {
3616        self.invalidator.debug_assert_paint();
3617        self.next_frame.dispatch_tree.set_key_context(context);
3618    }
3619
3620    /// Sets the focus handle for the current element. This handle will be used to manage focus state
3621    /// and keyboard event dispatch for the element.
3622    ///
3623    /// This method should only be called as part of the prepaint phase of element drawing.
3624    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3625        self.invalidator.debug_assert_prepaint();
3626        if focus_handle.is_focused(self) {
3627            self.next_frame.focus = Some(focus_handle.id);
3628        }
3629        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3630    }
3631
3632    /// Sets the view id for the current element, which will be used to manage view caching.
3633    ///
3634    /// This method should only be called as part of element prepaint. We plan on removing this
3635    /// method eventually when we solve some issues that require us to construct editor elements
3636    /// directly instead of always using editors via views.
3637    pub fn set_view_id(&mut self, view_id: EntityId) {
3638        self.invalidator.debug_assert_prepaint();
3639        self.next_frame.dispatch_tree.set_view_id(view_id);
3640    }
3641
3642    /// Get the entity ID for the currently rendering view
3643    pub fn current_view(&self) -> EntityId {
3644        self.invalidator.debug_assert_paint_or_prepaint();
3645        self.rendered_entity_stack.last().copied().unwrap()
3646    }
3647
3648    #[inline]
3649    pub(crate) fn with_rendered_view<R>(
3650        &mut self,
3651        id: EntityId,
3652        f: impl FnOnce(&mut Self) -> R,
3653    ) -> R {
3654        self.rendered_entity_stack.push(id);
3655        let result = f(self);
3656        self.rendered_entity_stack.pop();
3657        result
3658    }
3659
3660    /// Executes the provided function with the specified image cache.
3661    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3662    where
3663        F: FnOnce(&mut Self) -> R,
3664    {
3665        if let Some(image_cache) = image_cache {
3666            self.image_cache_stack.push(image_cache);
3667            let result = f(self);
3668            self.image_cache_stack.pop();
3669            result
3670        } else {
3671            f(self)
3672        }
3673    }
3674
3675    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
3676    /// platform to receive textual input with proper integration with concerns such
3677    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
3678    /// rendered.
3679    ///
3680    /// This method should only be called as part of the paint phase of element drawing.
3681    ///
3682    /// [element_input_handler]: crate::ElementInputHandler
3683    pub fn handle_input(
3684        &mut self,
3685        focus_handle: &FocusHandle,
3686        input_handler: impl InputHandler,
3687        cx: &App,
3688    ) {
3689        self.invalidator.debug_assert_paint();
3690
3691        if focus_handle.is_focused(self) {
3692            let cx = self.to_async(cx);
3693            self.next_frame
3694                .input_handlers
3695                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3696        }
3697    }
3698
3699    /// Register a mouse event listener on the window for the next frame. The type of event
3700    /// is determined by the first parameter of the given listener. When the next frame is rendered
3701    /// the listener will be cleared.
3702    ///
3703    /// This method should only be called as part of the paint phase of element drawing.
3704    pub fn on_mouse_event<Event: MouseEvent>(
3705        &mut self,
3706        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3707    ) {
3708        self.invalidator.debug_assert_paint();
3709
3710        self.next_frame.mouse_listeners.push(Some(Box::new(
3711            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3712                if let Some(event) = event.downcast_ref() {
3713                    listener(event, phase, window, cx)
3714                }
3715            },
3716        )));
3717    }
3718
3719    /// Register a key event listener on this node for the next frame. The type of event
3720    /// is determined by the first parameter of the given listener. When the next frame is rendered
3721    /// the listener will be cleared.
3722    ///
3723    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3724    /// a specific need to register a listener yourself.
3725    ///
3726    /// This method should only be called as part of the paint phase of element drawing.
3727    pub fn on_key_event<Event: KeyEvent>(
3728        &mut self,
3729        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3730    ) {
3731        self.invalidator.debug_assert_paint();
3732
3733        self.next_frame.dispatch_tree.on_key_event(Rc::new(
3734            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
3735                if let Some(event) = event.downcast_ref::<Event>() {
3736                    listener(event, phase, window, cx)
3737                }
3738            },
3739        ));
3740    }
3741
3742    /// Register a modifiers changed event listener on the window for the next frame.
3743    ///
3744    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3745    /// a specific need to register a global listener.
3746    ///
3747    /// This method should only be called as part of the paint phase of element drawing.
3748    pub fn on_modifiers_changed(
3749        &mut self,
3750        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
3751    ) {
3752        self.invalidator.debug_assert_paint();
3753
3754        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
3755            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
3756                listener(event, window, cx)
3757            },
3758        ));
3759    }
3760
3761    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
3762    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
3763    /// Returns a subscription and persists until the subscription is dropped.
3764    pub fn on_focus_in(
3765        &mut self,
3766        handle: &FocusHandle,
3767        cx: &mut App,
3768        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
3769    ) -> Subscription {
3770        let focus_id = handle.id;
3771        let (subscription, activate) =
3772            self.new_focus_listener(Box::new(move |event, window, cx| {
3773                if event.is_focus_in(focus_id) {
3774                    listener(window, cx);
3775                }
3776                true
3777            }));
3778        cx.defer(move |_| activate());
3779        subscription
3780    }
3781
3782    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
3783    /// Returns a subscription and persists until the subscription is dropped.
3784    pub fn on_focus_out(
3785        &mut self,
3786        handle: &FocusHandle,
3787        cx: &mut App,
3788        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
3789    ) -> Subscription {
3790        let focus_id = handle.id;
3791        let (subscription, activate) =
3792            self.new_focus_listener(Box::new(move |event, window, cx| {
3793                if let Some(blurred_id) = event.previous_focus_path.last().copied()
3794                    && event.is_focus_out(focus_id)
3795                {
3796                    let event = FocusOutEvent {
3797                        blurred: WeakFocusHandle {
3798                            id: blurred_id,
3799                            handles: Arc::downgrade(&cx.focus_handles),
3800                        },
3801                    };
3802                    listener(event, window, cx)
3803                }
3804                true
3805            }));
3806        cx.defer(move |_| activate());
3807        subscription
3808    }
3809
3810    fn reset_cursor_style(&self, cx: &mut App) {
3811        // Set the cursor only if we're the active window.
3812        if self.is_window_hovered() {
3813            let style = self
3814                .rendered_frame
3815                .cursor_style(self)
3816                .unwrap_or(CursorStyle::Arrow);
3817            cx.platform.set_cursor_style(style);
3818        }
3819    }
3820
3821    /// Dispatch a given keystroke as though the user had typed it.
3822    /// You can create a keystroke with Keystroke::parse("").
3823    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
3824        let keystroke = keystroke.with_simulated_ime();
3825        let result = self.dispatch_event(
3826            PlatformInput::KeyDown(KeyDownEvent {
3827                keystroke: keystroke.clone(),
3828                is_held: false,
3829                prefer_character_input: false,
3830            }),
3831            cx,
3832        );
3833        if !result.propagate {
3834            return true;
3835        }
3836
3837        if let Some(input) = keystroke.key_char
3838            && let Some(mut input_handler) = self.platform_window.take_input_handler()
3839        {
3840            input_handler.dispatch_input(&input, self, cx);
3841            self.platform_window.set_input_handler(input_handler);
3842            return true;
3843        }
3844
3845        false
3846    }
3847
3848    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3849    /// binding for the action (last binding added to the keymap).
3850    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3851        self.highest_precedence_binding_for_action(action)
3852            .map(|binding| {
3853                binding
3854                    .keystrokes()
3855                    .iter()
3856                    .map(ToString::to_string)
3857                    .collect::<Vec<_>>()
3858                    .join(" ")
3859            })
3860            .unwrap_or_else(|| action.name().to_string())
3861    }
3862
3863    /// Dispatch a mouse or keyboard event on the window.
3864    #[profiling::function]
3865    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3866        // Track whether this input was keyboard-based for focus-visible styling
3867        self.last_input_modality = match &event {
3868            PlatformInput::KeyDown(_) | PlatformInput::ModifiersChanged(_) => {
3869                InputModality::Keyboard
3870            }
3871            PlatformInput::MouseDown(e) if e.is_focusing() => InputModality::Mouse,
3872            _ => self.last_input_modality,
3873        };
3874
3875        // Handlers may set this to false by calling `stop_propagation`.
3876        cx.propagate_event = true;
3877        // Handlers may set this to true by calling `prevent_default`.
3878        self.default_prevented = false;
3879
3880        let event = match event {
3881            // Track the mouse position with our own state, since accessing the platform
3882            // API for the mouse position can only occur on the main thread.
3883            PlatformInput::MouseMove(mouse_move) => {
3884                self.mouse_position = mouse_move.position;
3885                self.modifiers = mouse_move.modifiers;
3886                PlatformInput::MouseMove(mouse_move)
3887            }
3888            PlatformInput::MouseDown(mouse_down) => {
3889                self.mouse_position = mouse_down.position;
3890                self.modifiers = mouse_down.modifiers;
3891                PlatformInput::MouseDown(mouse_down)
3892            }
3893            PlatformInput::MouseUp(mouse_up) => {
3894                self.mouse_position = mouse_up.position;
3895                self.modifiers = mouse_up.modifiers;
3896                PlatformInput::MouseUp(mouse_up)
3897            }
3898            PlatformInput::MousePressure(mouse_pressure) => {
3899                PlatformInput::MousePressure(mouse_pressure)
3900            }
3901            PlatformInput::MouseExited(mouse_exited) => {
3902                self.modifiers = mouse_exited.modifiers;
3903                PlatformInput::MouseExited(mouse_exited)
3904            }
3905            PlatformInput::ModifiersChanged(modifiers_changed) => {
3906                self.modifiers = modifiers_changed.modifiers;
3907                self.capslock = modifiers_changed.capslock;
3908                PlatformInput::ModifiersChanged(modifiers_changed)
3909            }
3910            PlatformInput::ScrollWheel(scroll_wheel) => {
3911                self.mouse_position = scroll_wheel.position;
3912                self.modifiers = scroll_wheel.modifiers;
3913                PlatformInput::ScrollWheel(scroll_wheel)
3914            }
3915            // Translate dragging and dropping of external files from the operating system
3916            // to internal drag and drop events.
3917            PlatformInput::FileDrop(file_drop) => match file_drop {
3918                FileDropEvent::Entered { position, paths } => {
3919                    self.mouse_position = position;
3920                    if cx.active_drag.is_none() {
3921                        cx.active_drag = Some(AnyDrag {
3922                            value: Arc::new(paths.clone()),
3923                            view: cx.new(|_| paths).into(),
3924                            cursor_offset: position,
3925                            cursor_style: None,
3926                        });
3927                    }
3928                    PlatformInput::MouseMove(MouseMoveEvent {
3929                        position,
3930                        pressed_button: Some(MouseButton::Left),
3931                        modifiers: Modifiers::default(),
3932                    })
3933                }
3934                FileDropEvent::Pending { position } => {
3935                    self.mouse_position = position;
3936                    PlatformInput::MouseMove(MouseMoveEvent {
3937                        position,
3938                        pressed_button: Some(MouseButton::Left),
3939                        modifiers: Modifiers::default(),
3940                    })
3941                }
3942                FileDropEvent::Submit { position } => {
3943                    cx.activate(true);
3944                    self.mouse_position = position;
3945                    PlatformInput::MouseUp(MouseUpEvent {
3946                        button: MouseButton::Left,
3947                        position,
3948                        modifiers: Modifiers::default(),
3949                        click_count: 1,
3950                    })
3951                }
3952                FileDropEvent::Exited => {
3953                    cx.active_drag.take();
3954                    PlatformInput::FileDrop(FileDropEvent::Exited)
3955                }
3956            },
3957            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3958        };
3959
3960        if let Some(any_mouse_event) = event.mouse_event() {
3961            self.dispatch_mouse_event(any_mouse_event, cx);
3962        } else if let Some(any_key_event) = event.keyboard_event() {
3963            self.dispatch_key_event(any_key_event, cx);
3964        }
3965
3966        if self.invalidator.is_dirty() {
3967            self.input_rate_tracker.borrow_mut().record_input();
3968        }
3969
3970        DispatchEventResult {
3971            propagate: cx.propagate_event,
3972            default_prevented: self.default_prevented,
3973        }
3974    }
3975
3976    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3977        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3978        if hit_test != self.mouse_hit_test {
3979            self.mouse_hit_test = hit_test;
3980            self.reset_cursor_style(cx);
3981        }
3982
3983        #[cfg(any(feature = "inspector", debug_assertions))]
3984        if self.is_inspector_picking(cx) {
3985            self.handle_inspector_mouse_event(event, cx);
3986            // When inspector is picking, all other mouse handling is skipped.
3987            return;
3988        }
3989
3990        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3991
3992        // Capture phase, events bubble from back to front. Handlers for this phase are used for
3993        // special purposes, such as detecting events outside of a given Bounds.
3994        for listener in &mut mouse_listeners {
3995            let listener = listener.as_mut().unwrap();
3996            listener(event, DispatchPhase::Capture, self, cx);
3997            if !cx.propagate_event {
3998                break;
3999            }
4000        }
4001
4002        // Bubble phase, where most normal handlers do their work.
4003        if cx.propagate_event {
4004            for listener in mouse_listeners.iter_mut().rev() {
4005                let listener = listener.as_mut().unwrap();
4006                listener(event, DispatchPhase::Bubble, self, cx);
4007                if !cx.propagate_event {
4008                    break;
4009                }
4010            }
4011        }
4012
4013        self.rendered_frame.mouse_listeners = mouse_listeners;
4014
4015        if cx.has_active_drag() {
4016            if event.is::<MouseMoveEvent>() {
4017                // If this was a mouse move event, redraw the window so that the
4018                // active drag can follow the mouse cursor.
4019                self.refresh();
4020            } else if event.is::<MouseUpEvent>() {
4021                // If this was a mouse up event, cancel the active drag and redraw
4022                // the window.
4023                cx.active_drag = None;
4024                self.refresh();
4025            }
4026        }
4027    }
4028
4029    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4030        if self.invalidator.is_dirty() {
4031            self.draw(cx).clear();
4032        }
4033
4034        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4035        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4036
4037        let mut keystroke: Option<Keystroke> = None;
4038
4039        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4040            if event.modifiers.number_of_modifiers() == 0
4041                && self.pending_modifier.modifiers.number_of_modifiers() == 1
4042                && !self.pending_modifier.saw_keystroke
4043            {
4044                let key = match self.pending_modifier.modifiers {
4045                    modifiers if modifiers.shift => Some("shift"),
4046                    modifiers if modifiers.control => Some("control"),
4047                    modifiers if modifiers.alt => Some("alt"),
4048                    modifiers if modifiers.platform => Some("platform"),
4049                    modifiers if modifiers.function => Some("function"),
4050                    _ => None,
4051                };
4052                if let Some(key) = key {
4053                    keystroke = Some(Keystroke {
4054                        key: key.to_string(),
4055                        key_char: None,
4056                        modifiers: Modifiers::default(),
4057                    });
4058                }
4059            }
4060
4061            if self.pending_modifier.modifiers.number_of_modifiers() == 0
4062                && event.modifiers.number_of_modifiers() == 1
4063            {
4064                self.pending_modifier.saw_keystroke = false
4065            }
4066            self.pending_modifier.modifiers = event.modifiers
4067        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4068            self.pending_modifier.saw_keystroke = true;
4069            keystroke = Some(key_down_event.keystroke.clone());
4070        }
4071
4072        let Some(keystroke) = keystroke else {
4073            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4074            return;
4075        };
4076
4077        cx.propagate_event = true;
4078        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4079        if !cx.propagate_event {
4080            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4081            return;
4082        }
4083
4084        let mut currently_pending = self.pending_input.take().unwrap_or_default();
4085        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4086            currently_pending = PendingInput::default();
4087        }
4088
4089        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4090            currently_pending.keystrokes,
4091            keystroke,
4092            &dispatch_path,
4093        );
4094
4095        if !match_result.to_replay.is_empty() {
4096            self.replay_pending_input(match_result.to_replay, cx);
4097            cx.propagate_event = true;
4098        }
4099
4100        if !match_result.pending.is_empty() {
4101            currently_pending.timer.take();
4102            currently_pending.keystrokes = match_result.pending;
4103            currently_pending.focus = self.focus;
4104
4105            let text_input_requires_timeout = event
4106                .downcast_ref::<KeyDownEvent>()
4107                .filter(|key_down| key_down.keystroke.key_char.is_some())
4108                .and_then(|_| self.platform_window.take_input_handler())
4109                .map_or(false, |mut input_handler| {
4110                    let accepts = input_handler.accepts_text_input(self, cx);
4111                    self.platform_window.set_input_handler(input_handler);
4112                    accepts
4113                });
4114
4115            currently_pending.needs_timeout |=
4116                match_result.pending_has_binding || text_input_requires_timeout;
4117
4118            if currently_pending.needs_timeout {
4119                currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4120                    cx.background_executor.timer(Duration::from_secs(1)).await;
4121                    cx.update(move |window, cx| {
4122                        let Some(currently_pending) = window
4123                            .pending_input
4124                            .take()
4125                            .filter(|pending| pending.focus == window.focus)
4126                        else {
4127                            return;
4128                        };
4129
4130                        let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4131                        let dispatch_path =
4132                            window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4133
4134                        let to_replay = window
4135                            .rendered_frame
4136                            .dispatch_tree
4137                            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4138
4139                        window.pending_input_changed(cx);
4140                        window.replay_pending_input(to_replay, cx)
4141                    })
4142                    .log_err();
4143                }));
4144            } else {
4145                currently_pending.timer = None;
4146            }
4147            self.pending_input = Some(currently_pending);
4148            self.pending_input_changed(cx);
4149            cx.propagate_event = false;
4150            return;
4151        }
4152
4153        let skip_bindings = event
4154            .downcast_ref::<KeyDownEvent>()
4155            .filter(|key_down_event| key_down_event.prefer_character_input)
4156            .map(|_| {
4157                self.platform_window
4158                    .take_input_handler()
4159                    .map_or(false, |mut input_handler| {
4160                        let accepts = input_handler.accepts_text_input(self, cx);
4161                        self.platform_window.set_input_handler(input_handler);
4162                        // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
4163                        // we prefer the text input over bindings.
4164                        accepts
4165                    })
4166            })
4167            .unwrap_or(false);
4168
4169        if !skip_bindings {
4170            for binding in match_result.bindings {
4171                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4172                if !cx.propagate_event {
4173                    self.dispatch_keystroke_observers(
4174                        event,
4175                        Some(binding.action),
4176                        match_result.context_stack,
4177                        cx,
4178                    );
4179                    self.pending_input_changed(cx);
4180                    return;
4181                }
4182            }
4183        }
4184
4185        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4186        self.pending_input_changed(cx);
4187    }
4188
4189    fn finish_dispatch_key_event(
4190        &mut self,
4191        event: &dyn Any,
4192        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4193        context_stack: Vec<KeyContext>,
4194        cx: &mut App,
4195    ) {
4196        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4197        if !cx.propagate_event {
4198            return;
4199        }
4200
4201        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4202        if !cx.propagate_event {
4203            return;
4204        }
4205
4206        self.dispatch_keystroke_observers(event, None, context_stack, cx);
4207    }
4208
4209    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4210        self.pending_input_observers
4211            .clone()
4212            .retain(&(), |callback| callback(self, cx));
4213    }
4214
4215    fn dispatch_key_down_up_event(
4216        &mut self,
4217        event: &dyn Any,
4218        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4219        cx: &mut App,
4220    ) {
4221        // Capture phase
4222        for node_id in dispatch_path {
4223            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4224
4225            for key_listener in node.key_listeners.clone() {
4226                key_listener(event, DispatchPhase::Capture, self, cx);
4227                if !cx.propagate_event {
4228                    return;
4229                }
4230            }
4231        }
4232
4233        // Bubble phase
4234        for node_id in dispatch_path.iter().rev() {
4235            // Handle low level key events
4236            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4237            for key_listener in node.key_listeners.clone() {
4238                key_listener(event, DispatchPhase::Bubble, self, cx);
4239                if !cx.propagate_event {
4240                    return;
4241                }
4242            }
4243        }
4244    }
4245
4246    fn dispatch_modifiers_changed_event(
4247        &mut self,
4248        event: &dyn Any,
4249        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4250        cx: &mut App,
4251    ) {
4252        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4253            return;
4254        };
4255        for node_id in dispatch_path.iter().rev() {
4256            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4257            for listener in node.modifiers_changed_listeners.clone() {
4258                listener(event, self, cx);
4259                if !cx.propagate_event {
4260                    return;
4261                }
4262            }
4263        }
4264    }
4265
4266    /// Determine whether a potential multi-stroke key binding is in progress on this window.
4267    pub fn has_pending_keystrokes(&self) -> bool {
4268        self.pending_input.is_some()
4269    }
4270
4271    pub(crate) fn clear_pending_keystrokes(&mut self) {
4272        self.pending_input.take();
4273    }
4274
4275    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4276    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4277        self.pending_input
4278            .as_ref()
4279            .map(|pending_input| pending_input.keystrokes.as_slice())
4280    }
4281
4282    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4283        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4284        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4285
4286        'replay: for replay in replays {
4287            let event = KeyDownEvent {
4288                keystroke: replay.keystroke.clone(),
4289                is_held: false,
4290                prefer_character_input: true,
4291            };
4292
4293            cx.propagate_event = true;
4294            for binding in replay.bindings {
4295                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4296                if !cx.propagate_event {
4297                    self.dispatch_keystroke_observers(
4298                        &event,
4299                        Some(binding.action),
4300                        Vec::default(),
4301                        cx,
4302                    );
4303                    continue 'replay;
4304                }
4305            }
4306
4307            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4308            if !cx.propagate_event {
4309                continue 'replay;
4310            }
4311            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4312                && let Some(mut input_handler) = self.platform_window.take_input_handler()
4313            {
4314                input_handler.dispatch_input(&input, self, cx);
4315                self.platform_window.set_input_handler(input_handler)
4316            }
4317        }
4318    }
4319
4320    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4321        focus_id
4322            .and_then(|focus_id| {
4323                self.rendered_frame
4324                    .dispatch_tree
4325                    .focusable_node_id(focus_id)
4326            })
4327            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4328    }
4329
4330    fn dispatch_action_on_node(
4331        &mut self,
4332        node_id: DispatchNodeId,
4333        action: &dyn Action,
4334        cx: &mut App,
4335    ) {
4336        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4337
4338        // Capture phase for global actions.
4339        cx.propagate_event = true;
4340        if let Some(mut global_listeners) = cx
4341            .global_action_listeners
4342            .remove(&action.as_any().type_id())
4343        {
4344            for listener in &global_listeners {
4345                listener(action.as_any(), DispatchPhase::Capture, cx);
4346                if !cx.propagate_event {
4347                    break;
4348                }
4349            }
4350
4351            global_listeners.extend(
4352                cx.global_action_listeners
4353                    .remove(&action.as_any().type_id())
4354                    .unwrap_or_default(),
4355            );
4356
4357            cx.global_action_listeners
4358                .insert(action.as_any().type_id(), global_listeners);
4359        }
4360
4361        if !cx.propagate_event {
4362            return;
4363        }
4364
4365        // Capture phase for window actions.
4366        for node_id in &dispatch_path {
4367            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4368            for DispatchActionListener {
4369                action_type,
4370                listener,
4371            } in node.action_listeners.clone()
4372            {
4373                let any_action = action.as_any();
4374                if action_type == any_action.type_id() {
4375                    listener(any_action, DispatchPhase::Capture, self, cx);
4376
4377                    if !cx.propagate_event {
4378                        return;
4379                    }
4380                }
4381            }
4382        }
4383
4384        // Bubble phase for window actions.
4385        for node_id in dispatch_path.iter().rev() {
4386            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4387            for DispatchActionListener {
4388                action_type,
4389                listener,
4390            } in node.action_listeners.clone()
4391            {
4392                let any_action = action.as_any();
4393                if action_type == any_action.type_id() {
4394                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4395                    listener(any_action, DispatchPhase::Bubble, self, cx);
4396
4397                    if !cx.propagate_event {
4398                        return;
4399                    }
4400                }
4401            }
4402        }
4403
4404        // Bubble phase for global actions.
4405        if let Some(mut global_listeners) = cx
4406            .global_action_listeners
4407            .remove(&action.as_any().type_id())
4408        {
4409            for listener in global_listeners.iter().rev() {
4410                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4411
4412                listener(action.as_any(), DispatchPhase::Bubble, cx);
4413                if !cx.propagate_event {
4414                    break;
4415                }
4416            }
4417
4418            global_listeners.extend(
4419                cx.global_action_listeners
4420                    .remove(&action.as_any().type_id())
4421                    .unwrap_or_default(),
4422            );
4423
4424            cx.global_action_listeners
4425                .insert(action.as_any().type_id(), global_listeners);
4426        }
4427    }
4428
4429    /// Register the given handler to be invoked whenever the global of the given type
4430    /// is updated.
4431    pub fn observe_global<G: Global>(
4432        &mut self,
4433        cx: &mut App,
4434        f: impl Fn(&mut Window, &mut App) + 'static,
4435    ) -> Subscription {
4436        let window_handle = self.handle;
4437        let (subscription, activate) = cx.global_observers.insert(
4438            TypeId::of::<G>(),
4439            Box::new(move |cx| {
4440                window_handle
4441                    .update(cx, |_, window, cx| f(window, cx))
4442                    .is_ok()
4443            }),
4444        );
4445        cx.defer(move |_| activate());
4446        subscription
4447    }
4448
4449    /// Focus the current window and bring it to the foreground at the platform level.
4450    pub fn activate_window(&self) {
4451        self.platform_window.activate();
4452    }
4453
4454    /// Minimize the current window at the platform level.
4455    pub fn minimize_window(&self) {
4456        self.platform_window.minimize();
4457    }
4458
4459    /// Toggle full screen status on the current window at the platform level.
4460    pub fn toggle_fullscreen(&self) {
4461        self.platform_window.toggle_fullscreen();
4462    }
4463
4464    /// Updates the IME panel position suggestions for languages like japanese, chinese.
4465    pub fn invalidate_character_coordinates(&self) {
4466        self.on_next_frame(|window, cx| {
4467            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4468                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4469                    window.platform_window.update_ime_position(bounds);
4470                }
4471                window.platform_window.set_input_handler(input_handler);
4472            }
4473        });
4474    }
4475
4476    /// Present a platform dialog.
4477    /// The provided message will be presented, along with buttons for each answer.
4478    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4479    pub fn prompt<T>(
4480        &mut self,
4481        level: PromptLevel,
4482        message: &str,
4483        detail: Option<&str>,
4484        answers: &[T],
4485        cx: &mut App,
4486    ) -> oneshot::Receiver<usize>
4487    where
4488        T: Clone + Into<PromptButton>,
4489    {
4490        let prompt_builder = cx.prompt_builder.take();
4491        let Some(prompt_builder) = prompt_builder else {
4492            unreachable!("Re-entrant window prompting is not supported by GPUI");
4493        };
4494
4495        let answers = answers
4496            .iter()
4497            .map(|answer| answer.clone().into())
4498            .collect::<Vec<_>>();
4499
4500        let receiver = match &prompt_builder {
4501            PromptBuilder::Default => self
4502                .platform_window
4503                .prompt(level, message, detail, &answers)
4504                .unwrap_or_else(|| {
4505                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4506                }),
4507            PromptBuilder::Custom(_) => {
4508                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4509            }
4510        };
4511
4512        cx.prompt_builder = Some(prompt_builder);
4513
4514        receiver
4515    }
4516
4517    fn build_custom_prompt(
4518        &mut self,
4519        prompt_builder: &PromptBuilder,
4520        level: PromptLevel,
4521        message: &str,
4522        detail: Option<&str>,
4523        answers: &[PromptButton],
4524        cx: &mut App,
4525    ) -> oneshot::Receiver<usize> {
4526        let (sender, receiver) = oneshot::channel();
4527        let handle = PromptHandle::new(sender);
4528        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4529        self.prompt = Some(handle);
4530        receiver
4531    }
4532
4533    /// Returns the current context stack.
4534    pub fn context_stack(&self) -> Vec<KeyContext> {
4535        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4536        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4537        dispatch_tree
4538            .dispatch_path(node_id)
4539            .iter()
4540            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4541            .collect()
4542    }
4543
4544    /// Returns all available actions for the focused element.
4545    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4546        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4547        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4548        for action_type in cx.global_action_listeners.keys() {
4549            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4550                let action = cx.actions.build_action_type(action_type).ok();
4551                if let Some(action) = action {
4552                    actions.insert(ix, action);
4553                }
4554            }
4555        }
4556        actions
4557    }
4558
4559    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4560    /// returned in the order they were added. For display, the last binding should take precedence.
4561    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4562        self.rendered_frame
4563            .dispatch_tree
4564            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4565    }
4566
4567    /// Returns the highest precedence key binding that invokes an action on the currently focused
4568    /// element. This is more efficient than getting the last result of `bindings_for_action`.
4569    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4570        self.rendered_frame
4571            .dispatch_tree
4572            .highest_precedence_binding_for_action(
4573                action,
4574                &self.rendered_frame.dispatch_tree.context_stack,
4575            )
4576    }
4577
4578    /// Returns the key bindings for an action in a context.
4579    pub fn bindings_for_action_in_context(
4580        &self,
4581        action: &dyn Action,
4582        context: KeyContext,
4583    ) -> Vec<KeyBinding> {
4584        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4585        dispatch_tree.bindings_for_action(action, &[context])
4586    }
4587
4588    /// Returns the highest precedence key binding for an action in a context. This is more
4589    /// efficient than getting the last result of `bindings_for_action_in_context`.
4590    pub fn highest_precedence_binding_for_action_in_context(
4591        &self,
4592        action: &dyn Action,
4593        context: KeyContext,
4594    ) -> Option<KeyBinding> {
4595        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4596        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4597    }
4598
4599    /// Returns any bindings that would invoke an action on the given focus handle if it were
4600    /// focused. Bindings are returned in the order they were added. For display, the last binding
4601    /// should take precedence.
4602    pub fn bindings_for_action_in(
4603        &self,
4604        action: &dyn Action,
4605        focus_handle: &FocusHandle,
4606    ) -> Vec<KeyBinding> {
4607        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4608        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4609            return vec![];
4610        };
4611        dispatch_tree.bindings_for_action(action, &context_stack)
4612    }
4613
4614    /// Returns the highest precedence key binding that would invoke an action on the given focus
4615    /// handle if it were focused. This is more efficient than getting the last result of
4616    /// `bindings_for_action_in`.
4617    pub fn highest_precedence_binding_for_action_in(
4618        &self,
4619        action: &dyn Action,
4620        focus_handle: &FocusHandle,
4621    ) -> Option<KeyBinding> {
4622        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4623        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4624        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4625    }
4626
4627    /// Find the bindings that can follow the current input sequence for the current context stack.
4628    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
4629        self.rendered_frame
4630            .dispatch_tree
4631            .possible_next_bindings_for_input(input, &self.context_stack())
4632    }
4633
4634    fn context_stack_for_focus_handle(
4635        &self,
4636        focus_handle: &FocusHandle,
4637    ) -> Option<Vec<KeyContext>> {
4638        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4639        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4640        let context_stack: Vec<_> = dispatch_tree
4641            .dispatch_path(node_id)
4642            .into_iter()
4643            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4644            .collect();
4645        Some(context_stack)
4646    }
4647
4648    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4649    pub fn listener_for<T: 'static, E>(
4650        &self,
4651        view: &Entity<T>,
4652        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
4653    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4654        let view = view.downgrade();
4655        move |e: &E, window: &mut Window, cx: &mut App| {
4656            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4657        }
4658    }
4659
4660    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4661    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
4662        &self,
4663        entity: &Entity<E>,
4664        f: Callback,
4665    ) -> impl Fn(&mut Window, &mut App) + 'static {
4666        let entity = entity.downgrade();
4667        move |window: &mut Window, cx: &mut App| {
4668            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
4669        }
4670    }
4671
4672    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4673    /// If the callback returns false, the window won't be closed.
4674    pub fn on_window_should_close(
4675        &self,
4676        cx: &App,
4677        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4678    ) {
4679        let mut cx = self.to_async(cx);
4680        self.platform_window.on_should_close(Box::new(move || {
4681            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4682        }))
4683    }
4684
4685    /// Register an action listener on this node for the next frame. The type of action
4686    /// is determined by the first parameter of the given listener. When the next frame is rendered
4687    /// the listener will be cleared.
4688    ///
4689    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4690    /// a specific need to register a listener yourself.
4691    ///
4692    /// This method should only be called as part of the paint phase of element drawing.
4693    pub fn on_action(
4694        &mut self,
4695        action_type: TypeId,
4696        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4697    ) {
4698        self.invalidator.debug_assert_paint();
4699
4700        self.next_frame
4701            .dispatch_tree
4702            .on_action(action_type, Rc::new(listener));
4703    }
4704
4705    /// Register a capturing action listener on this node for the next frame if the condition is true.
4706    /// The type of action is determined by the first parameter of the given listener. When the next
4707    /// frame is rendered the listener will be cleared.
4708    ///
4709    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4710    /// a specific need to register a listener yourself.
4711    ///
4712    /// This method should only be called as part of the paint phase of element drawing.
4713    pub fn on_action_when(
4714        &mut self,
4715        condition: bool,
4716        action_type: TypeId,
4717        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4718    ) {
4719        self.invalidator.debug_assert_paint();
4720
4721        if condition {
4722            self.next_frame
4723                .dispatch_tree
4724                .on_action(action_type, Rc::new(listener));
4725        }
4726    }
4727
4728    /// Read information about the GPU backing this window.
4729    /// Currently returns None on Mac and Windows.
4730    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4731        self.platform_window.gpu_specs()
4732    }
4733
4734    /// Perform titlebar double-click action.
4735    /// This is macOS specific.
4736    pub fn titlebar_double_click(&self) {
4737        self.platform_window.titlebar_double_click();
4738    }
4739
4740    /// Gets the window's title at the platform level.
4741    /// This is macOS specific.
4742    pub fn window_title(&self) -> String {
4743        self.platform_window.get_title()
4744    }
4745
4746    /// Returns a list of all tabbed windows and their titles.
4747    /// This is macOS specific.
4748    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
4749        self.platform_window.tabbed_windows()
4750    }
4751
4752    /// Returns the tab bar visibility.
4753    /// This is macOS specific.
4754    pub fn tab_bar_visible(&self) -> bool {
4755        self.platform_window.tab_bar_visible()
4756    }
4757
4758    /// Merges all open windows into a single tabbed window.
4759    /// This is macOS specific.
4760    pub fn merge_all_windows(&self) {
4761        self.platform_window.merge_all_windows()
4762    }
4763
4764    /// Moves the tab to a new containing window.
4765    /// This is macOS specific.
4766    pub fn move_tab_to_new_window(&self) {
4767        self.platform_window.move_tab_to_new_window()
4768    }
4769
4770    /// Shows or hides the window tab overview.
4771    /// This is macOS specific.
4772    pub fn toggle_window_tab_overview(&self) {
4773        self.platform_window.toggle_window_tab_overview()
4774    }
4775
4776    /// Sets the tabbing identifier for the window.
4777    /// This is macOS specific.
4778    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
4779        self.platform_window
4780            .set_tabbing_identifier(tabbing_identifier)
4781    }
4782
4783    /// Toggles the inspector mode on this window.
4784    #[cfg(any(feature = "inspector", debug_assertions))]
4785    pub fn toggle_inspector(&mut self, cx: &mut App) {
4786        self.inspector = match self.inspector {
4787            None => Some(cx.new(|_| Inspector::new())),
4788            Some(_) => None,
4789        };
4790        self.refresh();
4791    }
4792
4793    /// Returns true if the window is in inspector mode.
4794    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
4795        #[cfg(any(feature = "inspector", debug_assertions))]
4796        {
4797            if let Some(inspector) = &self.inspector {
4798                return inspector.read(_cx).is_picking();
4799            }
4800        }
4801        false
4802    }
4803
4804    /// Executes the provided function with mutable access to an inspector state.
4805    #[cfg(any(feature = "inspector", debug_assertions))]
4806    pub fn with_inspector_state<T: 'static, R>(
4807        &mut self,
4808        _inspector_id: Option<&crate::InspectorElementId>,
4809        cx: &mut App,
4810        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
4811    ) -> R {
4812        if let Some(inspector_id) = _inspector_id
4813            && let Some(inspector) = &self.inspector
4814        {
4815            let inspector = inspector.clone();
4816            let active_element_id = inspector.read(cx).active_element_id();
4817            if Some(inspector_id) == active_element_id {
4818                return inspector.update(cx, |inspector, _cx| {
4819                    inspector.with_active_element_state(self, f)
4820                });
4821            }
4822        }
4823        f(&mut None, self)
4824    }
4825
4826    #[cfg(any(feature = "inspector", debug_assertions))]
4827    pub(crate) fn build_inspector_element_id(
4828        &mut self,
4829        path: crate::InspectorElementPath,
4830    ) -> crate::InspectorElementId {
4831        self.invalidator.debug_assert_paint_or_prepaint();
4832        let path = Rc::new(path);
4833        let next_instance_id = self
4834            .next_frame
4835            .next_inspector_instance_ids
4836            .entry(path.clone())
4837            .or_insert(0);
4838        let instance_id = *next_instance_id;
4839        *next_instance_id += 1;
4840        crate::InspectorElementId { path, instance_id }
4841    }
4842
4843    #[cfg(any(feature = "inspector", debug_assertions))]
4844    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
4845        if let Some(inspector) = self.inspector.take() {
4846            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
4847            inspector_element.prepaint_as_root(
4848                point(self.viewport_size.width - inspector_width, px(0.0)),
4849                size(inspector_width, self.viewport_size.height).into(),
4850                self,
4851                cx,
4852            );
4853            self.inspector = Some(inspector);
4854            Some(inspector_element)
4855        } else {
4856            None
4857        }
4858    }
4859
4860    #[cfg(any(feature = "inspector", debug_assertions))]
4861    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
4862        if let Some(mut inspector_element) = inspector_element {
4863            inspector_element.paint(self, cx);
4864        };
4865    }
4866
4867    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
4868    /// inspect UI elements by clicking on them.
4869    #[cfg(any(feature = "inspector", debug_assertions))]
4870    pub fn insert_inspector_hitbox(
4871        &mut self,
4872        hitbox_id: HitboxId,
4873        inspector_id: Option<&crate::InspectorElementId>,
4874        cx: &App,
4875    ) {
4876        self.invalidator.debug_assert_paint_or_prepaint();
4877        if !self.is_inspector_picking(cx) {
4878            return;
4879        }
4880        if let Some(inspector_id) = inspector_id {
4881            self.next_frame
4882                .inspector_hitboxes
4883                .insert(hitbox_id, inspector_id.clone());
4884        }
4885    }
4886
4887    #[cfg(any(feature = "inspector", debug_assertions))]
4888    fn paint_inspector_hitbox(&mut self, cx: &App) {
4889        if let Some(inspector) = self.inspector.as_ref() {
4890            let inspector = inspector.read(cx);
4891            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
4892                && let Some(hitbox) = self
4893                    .next_frame
4894                    .hitboxes
4895                    .iter()
4896                    .find(|hitbox| hitbox.id == hitbox_id)
4897            {
4898                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
4899            }
4900        }
4901    }
4902
4903    #[cfg(any(feature = "inspector", debug_assertions))]
4904    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4905        let Some(inspector) = self.inspector.clone() else {
4906            return;
4907        };
4908        if event.downcast_ref::<MouseMoveEvent>().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.hover(inspector_id, self);
4914                }
4915            });
4916        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
4917            inspector.update(cx, |inspector, _cx| {
4918                if let Some((_, inspector_id)) =
4919                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4920                {
4921                    inspector.select(inspector_id, self);
4922                }
4923            });
4924        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
4925            // This should be kept in sync with SCROLL_LINES in x11 platform.
4926            const SCROLL_LINES: f32 = 3.0;
4927            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
4928            let delta_y = event
4929                .delta
4930                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
4931                .y;
4932            if let Some(inspector) = self.inspector.clone() {
4933                inspector.update(cx, |inspector, _cx| {
4934                    if let Some(depth) = inspector.pick_depth.as_mut() {
4935                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
4936                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
4937                        if *depth < 0.0 {
4938                            *depth = 0.0;
4939                        } else if *depth > max_depth {
4940                            *depth = max_depth;
4941                        }
4942                        if let Some((_, inspector_id)) =
4943                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4944                        {
4945                            inspector.set_active_element_id(inspector_id, self);
4946                        }
4947                    }
4948                });
4949            }
4950        }
4951    }
4952
4953    #[cfg(any(feature = "inspector", debug_assertions))]
4954    fn hovered_inspector_hitbox(
4955        &self,
4956        inspector: &Inspector,
4957        frame: &Frame,
4958    ) -> Option<(HitboxId, crate::InspectorElementId)> {
4959        if let Some(pick_depth) = inspector.pick_depth {
4960            let depth = (pick_depth as i64).try_into().unwrap_or(0);
4961            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
4962            let skip_count = (depth as usize).min(max_skipped);
4963            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
4964                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
4965                    return Some((*hitbox_id, inspector_id.clone()));
4966                }
4967            }
4968        }
4969        None
4970    }
4971
4972    /// For testing: set the current modifier keys state.
4973    /// This does not generate any events.
4974    #[cfg(any(test, feature = "test-support"))]
4975    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
4976        self.modifiers = modifiers;
4977    }
4978
4979    /// For testing: simulate a mouse move event to the given position.
4980    /// This dispatches the event through the normal event handling path,
4981    /// which will trigger hover states and tooltips.
4982    #[cfg(any(test, feature = "test-support"))]
4983    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
4984        let event = PlatformInput::MouseMove(MouseMoveEvent {
4985            position,
4986            modifiers: self.modifiers,
4987            pressed_button: None,
4988        });
4989        let _ = self.dispatch_event(event, cx);
4990    }
4991}
4992
4993// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4994slotmap::new_key_type! {
4995    /// A unique identifier for a window.
4996    pub struct WindowId;
4997}
4998
4999impl WindowId {
5000    /// Converts this window ID to a `u64`.
5001    pub fn as_u64(&self) -> u64 {
5002        self.0.as_ffi()
5003    }
5004}
5005
5006impl From<u64> for WindowId {
5007    fn from(value: u64) -> Self {
5008        WindowId(slotmap::KeyData::from_ffi(value))
5009    }
5010}
5011
5012/// A handle to a window with a specific root view type.
5013/// Note that this does not keep the window alive on its own.
5014#[derive(Deref, DerefMut)]
5015pub struct WindowHandle<V> {
5016    #[deref]
5017    #[deref_mut]
5018    pub(crate) any_handle: AnyWindowHandle,
5019    state_type: PhantomData<fn(V) -> V>,
5020}
5021
5022impl<V> Debug for WindowHandle<V> {
5023    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5024        f.debug_struct("WindowHandle")
5025            .field("any_handle", &self.any_handle.id.as_u64())
5026            .finish()
5027    }
5028}
5029
5030impl<V: 'static + Render> WindowHandle<V> {
5031    /// Creates a new handle from a window ID.
5032    /// This does not check if the root type of the window is `V`.
5033    pub fn new(id: WindowId) -> Self {
5034        WindowHandle {
5035            any_handle: AnyWindowHandle {
5036                id,
5037                state_type: TypeId::of::<V>(),
5038            },
5039            state_type: PhantomData,
5040        }
5041    }
5042
5043    /// Get the root view out of this window.
5044    ///
5045    /// This will fail if the window is closed or if the root view's type does not match `V`.
5046    #[cfg(any(test, feature = "test-support"))]
5047    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5048    where
5049        C: AppContext,
5050    {
5051        cx.update_window(self.any_handle, |root_view, _, _| {
5052            root_view
5053                .downcast::<V>()
5054                .map_err(|_| anyhow!("the type of the window's root view has changed"))
5055        })?
5056    }
5057
5058    /// Updates the root view of this window.
5059    ///
5060    /// This will fail if the window has been closed or if the root view's type does not match
5061    pub fn update<C, R>(
5062        &self,
5063        cx: &mut C,
5064        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5065    ) -> Result<R>
5066    where
5067        C: AppContext,
5068    {
5069        cx.update_window(self.any_handle, |root_view, window, cx| {
5070            let view = root_view
5071                .downcast::<V>()
5072                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5073
5074            Ok(view.update(cx, |view, cx| update(view, window, cx)))
5075        })?
5076    }
5077
5078    /// Read the root view out of this window.
5079    ///
5080    /// This will fail if the window is closed or if the root view's type does not match `V`.
5081    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5082        let x = cx
5083            .windows
5084            .get(self.id)
5085            .and_then(|window| {
5086                window
5087                    .as_deref()
5088                    .and_then(|window| window.root.clone())
5089                    .map(|root_view| root_view.downcast::<V>())
5090            })
5091            .context("window not found")?
5092            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5093
5094        Ok(x.read(cx))
5095    }
5096
5097    /// Read the root view out of this window, with a callback
5098    ///
5099    /// This will fail if the window is closed or if the root view's type does not match `V`.
5100    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5101    where
5102        C: AppContext,
5103    {
5104        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5105    }
5106
5107    /// Read the root view pointer off of this window.
5108    ///
5109    /// This will fail if the window is closed or if the root view's type does not match `V`.
5110    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5111    where
5112        C: AppContext,
5113    {
5114        cx.read_window(self, |root_view, _cx| root_view)
5115    }
5116
5117    /// Check if this window is 'active'.
5118    ///
5119    /// Will return `None` if the window is closed or currently
5120    /// borrowed.
5121    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5122        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5123            .ok()
5124    }
5125}
5126
5127impl<V> Copy for WindowHandle<V> {}
5128
5129impl<V> Clone for WindowHandle<V> {
5130    fn clone(&self) -> Self {
5131        *self
5132    }
5133}
5134
5135impl<V> PartialEq for WindowHandle<V> {
5136    fn eq(&self, other: &Self) -> bool {
5137        self.any_handle == other.any_handle
5138    }
5139}
5140
5141impl<V> Eq for WindowHandle<V> {}
5142
5143impl<V> Hash for WindowHandle<V> {
5144    fn hash<H: Hasher>(&self, state: &mut H) {
5145        self.any_handle.hash(state);
5146    }
5147}
5148
5149impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5150    fn from(val: WindowHandle<V>) -> Self {
5151        val.any_handle
5152    }
5153}
5154
5155/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
5156#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5157pub struct AnyWindowHandle {
5158    pub(crate) id: WindowId,
5159    state_type: TypeId,
5160}
5161
5162impl AnyWindowHandle {
5163    /// Get the ID of this window.
5164    pub fn window_id(&self) -> WindowId {
5165        self.id
5166    }
5167
5168    /// Attempt to convert this handle to a window handle with a specific root view type.
5169    /// If the types do not match, this will return `None`.
5170    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5171        if TypeId::of::<T>() == self.state_type {
5172            Some(WindowHandle {
5173                any_handle: *self,
5174                state_type: PhantomData,
5175            })
5176        } else {
5177            None
5178        }
5179    }
5180
5181    /// Updates the state of the root view of this window.
5182    ///
5183    /// This will fail if the window has been closed.
5184    pub fn update<C, R>(
5185        self,
5186        cx: &mut C,
5187        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5188    ) -> Result<R>
5189    where
5190        C: AppContext,
5191    {
5192        cx.update_window(self, update)
5193    }
5194
5195    /// Read the state of the root view of this window.
5196    ///
5197    /// This will fail if the window has been closed.
5198    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5199    where
5200        C: AppContext,
5201        T: 'static,
5202    {
5203        let view = self
5204            .downcast::<T>()
5205            .context("the type of the window's root view has changed")?;
5206
5207        cx.read_window(&view, read)
5208    }
5209}
5210
5211impl HasWindowHandle for Window {
5212    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5213        self.platform_window.window_handle()
5214    }
5215}
5216
5217impl HasDisplayHandle for Window {
5218    fn display_handle(
5219        &self,
5220    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5221        self.platform_window.display_handle()
5222    }
5223}
5224
5225/// An identifier for an [`Element`].
5226///
5227/// Can be constructed with a string, a number, or both, as well
5228/// as other internal representations.
5229#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5230pub enum ElementId {
5231    /// The ID of a View element
5232    View(EntityId),
5233    /// An integer ID.
5234    Integer(u64),
5235    /// A string based ID.
5236    Name(SharedString),
5237    /// A UUID.
5238    Uuid(Uuid),
5239    /// An ID that's equated with a focus handle.
5240    FocusHandle(FocusId),
5241    /// A combination of a name and an integer.
5242    NamedInteger(SharedString, u64),
5243    /// A path.
5244    Path(Arc<std::path::Path>),
5245    /// A code location.
5246    CodeLocation(core::panic::Location<'static>),
5247    /// A labeled child of an element.
5248    NamedChild(Arc<ElementId>, SharedString),
5249}
5250
5251impl ElementId {
5252    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5253    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5254        Self::NamedInteger(name.into(), integer as u64)
5255    }
5256}
5257
5258impl Display for ElementId {
5259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5260        match self {
5261            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5262            ElementId::Integer(ix) => write!(f, "{}", ix)?,
5263            ElementId::Name(name) => write!(f, "{}", name)?,
5264            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5265            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5266            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5267            ElementId::Path(path) => write!(f, "{}", path.display())?,
5268            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5269            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5270        }
5271
5272        Ok(())
5273    }
5274}
5275
5276impl TryInto<SharedString> for ElementId {
5277    type Error = anyhow::Error;
5278
5279    fn try_into(self) -> anyhow::Result<SharedString> {
5280        if let ElementId::Name(name) = self {
5281            Ok(name)
5282        } else {
5283            anyhow::bail!("element id is not string")
5284        }
5285    }
5286}
5287
5288impl From<usize> for ElementId {
5289    fn from(id: usize) -> Self {
5290        ElementId::Integer(id as u64)
5291    }
5292}
5293
5294impl From<i32> for ElementId {
5295    fn from(id: i32) -> Self {
5296        Self::Integer(id as u64)
5297    }
5298}
5299
5300impl From<SharedString> for ElementId {
5301    fn from(name: SharedString) -> Self {
5302        ElementId::Name(name)
5303    }
5304}
5305
5306impl From<String> for ElementId {
5307    fn from(name: String) -> Self {
5308        ElementId::Name(name.into())
5309    }
5310}
5311
5312impl From<Arc<str>> for ElementId {
5313    fn from(name: Arc<str>) -> Self {
5314        ElementId::Name(name.into())
5315    }
5316}
5317
5318impl From<Arc<std::path::Path>> for ElementId {
5319    fn from(path: Arc<std::path::Path>) -> Self {
5320        ElementId::Path(path)
5321    }
5322}
5323
5324impl From<&'static str> for ElementId {
5325    fn from(name: &'static str) -> Self {
5326        ElementId::Name(name.into())
5327    }
5328}
5329
5330impl<'a> From<&'a FocusHandle> for ElementId {
5331    fn from(handle: &'a FocusHandle) -> Self {
5332        ElementId::FocusHandle(handle.id)
5333    }
5334}
5335
5336impl From<(&'static str, EntityId)> for ElementId {
5337    fn from((name, id): (&'static str, EntityId)) -> Self {
5338        ElementId::NamedInteger(name.into(), id.as_u64())
5339    }
5340}
5341
5342impl From<(&'static str, usize)> for ElementId {
5343    fn from((name, id): (&'static str, usize)) -> Self {
5344        ElementId::NamedInteger(name.into(), id as u64)
5345    }
5346}
5347
5348impl From<(SharedString, usize)> for ElementId {
5349    fn from((name, id): (SharedString, usize)) -> Self {
5350        ElementId::NamedInteger(name, id as u64)
5351    }
5352}
5353
5354impl From<(&'static str, u64)> for ElementId {
5355    fn from((name, id): (&'static str, u64)) -> Self {
5356        ElementId::NamedInteger(name.into(), id)
5357    }
5358}
5359
5360impl From<Uuid> for ElementId {
5361    fn from(value: Uuid) -> Self {
5362        Self::Uuid(value)
5363    }
5364}
5365
5366impl From<(&'static str, u32)> for ElementId {
5367    fn from((name, id): (&'static str, u32)) -> Self {
5368        ElementId::NamedInteger(name.into(), id.into())
5369    }
5370}
5371
5372impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5373    fn from((id, name): (ElementId, T)) -> Self {
5374        ElementId::NamedChild(Arc::new(id), name.into())
5375    }
5376}
5377
5378impl From<&'static core::panic::Location<'static>> for ElementId {
5379    fn from(location: &'static core::panic::Location<'static>) -> Self {
5380        ElementId::CodeLocation(*location)
5381    }
5382}
5383
5384/// A rectangle to be rendered in the window at the given position and size.
5385/// Passed as an argument [`Window::paint_quad`].
5386#[derive(Clone)]
5387pub struct PaintQuad {
5388    /// The bounds of the quad within the window.
5389    pub bounds: Bounds<Pixels>,
5390    /// The radii of the quad's corners.
5391    pub corner_radii: Corners<Pixels>,
5392    /// The background color of the quad.
5393    pub background: Background,
5394    /// The widths of the quad's borders.
5395    pub border_widths: Edges<Pixels>,
5396    /// The color of the quad's borders.
5397    pub border_color: Hsla,
5398    /// The style of the quad's borders.
5399    pub border_style: BorderStyle,
5400}
5401
5402impl PaintQuad {
5403    /// Sets the corner radii of the quad.
5404    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5405        PaintQuad {
5406            corner_radii: corner_radii.into(),
5407            ..self
5408        }
5409    }
5410
5411    /// Sets the border widths of the quad.
5412    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5413        PaintQuad {
5414            border_widths: border_widths.into(),
5415            ..self
5416        }
5417    }
5418
5419    /// Sets the border color of the quad.
5420    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5421        PaintQuad {
5422            border_color: border_color.into(),
5423            ..self
5424        }
5425    }
5426
5427    /// Sets the background color of the quad.
5428    pub fn background(self, background: impl Into<Background>) -> Self {
5429        PaintQuad {
5430            background: background.into(),
5431            ..self
5432        }
5433    }
5434}
5435
5436/// Creates a quad with the given parameters.
5437pub fn quad(
5438    bounds: Bounds<Pixels>,
5439    corner_radii: impl Into<Corners<Pixels>>,
5440    background: impl Into<Background>,
5441    border_widths: impl Into<Edges<Pixels>>,
5442    border_color: impl Into<Hsla>,
5443    border_style: BorderStyle,
5444) -> PaintQuad {
5445    PaintQuad {
5446        bounds,
5447        corner_radii: corner_radii.into(),
5448        background: background.into(),
5449        border_widths: border_widths.into(),
5450        border_color: border_color.into(),
5451        border_style,
5452    }
5453}
5454
5455/// Creates a filled quad with the given bounds and background color.
5456pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5457    PaintQuad {
5458        bounds: bounds.into(),
5459        corner_radii: (0.).into(),
5460        background: background.into(),
5461        border_widths: (0.).into(),
5462        border_color: transparent_black(),
5463        border_style: BorderStyle::default(),
5464    }
5465}
5466
5467/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5468pub fn outline(
5469    bounds: impl Into<Bounds<Pixels>>,
5470    border_color: impl Into<Hsla>,
5471    border_style: BorderStyle,
5472) -> PaintQuad {
5473    PaintQuad {
5474        bounds: bounds.into(),
5475        corner_radii: (0.).into(),
5476        background: transparent_black().into(),
5477        border_widths: (1.).into(),
5478        border_color: border_color.into(),
5479        border_style,
5480    }
5481}