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