window.rs

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