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