window.rs

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