window.rs

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