window.rs

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