window.rs

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