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