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