window.rs

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