window.rs

   1use crate::{
   2    point, prelude::*, px, size, transparent_black, Action, AnyDrag, AnyElement, AnyTooltip,
   3    AnyView, App, AppContext, Arena, Asset, AsyncWindowContext, AvailableSpace, Background, Bounds,
   4    BoxShadow, Context, Corners, CursorStyle, Decorations, DevicePixels, DispatchActionListener,
   5    DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
   6    FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, IsZero,
   7    KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId,
   8    LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
   9    MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
  10    PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render,
  11    RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge,
  12    ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubscriberSet,
  13    Subscription, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement, TransformationMatrix,
  14    Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
  15    WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
  16    SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS,
  17};
  18use anyhow::{anyhow, Context as _, Result};
  19use collections::{FxHashMap, FxHashSet};
  20use derive_more::{Deref, DerefMut};
  21use futures::channel::oneshot;
  22use futures::FutureExt;
  23#[cfg(target_os = "macos")]
  24use media::core_video::CVImageBuffer;
  25use parking_lot::RwLock;
  26use raw_window_handle::{HandleError, HasWindowHandle};
  27use refineable::Refineable;
  28use slotmap::SlotMap;
  29use smallvec::SmallVec;
  30use std::{
  31    any::{Any, TypeId},
  32    borrow::Cow,
  33    cell::{Cell, RefCell},
  34    cmp,
  35    fmt::{Debug, Display},
  36    hash::{Hash, Hasher},
  37    marker::PhantomData,
  38    mem,
  39    ops::{DerefMut, Range},
  40    rc::Rc,
  41    sync::{
  42        atomic::{AtomicUsize, Ordering::SeqCst},
  43        Arc, Weak,
  44    },
  45    time::{Duration, Instant},
  46};
  47use util::post_inc;
  48use util::{measure, ResultExt};
  49use uuid::Uuid;
  50
  51mod prompts;
  52
  53pub use prompts::*;
  54
  55pub(crate) const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1024.), px(700.));
  56
  57/// Represents the two different phases when dispatching events.
  58#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  59pub enum DispatchPhase {
  60    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  61    /// invoked front to back and keyboard event listeners are invoked from the focused element
  62    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  63    /// registering event listeners.
  64    #[default]
  65    Bubble,
  66    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  67    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  68    /// is used for special purposes such as clearing the "pressed" state for click events. If
  69    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  70    /// outside of the immediate region may rely on detecting non-local events during this phase.
  71    Capture,
  72}
  73
  74impl DispatchPhase {
  75    /// Returns true if this represents the "bubble" phase.
  76    pub fn bubble(self) -> bool {
  77        self == DispatchPhase::Bubble
  78    }
  79
  80    /// Returns true if this represents the "capture" phase.
  81    pub fn capture(self) -> bool {
  82        self == DispatchPhase::Capture
  83    }
  84}
  85
  86struct WindowInvalidatorInner {
  87    pub dirty: bool,
  88    pub draw_phase: DrawPhase,
  89    pub dirty_views: FxHashSet<EntityId>,
  90}
  91
  92#[derive(Clone)]
  93pub(crate) struct WindowInvalidator {
  94    inner: Rc<RefCell<WindowInvalidatorInner>>,
  95}
  96
  97impl WindowInvalidator {
  98    pub fn new() -> Self {
  99        WindowInvalidator {
 100            inner: Rc::new(RefCell::new(WindowInvalidatorInner {
 101                dirty: true,
 102                draw_phase: DrawPhase::None,
 103                dirty_views: FxHashSet::default(),
 104            })),
 105        }
 106    }
 107
 108    pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
 109        let mut inner = self.inner.borrow_mut();
 110        inner.dirty_views.insert(entity);
 111        if inner.draw_phase == DrawPhase::None {
 112            inner.dirty = true;
 113            cx.push_effect(Effect::Notify { emitter: entity });
 114            true
 115        } else {
 116            false
 117        }
 118    }
 119
 120    pub fn is_dirty(&self) -> bool {
 121        self.inner.borrow().dirty
 122    }
 123
 124    pub fn set_dirty(&self, dirty: bool) {
 125        self.inner.borrow_mut().dirty = dirty
 126    }
 127
 128    pub fn set_phase(&self, phase: DrawPhase) {
 129        self.inner.borrow_mut().draw_phase = phase
 130    }
 131
 132    pub fn take_views(&self) -> FxHashSet<EntityId> {
 133        mem::take(&mut self.inner.borrow_mut().dirty_views)
 134    }
 135
 136    pub fn replace_views(&self, views: FxHashSet<EntityId>) {
 137        self.inner.borrow_mut().dirty_views = views;
 138    }
 139
 140    pub fn not_drawing(&self) -> bool {
 141        self.inner.borrow().draw_phase == DrawPhase::None
 142    }
 143
 144    #[track_caller]
 145    pub fn debug_assert_paint(&self) {
 146        debug_assert!(
 147            matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
 148            "this method can only be called during paint"
 149        );
 150    }
 151
 152    #[track_caller]
 153    pub fn debug_assert_prepaint(&self) {
 154        debug_assert!(
 155            matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
 156            "this method can only be called during request_layout, or prepaint"
 157        );
 158    }
 159
 160    #[track_caller]
 161    pub fn debug_assert_paint_or_prepaint(&self) {
 162        debug_assert!(
 163            matches!(
 164                self.inner.borrow().draw_phase,
 165                DrawPhase::Paint | DrawPhase::Prepaint
 166            ),
 167            "this method can only be called during request_layout, prepaint, or paint"
 168        );
 169    }
 170}
 171
 172type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
 173
 174pub(crate) type AnyWindowFocusListener =
 175    Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
 176
 177pub(crate) struct WindowFocusEvent {
 178    pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
 179    pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
 180}
 181
 182impl WindowFocusEvent {
 183    pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
 184        !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
 185    }
 186
 187    pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
 188        self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
 189    }
 190}
 191
 192/// This is provided when subscribing for `Context::on_focus_out` events.
 193pub struct FocusOutEvent {
 194    /// A weak focus handle representing what was blurred.
 195    pub blurred: WeakFocusHandle,
 196}
 197
 198slotmap::new_key_type! {
 199    /// A globally unique identifier for a focusable element.
 200    pub struct FocusId;
 201}
 202
 203thread_local! {
 204    /// 8MB wasn't quite enough...
 205    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(32 * 1024 * 1024));
 206}
 207
 208pub(crate) type FocusMap = RwLock<SlotMap<FocusId, AtomicUsize>>;
 209
 210impl FocusId {
 211    /// Obtains whether the element associated with this handle is currently focused.
 212    pub fn is_focused(&self, window: &Window) -> bool {
 213        window.focus == Some(*self)
 214    }
 215
 216    /// Obtains whether the element associated with this handle contains the focused
 217    /// element or is itself focused.
 218    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
 219        window
 220            .focused(cx)
 221            .map_or(false, |focused| self.contains(focused.id, window))
 222    }
 223
 224    /// Obtains whether the element associated with this handle is contained within the
 225    /// focused element or is itself focused.
 226    pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
 227        let focused = window.focused(cx);
 228        focused.map_or(false, |focused| focused.id.contains(*self, window))
 229    }
 230
 231    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 232    pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
 233        window
 234            .rendered_frame
 235            .dispatch_tree
 236            .focus_contains(*self, other)
 237    }
 238}
 239
 240/// A handle which can be used to track and manipulate the focused element in a window.
 241pub struct FocusHandle {
 242    pub(crate) id: FocusId,
 243    handles: Arc<FocusMap>,
 244}
 245
 246impl std::fmt::Debug for FocusHandle {
 247    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 248        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 249    }
 250}
 251
 252impl FocusHandle {
 253    pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
 254        let id = handles.write().insert(AtomicUsize::new(1));
 255        Self {
 256            id,
 257            handles: handles.clone(),
 258        }
 259    }
 260
 261    pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
 262        let lock = handles.read();
 263        let ref_count = lock.get(id)?;
 264        if ref_count.load(SeqCst) == 0 {
 265            None
 266        } else {
 267            ref_count.fetch_add(1, SeqCst);
 268            Some(Self {
 269                id,
 270                handles: handles.clone(),
 271            })
 272        }
 273    }
 274
 275    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
 276    pub fn downgrade(&self) -> WeakFocusHandle {
 277        WeakFocusHandle {
 278            id: self.id,
 279            handles: Arc::downgrade(&self.handles),
 280        }
 281    }
 282
 283    /// Moves the focus to the element associated with this handle.
 284    pub fn focus(&self, window: &mut Window) {
 285        window.focus(self)
 286    }
 287
 288    /// Obtains whether the element associated with this handle is currently focused.
 289    pub fn is_focused(&self, window: &Window) -> bool {
 290        self.id.is_focused(window)
 291    }
 292
 293    /// Obtains whether the element associated with this handle contains the focused
 294    /// element or is itself focused.
 295    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
 296        self.id.contains_focused(window, cx)
 297    }
 298
 299    /// Obtains whether the element associated with this handle is contained within the
 300    /// focused element or is itself focused.
 301    pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
 302        self.id.within_focused(window, cx)
 303    }
 304
 305    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 306    pub fn contains(&self, other: &Self, window: &Window) -> bool {
 307        self.id.contains(other.id, window)
 308    }
 309
 310    /// Dispatch an action on the element that rendered this focus handle
 311    pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
 312        if let Some(node_id) = window
 313            .rendered_frame
 314            .dispatch_tree
 315            .focusable_node_id(self.id)
 316        {
 317            window.dispatch_action_on_node(node_id, action, cx)
 318        }
 319    }
 320}
 321
 322impl Clone for FocusHandle {
 323    fn clone(&self) -> Self {
 324        Self::for_id(self.id, &self.handles).unwrap()
 325    }
 326}
 327
 328impl PartialEq for FocusHandle {
 329    fn eq(&self, other: &Self) -> bool {
 330        self.id == other.id
 331    }
 332}
 333
 334impl Eq for FocusHandle {}
 335
 336impl Drop for FocusHandle {
 337    fn drop(&mut self) {
 338        self.handles
 339            .read()
 340            .get(self.id)
 341            .unwrap()
 342            .fetch_sub(1, SeqCst);
 343    }
 344}
 345
 346/// A weak reference to a focus handle.
 347#[derive(Clone, Debug)]
 348pub struct WeakFocusHandle {
 349    pub(crate) id: FocusId,
 350    pub(crate) handles: Weak<FocusMap>,
 351}
 352
 353impl WeakFocusHandle {
 354    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
 355    pub fn upgrade(&self) -> Option<FocusHandle> {
 356        let handles = self.handles.upgrade()?;
 357        FocusHandle::for_id(self.id, &handles)
 358    }
 359}
 360
 361impl PartialEq for WeakFocusHandle {
 362    fn eq(&self, other: &WeakFocusHandle) -> bool {
 363        self.id == other.id
 364    }
 365}
 366
 367impl Eq for WeakFocusHandle {}
 368
 369impl PartialEq<FocusHandle> for WeakFocusHandle {
 370    fn eq(&self, other: &FocusHandle) -> bool {
 371        self.id == other.id
 372    }
 373}
 374
 375impl PartialEq<WeakFocusHandle> for FocusHandle {
 376    fn eq(&self, other: &WeakFocusHandle) -> bool {
 377        self.id == other.id
 378    }
 379}
 380
 381/// Focusable allows users of your view to easily
 382/// focus it (using window.focus_view(cx, view))
 383pub trait Focusable: 'static {
 384    /// Returns the focus handle associated with this view.
 385    fn focus_handle(&self, cx: &App) -> FocusHandle;
 386}
 387
 388impl<V: Focusable> Focusable for Entity<V> {
 389    fn focus_handle(&self, cx: &App) -> FocusHandle {
 390        self.read(cx).focus_handle(cx)
 391    }
 392}
 393
 394/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 395/// where the lifecycle of the view is handled by another view.
 396pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
 397
 398impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
 399
 400/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 401pub struct DismissEvent;
 402
 403type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
 404
 405pub(crate) type AnyMouseListener =
 406    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
 407
 408#[derive(Clone)]
 409pub(crate) struct CursorStyleRequest {
 410    pub(crate) hitbox_id: HitboxId,
 411    pub(crate) style: CursorStyle,
 412}
 413
 414/// An identifier for a [Hitbox].
 415#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 416pub struct HitboxId(usize);
 417
 418impl HitboxId {
 419    /// Checks if the hitbox with this id is currently hovered.
 420    pub fn is_hovered(&self, window: &Window) -> bool {
 421        window.mouse_hit_test.0.contains(self)
 422    }
 423}
 424
 425/// A rectangular region that potentially blocks hitboxes inserted prior.
 426/// See [Window::insert_hitbox] for more details.
 427#[derive(Clone, Debug, Deref)]
 428pub struct Hitbox {
 429    /// A unique identifier for the hitbox.
 430    pub id: HitboxId,
 431    /// The bounds of the hitbox.
 432    #[deref]
 433    pub bounds: Bounds<Pixels>,
 434    /// The content mask when the hitbox was inserted.
 435    pub content_mask: ContentMask<Pixels>,
 436    /// Whether the hitbox occludes other hitboxes inserted prior.
 437    pub opaque: bool,
 438}
 439
 440impl Hitbox {
 441    /// Checks if the hitbox is currently hovered.
 442    pub fn is_hovered(&self, window: &Window) -> bool {
 443        self.id.is_hovered(window)
 444    }
 445}
 446
 447#[derive(Default, Eq, PartialEq)]
 448pub(crate) struct HitTest(SmallVec<[HitboxId; 8]>);
 449
 450/// An identifier for a tooltip.
 451#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 452pub struct TooltipId(usize);
 453
 454impl TooltipId {
 455    /// Checks if the tooltip is currently hovered.
 456    pub fn is_hovered(&self, window: &Window) -> bool {
 457        window
 458            .tooltip_bounds
 459            .as_ref()
 460            .map_or(false, |tooltip_bounds| {
 461                tooltip_bounds.id == *self
 462                    && tooltip_bounds.bounds.contains(&window.mouse_position())
 463            })
 464    }
 465}
 466
 467pub(crate) struct TooltipBounds {
 468    id: TooltipId,
 469    bounds: Bounds<Pixels>,
 470}
 471
 472#[derive(Clone)]
 473pub(crate) struct TooltipRequest {
 474    id: TooltipId,
 475    tooltip: AnyTooltip,
 476}
 477
 478pub(crate) struct DeferredDraw {
 479    current_view: EntityId,
 480    priority: usize,
 481    parent_node: DispatchNodeId,
 482    element_id_stack: SmallVec<[ElementId; 32]>,
 483    text_style_stack: Vec<TextStyleRefinement>,
 484    element: Option<AnyElement>,
 485    absolute_offset: Point<Pixels>,
 486    prepaint_range: Range<PrepaintStateIndex>,
 487    paint_range: Range<PaintIndex>,
 488}
 489
 490pub(crate) struct Frame {
 491    pub(crate) focus: Option<FocusId>,
 492    pub(crate) window_active: bool,
 493    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
 494    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
 495    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
 496    pub(crate) dispatch_tree: DispatchTree,
 497    pub(crate) scene: Scene,
 498    pub(crate) hitboxes: Vec<Hitbox>,
 499    pub(crate) deferred_draws: Vec<DeferredDraw>,
 500    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
 501    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
 502    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
 503    #[cfg(any(test, feature = "test-support"))]
 504    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
 505}
 506
 507#[derive(Clone, Default)]
 508pub(crate) struct PrepaintStateIndex {
 509    hitboxes_index: usize,
 510    tooltips_index: usize,
 511    deferred_draws_index: usize,
 512    dispatch_tree_index: usize,
 513    accessed_element_states_index: usize,
 514    line_layout_index: LineLayoutIndex,
 515}
 516
 517#[derive(Clone, Default)]
 518pub(crate) struct PaintIndex {
 519    scene_index: usize,
 520    mouse_listeners_index: usize,
 521    input_handlers_index: usize,
 522    cursor_styles_index: usize,
 523    accessed_element_states_index: usize,
 524    line_layout_index: LineLayoutIndex,
 525}
 526
 527impl Frame {
 528    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
 529        Frame {
 530            focus: None,
 531            window_active: false,
 532            element_states: FxHashMap::default(),
 533            accessed_element_states: Vec::new(),
 534            mouse_listeners: Vec::new(),
 535            dispatch_tree,
 536            scene: Scene::default(),
 537            hitboxes: Vec::new(),
 538            deferred_draws: Vec::new(),
 539            input_handlers: Vec::new(),
 540            tooltip_requests: Vec::new(),
 541            cursor_styles: Vec::new(),
 542
 543            #[cfg(any(test, feature = "test-support"))]
 544            debug_bounds: FxHashMap::default(),
 545        }
 546    }
 547
 548    pub(crate) fn clear(&mut self) {
 549        self.element_states.clear();
 550        self.accessed_element_states.clear();
 551        self.mouse_listeners.clear();
 552        self.dispatch_tree.clear();
 553        self.scene.clear();
 554        self.input_handlers.clear();
 555        self.tooltip_requests.clear();
 556        self.cursor_styles.clear();
 557        self.hitboxes.clear();
 558        self.deferred_draws.clear();
 559        self.focus = None;
 560    }
 561
 562    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
 563        let mut hit_test = HitTest::default();
 564        for hitbox in self.hitboxes.iter().rev() {
 565            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
 566            if bounds.contains(&position) {
 567                hit_test.0.push(hitbox.id);
 568                if hitbox.opaque {
 569                    break;
 570                }
 571            }
 572        }
 573        hit_test
 574    }
 575
 576    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 577        self.focus
 578            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 579            .unwrap_or_default()
 580    }
 581
 582    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
 583        for element_state_key in &self.accessed_element_states {
 584            if let Some((element_state_key, element_state)) =
 585                prev_frame.element_states.remove_entry(element_state_key)
 586            {
 587                self.element_states.insert(element_state_key, element_state);
 588            }
 589        }
 590
 591        self.scene.finish();
 592    }
 593}
 594
 595/// Holds the state for a specific window.
 596pub struct Window {
 597    pub(crate) handle: AnyWindowHandle,
 598    pub(crate) invalidator: WindowInvalidator,
 599    pub(crate) removed: bool,
 600    pub(crate) platform_window: Box<dyn PlatformWindow>,
 601    display_id: Option<DisplayId>,
 602    sprite_atlas: Arc<dyn PlatformAtlas>,
 603    text_system: Arc<WindowTextSystem>,
 604    rem_size: Pixels,
 605    /// The stack of override values for the window's rem size.
 606    ///
 607    /// This is used by `with_rem_size` to allow rendering an element tree with
 608    /// a given rem size.
 609    rem_size_override_stack: SmallVec<[Pixels; 8]>,
 610    pub(crate) viewport_size: Size<Pixels>,
 611    layout_engine: Option<TaffyLayoutEngine>,
 612    pub(crate) root: Option<AnyView>,
 613    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
 614    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
 615    pub(crate) rendered_entity_stack: Vec<EntityId>,
 616    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
 617    pub(crate) element_opacity: Option<f32>,
 618    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
 619    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
 620    pub(crate) rendered_frame: Frame,
 621    pub(crate) next_frame: Frame,
 622    pub(crate) next_hitbox_id: HitboxId,
 623    pub(crate) next_tooltip_id: TooltipId,
 624    pub(crate) tooltip_bounds: Option<TooltipBounds>,
 625    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
 626    pub(crate) dirty_views: FxHashSet<EntityId>,
 627    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 628    pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 629    default_prevented: bool,
 630    mouse_position: Point<Pixels>,
 631    mouse_hit_test: HitTest,
 632    modifiers: Modifiers,
 633    scale_factor: f32,
 634    pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
 635    appearance: WindowAppearance,
 636    pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
 637    active: Rc<Cell<bool>>,
 638    hovered: Rc<Cell<bool>>,
 639    pub(crate) needs_present: Rc<Cell<bool>>,
 640    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
 641    pub(crate) refreshing: bool,
 642    pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
 643    pub(crate) focus: Option<FocusId>,
 644    focus_enabled: bool,
 645    pending_input: Option<PendingInput>,
 646    pending_modifier: ModifierState,
 647    pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
 648    prompt: Option<RenderablePromptHandle>,
 649}
 650
 651#[derive(Clone, Debug, Default)]
 652struct ModifierState {
 653    modifiers: Modifiers,
 654    saw_keystroke: bool,
 655}
 656
 657#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 658pub(crate) enum DrawPhase {
 659    None,
 660    Prepaint,
 661    Paint,
 662    Focus,
 663}
 664
 665#[derive(Default, Debug)]
 666struct PendingInput {
 667    keystrokes: SmallVec<[Keystroke; 1]>,
 668    focus: Option<FocusId>,
 669    timer: Option<Task<()>>,
 670}
 671
 672pub(crate) struct ElementStateBox {
 673    pub(crate) inner: Box<dyn Any>,
 674    #[cfg(debug_assertions)]
 675    pub(crate) type_name: &'static str,
 676}
 677
 678fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> Bounds<Pixels> {
 679    const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
 680
 681    // TODO, BUG: if you open a window with the currently active window
 682    // on the stack, this will erroneously select the 'unwrap_or_else'
 683    // code path
 684    cx.active_window()
 685        .and_then(|w| w.update(cx, |_, window, _| window.bounds()).ok())
 686        .map(|mut bounds| {
 687            bounds.origin += DEFAULT_WINDOW_OFFSET;
 688            bounds
 689        })
 690        .unwrap_or_else(|| {
 691            let display = display_id
 692                .map(|id| cx.find_display(id))
 693                .unwrap_or_else(|| cx.primary_display());
 694
 695            display
 696                .map(|display| display.default_bounds())
 697                .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
 698        })
 699}
 700
 701impl Window {
 702    pub(crate) fn new(
 703        handle: AnyWindowHandle,
 704        options: WindowOptions,
 705        cx: &mut App,
 706    ) -> Result<Self> {
 707        let WindowOptions {
 708            window_bounds,
 709            titlebar,
 710            focus,
 711            show,
 712            kind,
 713            is_movable,
 714            display_id,
 715            window_background,
 716            app_id,
 717            window_min_size,
 718            window_decorations,
 719        } = options;
 720
 721        let bounds = window_bounds
 722            .map(|bounds| bounds.get_bounds())
 723            .unwrap_or_else(|| default_bounds(display_id, cx));
 724        let mut platform_window = cx.platform.open_window(
 725            handle,
 726            WindowParams {
 727                bounds,
 728                titlebar,
 729                kind,
 730                is_movable,
 731                focus,
 732                show,
 733                display_id,
 734                window_min_size,
 735            },
 736        )?;
 737        let display_id = platform_window.display().map(|display| display.id());
 738        let sprite_atlas = platform_window.sprite_atlas();
 739        let mouse_position = platform_window.mouse_position();
 740        let modifiers = platform_window.modifiers();
 741        let content_size = platform_window.content_size();
 742        let scale_factor = platform_window.scale_factor();
 743        let appearance = platform_window.appearance();
 744        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
 745        let invalidator = WindowInvalidator::new();
 746        let active = Rc::new(Cell::new(platform_window.is_active()));
 747        let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
 748        let needs_present = Rc::new(Cell::new(false));
 749        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
 750        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
 751
 752        platform_window
 753            .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
 754        platform_window.set_background_appearance(window_background);
 755
 756        if let Some(ref window_open_state) = window_bounds {
 757            match window_open_state {
 758                WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
 759                WindowBounds::Maximized(_) => platform_window.zoom(),
 760                WindowBounds::Windowed(_) => {}
 761            }
 762        }
 763
 764        platform_window.on_close(Box::new({
 765            let mut cx = cx.to_async();
 766            move || {
 767                let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
 768            }
 769        }));
 770        platform_window.on_request_frame(Box::new({
 771            let mut cx = cx.to_async();
 772            let invalidator = invalidator.clone();
 773            let active = active.clone();
 774            let needs_present = needs_present.clone();
 775            let next_frame_callbacks = next_frame_callbacks.clone();
 776            let last_input_timestamp = last_input_timestamp.clone();
 777            move |request_frame_options| {
 778                let next_frame_callbacks = next_frame_callbacks.take();
 779                if !next_frame_callbacks.is_empty() {
 780                    handle
 781                        .update(&mut cx, |_, window, cx| {
 782                            for callback in next_frame_callbacks {
 783                                callback(window, cx);
 784                            }
 785                        })
 786                        .log_err();
 787                }
 788
 789                // Keep presenting the current scene for 1 extra second since the
 790                // last input to prevent the display from underclocking the refresh rate.
 791                let needs_present = request_frame_options.require_presentation
 792                    || needs_present.get()
 793                    || (active.get()
 794                        && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
 795
 796                if invalidator.is_dirty() {
 797                    measure("frame duration", || {
 798                        handle
 799                            .update(&mut cx, |_, window, cx| {
 800                                window.draw(cx);
 801                                window.present();
 802                            })
 803                            .log_err();
 804                    })
 805                } else if needs_present {
 806                    handle
 807                        .update(&mut cx, |_, window, _| window.present())
 808                        .log_err();
 809                }
 810
 811                handle
 812                    .update(&mut cx, |_, window, _| {
 813                        window.complete_frame();
 814                    })
 815                    .log_err();
 816            }
 817        }));
 818        platform_window.on_resize(Box::new({
 819            let mut cx = cx.to_async();
 820            move |_, _| {
 821                handle
 822                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
 823                    .log_err();
 824            }
 825        }));
 826        platform_window.on_moved(Box::new({
 827            let mut cx = cx.to_async();
 828            move || {
 829                handle
 830                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
 831                    .log_err();
 832            }
 833        }));
 834        platform_window.on_appearance_changed(Box::new({
 835            let mut cx = cx.to_async();
 836            move || {
 837                handle
 838                    .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
 839                    .log_err();
 840            }
 841        }));
 842        platform_window.on_active_status_change(Box::new({
 843            let mut cx = cx.to_async();
 844            move |active| {
 845                handle
 846                    .update(&mut cx, |_, window, cx| {
 847                        window.active.set(active);
 848                        window
 849                            .activation_observers
 850                            .clone()
 851                            .retain(&(), |callback| callback(window, cx));
 852                        window.refresh();
 853                    })
 854                    .log_err();
 855            }
 856        }));
 857        platform_window.on_hover_status_change(Box::new({
 858            let mut cx = cx.to_async();
 859            move |active| {
 860                handle
 861                    .update(&mut cx, |_, window, _| {
 862                        window.hovered.set(active);
 863                        window.refresh();
 864                    })
 865                    .log_err();
 866            }
 867        }));
 868        platform_window.on_input({
 869            let mut cx = cx.to_async();
 870            Box::new(move |event| {
 871                handle
 872                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
 873                    .log_err()
 874                    .unwrap_or(DispatchEventResult::default())
 875            })
 876        });
 877
 878        if let Some(app_id) = app_id {
 879            platform_window.set_app_id(&app_id);
 880        }
 881
 882        platform_window.map_window().unwrap();
 883
 884        Ok(Window {
 885            handle,
 886            invalidator,
 887            removed: false,
 888            platform_window,
 889            display_id,
 890            sprite_atlas,
 891            text_system,
 892            rem_size: px(16.),
 893            rem_size_override_stack: SmallVec::new(),
 894            viewport_size: content_size,
 895            layout_engine: Some(TaffyLayoutEngine::new()),
 896            root: None,
 897            element_id_stack: SmallVec::default(),
 898            text_style_stack: Vec::new(),
 899            rendered_entity_stack: Vec::new(),
 900            element_offset_stack: Vec::new(),
 901            content_mask_stack: Vec::new(),
 902            element_opacity: None,
 903            requested_autoscroll: None,
 904            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 905            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 906            next_frame_callbacks,
 907            next_hitbox_id: HitboxId::default(),
 908            next_tooltip_id: TooltipId::default(),
 909            tooltip_bounds: None,
 910            dirty_views: FxHashSet::default(),
 911            focus_listeners: SubscriberSet::new(),
 912            focus_lost_listeners: SubscriberSet::new(),
 913            default_prevented: true,
 914            mouse_position,
 915            mouse_hit_test: HitTest::default(),
 916            modifiers,
 917            scale_factor,
 918            bounds_observers: SubscriberSet::new(),
 919            appearance,
 920            appearance_observers: SubscriberSet::new(),
 921            active,
 922            hovered,
 923            needs_present,
 924            last_input_timestamp,
 925            refreshing: false,
 926            activation_observers: SubscriberSet::new(),
 927            focus: None,
 928            focus_enabled: true,
 929            pending_input: None,
 930            pending_modifier: ModifierState::default(),
 931            pending_input_observers: SubscriberSet::new(),
 932            prompt: None,
 933        })
 934    }
 935
 936    pub(crate) fn new_focus_listener(
 937        &self,
 938        value: AnyWindowFocusListener,
 939    ) -> (Subscription, impl FnOnce()) {
 940        self.focus_listeners.insert((), value)
 941    }
 942}
 943
 944#[derive(Clone, Debug, Default, PartialEq, Eq)]
 945pub(crate) struct DispatchEventResult {
 946    pub propagate: bool,
 947    pub default_prevented: bool,
 948}
 949
 950/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 951/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 952/// to leave room to support more complex shapes in the future.
 953#[derive(Clone, Debug, Default, PartialEq, Eq)]
 954#[repr(C)]
 955pub struct ContentMask<P: Clone + Default + Debug> {
 956    /// The bounds
 957    pub bounds: Bounds<P>,
 958}
 959
 960impl ContentMask<Pixels> {
 961    /// Scale the content mask's pixel units by the given scaling factor.
 962    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 963        ContentMask {
 964            bounds: self.bounds.scale(factor),
 965        }
 966    }
 967
 968    /// Intersect the content mask with the given content mask.
 969    pub fn intersect(&self, other: &Self) -> Self {
 970        let bounds = self.bounds.intersect(&other.bounds);
 971        ContentMask { bounds }
 972    }
 973}
 974
 975impl Window {
 976    fn mark_view_dirty(&mut self, view_id: EntityId) {
 977        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
 978        // should already be dirty.
 979        for view_id in self
 980            .rendered_frame
 981            .dispatch_tree
 982            .view_path(view_id)
 983            .into_iter()
 984            .rev()
 985        {
 986            if !self.dirty_views.insert(view_id) {
 987                break;
 988            }
 989        }
 990    }
 991
 992    /// Registers a callback to be invoked when the window appearance changes.
 993    pub fn observe_window_appearance(
 994        &self,
 995        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
 996    ) -> Subscription {
 997        let (subscription, activate) = self.appearance_observers.insert(
 998            (),
 999            Box::new(move |window, cx| {
1000                callback(window, cx);
1001                true
1002            }),
1003        );
1004        activate();
1005        subscription
1006    }
1007
1008    /// Replaces the root entity of the window with a new one.
1009    pub fn replace_root<E>(
1010        &mut self,
1011        cx: &mut App,
1012        build_view: impl FnOnce(&mut Window, &mut Context<'_, E>) -> E,
1013    ) -> Entity<E>
1014    where
1015        E: 'static + Render,
1016    {
1017        let view = cx.new(|cx| build_view(self, cx));
1018        self.root = Some(view.clone().into());
1019        self.refresh();
1020        view
1021    }
1022
1023    /// Returns the root entity of the window, if it has one.
1024    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1025    where
1026        E: 'static + Render,
1027    {
1028        self.root
1029            .as_ref()
1030            .map(|view| view.clone().downcast::<E>().ok())
1031    }
1032
1033    /// Obtain a handle to the window that belongs to this context.
1034    pub fn window_handle(&self) -> AnyWindowHandle {
1035        self.handle
1036    }
1037
1038    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1039    pub fn refresh(&mut self) {
1040        if self.invalidator.not_drawing() {
1041            self.refreshing = true;
1042            self.invalidator.set_dirty(true);
1043        }
1044    }
1045
1046    /// Close this window.
1047    pub fn remove_window(&mut self) {
1048        self.removed = true;
1049    }
1050
1051    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1052    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1053        self.focus
1054            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1055    }
1056
1057    /// Move focus to the element associated with the given [`FocusHandle`].
1058    pub fn focus(&mut self, handle: &FocusHandle) {
1059        if !self.focus_enabled || self.focus == Some(handle.id) {
1060            return;
1061        }
1062
1063        self.focus = Some(handle.id);
1064        self.clear_pending_keystrokes();
1065        self.refresh();
1066    }
1067
1068    /// Remove focus from all elements within this context's window.
1069    pub fn blur(&mut self) {
1070        if !self.focus_enabled {
1071            return;
1072        }
1073
1074        self.focus = None;
1075        self.refresh();
1076    }
1077
1078    /// Blur the window and don't allow anything in it to be focused again.
1079    pub fn disable_focus(&mut self) {
1080        self.blur();
1081        self.focus_enabled = false;
1082    }
1083
1084    /// Accessor for the text system.
1085    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1086        &self.text_system
1087    }
1088
1089    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1090    pub fn text_style(&self) -> TextStyle {
1091        let mut style = TextStyle::default();
1092        for refinement in &self.text_style_stack {
1093            style.refine(refinement);
1094        }
1095        style
1096    }
1097
1098    /// Check if the platform window is maximized
1099    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1100    pub fn is_maximized(&self) -> bool {
1101        self.platform_window.is_maximized()
1102    }
1103
1104    /// request a certain window decoration (Wayland)
1105    pub fn request_decorations(&self, decorations: WindowDecorations) {
1106        self.platform_window.request_decorations(decorations);
1107    }
1108
1109    /// Start a window resize operation (Wayland)
1110    pub fn start_window_resize(&self, edge: ResizeEdge) {
1111        self.platform_window.start_window_resize(edge);
1112    }
1113
1114    /// Return the `WindowBounds` to indicate that how a window should be opened
1115    /// after it has been closed
1116    pub fn window_bounds(&self) -> WindowBounds {
1117        self.platform_window.window_bounds()
1118    }
1119
1120    /// Return the `WindowBounds` excluding insets (Wayland and X11)
1121    pub fn inner_window_bounds(&self) -> WindowBounds {
1122        self.platform_window.inner_window_bounds()
1123    }
1124
1125    /// Dispatch the given action on the currently focused element.
1126    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1127        let focus_handle = self.focused(cx);
1128
1129        let window = self.handle;
1130        cx.defer(move |cx| {
1131            window
1132                .update(cx, |_, window, cx| {
1133                    let node_id = focus_handle
1134                        .and_then(|handle| {
1135                            window
1136                                .rendered_frame
1137                                .dispatch_tree
1138                                .focusable_node_id(handle.id)
1139                        })
1140                        .unwrap_or_else(|| window.rendered_frame.dispatch_tree.root_node_id());
1141
1142                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1143                })
1144                .log_err();
1145        })
1146    }
1147
1148    pub(crate) fn dispatch_keystroke_observers(
1149        &mut self,
1150        event: &dyn Any,
1151        action: Option<Box<dyn Action>>,
1152        cx: &mut App,
1153    ) {
1154        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1155            return;
1156        };
1157
1158        cx.keystroke_observers.clone().retain(&(), move |callback| {
1159            (callback)(
1160                &KeystrokeEvent {
1161                    keystroke: key_down_event.keystroke.clone(),
1162                    action: action.as_ref().map(|action| action.boxed_clone()),
1163                },
1164                self,
1165                cx,
1166            )
1167        });
1168    }
1169
1170    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1171    /// that are currently on the stack to be returned to the app.
1172    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1173        let handle = self.handle;
1174        cx.defer(move |cx| {
1175            handle.update(cx, |_, window, cx| f(window, cx)).ok();
1176        });
1177    }
1178
1179    /// Subscribe to events emitted by a entity.
1180    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1181    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1182    pub fn observe<T: 'static>(
1183        &mut self,
1184        observed: &Entity<T>,
1185        cx: &mut App,
1186        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1187    ) -> Subscription {
1188        let entity_id = observed.entity_id();
1189        let observed = observed.downgrade();
1190        let window_handle = self.handle;
1191        cx.new_observer(
1192            entity_id,
1193            Box::new(move |cx| {
1194                window_handle
1195                    .update(cx, |_, window, cx| {
1196                        if let Some(handle) = observed.upgrade() {
1197                            on_notify(handle, window, cx);
1198                            true
1199                        } else {
1200                            false
1201                        }
1202                    })
1203                    .unwrap_or(false)
1204            }),
1205        )
1206    }
1207
1208    /// Subscribe to events emitted by a entity.
1209    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1210    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1211    pub fn subscribe<Emitter, Evt>(
1212        &mut self,
1213        entity: &Entity<Emitter>,
1214        cx: &mut App,
1215        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1216    ) -> Subscription
1217    where
1218        Emitter: EventEmitter<Evt>,
1219        Evt: 'static,
1220    {
1221        let entity_id = entity.entity_id();
1222        let entity = entity.downgrade();
1223        let window_handle = self.handle;
1224        cx.new_subscription(
1225            entity_id,
1226            (
1227                TypeId::of::<Evt>(),
1228                Box::new(move |event, cx| {
1229                    window_handle
1230                        .update(cx, |_, window, cx| {
1231                            if let Some(handle) = Entity::<Emitter>::upgrade_from(&entity) {
1232                                let event = event.downcast_ref().expect("invalid event type");
1233                                on_event(handle, event, window, cx);
1234                                true
1235                            } else {
1236                                false
1237                            }
1238                        })
1239                        .unwrap_or(false)
1240                }),
1241            ),
1242        )
1243    }
1244
1245    /// Register a callback to be invoked when the given `Entity` is released.
1246    pub fn observe_release<T>(
1247        &self,
1248        entity: &Entity<T>,
1249        cx: &mut App,
1250        mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1251    ) -> Subscription
1252    where
1253        T: 'static,
1254    {
1255        let entity_id = entity.entity_id();
1256        let window_handle = self.handle;
1257        let (subscription, activate) = cx.release_listeners.insert(
1258            entity_id,
1259            Box::new(move |entity, cx| {
1260                let entity = entity.downcast_mut().expect("invalid entity type");
1261                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1262            }),
1263        );
1264        activate();
1265        subscription
1266    }
1267
1268    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1269    /// await points in async code.
1270    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1271        AsyncWindowContext::new_context(cx.to_async(), self.handle)
1272    }
1273
1274    /// Schedule the given closure to be run directly after the current frame is rendered.
1275    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1276        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1277    }
1278
1279    /// Schedule a frame to be drawn on the next animation frame.
1280    ///
1281    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
1282    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
1283    ///
1284    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
1285    pub fn request_animation_frame(&self) {
1286        let entity = self.current_view();
1287        self.on_next_frame(move |_, cx| cx.notify(entity));
1288    }
1289
1290    /// Spawn the future returned by the given closure on the application thread pool.
1291    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1292    /// use within your future.
1293    #[track_caller]
1294    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
1295    where
1296        R: 'static,
1297        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1298    {
1299        let handle = self.handle;
1300        cx.spawn(async move |app| {
1301            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1302            f(&mut async_window_cx).await
1303        })
1304    }
1305
1306    fn bounds_changed(&mut self, cx: &mut App) {
1307        self.scale_factor = self.platform_window.scale_factor();
1308        self.viewport_size = self.platform_window.content_size();
1309        self.display_id = self.platform_window.display().map(|display| display.id());
1310
1311        self.refresh();
1312
1313        self.bounds_observers
1314            .clone()
1315            .retain(&(), |callback| callback(self, cx));
1316    }
1317
1318    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1319    pub fn bounds(&self) -> Bounds<Pixels> {
1320        self.platform_window.bounds()
1321    }
1322
1323    /// Returns whether or not the window is currently fullscreen
1324    pub fn is_fullscreen(&self) -> bool {
1325        self.platform_window.is_fullscreen()
1326    }
1327
1328    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1329        self.appearance = self.platform_window.appearance();
1330
1331        self.appearance_observers
1332            .clone()
1333            .retain(&(), |callback| callback(self, cx));
1334    }
1335
1336    /// Returns the appearance of the current window.
1337    pub fn appearance(&self) -> WindowAppearance {
1338        self.appearance
1339    }
1340
1341    /// Returns the size of the drawable area within the window.
1342    pub fn viewport_size(&self) -> Size<Pixels> {
1343        self.viewport_size
1344    }
1345
1346    /// Returns whether this window is focused by the operating system (receiving key events).
1347    pub fn is_window_active(&self) -> bool {
1348        self.active.get()
1349    }
1350
1351    /// Returns whether this window is considered to be the window
1352    /// that currently owns the mouse cursor.
1353    /// On mac, this is equivalent to `is_window_active`.
1354    pub fn is_window_hovered(&self) -> bool {
1355        if cfg!(any(
1356            target_os = "windows",
1357            target_os = "linux",
1358            target_os = "freebsd"
1359        )) {
1360            self.hovered.get()
1361        } else {
1362            self.is_window_active()
1363        }
1364    }
1365
1366    /// Toggle zoom on the window.
1367    pub fn zoom_window(&self) {
1368        self.platform_window.zoom();
1369    }
1370
1371    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1372    pub fn show_window_menu(&self, position: Point<Pixels>) {
1373        self.platform_window.show_window_menu(position)
1374    }
1375
1376    /// Tells the compositor to take control of window movement (Wayland and X11)
1377    ///
1378    /// Events may not be received during a move operation.
1379    pub fn start_window_move(&self) {
1380        self.platform_window.start_window_move()
1381    }
1382
1383    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
1384    pub fn set_client_inset(&self, inset: Pixels) {
1385        self.platform_window.set_client_inset(inset);
1386    }
1387
1388    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1389    pub fn window_decorations(&self) -> Decorations {
1390        self.platform_window.window_decorations()
1391    }
1392
1393    /// Returns which window controls are currently visible (Wayland)
1394    pub fn window_controls(&self) -> WindowControls {
1395        self.platform_window.window_controls()
1396    }
1397
1398    /// Updates the window's title at the platform level.
1399    pub fn set_window_title(&mut self, title: &str) {
1400        self.platform_window.set_title(title);
1401    }
1402
1403    /// Sets the application identifier.
1404    pub fn set_app_id(&mut self, app_id: &str) {
1405        self.platform_window.set_app_id(app_id);
1406    }
1407
1408    /// Sets the window background appearance.
1409    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1410        self.platform_window
1411            .set_background_appearance(background_appearance);
1412    }
1413
1414    /// Mark the window as dirty at the platform level.
1415    pub fn set_window_edited(&mut self, edited: bool) {
1416        self.platform_window.set_edited(edited);
1417    }
1418
1419    /// Determine the display on which the window is visible.
1420    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
1421        cx.platform
1422            .displays()
1423            .into_iter()
1424            .find(|display| Some(display.id()) == self.display_id)
1425    }
1426
1427    /// Show the platform character palette.
1428    pub fn show_character_palette(&self) {
1429        self.platform_window.show_character_palette();
1430    }
1431
1432    /// The scale factor of the display associated with the window. For example, it could
1433    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1434    /// be rendered as two pixels on screen.
1435    pub fn scale_factor(&self) -> f32 {
1436        self.scale_factor
1437    }
1438
1439    /// The size of an em for the base font of the application. Adjusting this value allows the
1440    /// UI to scale, just like zooming a web page.
1441    pub fn rem_size(&self) -> Pixels {
1442        self.rem_size_override_stack
1443            .last()
1444            .copied()
1445            .unwrap_or(self.rem_size)
1446    }
1447
1448    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1449    /// UI to scale, just like zooming a web page.
1450    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1451        self.rem_size = rem_size.into();
1452    }
1453
1454    /// Executes the provided function with the specified rem size.
1455    ///
1456    /// This method must only be called as part of element drawing.
1457    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1458    where
1459        F: FnOnce(&mut Self) -> R,
1460    {
1461        self.invalidator.debug_assert_paint_or_prepaint();
1462
1463        if let Some(rem_size) = rem_size {
1464            self.rem_size_override_stack.push(rem_size.into());
1465            let result = f(self);
1466            self.rem_size_override_stack.pop();
1467            result
1468        } else {
1469            f(self)
1470        }
1471    }
1472
1473    /// The line height associated with the current text style.
1474    pub fn line_height(&self) -> Pixels {
1475        self.text_style().line_height_in_pixels(self.rem_size())
1476    }
1477
1478    /// Call to prevent the default action of an event. Currently only used to prevent
1479    /// parent elements from becoming focused on mouse down.
1480    pub fn prevent_default(&mut self) {
1481        self.default_prevented = true;
1482    }
1483
1484    /// Obtain whether default has been prevented for the event currently being dispatched.
1485    pub fn default_prevented(&self) -> bool {
1486        self.default_prevented
1487    }
1488
1489    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1490    pub fn is_action_available(&self, action: &dyn Action, cx: &mut App) -> bool {
1491        let target = self
1492            .focused(cx)
1493            .and_then(|focused_handle| {
1494                self.rendered_frame
1495                    .dispatch_tree
1496                    .focusable_node_id(focused_handle.id)
1497            })
1498            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
1499        self.rendered_frame
1500            .dispatch_tree
1501            .is_action_available(action, target)
1502    }
1503
1504    /// The position of the mouse relative to the window.
1505    pub fn mouse_position(&self) -> Point<Pixels> {
1506        self.mouse_position
1507    }
1508
1509    /// The current state of the keyboard's modifiers
1510    pub fn modifiers(&self) -> Modifiers {
1511        self.modifiers
1512    }
1513
1514    fn complete_frame(&self) {
1515        self.platform_window.completed_frame();
1516    }
1517
1518    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1519    /// the contents of the new [Scene], use [present].
1520    #[profiling::function]
1521    pub fn draw(&mut self, cx: &mut App) {
1522        self.invalidate_entities();
1523        cx.entities.clear_accessed();
1524        debug_assert!(self.rendered_entity_stack.is_empty());
1525        self.invalidator.set_dirty(false);
1526        self.requested_autoscroll = None;
1527
1528        // Restore the previously-used input handler.
1529        if let Some(input_handler) = self.platform_window.take_input_handler() {
1530            self.rendered_frame.input_handlers.push(Some(input_handler));
1531        }
1532        self.draw_roots(cx);
1533        self.dirty_views.clear();
1534        self.next_frame.window_active = self.active.get();
1535
1536        // Register requested input handler with the platform window.
1537        if let Some(input_handler) = self.next_frame.input_handlers.pop() {
1538            self.platform_window
1539                .set_input_handler(input_handler.unwrap());
1540        }
1541
1542        self.layout_engine.as_mut().unwrap().clear();
1543        self.text_system().finish_frame();
1544        self.next_frame.finish(&mut self.rendered_frame);
1545        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1546            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1547            if percentage >= 80. {
1548                log::warn!("elevated element arena occupation: {}.", percentage);
1549            }
1550            element_arena.clear();
1551        });
1552
1553        self.invalidator.set_phase(DrawPhase::Focus);
1554        let previous_focus_path = self.rendered_frame.focus_path();
1555        let previous_window_active = self.rendered_frame.window_active;
1556        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
1557        self.next_frame.clear();
1558        let current_focus_path = self.rendered_frame.focus_path();
1559        let current_window_active = self.rendered_frame.window_active;
1560
1561        if previous_focus_path != current_focus_path
1562            || previous_window_active != current_window_active
1563        {
1564            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1565                self.focus_lost_listeners
1566                    .clone()
1567                    .retain(&(), |listener| listener(self, cx));
1568            }
1569
1570            let event = WindowFocusEvent {
1571                previous_focus_path: if previous_window_active {
1572                    previous_focus_path
1573                } else {
1574                    Default::default()
1575                },
1576                current_focus_path: if current_window_active {
1577                    current_focus_path
1578                } else {
1579                    Default::default()
1580                },
1581            };
1582            self.focus_listeners
1583                .clone()
1584                .retain(&(), |listener| listener(&event, self, cx));
1585        }
1586
1587        debug_assert!(self.rendered_entity_stack.is_empty());
1588        self.record_entities_accessed(cx);
1589        self.reset_cursor_style(cx);
1590        self.refreshing = false;
1591        self.invalidator.set_phase(DrawPhase::None);
1592        self.needs_present.set(true);
1593    }
1594
1595    fn record_entities_accessed(&mut self, cx: &mut App) {
1596        let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
1597        let mut entities = mem::take(entities_ref.deref_mut());
1598        drop(entities_ref);
1599        let handle = self.handle;
1600        cx.record_entities_accessed(
1601            handle,
1602            // Try moving window invalidator into the Window
1603            self.invalidator.clone(),
1604            &entities,
1605        );
1606        let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
1607        mem::swap(&mut entities, entities_ref.deref_mut());
1608    }
1609
1610    fn invalidate_entities(&mut self) {
1611        let mut views = self.invalidator.take_views();
1612        for entity in views.drain() {
1613            self.mark_view_dirty(entity);
1614        }
1615        self.invalidator.replace_views(views);
1616    }
1617
1618    #[profiling::function]
1619    fn present(&self) {
1620        self.platform_window.draw(&self.rendered_frame.scene);
1621        self.needs_present.set(false);
1622        profiling::finish_frame!();
1623    }
1624
1625    fn draw_roots(&mut self, cx: &mut App) {
1626        self.invalidator.set_phase(DrawPhase::Prepaint);
1627        self.tooltip_bounds.take();
1628
1629        // Layout all root elements.
1630        let mut root_element = self.root.as_ref().unwrap().clone().into_any();
1631        root_element.prepaint_as_root(Point::default(), self.viewport_size.into(), self, cx);
1632
1633        let mut sorted_deferred_draws =
1634            (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1635        sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
1636        self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
1637
1638        let mut prompt_element = None;
1639        let mut active_drag_element = None;
1640        let mut tooltip_element = None;
1641        if let Some(prompt) = self.prompt.take() {
1642            let mut element = prompt.view.any_view().into_any();
1643            element.prepaint_as_root(Point::default(), self.viewport_size.into(), self, cx);
1644            prompt_element = Some(element);
1645            self.prompt = Some(prompt);
1646        } else if let Some(active_drag) = cx.active_drag.take() {
1647            let mut element = active_drag.view.clone().into_any();
1648            let offset = self.mouse_position() - active_drag.cursor_offset;
1649            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
1650            active_drag_element = Some(element);
1651            cx.active_drag = Some(active_drag);
1652        } else {
1653            tooltip_element = self.prepaint_tooltip(cx);
1654        }
1655
1656        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
1657
1658        // Now actually paint the elements.
1659        self.invalidator.set_phase(DrawPhase::Paint);
1660        root_element.paint(self, cx);
1661
1662        self.paint_deferred_draws(&sorted_deferred_draws, cx);
1663
1664        if let Some(mut prompt_element) = prompt_element {
1665            prompt_element.paint(self, cx);
1666        } else if let Some(mut drag_element) = active_drag_element {
1667            drag_element.paint(self, cx);
1668        } else if let Some(mut tooltip_element) = tooltip_element {
1669            tooltip_element.paint(self, cx);
1670        }
1671    }
1672
1673    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
1674        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
1675        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
1676            let Some(Some(tooltip_request)) = self
1677                .next_frame
1678                .tooltip_requests
1679                .get(tooltip_request_index)
1680                .cloned()
1681            else {
1682                log::error!("Unexpectedly absent TooltipRequest");
1683                continue;
1684            };
1685            let mut element = tooltip_request.tooltip.view.clone().into_any();
1686            let mouse_position = tooltip_request.tooltip.mouse_position;
1687            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
1688
1689            let mut tooltip_bounds =
1690                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1691            let window_bounds = Bounds {
1692                origin: Point::default(),
1693                size: self.viewport_size(),
1694            };
1695
1696            if tooltip_bounds.right() > window_bounds.right() {
1697                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1698                if new_x >= Pixels::ZERO {
1699                    tooltip_bounds.origin.x = new_x;
1700                } else {
1701                    tooltip_bounds.origin.x = cmp::max(
1702                        Pixels::ZERO,
1703                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1704                    );
1705                }
1706            }
1707
1708            if tooltip_bounds.bottom() > window_bounds.bottom() {
1709                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
1710                if new_y >= Pixels::ZERO {
1711                    tooltip_bounds.origin.y = new_y;
1712                } else {
1713                    tooltip_bounds.origin.y = cmp::max(
1714                        Pixels::ZERO,
1715                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
1716                    );
1717                }
1718            }
1719
1720            // It's possible for an element to have an active tooltip while not being painted (e.g.
1721            // via the `visible_on_hover` method). Since mouse listeners are not active in this
1722            // case, instead update the tooltip's visibility here.
1723            let is_visible =
1724                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
1725            if !is_visible {
1726                continue;
1727            }
1728
1729            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
1730                element.prepaint(window, cx)
1731            });
1732
1733            self.tooltip_bounds = Some(TooltipBounds {
1734                id: tooltip_request.id,
1735                bounds: tooltip_bounds,
1736            });
1737            return Some(element);
1738        }
1739        None
1740    }
1741
1742    fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
1743        assert_eq!(self.element_id_stack.len(), 0);
1744
1745        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
1746        for deferred_draw_ix in deferred_draw_indices {
1747            let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1748            self.element_id_stack
1749                .clone_from(&deferred_draw.element_id_stack);
1750            self.text_style_stack
1751                .clone_from(&deferred_draw.text_style_stack);
1752            self.next_frame
1753                .dispatch_tree
1754                .set_active_node(deferred_draw.parent_node);
1755
1756            let prepaint_start = self.prepaint_index();
1757            if let Some(element) = deferred_draw.element.as_mut() {
1758                self.with_rendered_view(deferred_draw.current_view, |window| {
1759                    window.with_absolute_element_offset(deferred_draw.absolute_offset, |window| {
1760                        element.prepaint(window, cx)
1761                    });
1762                })
1763            } else {
1764                self.reuse_prepaint(deferred_draw.prepaint_range.clone());
1765            }
1766            let prepaint_end = self.prepaint_index();
1767            deferred_draw.prepaint_range = prepaint_start..prepaint_end;
1768        }
1769        assert_eq!(
1770            self.next_frame.deferred_draws.len(),
1771            0,
1772            "cannot call defer_draw during deferred drawing"
1773        );
1774        self.next_frame.deferred_draws = deferred_draws;
1775        self.element_id_stack.clear();
1776        self.text_style_stack.clear();
1777    }
1778
1779    fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
1780        assert_eq!(self.element_id_stack.len(), 0);
1781
1782        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
1783        for deferred_draw_ix in deferred_draw_indices {
1784            let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1785            self.element_id_stack
1786                .clone_from(&deferred_draw.element_id_stack);
1787            self.next_frame
1788                .dispatch_tree
1789                .set_active_node(deferred_draw.parent_node);
1790
1791            let paint_start = self.paint_index();
1792            if let Some(element) = deferred_draw.element.as_mut() {
1793                self.with_rendered_view(deferred_draw.current_view, |window| {
1794                    element.paint(window, cx);
1795                })
1796            } else {
1797                self.reuse_paint(deferred_draw.paint_range.clone());
1798            }
1799            let paint_end = self.paint_index();
1800            deferred_draw.paint_range = paint_start..paint_end;
1801        }
1802        self.next_frame.deferred_draws = deferred_draws;
1803        self.element_id_stack.clear();
1804    }
1805
1806    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
1807        PrepaintStateIndex {
1808            hitboxes_index: self.next_frame.hitboxes.len(),
1809            tooltips_index: self.next_frame.tooltip_requests.len(),
1810            deferred_draws_index: self.next_frame.deferred_draws.len(),
1811            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
1812            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
1813            line_layout_index: self.text_system.layout_index(),
1814        }
1815    }
1816
1817    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
1818        self.next_frame.hitboxes.extend(
1819            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
1820                .iter()
1821                .cloned(),
1822        );
1823        self.next_frame.tooltip_requests.extend(
1824            self.rendered_frame.tooltip_requests
1825                [range.start.tooltips_index..range.end.tooltips_index]
1826                .iter_mut()
1827                .map(|request| request.take()),
1828        );
1829        self.next_frame.accessed_element_states.extend(
1830            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1831                ..range.end.accessed_element_states_index]
1832                .iter()
1833                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1834        );
1835        self.text_system
1836            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1837
1838        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
1839            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
1840            &mut self.rendered_frame.dispatch_tree,
1841            self.focus,
1842        );
1843
1844        if reused_subtree.contains_focus() {
1845            self.next_frame.focus = self.focus;
1846        }
1847
1848        self.next_frame.deferred_draws.extend(
1849            self.rendered_frame.deferred_draws
1850                [range.start.deferred_draws_index..range.end.deferred_draws_index]
1851                .iter()
1852                .map(|deferred_draw| DeferredDraw {
1853                    current_view: deferred_draw.current_view,
1854                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
1855                    element_id_stack: deferred_draw.element_id_stack.clone(),
1856                    text_style_stack: deferred_draw.text_style_stack.clone(),
1857                    priority: deferred_draw.priority,
1858                    element: None,
1859                    absolute_offset: deferred_draw.absolute_offset,
1860                    prepaint_range: deferred_draw.prepaint_range.clone(),
1861                    paint_range: deferred_draw.paint_range.clone(),
1862                }),
1863        );
1864    }
1865
1866    pub(crate) fn paint_index(&self) -> PaintIndex {
1867        PaintIndex {
1868            scene_index: self.next_frame.scene.len(),
1869            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
1870            input_handlers_index: self.next_frame.input_handlers.len(),
1871            cursor_styles_index: self.next_frame.cursor_styles.len(),
1872            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
1873            line_layout_index: self.text_system.layout_index(),
1874        }
1875    }
1876
1877    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
1878        self.next_frame.cursor_styles.extend(
1879            self.rendered_frame.cursor_styles
1880                [range.start.cursor_styles_index..range.end.cursor_styles_index]
1881                .iter()
1882                .cloned(),
1883        );
1884        self.next_frame.input_handlers.extend(
1885            self.rendered_frame.input_handlers
1886                [range.start.input_handlers_index..range.end.input_handlers_index]
1887                .iter_mut()
1888                .map(|handler| handler.take()),
1889        );
1890        self.next_frame.mouse_listeners.extend(
1891            self.rendered_frame.mouse_listeners
1892                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
1893                .iter_mut()
1894                .map(|listener| listener.take()),
1895        );
1896        self.next_frame.accessed_element_states.extend(
1897            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1898                ..range.end.accessed_element_states_index]
1899                .iter()
1900                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1901        );
1902
1903        self.text_system
1904            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1905        self.next_frame.scene.replay(
1906            range.start.scene_index..range.end.scene_index,
1907            &self.rendered_frame.scene,
1908        );
1909    }
1910
1911    /// Push a text style onto the stack, and call a function with that style active.
1912    /// Use [`Window::text_style`] to get the current, combined text style. This method
1913    /// should only be called as part of element drawing.
1914    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
1915    where
1916        F: FnOnce(&mut Self) -> R,
1917    {
1918        self.invalidator.debug_assert_paint_or_prepaint();
1919        if let Some(style) = style {
1920            self.text_style_stack.push(style);
1921            let result = f(self);
1922            self.text_style_stack.pop();
1923            result
1924        } else {
1925            f(self)
1926        }
1927    }
1928
1929    /// Updates the cursor style at the platform level. This method should only be called
1930    /// during the prepaint phase of element drawing.
1931    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
1932        self.invalidator.debug_assert_paint();
1933        self.next_frame.cursor_styles.push(CursorStyleRequest {
1934            hitbox_id: hitbox.id,
1935            style,
1936        });
1937    }
1938
1939    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
1940    /// during the paint phase of element drawing.
1941    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
1942        self.invalidator.debug_assert_prepaint();
1943        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
1944        self.next_frame
1945            .tooltip_requests
1946            .push(Some(TooltipRequest { id, tooltip }));
1947        id
1948    }
1949
1950    /// Invoke the given function with the given content mask after intersecting it
1951    /// with the current mask. This method should only be called during element drawing.
1952    pub fn with_content_mask<R>(
1953        &mut self,
1954        mask: Option<ContentMask<Pixels>>,
1955        f: impl FnOnce(&mut Self) -> R,
1956    ) -> R {
1957        self.invalidator.debug_assert_paint_or_prepaint();
1958        if let Some(mask) = mask {
1959            let mask = mask.intersect(&self.content_mask());
1960            self.content_mask_stack.push(mask);
1961            let result = f(self);
1962            self.content_mask_stack.pop();
1963            result
1964        } else {
1965            f(self)
1966        }
1967    }
1968
1969    /// Updates the global element offset relative to the current offset. This is used to implement
1970    /// scrolling. This method should only be called during the prepaint phase of element drawing.
1971    pub fn with_element_offset<R>(
1972        &mut self,
1973        offset: Point<Pixels>,
1974        f: impl FnOnce(&mut Self) -> R,
1975    ) -> R {
1976        self.invalidator.debug_assert_prepaint();
1977
1978        if offset.is_zero() {
1979            return f(self);
1980        };
1981
1982        let abs_offset = self.element_offset() + offset;
1983        self.with_absolute_element_offset(abs_offset, f)
1984    }
1985
1986    /// Updates the global element offset based on the given offset. This is used to implement
1987    /// drag handles and other manual painting of elements. This method should only be called during
1988    /// the prepaint phase of element drawing.
1989    pub fn with_absolute_element_offset<R>(
1990        &mut self,
1991        offset: Point<Pixels>,
1992        f: impl FnOnce(&mut Self) -> R,
1993    ) -> R {
1994        self.invalidator.debug_assert_prepaint();
1995        self.element_offset_stack.push(offset);
1996        let result = f(self);
1997        self.element_offset_stack.pop();
1998        result
1999    }
2000
2001    pub(crate) fn with_element_opacity<R>(
2002        &mut self,
2003        opacity: Option<f32>,
2004        f: impl FnOnce(&mut Self) -> R,
2005    ) -> R {
2006        if opacity.is_none() {
2007            return f(self);
2008        }
2009
2010        self.invalidator.debug_assert_paint_or_prepaint();
2011        self.element_opacity = opacity;
2012        let result = f(self);
2013        self.element_opacity = None;
2014        result
2015    }
2016
2017    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2018    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2019    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2020    /// element offset and prepaint again. See [`List`] for an example. This method should only be
2021    /// called during the prepaint phase of element drawing.
2022    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2023        self.invalidator.debug_assert_prepaint();
2024        let index = self.prepaint_index();
2025        let result = f(self);
2026        if result.is_err() {
2027            self.next_frame.hitboxes.truncate(index.hitboxes_index);
2028            self.next_frame
2029                .tooltip_requests
2030                .truncate(index.tooltips_index);
2031            self.next_frame
2032                .deferred_draws
2033                .truncate(index.deferred_draws_index);
2034            self.next_frame
2035                .dispatch_tree
2036                .truncate(index.dispatch_tree_index);
2037            self.next_frame
2038                .accessed_element_states
2039                .truncate(index.accessed_element_states_index);
2040            self.text_system.truncate_layouts(index.line_layout_index);
2041        }
2042        result
2043    }
2044
2045    /// When you call this method during [`prepaint`], containing elements will attempt to
2046    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2047    /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
2048    /// that supports this method being called on the elements it contains. This method should only be
2049    /// called during the prepaint phase of element drawing.
2050    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2051        self.invalidator.debug_assert_prepaint();
2052        self.requested_autoscroll = Some(bounds);
2053    }
2054
2055    /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
2056    /// described in [`request_autoscroll`].
2057    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2058        self.invalidator.debug_assert_prepaint();
2059        self.requested_autoscroll.take()
2060    }
2061
2062    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2063    /// Your view will be re-drawn once the asset has finished loading.
2064    ///
2065    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2066    /// time.
2067    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2068        let (task, is_first) = cx.fetch_asset::<A>(source);
2069        task.clone().now_or_never().or_else(|| {
2070            if is_first {
2071                let entity = self.current_view();
2072                self.spawn(cx, {
2073                    let task = task.clone();
2074                    async move |cx| {
2075                        task.await;
2076
2077                        cx.on_next_frame(move |_, cx| {
2078                            cx.notify(entity);
2079                        });
2080                    }
2081                })
2082                .detach();
2083            }
2084
2085            None
2086        })
2087    }
2088    /// Obtain the current element offset. This method should only be called during the
2089    /// prepaint phase of element drawing.
2090    pub fn element_offset(&self) -> Point<Pixels> {
2091        self.invalidator.debug_assert_prepaint();
2092        self.element_offset_stack
2093            .last()
2094            .copied()
2095            .unwrap_or_default()
2096    }
2097
2098    /// Obtain the current element opacity. This method should only be called during the
2099    /// prepaint phase of element drawing.
2100    pub(crate) fn element_opacity(&self) -> f32 {
2101        self.invalidator.debug_assert_paint_or_prepaint();
2102        self.element_opacity.unwrap_or(1.0)
2103    }
2104
2105    /// Obtain the current content mask. This method should only be called during element drawing.
2106    pub fn content_mask(&self) -> ContentMask<Pixels> {
2107        self.invalidator.debug_assert_paint_or_prepaint();
2108        self.content_mask_stack
2109            .last()
2110            .cloned()
2111            .unwrap_or_else(|| ContentMask {
2112                bounds: Bounds {
2113                    origin: Point::default(),
2114                    size: self.viewport_size,
2115                },
2116            })
2117    }
2118
2119    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2120    /// This can be used within a custom element to distinguish multiple sets of child elements.
2121    pub fn with_element_namespace<R>(
2122        &mut self,
2123        element_id: impl Into<ElementId>,
2124        f: impl FnOnce(&mut Self) -> R,
2125    ) -> R {
2126        self.element_id_stack.push(element_id.into());
2127        let result = f(self);
2128        self.element_id_stack.pop();
2129        result
2130    }
2131
2132    /// Updates or initializes state for an element with the given id that lives across multiple
2133    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2134    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2135    /// when drawing the next frame. This method should only be called as part of element drawing.
2136    pub fn with_element_state<S, R>(
2137        &mut self,
2138        global_id: &GlobalElementId,
2139        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2140    ) -> R
2141    where
2142        S: 'static,
2143    {
2144        self.invalidator.debug_assert_paint_or_prepaint();
2145
2146        let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
2147        self.next_frame
2148            .accessed_element_states
2149            .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2150
2151        if let Some(any) = self
2152            .next_frame
2153            .element_states
2154            .remove(&key)
2155            .or_else(|| self.rendered_frame.element_states.remove(&key))
2156        {
2157            let ElementStateBox {
2158                inner,
2159                #[cfg(debug_assertions)]
2160                type_name,
2161            } = any;
2162            // Using the extra inner option to avoid needing to reallocate a new box.
2163            let mut state_box = inner
2164                .downcast::<Option<S>>()
2165                .map_err(|_| {
2166                    #[cfg(debug_assertions)]
2167                    {
2168                        anyhow::anyhow!(
2169                            "invalid element state type for id, requested {:?}, actual: {:?}",
2170                            std::any::type_name::<S>(),
2171                            type_name
2172                        )
2173                    }
2174
2175                    #[cfg(not(debug_assertions))]
2176                    {
2177                        anyhow::anyhow!(
2178                            "invalid element state type for id, requested {:?}",
2179                            std::any::type_name::<S>(),
2180                        )
2181                    }
2182                })
2183                .unwrap();
2184
2185            let state = state_box.take().expect(
2186                "reentrant call to with_element_state for the same state type and element id",
2187            );
2188            let (result, state) = f(Some(state), self);
2189            state_box.replace(state);
2190            self.next_frame.element_states.insert(
2191                key,
2192                ElementStateBox {
2193                    inner: state_box,
2194                    #[cfg(debug_assertions)]
2195                    type_name,
2196                },
2197            );
2198            result
2199        } else {
2200            let (result, state) = f(None, self);
2201            self.next_frame.element_states.insert(
2202                key,
2203                ElementStateBox {
2204                    inner: Box::new(Some(state)),
2205                    #[cfg(debug_assertions)]
2206                    type_name: std::any::type_name::<S>(),
2207                },
2208            );
2209            result
2210        }
2211    }
2212
2213    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2214    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2215    /// when the element is guaranteed to have an id.
2216    ///
2217    /// The first option means 'no ID provided'
2218    /// The second option means 'not yet initialized'
2219    pub fn with_optional_element_state<S, R>(
2220        &mut self,
2221        global_id: Option<&GlobalElementId>,
2222        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2223    ) -> R
2224    where
2225        S: 'static,
2226    {
2227        self.invalidator.debug_assert_paint_or_prepaint();
2228
2229        if let Some(global_id) = global_id {
2230            self.with_element_state(global_id, |state, cx| {
2231                let (result, state) = f(Some(state), cx);
2232                let state =
2233                    state.expect("you must return some state when you pass some element id");
2234                (result, state)
2235            })
2236        } else {
2237            let (result, state) = f(None, self);
2238            debug_assert!(
2239                state.is_none(),
2240                "you must not return an element state when passing None for the global id"
2241            );
2242            result
2243        }
2244    }
2245
2246    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2247    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2248    /// with higher values being drawn on top.
2249    ///
2250    /// This method should only be called as part of the prepaint phase of element drawing.
2251    pub fn defer_draw(
2252        &mut self,
2253        element: AnyElement,
2254        absolute_offset: Point<Pixels>,
2255        priority: usize,
2256    ) {
2257        self.invalidator.debug_assert_prepaint();
2258        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
2259        self.next_frame.deferred_draws.push(DeferredDraw {
2260            current_view: self.current_view(),
2261            parent_node,
2262            element_id_stack: self.element_id_stack.clone(),
2263            text_style_stack: self.text_style_stack.clone(),
2264            priority,
2265            element: Some(element),
2266            absolute_offset,
2267            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2268            paint_range: PaintIndex::default()..PaintIndex::default(),
2269        });
2270    }
2271
2272    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2273    /// of geometry that are non-overlapping and have the same draw order. This is typically used
2274    /// for performance reasons.
2275    ///
2276    /// This method should only be called as part of the paint phase of element drawing.
2277    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2278        self.invalidator.debug_assert_paint();
2279
2280        let scale_factor = self.scale_factor();
2281        let content_mask = self.content_mask();
2282        let clipped_bounds = bounds.intersect(&content_mask.bounds);
2283        if !clipped_bounds.is_empty() {
2284            self.next_frame
2285                .scene
2286                .push_layer(clipped_bounds.scale(scale_factor));
2287        }
2288
2289        let result = f(self);
2290
2291        if !clipped_bounds.is_empty() {
2292            self.next_frame.scene.pop_layer();
2293        }
2294
2295        result
2296    }
2297
2298    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2299    ///
2300    /// This method should only be called as part of the paint phase of element drawing.
2301    pub fn paint_shadows(
2302        &mut self,
2303        bounds: Bounds<Pixels>,
2304        corner_radii: Corners<Pixels>,
2305        shadows: &[BoxShadow],
2306    ) {
2307        self.invalidator.debug_assert_paint();
2308
2309        let scale_factor = self.scale_factor();
2310        let content_mask = self.content_mask();
2311        let opacity = self.element_opacity();
2312        for shadow in shadows {
2313            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
2314            self.next_frame.scene.insert_primitive(Shadow {
2315                order: 0,
2316                blur_radius: shadow.blur_radius.scale(scale_factor),
2317                bounds: shadow_bounds.scale(scale_factor),
2318                content_mask: content_mask.scale(scale_factor),
2319                corner_radii: corner_radii.scale(scale_factor),
2320                color: shadow.color.opacity(opacity),
2321            });
2322        }
2323    }
2324
2325    /// Paint one or more quads into the scene for the next frame at the current stacking context.
2326    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2327    /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2328    ///
2329    /// This method should only be called as part of the paint phase of element drawing.
2330    pub fn paint_quad(&mut self, quad: PaintQuad) {
2331        self.invalidator.debug_assert_paint();
2332
2333        let scale_factor = self.scale_factor();
2334        let content_mask = self.content_mask();
2335        let opacity = self.element_opacity();
2336        self.next_frame.scene.insert_primitive(Quad {
2337            order: 0,
2338            pad: 0,
2339            bounds: quad.bounds.scale(scale_factor),
2340            content_mask: content_mask.scale(scale_factor),
2341            background: quad.background.opacity(opacity),
2342            border_color: quad.border_color.opacity(opacity),
2343            corner_radii: quad.corner_radii.scale(scale_factor),
2344            border_widths: quad.border_widths.scale(scale_factor),
2345        });
2346    }
2347
2348    /// Paint the given `Path` into the scene for the next frame at the current z-index.
2349    ///
2350    /// This method should only be called as part of the paint phase of element drawing.
2351    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
2352        self.invalidator.debug_assert_paint();
2353
2354        let scale_factor = self.scale_factor();
2355        let content_mask = self.content_mask();
2356        let opacity = self.element_opacity();
2357        path.content_mask = content_mask;
2358        let color: Background = color.into();
2359        path.color = color.opacity(opacity);
2360        self.next_frame
2361            .scene
2362            .insert_primitive(path.scale(scale_factor));
2363    }
2364
2365    /// Paint an underline into the scene for the next frame at the current z-index.
2366    ///
2367    /// This method should only be called as part of the paint phase of element drawing.
2368    pub fn paint_underline(
2369        &mut self,
2370        origin: Point<Pixels>,
2371        width: Pixels,
2372        style: &UnderlineStyle,
2373    ) {
2374        self.invalidator.debug_assert_paint();
2375
2376        let scale_factor = self.scale_factor();
2377        let height = if style.wavy {
2378            style.thickness * 3.
2379        } else {
2380            style.thickness
2381        };
2382        let bounds = Bounds {
2383            origin,
2384            size: size(width, height),
2385        };
2386        let content_mask = self.content_mask();
2387        let element_opacity = self.element_opacity();
2388
2389        self.next_frame.scene.insert_primitive(Underline {
2390            order: 0,
2391            pad: 0,
2392            bounds: bounds.scale(scale_factor),
2393            content_mask: content_mask.scale(scale_factor),
2394            color: style.color.unwrap_or_default().opacity(element_opacity),
2395            thickness: style.thickness.scale(scale_factor),
2396            wavy: style.wavy,
2397        });
2398    }
2399
2400    /// Paint a strikethrough into the scene for the next frame at the current z-index.
2401    ///
2402    /// This method should only be called as part of the paint phase of element drawing.
2403    pub fn paint_strikethrough(
2404        &mut self,
2405        origin: Point<Pixels>,
2406        width: Pixels,
2407        style: &StrikethroughStyle,
2408    ) {
2409        self.invalidator.debug_assert_paint();
2410
2411        let scale_factor = self.scale_factor();
2412        let height = style.thickness;
2413        let bounds = Bounds {
2414            origin,
2415            size: size(width, height),
2416        };
2417        let content_mask = self.content_mask();
2418        let opacity = self.element_opacity();
2419
2420        self.next_frame.scene.insert_primitive(Underline {
2421            order: 0,
2422            pad: 0,
2423            bounds: bounds.scale(scale_factor),
2424            content_mask: content_mask.scale(scale_factor),
2425            thickness: style.thickness.scale(scale_factor),
2426            color: style.color.unwrap_or_default().opacity(opacity),
2427            wavy: false,
2428        });
2429    }
2430
2431    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2432    ///
2433    /// The y component of the origin is the baseline of the glyph.
2434    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2435    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2436    /// This method is only useful if you need to paint a single glyph that has already been shaped.
2437    ///
2438    /// This method should only be called as part of the paint phase of element drawing.
2439    pub fn paint_glyph(
2440        &mut self,
2441        origin: Point<Pixels>,
2442        font_id: FontId,
2443        glyph_id: GlyphId,
2444        font_size: Pixels,
2445        color: Hsla,
2446    ) -> Result<()> {
2447        self.invalidator.debug_assert_paint();
2448
2449        let element_opacity = self.element_opacity();
2450        let scale_factor = self.scale_factor();
2451        let glyph_origin = origin.scale(scale_factor);
2452        let subpixel_variant = Point {
2453            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2454            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2455        };
2456        let params = RenderGlyphParams {
2457            font_id,
2458            glyph_id,
2459            font_size,
2460            subpixel_variant,
2461            scale_factor,
2462            is_emoji: false,
2463        };
2464
2465        let raster_bounds = self.text_system().raster_bounds(&params)?;
2466        if !raster_bounds.is_zero() {
2467            let tile = self
2468                .sprite_atlas
2469                .get_or_insert_with(&params.clone().into(), &mut || {
2470                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2471                    Ok(Some((size, Cow::Owned(bytes))))
2472                })?
2473                .expect("Callback above only errors or returns Some");
2474            let bounds = Bounds {
2475                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2476                size: tile.bounds.size.map(Into::into),
2477            };
2478            let content_mask = self.content_mask().scale(scale_factor);
2479            self.next_frame.scene.insert_primitive(MonochromeSprite {
2480                order: 0,
2481                pad: 0,
2482                bounds,
2483                content_mask,
2484                color: color.opacity(element_opacity),
2485                tile,
2486                transformation: TransformationMatrix::unit(),
2487            });
2488        }
2489        Ok(())
2490    }
2491
2492    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2493    ///
2494    /// The y component of the origin is the baseline of the glyph.
2495    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2496    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2497    /// This method is only useful if you need to paint a single emoji that has already been shaped.
2498    ///
2499    /// This method should only be called as part of the paint phase of element drawing.
2500    pub fn paint_emoji(
2501        &mut self,
2502        origin: Point<Pixels>,
2503        font_id: FontId,
2504        glyph_id: GlyphId,
2505        font_size: Pixels,
2506    ) -> Result<()> {
2507        self.invalidator.debug_assert_paint();
2508
2509        let scale_factor = self.scale_factor();
2510        let glyph_origin = origin.scale(scale_factor);
2511        let params = RenderGlyphParams {
2512            font_id,
2513            glyph_id,
2514            font_size,
2515            // We don't render emojis with subpixel variants.
2516            subpixel_variant: Default::default(),
2517            scale_factor,
2518            is_emoji: true,
2519        };
2520
2521        let raster_bounds = self.text_system().raster_bounds(&params)?;
2522        if !raster_bounds.is_zero() {
2523            let tile = self
2524                .sprite_atlas
2525                .get_or_insert_with(&params.clone().into(), &mut || {
2526                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2527                    Ok(Some((size, Cow::Owned(bytes))))
2528                })?
2529                .expect("Callback above only errors or returns Some");
2530
2531            let bounds = Bounds {
2532                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2533                size: tile.bounds.size.map(Into::into),
2534            };
2535            let content_mask = self.content_mask().scale(scale_factor);
2536            let opacity = self.element_opacity();
2537
2538            self.next_frame.scene.insert_primitive(PolychromeSprite {
2539                order: 0,
2540                pad: 0,
2541                grayscale: false,
2542                bounds,
2543                corner_radii: Default::default(),
2544                content_mask,
2545                tile,
2546                opacity,
2547            });
2548        }
2549        Ok(())
2550    }
2551
2552    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2553    ///
2554    /// This method should only be called as part of the paint phase of element drawing.
2555    pub fn paint_svg(
2556        &mut self,
2557        bounds: Bounds<Pixels>,
2558        path: SharedString,
2559        transformation: TransformationMatrix,
2560        color: Hsla,
2561        cx: &App,
2562    ) -> Result<()> {
2563        self.invalidator.debug_assert_paint();
2564
2565        let element_opacity = self.element_opacity();
2566        let scale_factor = self.scale_factor();
2567        let bounds = bounds.scale(scale_factor);
2568        let params = RenderSvgParams {
2569            path,
2570            size: bounds.size.map(|pixels| {
2571                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
2572            }),
2573        };
2574
2575        let Some(tile) =
2576            self.sprite_atlas
2577                .get_or_insert_with(&params.clone().into(), &mut || {
2578                    let Some(bytes) = cx.svg_renderer.render(&params)? else {
2579                        return Ok(None);
2580                    };
2581                    Ok(Some((params.size, Cow::Owned(bytes))))
2582                })?
2583        else {
2584            return Ok(());
2585        };
2586        let content_mask = self.content_mask().scale(scale_factor);
2587
2588        self.next_frame.scene.insert_primitive(MonochromeSprite {
2589            order: 0,
2590            pad: 0,
2591            bounds: bounds
2592                .map_origin(|origin| origin.floor())
2593                .map_size(|size| size.ceil()),
2594            content_mask,
2595            color: color.opacity(element_opacity),
2596            tile,
2597            transformation,
2598        });
2599
2600        Ok(())
2601    }
2602
2603    /// Paint an image into the scene for the next frame at the current z-index.
2604    /// This method will panic if the frame_index is not valid
2605    ///
2606    /// This method should only be called as part of the paint phase of element drawing.
2607    pub fn paint_image(
2608        &mut self,
2609        bounds: Bounds<Pixels>,
2610        corner_radii: Corners<Pixels>,
2611        data: Arc<RenderImage>,
2612        frame_index: usize,
2613        grayscale: bool,
2614    ) -> Result<()> {
2615        self.invalidator.debug_assert_paint();
2616
2617        let scale_factor = self.scale_factor();
2618        let bounds = bounds.scale(scale_factor);
2619        let params = RenderImageParams {
2620            image_id: data.id,
2621            frame_index,
2622        };
2623
2624        let tile = self
2625            .sprite_atlas
2626            .get_or_insert_with(&params.clone().into(), &mut || {
2627                Ok(Some((
2628                    data.size(frame_index),
2629                    Cow::Borrowed(
2630                        data.as_bytes(frame_index)
2631                            .expect("It's the caller's job to pass a valid frame index"),
2632                    ),
2633                )))
2634            })?
2635            .expect("Callback above only returns Some");
2636        let content_mask = self.content_mask().scale(scale_factor);
2637        let corner_radii = corner_radii.scale(scale_factor);
2638        let opacity = self.element_opacity();
2639
2640        self.next_frame.scene.insert_primitive(PolychromeSprite {
2641            order: 0,
2642            pad: 0,
2643            grayscale,
2644            bounds,
2645            content_mask,
2646            corner_radii,
2647            tile,
2648            opacity,
2649        });
2650        Ok(())
2651    }
2652
2653    /// Paint a surface into the scene for the next frame at the current z-index.
2654    ///
2655    /// This method should only be called as part of the paint phase of element drawing.
2656    #[cfg(target_os = "macos")]
2657    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2658        use crate::PaintSurface;
2659
2660        self.invalidator.debug_assert_paint();
2661
2662        let scale_factor = self.scale_factor();
2663        let bounds = bounds.scale(scale_factor);
2664        let content_mask = self.content_mask().scale(scale_factor);
2665        self.next_frame.scene.insert_primitive(PaintSurface {
2666            order: 0,
2667            bounds,
2668            content_mask,
2669            image_buffer,
2670        });
2671    }
2672
2673    /// Removes an image from the sprite atlas.
2674    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
2675        for frame_index in 0..data.frame_count() {
2676            let params = RenderImageParams {
2677                image_id: data.id,
2678                frame_index,
2679            };
2680
2681            self.sprite_atlas.remove(&params.clone().into());
2682        }
2683
2684        Ok(())
2685    }
2686
2687    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2688    /// layout is being requested, along with the layout ids of any children. This method is called during
2689    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2690    ///
2691    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2692    #[must_use]
2693    pub fn request_layout(
2694        &mut self,
2695        style: Style,
2696        children: impl IntoIterator<Item = LayoutId>,
2697        cx: &mut App,
2698    ) -> LayoutId {
2699        self.invalidator.debug_assert_prepaint();
2700
2701        cx.layout_id_buffer.clear();
2702        cx.layout_id_buffer.extend(children);
2703        let rem_size = self.rem_size();
2704
2705        self.layout_engine
2706            .as_mut()
2707            .unwrap()
2708            .request_layout(style, rem_size, &cx.layout_id_buffer)
2709    }
2710
2711    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2712    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2713    /// determine the element's size. One place this is used internally is when measuring text.
2714    ///
2715    /// The given closure is invoked at layout time with the known dimensions and available space and
2716    /// returns a `Size`.
2717    ///
2718    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2719    pub fn request_measured_layout<
2720        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
2721            + 'static,
2722    >(
2723        &mut self,
2724        style: Style,
2725        measure: F,
2726    ) -> LayoutId {
2727        self.invalidator.debug_assert_prepaint();
2728
2729        let rem_size = self.rem_size();
2730        self.layout_engine
2731            .as_mut()
2732            .unwrap()
2733            .request_measured_layout(style, rem_size, measure)
2734    }
2735
2736    /// Compute the layout for the given id within the given available space.
2737    /// This method is called for its side effect, typically by the framework prior to painting.
2738    /// After calling it, you can request the bounds of the given layout node id or any descendant.
2739    ///
2740    /// This method should only be called as part of the prepaint phase of element drawing.
2741    pub fn compute_layout(
2742        &mut self,
2743        layout_id: LayoutId,
2744        available_space: Size<AvailableSpace>,
2745        cx: &mut App,
2746    ) {
2747        self.invalidator.debug_assert_prepaint();
2748
2749        let mut layout_engine = self.layout_engine.take().unwrap();
2750        layout_engine.compute_layout(layout_id, available_space, self, cx);
2751        self.layout_engine = Some(layout_engine);
2752    }
2753
2754    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2755    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2756    ///
2757    /// This method should only be called as part of element drawing.
2758    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2759        self.invalidator.debug_assert_prepaint();
2760
2761        let mut bounds = self
2762            .layout_engine
2763            .as_mut()
2764            .unwrap()
2765            .layout_bounds(layout_id)
2766            .map(Into::into);
2767        bounds.origin += self.element_offset();
2768        bounds
2769    }
2770
2771    /// This method should be called during `prepaint`. You can use
2772    /// the returned [Hitbox] during `paint` or in an event handler
2773    /// to determine whether the inserted hitbox was the topmost.
2774    ///
2775    /// This method should only be called as part of the prepaint phase of element drawing.
2776    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2777        self.invalidator.debug_assert_prepaint();
2778
2779        let content_mask = self.content_mask();
2780        let id = self.next_hitbox_id;
2781        self.next_hitbox_id.0 += 1;
2782        let hitbox = Hitbox {
2783            id,
2784            bounds,
2785            content_mask,
2786            opaque,
2787        };
2788        self.next_frame.hitboxes.push(hitbox.clone());
2789        hitbox
2790    }
2791
2792    /// Sets the key context for the current element. This context will be used to translate
2793    /// keybindings into actions.
2794    ///
2795    /// This method should only be called as part of the paint phase of element drawing.
2796    pub fn set_key_context(&mut self, context: KeyContext) {
2797        self.invalidator.debug_assert_paint();
2798        self.next_frame.dispatch_tree.set_key_context(context);
2799    }
2800
2801    /// Sets the focus handle for the current element. This handle will be used to manage focus state
2802    /// and keyboard event dispatch for the element.
2803    ///
2804    /// This method should only be called as part of the prepaint phase of element drawing.
2805    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
2806        self.invalidator.debug_assert_prepaint();
2807        if focus_handle.is_focused(self) {
2808            self.next_frame.focus = Some(focus_handle.id);
2809        }
2810        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
2811    }
2812
2813    /// Sets the view id for the current element, which will be used to manage view caching.
2814    ///
2815    /// This method should only be called as part of element prepaint. We plan on removing this
2816    /// method eventually when we solve some issues that require us to construct editor elements
2817    /// directly instead of always using editors via views.
2818    pub fn set_view_id(&mut self, view_id: EntityId) {
2819        self.invalidator.debug_assert_prepaint();
2820        self.next_frame.dispatch_tree.set_view_id(view_id);
2821    }
2822
2823    /// Get the entity ID for the currently rendering view
2824    pub fn current_view(&self) -> EntityId {
2825        self.invalidator.debug_assert_paint_or_prepaint();
2826        self.rendered_entity_stack.last().copied().unwrap()
2827    }
2828
2829    pub(crate) fn with_rendered_view<R>(
2830        &mut self,
2831        id: EntityId,
2832        f: impl FnOnce(&mut Self) -> R,
2833    ) -> R {
2834        self.rendered_entity_stack.push(id);
2835        let result = f(self);
2836        self.rendered_entity_stack.pop();
2837        result
2838    }
2839
2840    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2841    /// platform to receive textual input with proper integration with concerns such
2842    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2843    /// rendered.
2844    ///
2845    /// This method should only be called as part of the paint phase of element drawing.
2846    ///
2847    /// [element_input_handler]: crate::ElementInputHandler
2848    pub fn handle_input(
2849        &mut self,
2850        focus_handle: &FocusHandle,
2851        input_handler: impl InputHandler,
2852        cx: &App,
2853    ) {
2854        self.invalidator.debug_assert_paint();
2855
2856        if focus_handle.is_focused(self) {
2857            let cx = self.to_async(cx);
2858            self.next_frame
2859                .input_handlers
2860                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2861        }
2862    }
2863
2864    /// Register a mouse event listener on the window for the next frame. The type of event
2865    /// is determined by the first parameter of the given listener. When the next frame is rendered
2866    /// the listener will be cleared.
2867    ///
2868    /// This method should only be called as part of the paint phase of element drawing.
2869    pub fn on_mouse_event<Event: MouseEvent>(
2870        &mut self,
2871        mut handler: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2872    ) {
2873        self.invalidator.debug_assert_paint();
2874
2875        self.next_frame.mouse_listeners.push(Some(Box::new(
2876            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
2877                if let Some(event) = event.downcast_ref() {
2878                    handler(event, phase, window, cx)
2879                }
2880            },
2881        )));
2882    }
2883
2884    /// Register a key event listener on the window for the next frame. The type of event
2885    /// is determined by the first parameter of the given listener. When the next frame is rendered
2886    /// the listener will be cleared.
2887    ///
2888    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2889    /// a specific need to register a global listener.
2890    ///
2891    /// This method should only be called as part of the paint phase of element drawing.
2892    pub fn on_key_event<Event: KeyEvent>(
2893        &mut self,
2894        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2895    ) {
2896        self.invalidator.debug_assert_paint();
2897
2898        self.next_frame.dispatch_tree.on_key_event(Rc::new(
2899            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
2900                if let Some(event) = event.downcast_ref::<Event>() {
2901                    listener(event, phase, window, cx)
2902                }
2903            },
2904        ));
2905    }
2906
2907    /// Register a modifiers changed event listener on the window for the next frame.
2908    ///
2909    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2910    /// a specific need to register a global listener.
2911    ///
2912    /// This method should only be called as part of the paint phase of element drawing.
2913    pub fn on_modifiers_changed(
2914        &mut self,
2915        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
2916    ) {
2917        self.invalidator.debug_assert_paint();
2918
2919        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
2920            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
2921                listener(event, window, cx)
2922            },
2923        ));
2924    }
2925
2926    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2927    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
2928    /// Returns a subscription and persists until the subscription is dropped.
2929    pub fn on_focus_in(
2930        &mut self,
2931        handle: &FocusHandle,
2932        cx: &mut App,
2933        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
2934    ) -> Subscription {
2935        let focus_id = handle.id;
2936        let (subscription, activate) =
2937            self.new_focus_listener(Box::new(move |event, window, cx| {
2938                if event.is_focus_in(focus_id) {
2939                    listener(window, cx);
2940                }
2941                true
2942            }));
2943        cx.defer(move |_| activate());
2944        subscription
2945    }
2946
2947    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2948    /// Returns a subscription and persists until the subscription is dropped.
2949    pub fn on_focus_out(
2950        &mut self,
2951        handle: &FocusHandle,
2952        cx: &mut App,
2953        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
2954    ) -> Subscription {
2955        let focus_id = handle.id;
2956        let (subscription, activate) =
2957            self.new_focus_listener(Box::new(move |event, window, cx| {
2958                if let Some(blurred_id) = event.previous_focus_path.last().copied() {
2959                    if event.is_focus_out(focus_id) {
2960                        let event = FocusOutEvent {
2961                            blurred: WeakFocusHandle {
2962                                id: blurred_id,
2963                                handles: Arc::downgrade(&cx.focus_handles),
2964                            },
2965                        };
2966                        listener(event, window, cx)
2967                    }
2968                }
2969                true
2970            }));
2971        cx.defer(move |_| activate());
2972        subscription
2973    }
2974
2975    fn reset_cursor_style(&self, cx: &mut App) {
2976        // Set the cursor only if we're the active window.
2977        if self.is_window_hovered() {
2978            let style = self
2979                .rendered_frame
2980                .cursor_styles
2981                .iter()
2982                .rev()
2983                .find(|request| request.hitbox_id.is_hovered(self))
2984                .map(|request| request.style)
2985                .unwrap_or(CursorStyle::Arrow);
2986            cx.platform.set_cursor_style(style);
2987        }
2988    }
2989
2990    /// Dispatch a given keystroke as though the user had typed it.
2991    /// You can create a keystroke with Keystroke::parse("").
2992    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
2993        let keystroke = keystroke.with_simulated_ime();
2994        let result = self.dispatch_event(
2995            PlatformInput::KeyDown(KeyDownEvent {
2996                keystroke: keystroke.clone(),
2997                is_held: false,
2998            }),
2999            cx,
3000        );
3001        if !result.propagate {
3002            return true;
3003        }
3004
3005        if let Some(input) = keystroke.key_char {
3006            if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3007                input_handler.dispatch_input(&input, self, cx);
3008                self.platform_window.set_input_handler(input_handler);
3009                return true;
3010            }
3011        }
3012
3013        false
3014    }
3015
3016    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3017    /// binding for the action (last binding added to the keymap).
3018    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3019        self.bindings_for_action(action)
3020            .last()
3021            .map(|binding| {
3022                binding
3023                    .keystrokes()
3024                    .iter()
3025                    .map(ToString::to_string)
3026                    .collect::<Vec<_>>()
3027                    .join(" ")
3028            })
3029            .unwrap_or_else(|| action.name().to_string())
3030    }
3031
3032    /// Dispatch a mouse or keyboard event on the window.
3033    #[profiling::function]
3034    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3035        self.last_input_timestamp.set(Instant::now());
3036        // Handlers may set this to false by calling `stop_propagation`.
3037        cx.propagate_event = true;
3038        // Handlers may set this to true by calling `prevent_default`.
3039        self.default_prevented = false;
3040
3041        let event = match event {
3042            // Track the mouse position with our own state, since accessing the platform
3043            // API for the mouse position can only occur on the main thread.
3044            PlatformInput::MouseMove(mouse_move) => {
3045                self.mouse_position = mouse_move.position;
3046                self.modifiers = mouse_move.modifiers;
3047                PlatformInput::MouseMove(mouse_move)
3048            }
3049            PlatformInput::MouseDown(mouse_down) => {
3050                self.mouse_position = mouse_down.position;
3051                self.modifiers = mouse_down.modifiers;
3052                PlatformInput::MouseDown(mouse_down)
3053            }
3054            PlatformInput::MouseUp(mouse_up) => {
3055                self.mouse_position = mouse_up.position;
3056                self.modifiers = mouse_up.modifiers;
3057                PlatformInput::MouseUp(mouse_up)
3058            }
3059            PlatformInput::MouseExited(mouse_exited) => {
3060                self.modifiers = mouse_exited.modifiers;
3061                PlatformInput::MouseExited(mouse_exited)
3062            }
3063            PlatformInput::ModifiersChanged(modifiers_changed) => {
3064                self.modifiers = modifiers_changed.modifiers;
3065                PlatformInput::ModifiersChanged(modifiers_changed)
3066            }
3067            PlatformInput::ScrollWheel(scroll_wheel) => {
3068                self.mouse_position = scroll_wheel.position;
3069                self.modifiers = scroll_wheel.modifiers;
3070                PlatformInput::ScrollWheel(scroll_wheel)
3071            }
3072            // Translate dragging and dropping of external files from the operating system
3073            // to internal drag and drop events.
3074            PlatformInput::FileDrop(file_drop) => match file_drop {
3075                FileDropEvent::Entered { position, paths } => {
3076                    self.mouse_position = position;
3077                    if cx.active_drag.is_none() {
3078                        cx.active_drag = Some(AnyDrag {
3079                            value: Arc::new(paths.clone()),
3080                            view: cx.new(|_| paths).into(),
3081                            cursor_offset: position,
3082                        });
3083                    }
3084                    PlatformInput::MouseMove(MouseMoveEvent {
3085                        position,
3086                        pressed_button: Some(MouseButton::Left),
3087                        modifiers: Modifiers::default(),
3088                    })
3089                }
3090                FileDropEvent::Pending { position } => {
3091                    self.mouse_position = position;
3092                    PlatformInput::MouseMove(MouseMoveEvent {
3093                        position,
3094                        pressed_button: Some(MouseButton::Left),
3095                        modifiers: Modifiers::default(),
3096                    })
3097                }
3098                FileDropEvent::Submit { position } => {
3099                    cx.activate(true);
3100                    self.mouse_position = position;
3101                    PlatformInput::MouseUp(MouseUpEvent {
3102                        button: MouseButton::Left,
3103                        position,
3104                        modifiers: Modifiers::default(),
3105                        click_count: 1,
3106                    })
3107                }
3108                FileDropEvent::Exited => {
3109                    cx.active_drag.take();
3110                    PlatformInput::FileDrop(FileDropEvent::Exited)
3111                }
3112            },
3113            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3114        };
3115
3116        if let Some(any_mouse_event) = event.mouse_event() {
3117            self.dispatch_mouse_event(any_mouse_event, cx);
3118        } else if let Some(any_key_event) = event.keyboard_event() {
3119            self.dispatch_key_event(any_key_event, cx);
3120        }
3121
3122        DispatchEventResult {
3123            propagate: cx.propagate_event,
3124            default_prevented: self.default_prevented,
3125        }
3126    }
3127
3128    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3129        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3130        if hit_test != self.mouse_hit_test {
3131            self.mouse_hit_test = hit_test;
3132            self.reset_cursor_style(cx);
3133        }
3134
3135        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3136
3137        // Capture phase, events bubble from back to front. Handlers for this phase are used for
3138        // special purposes, such as detecting events outside of a given Bounds.
3139        for listener in &mut mouse_listeners {
3140            let listener = listener.as_mut().unwrap();
3141            listener(event, DispatchPhase::Capture, self, cx);
3142            if !cx.propagate_event {
3143                break;
3144            }
3145        }
3146
3147        // Bubble phase, where most normal handlers do their work.
3148        if cx.propagate_event {
3149            for listener in mouse_listeners.iter_mut().rev() {
3150                let listener = listener.as_mut().unwrap();
3151                listener(event, DispatchPhase::Bubble, self, cx);
3152                if !cx.propagate_event {
3153                    break;
3154                }
3155            }
3156        }
3157
3158        self.rendered_frame.mouse_listeners = mouse_listeners;
3159
3160        if cx.has_active_drag() {
3161            if event.is::<MouseMoveEvent>() {
3162                // If this was a mouse move event, redraw the window so that the
3163                // active drag can follow the mouse cursor.
3164                self.refresh();
3165            } else if event.is::<MouseUpEvent>() {
3166                // If this was a mouse up event, cancel the active drag and redraw
3167                // the window.
3168                cx.active_drag = None;
3169                self.refresh();
3170            }
3171        }
3172    }
3173
3174    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3175        if self.invalidator.is_dirty() {
3176            self.draw(cx);
3177        }
3178
3179        let node_id = self
3180            .focus
3181            .and_then(|focus_id| {
3182                self.rendered_frame
3183                    .dispatch_tree
3184                    .focusable_node_id(focus_id)
3185            })
3186            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3187
3188        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3189
3190        let mut keystroke: Option<Keystroke> = None;
3191
3192        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3193            if event.modifiers.number_of_modifiers() == 0
3194                && self.pending_modifier.modifiers.number_of_modifiers() == 1
3195                && !self.pending_modifier.saw_keystroke
3196            {
3197                let key = match self.pending_modifier.modifiers {
3198                    modifiers if modifiers.shift => Some("shift"),
3199                    modifiers if modifiers.control => Some("control"),
3200                    modifiers if modifiers.alt => Some("alt"),
3201                    modifiers if modifiers.platform => Some("platform"),
3202                    modifiers if modifiers.function => Some("function"),
3203                    _ => None,
3204                };
3205                if let Some(key) = key {
3206                    keystroke = Some(Keystroke {
3207                        key: key.to_string(),
3208                        key_char: None,
3209                        modifiers: Modifiers::default(),
3210                    });
3211                }
3212            }
3213
3214            if self.pending_modifier.modifiers.number_of_modifiers() == 0
3215                && event.modifiers.number_of_modifiers() == 1
3216            {
3217                self.pending_modifier.saw_keystroke = false
3218            }
3219            self.pending_modifier.modifiers = event.modifiers
3220        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3221            self.pending_modifier.saw_keystroke = true;
3222            keystroke = Some(key_down_event.keystroke.clone());
3223        }
3224
3225        let Some(keystroke) = keystroke else {
3226            self.finish_dispatch_key_event(event, dispatch_path, cx);
3227            return;
3228        };
3229
3230        let mut currently_pending = self.pending_input.take().unwrap_or_default();
3231        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3232            currently_pending = PendingInput::default();
3233        }
3234
3235        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3236            currently_pending.keystrokes,
3237            keystroke,
3238            &dispatch_path,
3239        );
3240        if !match_result.to_replay.is_empty() {
3241            self.replay_pending_input(match_result.to_replay, cx)
3242        }
3243
3244        if !match_result.pending.is_empty() {
3245            currently_pending.keystrokes = match_result.pending;
3246            currently_pending.focus = self.focus;
3247            currently_pending.timer = Some(self.spawn(cx, async move |cx| {
3248                cx.background_executor.timer(Duration::from_secs(1)).await;
3249                cx.update(move |window, cx| {
3250                    let Some(currently_pending) = window
3251                        .pending_input
3252                        .take()
3253                        .filter(|pending| pending.focus == window.focus)
3254                    else {
3255                        return;
3256                    };
3257
3258                    let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3259
3260                    let to_replay = window
3261                        .rendered_frame
3262                        .dispatch_tree
3263                        .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3264
3265                    window.replay_pending_input(to_replay, cx)
3266                })
3267                .log_err();
3268            }));
3269            self.pending_input = Some(currently_pending);
3270            self.pending_input_changed(cx);
3271            cx.propagate_event = false;
3272            return;
3273        }
3274
3275        cx.propagate_event = true;
3276        for binding in match_result.bindings {
3277            self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3278            if !cx.propagate_event {
3279                self.dispatch_keystroke_observers(event, Some(binding.action), cx);
3280                self.pending_input_changed(cx);
3281                return;
3282            }
3283        }
3284
3285        self.finish_dispatch_key_event(event, dispatch_path, cx);
3286        self.pending_input_changed(cx);
3287    }
3288
3289    fn finish_dispatch_key_event(
3290        &mut self,
3291        event: &dyn Any,
3292        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3293        cx: &mut App,
3294    ) {
3295        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
3296        if !cx.propagate_event {
3297            return;
3298        }
3299
3300        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
3301        if !cx.propagate_event {
3302            return;
3303        }
3304
3305        self.dispatch_keystroke_observers(event, None, cx);
3306    }
3307
3308    fn pending_input_changed(&mut self, cx: &mut App) {
3309        self.pending_input_observers
3310            .clone()
3311            .retain(&(), |callback| callback(self, cx));
3312    }
3313
3314    fn dispatch_key_down_up_event(
3315        &mut self,
3316        event: &dyn Any,
3317        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3318        cx: &mut App,
3319    ) {
3320        // Capture phase
3321        for node_id in dispatch_path {
3322            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3323
3324            for key_listener in node.key_listeners.clone() {
3325                key_listener(event, DispatchPhase::Capture, self, cx);
3326                if !cx.propagate_event {
3327                    return;
3328                }
3329            }
3330        }
3331
3332        // Bubble phase
3333        for node_id in dispatch_path.iter().rev() {
3334            // Handle low level key events
3335            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3336            for key_listener in node.key_listeners.clone() {
3337                key_listener(event, DispatchPhase::Bubble, self, cx);
3338                if !cx.propagate_event {
3339                    return;
3340                }
3341            }
3342        }
3343    }
3344
3345    fn dispatch_modifiers_changed_event(
3346        &mut self,
3347        event: &dyn Any,
3348        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3349        cx: &mut App,
3350    ) {
3351        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3352            return;
3353        };
3354        for node_id in dispatch_path.iter().rev() {
3355            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3356            for listener in node.modifiers_changed_listeners.clone() {
3357                listener(event, self, cx);
3358                if !cx.propagate_event {
3359                    return;
3360                }
3361            }
3362        }
3363    }
3364
3365    /// Determine whether a potential multi-stroke key binding is in progress on this window.
3366    pub fn has_pending_keystrokes(&self) -> bool {
3367        self.pending_input.is_some()
3368    }
3369
3370    pub(crate) fn clear_pending_keystrokes(&mut self) {
3371        self.pending_input.take();
3372    }
3373
3374    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3375    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3376        self.pending_input
3377            .as_ref()
3378            .map(|pending_input| pending_input.keystrokes.as_slice())
3379    }
3380
3381    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
3382        let node_id = self
3383            .focus
3384            .and_then(|focus_id| {
3385                self.rendered_frame
3386                    .dispatch_tree
3387                    .focusable_node_id(focus_id)
3388            })
3389            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3390
3391        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3392
3393        'replay: for replay in replays {
3394            let event = KeyDownEvent {
3395                keystroke: replay.keystroke.clone(),
3396                is_held: false,
3397            };
3398
3399            cx.propagate_event = true;
3400            for binding in replay.bindings {
3401                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3402                if !cx.propagate_event {
3403                    self.dispatch_keystroke_observers(&event, Some(binding.action), cx);
3404                    continue 'replay;
3405                }
3406            }
3407
3408            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
3409            if !cx.propagate_event {
3410                continue 'replay;
3411            }
3412            if let Some(input) = replay.keystroke.key_char.as_ref().cloned() {
3413                if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3414                    input_handler.dispatch_input(&input, self, cx);
3415                    self.platform_window.set_input_handler(input_handler)
3416                }
3417            }
3418        }
3419    }
3420
3421    fn dispatch_action_on_node(
3422        &mut self,
3423        node_id: DispatchNodeId,
3424        action: &dyn Action,
3425        cx: &mut App,
3426    ) {
3427        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3428
3429        // Capture phase for global actions.
3430        cx.propagate_event = true;
3431        if let Some(mut global_listeners) = cx
3432            .global_action_listeners
3433            .remove(&action.as_any().type_id())
3434        {
3435            for listener in &global_listeners {
3436                listener(action.as_any(), DispatchPhase::Capture, cx);
3437                if !cx.propagate_event {
3438                    break;
3439                }
3440            }
3441
3442            global_listeners.extend(
3443                cx.global_action_listeners
3444                    .remove(&action.as_any().type_id())
3445                    .unwrap_or_default(),
3446            );
3447
3448            cx.global_action_listeners
3449                .insert(action.as_any().type_id(), global_listeners);
3450        }
3451
3452        if !cx.propagate_event {
3453            return;
3454        }
3455
3456        // Capture phase for window actions.
3457        for node_id in &dispatch_path {
3458            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3459            for DispatchActionListener {
3460                action_type,
3461                listener,
3462            } in node.action_listeners.clone()
3463            {
3464                let any_action = action.as_any();
3465                if action_type == any_action.type_id() {
3466                    listener(any_action, DispatchPhase::Capture, self, cx);
3467
3468                    if !cx.propagate_event {
3469                        return;
3470                    }
3471                }
3472            }
3473        }
3474
3475        // Bubble phase for window actions.
3476        for node_id in dispatch_path.iter().rev() {
3477            let node = self.rendered_frame.dispatch_tree.node(*node_id);
3478            for DispatchActionListener {
3479                action_type,
3480                listener,
3481            } in node.action_listeners.clone()
3482            {
3483                let any_action = action.as_any();
3484                if action_type == any_action.type_id() {
3485                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3486                    listener(any_action, DispatchPhase::Bubble, self, cx);
3487
3488                    if !cx.propagate_event {
3489                        return;
3490                    }
3491                }
3492            }
3493        }
3494
3495        // Bubble phase for global actions.
3496        if let Some(mut global_listeners) = cx
3497            .global_action_listeners
3498            .remove(&action.as_any().type_id())
3499        {
3500            for listener in global_listeners.iter().rev() {
3501                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3502
3503                listener(action.as_any(), DispatchPhase::Bubble, cx);
3504                if !cx.propagate_event {
3505                    break;
3506                }
3507            }
3508
3509            global_listeners.extend(
3510                cx.global_action_listeners
3511                    .remove(&action.as_any().type_id())
3512                    .unwrap_or_default(),
3513            );
3514
3515            cx.global_action_listeners
3516                .insert(action.as_any().type_id(), global_listeners);
3517        }
3518    }
3519
3520    /// Register the given handler to be invoked whenever the global of the given type
3521    /// is updated.
3522    pub fn observe_global<G: Global>(
3523        &mut self,
3524        cx: &mut App,
3525        f: impl Fn(&mut Window, &mut App) + 'static,
3526    ) -> Subscription {
3527        let window_handle = self.handle;
3528        let (subscription, activate) = cx.global_observers.insert(
3529            TypeId::of::<G>(),
3530            Box::new(move |cx| {
3531                window_handle
3532                    .update(cx, |_, window, cx| f(window, cx))
3533                    .is_ok()
3534            }),
3535        );
3536        cx.defer(move |_| activate());
3537        subscription
3538    }
3539
3540    /// Focus the current window and bring it to the foreground at the platform level.
3541    pub fn activate_window(&self) {
3542        self.platform_window.activate();
3543    }
3544
3545    /// Minimize the current window at the platform level.
3546    pub fn minimize_window(&self) {
3547        self.platform_window.minimize();
3548    }
3549
3550    /// Toggle full screen status on the current window at the platform level.
3551    pub fn toggle_fullscreen(&self) {
3552        self.platform_window.toggle_fullscreen();
3553    }
3554
3555    /// Updates the IME panel position suggestions for languages like japanese, chinese.
3556    pub fn invalidate_character_coordinates(&self) {
3557        self.on_next_frame(|window, cx| {
3558            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
3559                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
3560                    window
3561                        .platform_window
3562                        .update_ime_position(bounds.scale(window.scale_factor()));
3563                }
3564                window.platform_window.set_input_handler(input_handler);
3565            }
3566        });
3567    }
3568
3569    /// Present a platform dialog.
3570    /// The provided message will be presented, along with buttons for each answer.
3571    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3572    pub fn prompt(
3573        &mut self,
3574        level: PromptLevel,
3575        message: &str,
3576        detail: Option<&str>,
3577        answers: &[&str],
3578        cx: &mut App,
3579    ) -> oneshot::Receiver<usize> {
3580        let prompt_builder = cx.prompt_builder.take();
3581        let Some(prompt_builder) = prompt_builder else {
3582            unreachable!("Re-entrant window prompting is not supported by GPUI");
3583        };
3584
3585        let receiver = match &prompt_builder {
3586            PromptBuilder::Default => self
3587                .platform_window
3588                .prompt(level, message, detail, answers)
3589                .unwrap_or_else(|| {
3590                    self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3591                }),
3592            PromptBuilder::Custom(_) => {
3593                self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3594            }
3595        };
3596
3597        cx.prompt_builder = Some(prompt_builder);
3598
3599        receiver
3600    }
3601
3602    fn build_custom_prompt(
3603        &mut self,
3604        prompt_builder: &PromptBuilder,
3605        level: PromptLevel,
3606        message: &str,
3607        detail: Option<&str>,
3608        answers: &[&str],
3609        cx: &mut App,
3610    ) -> oneshot::Receiver<usize> {
3611        let (sender, receiver) = oneshot::channel();
3612        let handle = PromptHandle::new(sender);
3613        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
3614        self.prompt = Some(handle);
3615        receiver
3616    }
3617
3618    /// Returns the current context stack.
3619    pub fn context_stack(&self) -> Vec<KeyContext> {
3620        let dispatch_tree = &self.rendered_frame.dispatch_tree;
3621        let node_id = self
3622            .focus
3623            .and_then(|focus_id| dispatch_tree.focusable_node_id(focus_id))
3624            .unwrap_or_else(|| dispatch_tree.root_node_id());
3625
3626        dispatch_tree
3627            .dispatch_path(node_id)
3628            .iter()
3629            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
3630            .collect()
3631    }
3632
3633    /// Returns all available actions for the focused element.
3634    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
3635        let node_id = self
3636            .focus
3637            .and_then(|focus_id| {
3638                self.rendered_frame
3639                    .dispatch_tree
3640                    .focusable_node_id(focus_id)
3641            })
3642            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3643
3644        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
3645        for action_type in cx.global_action_listeners.keys() {
3646            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3647                let action = cx.actions.build_action_type(action_type).ok();
3648                if let Some(action) = action {
3649                    actions.insert(ix, action);
3650                }
3651            }
3652        }
3653        actions
3654    }
3655
3656    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
3657    /// returned in the order they were added. For display, the last binding should take precedence.
3658    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3659        self.rendered_frame
3660            .dispatch_tree
3661            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
3662    }
3663
3664    /// Returns any bindings that would invoke an action on the given focus handle if it were
3665    /// focused. Bindings are returned in the order they were added. For display, the last binding
3666    /// should take precedence.
3667    pub fn bindings_for_action_in(
3668        &self,
3669        action: &dyn Action,
3670        focus_handle: &FocusHandle,
3671    ) -> Vec<KeyBinding> {
3672        let dispatch_tree = &self.rendered_frame.dispatch_tree;
3673
3674        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3675            return vec![];
3676        };
3677        let context_stack: Vec<_> = dispatch_tree
3678            .dispatch_path(node_id)
3679            .into_iter()
3680            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3681            .collect();
3682        dispatch_tree.bindings_for_action(action, &context_stack)
3683    }
3684
3685    /// Returns the key bindings for the given action in the given context.
3686    pub fn bindings_for_action_in_context(
3687        &self,
3688        action: &dyn Action,
3689        context: KeyContext,
3690    ) -> Vec<KeyBinding> {
3691        let dispatch_tree = &self.rendered_frame.dispatch_tree;
3692        dispatch_tree.bindings_for_action(action, &[context])
3693    }
3694
3695    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3696    pub fn listener_for<V: Render, E>(
3697        &self,
3698        view: &Entity<V>,
3699        f: impl Fn(&mut V, &E, &mut Window, &mut Context<V>) + 'static,
3700    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
3701        let view = view.downgrade();
3702        move |e: &E, window: &mut Window, cx: &mut App| {
3703            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
3704        }
3705    }
3706
3707    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3708    pub fn handler_for<V: Render>(
3709        &self,
3710        view: &Entity<V>,
3711        f: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
3712    ) -> impl Fn(&mut Window, &mut App) {
3713        let view = view.downgrade();
3714        move |window: &mut Window, cx: &mut App| {
3715            view.update(cx, |view, cx| f(view, window, cx)).ok();
3716        }
3717    }
3718
3719    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3720    /// If the callback returns false, the window won't be closed.
3721    pub fn on_window_should_close(
3722        &self,
3723        cx: &App,
3724        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
3725    ) {
3726        let mut cx = self.to_async(cx);
3727        self.platform_window.on_should_close(Box::new(move || {
3728            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
3729        }))
3730    }
3731
3732    /// Register an action listener on the window for the next frame. The type of action
3733    /// is determined by the first parameter of the given listener. When the next frame is rendered
3734    /// the listener will be cleared.
3735    ///
3736    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3737    /// a specific need to register a global listener.
3738    pub fn on_action(
3739        &mut self,
3740        action_type: TypeId,
3741        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
3742    ) {
3743        self.next_frame
3744            .dispatch_tree
3745            .on_action(action_type, Rc::new(listener));
3746    }
3747
3748    /// Read information about the GPU backing this window.
3749    /// Currently returns None on Mac and Windows.
3750    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
3751        self.platform_window.gpu_specs()
3752    }
3753}
3754
3755// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3756slotmap::new_key_type! {
3757    /// A unique identifier for a window.
3758    pub struct WindowId;
3759}
3760
3761impl WindowId {
3762    /// Converts this window ID to a `u64`.
3763    pub fn as_u64(&self) -> u64 {
3764        self.0.as_ffi()
3765    }
3766}
3767
3768impl From<u64> for WindowId {
3769    fn from(value: u64) -> Self {
3770        WindowId(slotmap::KeyData::from_ffi(value))
3771    }
3772}
3773
3774/// A handle to a window with a specific root view type.
3775/// Note that this does not keep the window alive on its own.
3776#[derive(Deref, DerefMut)]
3777pub struct WindowHandle<V> {
3778    #[deref]
3779    #[deref_mut]
3780    pub(crate) any_handle: AnyWindowHandle,
3781    state_type: PhantomData<V>,
3782}
3783
3784impl<V: 'static + Render> WindowHandle<V> {
3785    /// Creates a new handle from a window ID.
3786    /// This does not check if the root type of the window is `V`.
3787    pub fn new(id: WindowId) -> Self {
3788        WindowHandle {
3789            any_handle: AnyWindowHandle {
3790                id,
3791                state_type: TypeId::of::<V>(),
3792            },
3793            state_type: PhantomData,
3794        }
3795    }
3796
3797    /// Get the root view out of this window.
3798    ///
3799    /// This will fail if the window is closed or if the root view's type does not match `V`.
3800    #[cfg(any(test, feature = "test-support"))]
3801    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
3802    where
3803        C: AppContext,
3804    {
3805        crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
3806            root_view
3807                .downcast::<V>()
3808                .map_err(|_| anyhow!("the type of the window's root view has changed"))
3809        }))
3810    }
3811
3812    /// Updates the root view of this window.
3813    ///
3814    /// This will fail if the window has been closed or if the root view's type does not match
3815    pub fn update<C, R>(
3816        &self,
3817        cx: &mut C,
3818        update: impl FnOnce(&mut V, &mut Window, &mut Context<'_, V>) -> R,
3819    ) -> Result<R>
3820    where
3821        C: AppContext,
3822    {
3823        cx.update_window(self.any_handle, |root_view, window, cx| {
3824            let view = root_view
3825                .downcast::<V>()
3826                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3827
3828            Ok(view.update(cx, |view, cx| update(view, window, cx)))
3829        })?
3830    }
3831
3832    /// Read the root view out of this window.
3833    ///
3834    /// This will fail if the window is closed or if the root view's type does not match `V`.
3835    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
3836        let x = cx
3837            .windows
3838            .get(self.id)
3839            .and_then(|window| {
3840                window
3841                    .as_ref()
3842                    .and_then(|window| window.root.clone())
3843                    .map(|root_view| root_view.downcast::<V>())
3844            })
3845            .ok_or_else(|| anyhow!("window not found"))?
3846            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3847
3848        Ok(x.read(cx))
3849    }
3850
3851    /// Read the root view out of this window, with a callback
3852    ///
3853    /// This will fail if the window is closed or if the root view's type does not match `V`.
3854    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
3855    where
3856        C: AppContext,
3857    {
3858        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3859    }
3860
3861    /// Read the root view pointer off of this window.
3862    ///
3863    /// This will fail if the window is closed or if the root view's type does not match `V`.
3864    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
3865    where
3866        C: AppContext,
3867    {
3868        cx.read_window(self, |root_view, _cx| root_view.clone())
3869    }
3870
3871    /// Check if this window is 'active'.
3872    ///
3873    /// Will return `None` if the window is closed or currently
3874    /// borrowed.
3875    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
3876        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
3877            .ok()
3878    }
3879}
3880
3881impl<V> Copy for WindowHandle<V> {}
3882
3883impl<V> Clone for WindowHandle<V> {
3884    fn clone(&self) -> Self {
3885        *self
3886    }
3887}
3888
3889impl<V> PartialEq for WindowHandle<V> {
3890    fn eq(&self, other: &Self) -> bool {
3891        self.any_handle == other.any_handle
3892    }
3893}
3894
3895impl<V> Eq for WindowHandle<V> {}
3896
3897impl<V> Hash for WindowHandle<V> {
3898    fn hash<H: Hasher>(&self, state: &mut H) {
3899        self.any_handle.hash(state);
3900    }
3901}
3902
3903impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3904    fn from(val: WindowHandle<V>) -> Self {
3905        val.any_handle
3906    }
3907}
3908
3909unsafe impl<V> Send for WindowHandle<V> {}
3910unsafe impl<V> Sync for WindowHandle<V> {}
3911
3912/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3913#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3914pub struct AnyWindowHandle {
3915    pub(crate) id: WindowId,
3916    state_type: TypeId,
3917}
3918
3919impl AnyWindowHandle {
3920    /// Get the ID of this window.
3921    pub fn window_id(&self) -> WindowId {
3922        self.id
3923    }
3924
3925    /// Attempt to convert this handle to a window handle with a specific root view type.
3926    /// If the types do not match, this will return `None`.
3927    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3928        if TypeId::of::<T>() == self.state_type {
3929            Some(WindowHandle {
3930                any_handle: *self,
3931                state_type: PhantomData,
3932            })
3933        } else {
3934            None
3935        }
3936    }
3937
3938    /// Updates the state of the root view of this window.
3939    ///
3940    /// This will fail if the window has been closed.
3941    pub fn update<C, R>(
3942        self,
3943        cx: &mut C,
3944        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
3945    ) -> Result<R>
3946    where
3947        C: AppContext,
3948    {
3949        cx.update_window(self, update)
3950    }
3951
3952    /// Read the state of the root view of this window.
3953    ///
3954    /// This will fail if the window has been closed.
3955    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
3956    where
3957        C: AppContext,
3958        T: 'static,
3959    {
3960        let view = self
3961            .downcast::<T>()
3962            .context("the type of the window's root view has changed")?;
3963
3964        cx.read_window(&view, read)
3965    }
3966}
3967
3968impl HasWindowHandle for Window {
3969    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
3970        self.platform_window.window_handle()
3971    }
3972}
3973
3974/// An identifier for an [`Element`](crate::Element).
3975///
3976/// Can be constructed with a string, a number, or both, as well
3977/// as other internal representations.
3978#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3979pub enum ElementId {
3980    /// The ID of a View element
3981    View(EntityId),
3982    /// An integer ID.
3983    Integer(usize),
3984    /// A string based ID.
3985    Name(SharedString),
3986    /// A UUID.
3987    Uuid(Uuid),
3988    /// An ID that's equated with a focus handle.
3989    FocusHandle(FocusId),
3990    /// A combination of a name and an integer.
3991    NamedInteger(SharedString, usize),
3992    /// A path
3993    Path(Arc<std::path::Path>),
3994}
3995
3996impl Display for ElementId {
3997    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3998        match self {
3999            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4000            ElementId::Integer(ix) => write!(f, "{}", ix)?,
4001            ElementId::Name(name) => write!(f, "{}", name)?,
4002            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4003            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4004            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4005            ElementId::Path(path) => write!(f, "{}", path.display())?,
4006        }
4007
4008        Ok(())
4009    }
4010}
4011
4012impl TryInto<SharedString> for ElementId {
4013    type Error = anyhow::Error;
4014
4015    fn try_into(self) -> anyhow::Result<SharedString> {
4016        if let ElementId::Name(name) = self {
4017            Ok(name)
4018        } else {
4019            Err(anyhow!("element id is not string"))
4020        }
4021    }
4022}
4023
4024impl From<usize> for ElementId {
4025    fn from(id: usize) -> Self {
4026        ElementId::Integer(id)
4027    }
4028}
4029
4030impl From<i32> for ElementId {
4031    fn from(id: i32) -> Self {
4032        Self::Integer(id as usize)
4033    }
4034}
4035
4036impl From<SharedString> for ElementId {
4037    fn from(name: SharedString) -> Self {
4038        ElementId::Name(name)
4039    }
4040}
4041
4042impl From<Arc<std::path::Path>> for ElementId {
4043    fn from(path: Arc<std::path::Path>) -> Self {
4044        ElementId::Path(path)
4045    }
4046}
4047
4048impl From<&'static str> for ElementId {
4049    fn from(name: &'static str) -> Self {
4050        ElementId::Name(name.into())
4051    }
4052}
4053
4054impl<'a> From<&'a FocusHandle> for ElementId {
4055    fn from(handle: &'a FocusHandle) -> Self {
4056        ElementId::FocusHandle(handle.id)
4057    }
4058}
4059
4060impl From<(&'static str, EntityId)> for ElementId {
4061    fn from((name, id): (&'static str, EntityId)) -> Self {
4062        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4063    }
4064}
4065
4066impl From<(&'static str, usize)> for ElementId {
4067    fn from((name, id): (&'static str, usize)) -> Self {
4068        ElementId::NamedInteger(name.into(), id)
4069    }
4070}
4071
4072impl From<(SharedString, usize)> for ElementId {
4073    fn from((name, id): (SharedString, usize)) -> Self {
4074        ElementId::NamedInteger(name, id)
4075    }
4076}
4077
4078impl From<(&'static str, u64)> for ElementId {
4079    fn from((name, id): (&'static str, u64)) -> Self {
4080        ElementId::NamedInteger(name.into(), id as usize)
4081    }
4082}
4083
4084impl From<Uuid> for ElementId {
4085    fn from(value: Uuid) -> Self {
4086        Self::Uuid(value)
4087    }
4088}
4089
4090impl From<(&'static str, u32)> for ElementId {
4091    fn from((name, id): (&'static str, u32)) -> Self {
4092        ElementId::NamedInteger(name.into(), id as usize)
4093    }
4094}
4095
4096/// A rectangle to be rendered in the window at the given position and size.
4097/// Passed as an argument [`Window::paint_quad`].
4098#[derive(Clone)]
4099pub struct PaintQuad {
4100    /// The bounds of the quad within the window.
4101    pub bounds: Bounds<Pixels>,
4102    /// The radii of the quad's corners.
4103    pub corner_radii: Corners<Pixels>,
4104    /// The background color of the quad.
4105    pub background: Background,
4106    /// The widths of the quad's borders.
4107    pub border_widths: Edges<Pixels>,
4108    /// The color of the quad's borders.
4109    pub border_color: Hsla,
4110}
4111
4112impl PaintQuad {
4113    /// Sets the corner radii of the quad.
4114    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4115        PaintQuad {
4116            corner_radii: corner_radii.into(),
4117            ..self
4118        }
4119    }
4120
4121    /// Sets the border widths of the quad.
4122    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4123        PaintQuad {
4124            border_widths: border_widths.into(),
4125            ..self
4126        }
4127    }
4128
4129    /// Sets the border color of the quad.
4130    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4131        PaintQuad {
4132            border_color: border_color.into(),
4133            ..self
4134        }
4135    }
4136
4137    /// Sets the background color of the quad.
4138    pub fn background(self, background: impl Into<Background>) -> Self {
4139        PaintQuad {
4140            background: background.into(),
4141            ..self
4142        }
4143    }
4144}
4145
4146/// Creates a quad with the given parameters.
4147pub fn quad(
4148    bounds: Bounds<Pixels>,
4149    corner_radii: impl Into<Corners<Pixels>>,
4150    background: impl Into<Background>,
4151    border_widths: impl Into<Edges<Pixels>>,
4152    border_color: impl Into<Hsla>,
4153) -> PaintQuad {
4154    PaintQuad {
4155        bounds,
4156        corner_radii: corner_radii.into(),
4157        background: background.into(),
4158        border_widths: border_widths.into(),
4159        border_color: border_color.into(),
4160    }
4161}
4162
4163/// Creates a filled quad with the given bounds and background color.
4164pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
4165    PaintQuad {
4166        bounds: bounds.into(),
4167        corner_radii: (0.).into(),
4168        background: background.into(),
4169        border_widths: (0.).into(),
4170        border_color: transparent_black(),
4171    }
4172}
4173
4174/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4175pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4176    PaintQuad {
4177        bounds: bounds.into(),
4178        corner_radii: (0.).into(),
4179        background: transparent_black().into(),
4180        border_widths: (1.).into(),
4181        border_color: border_color.into(),
4182    }
4183}