window.rs

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