window.rs

   1#![deny(missing_docs)]
   2
   3use crate::{
   4    px, size, transparent_black, Action, AnyDrag, AnyView, AppContext, Arena, AsyncWindowContext,
   5    AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle, DevicePixels,
   6    DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
   7    EntityId, EventEmitter, FileDropEvent, Flatten, FontId, GlobalElementId, GlyphId, Hsla,
   8    ImageData, InputEvent, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeystrokeEvent, LayoutId,
   9    Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseMoveEvent, MouseUpEvent,
  10    Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point,
  11    PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams,
  12    RenderSvgParams, ScaledPixels, Scene, Shadow, SharedString, Size, Style, SubscriberSet,
  13    Subscription, Surface, TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext,
  14    WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
  15};
  16use anyhow::{anyhow, Context as _, Result};
  17use collections::{FxHashMap, FxHashSet};
  18use derive_more::{Deref, DerefMut};
  19use futures::{
  20    channel::{mpsc, oneshot},
  21    StreamExt,
  22};
  23use media::core_video::CVImageBuffer;
  24use parking_lot::RwLock;
  25use slotmap::SlotMap;
  26use smallvec::SmallVec;
  27use std::{
  28    any::{Any, TypeId},
  29    borrow::{Borrow, BorrowMut, Cow},
  30    cell::RefCell,
  31    collections::hash_map::Entry,
  32    fmt::Debug,
  33    future::Future,
  34    hash::{Hash, Hasher},
  35    marker::PhantomData,
  36    mem,
  37    rc::Rc,
  38    sync::{
  39        atomic::{AtomicUsize, Ordering::SeqCst},
  40        Arc,
  41    },
  42};
  43use util::{post_inc, ResultExt};
  44
  45const ACTIVE_DRAG_Z_INDEX: u8 = 1;
  46
  47/// A global stacking order, which is created by stacking successive z-index values.
  48/// Each z-index will always be interpreted in the context of its parent z-index.
  49#[derive(Deref, DerefMut, Clone, Ord, PartialOrd, PartialEq, Eq, Default)]
  50pub struct StackingOrder {
  51    #[deref]
  52    #[deref_mut]
  53    context_stack: SmallVec<[u8; 64]>,
  54    id: u32,
  55}
  56
  57impl std::fmt::Debug for StackingOrder {
  58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  59        let mut stacks = self.context_stack.iter().peekable();
  60        write!(f, "[({}): ", self.id)?;
  61        while let Some(z_index) = stacks.next() {
  62            write!(f, "{z_index}")?;
  63            if stacks.peek().is_some() {
  64                write!(f, "->")?;
  65            }
  66        }
  67        write!(f, "]")?;
  68        Ok(())
  69    }
  70}
  71
  72/// Represents the two different phases when dispatching events.
  73#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  74pub enum DispatchPhase {
  75    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  76    /// invoked front to back and keyboard event listeners are invoked from the focused element
  77    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  78    /// registering event listeners.
  79    #[default]
  80    Bubble,
  81    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  82    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  83    /// is used for special purposes such as clearing the "pressed" state for click events. If
  84    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  85    /// outside of the immediate region may rely on detecting non-local events during this phase.
  86    Capture,
  87}
  88
  89impl DispatchPhase {
  90    /// Returns true if this represents the "bubble" phase.
  91    pub fn bubble(self) -> bool {
  92        self == DispatchPhase::Bubble
  93    }
  94
  95    /// Returns true if this represents the "capture" phase.
  96    pub fn capture(self) -> bool {
  97        self == DispatchPhase::Capture
  98    }
  99}
 100
 101type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
 102type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
 103type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
 104
 105struct FocusEvent {
 106    previous_focus_path: SmallVec<[FocusId; 8]>,
 107    current_focus_path: SmallVec<[FocusId; 8]>,
 108}
 109
 110slotmap::new_key_type! {
 111    /// A globally unique identifier for a focusable element.
 112    pub struct FocusId;
 113}
 114
 115thread_local! {
 116    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(4 * 1024 * 1024));
 117}
 118
 119impl FocusId {
 120    /// Obtains whether the element associated with this handle is currently focused.
 121    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 122        cx.window.focus == Some(*self)
 123    }
 124
 125    /// Obtains whether the element associated with this handle contains the focused
 126    /// element or is itself focused.
 127    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 128        cx.focused()
 129            .map_or(false, |focused| self.contains(focused.id, cx))
 130    }
 131
 132    /// Obtains whether the element associated with this handle is contained within the
 133    /// focused element or is itself focused.
 134    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 135        let focused = cx.focused();
 136        focused.map_or(false, |focused| focused.id.contains(*self, cx))
 137    }
 138
 139    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 140    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 141        cx.window
 142            .rendered_frame
 143            .dispatch_tree
 144            .focus_contains(*self, other)
 145    }
 146}
 147
 148/// A handle which can be used to track and manipulate the focused element in a window.
 149pub struct FocusHandle {
 150    pub(crate) id: FocusId,
 151    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 152}
 153
 154impl std::fmt::Debug for FocusHandle {
 155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 156        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 157    }
 158}
 159
 160impl FocusHandle {
 161    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 162        let id = handles.write().insert(AtomicUsize::new(1));
 163        Self {
 164            id,
 165            handles: handles.clone(),
 166        }
 167    }
 168
 169    pub(crate) fn for_id(
 170        id: FocusId,
 171        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 172    ) -> Option<Self> {
 173        let lock = handles.read();
 174        let ref_count = lock.get(id)?;
 175        if ref_count.load(SeqCst) == 0 {
 176            None
 177        } else {
 178            ref_count.fetch_add(1, SeqCst);
 179            Some(Self {
 180                id,
 181                handles: handles.clone(),
 182            })
 183        }
 184    }
 185
 186    /// Moves the focus to the element associated with this handle.
 187    pub fn focus(&self, cx: &mut WindowContext) {
 188        cx.focus(self)
 189    }
 190
 191    /// Obtains whether the element associated with this handle is currently focused.
 192    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 193        self.id.is_focused(cx)
 194    }
 195
 196    /// Obtains whether the element associated with this handle contains the focused
 197    /// element or is itself focused.
 198    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 199        self.id.contains_focused(cx)
 200    }
 201
 202    /// Obtains whether the element associated with this handle is contained within the
 203    /// focused element or is itself focused.
 204    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 205        self.id.within_focused(cx)
 206    }
 207
 208    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 209    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 210        self.id.contains(other.id, cx)
 211    }
 212}
 213
 214impl Clone for FocusHandle {
 215    fn clone(&self) -> Self {
 216        Self::for_id(self.id, &self.handles).unwrap()
 217    }
 218}
 219
 220impl PartialEq for FocusHandle {
 221    fn eq(&self, other: &Self) -> bool {
 222        self.id == other.id
 223    }
 224}
 225
 226impl Eq for FocusHandle {}
 227
 228impl Drop for FocusHandle {
 229    fn drop(&mut self) {
 230        self.handles
 231            .read()
 232            .get(self.id)
 233            .unwrap()
 234            .fetch_sub(1, SeqCst);
 235    }
 236}
 237
 238/// FocusableView allows users of your view to easily
 239/// focus it (using cx.focus_view(view))
 240pub trait FocusableView: 'static + Render {
 241    /// Returns the focus handle associated with this view.
 242    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 243}
 244
 245/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 246/// where the lifecycle of the view is handled by another view.
 247pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 248
 249impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 250
 251/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 252pub struct DismissEvent;
 253
 254// Holds the state for a specific window.
 255#[doc(hidden)]
 256pub struct Window {
 257    pub(crate) handle: AnyWindowHandle,
 258    pub(crate) removed: bool,
 259    pub(crate) platform_window: Box<dyn PlatformWindow>,
 260    display_id: DisplayId,
 261    sprite_atlas: Arc<dyn PlatformAtlas>,
 262    rem_size: Pixels,
 263    viewport_size: Size<Pixels>,
 264    layout_engine: Option<TaffyLayoutEngine>,
 265    pub(crate) root_view: Option<AnyView>,
 266    pub(crate) element_id_stack: GlobalElementId,
 267    pub(crate) rendered_frame: Frame,
 268    pub(crate) next_frame: Frame,
 269    pub(crate) dirty_views: FxHashSet<EntityId>,
 270    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 271    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 272    focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 273    default_prevented: bool,
 274    mouse_position: Point<Pixels>,
 275    modifiers: Modifiers,
 276    requested_cursor_style: Option<CursorStyle>,
 277    scale_factor: f32,
 278    bounds: WindowBounds,
 279    bounds_observers: SubscriberSet<(), AnyObserver>,
 280    active: bool,
 281    pub(crate) dirty: bool,
 282    pub(crate) refreshing: bool,
 283    pub(crate) drawing: bool,
 284    activation_observers: SubscriberSet<(), AnyObserver>,
 285    pub(crate) focus: Option<FocusId>,
 286    focus_enabled: bool,
 287
 288    #[cfg(any(test, feature = "test-support"))]
 289    pub(crate) focus_invalidated: bool,
 290}
 291
 292pub(crate) struct ElementStateBox {
 293    inner: Box<dyn Any>,
 294    parent_view_id: EntityId,
 295    #[cfg(debug_assertions)]
 296    type_name: &'static str,
 297}
 298
 299pub(crate) struct Frame {
 300    focus: Option<FocusId>,
 301    window_active: bool,
 302    pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
 303    mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, EntityId, AnyMouseListener)>>,
 304    pub(crate) dispatch_tree: DispatchTree,
 305    pub(crate) scene: Scene,
 306    pub(crate) depth_map: Vec<(StackingOrder, EntityId, Bounds<Pixels>)>,
 307    pub(crate) z_index_stack: StackingOrder,
 308    pub(crate) next_stacking_order_id: u32,
 309    content_mask_stack: Vec<ContentMask<Pixels>>,
 310    element_offset_stack: Vec<Point<Pixels>>,
 311    pub(crate) view_stack: Vec<EntityId>,
 312    pub(crate) reused_views: FxHashSet<EntityId>,
 313}
 314
 315impl Frame {
 316    fn new(dispatch_tree: DispatchTree) -> Self {
 317        Frame {
 318            focus: None,
 319            window_active: false,
 320            element_states: FxHashMap::default(),
 321            mouse_listeners: FxHashMap::default(),
 322            dispatch_tree,
 323            scene: Scene::default(),
 324            z_index_stack: StackingOrder::default(),
 325            next_stacking_order_id: 0,
 326            depth_map: Default::default(),
 327            content_mask_stack: Vec::new(),
 328            element_offset_stack: Vec::new(),
 329            view_stack: Vec::new(),
 330            reused_views: FxHashSet::default(),
 331        }
 332    }
 333
 334    fn clear(&mut self) {
 335        self.element_states.clear();
 336        self.mouse_listeners.values_mut().for_each(Vec::clear);
 337        self.dispatch_tree.clear();
 338        self.depth_map.clear();
 339        self.next_stacking_order_id = 0;
 340        self.reused_views.clear();
 341        self.scene.clear();
 342        debug_assert_eq!(self.view_stack.len(), 0);
 343    }
 344
 345    fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 346        self.focus
 347            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 348            .unwrap_or_default()
 349    }
 350
 351    fn reuse_views(&mut self, prev_frame: &mut Self) {
 352        // Reuse mouse listeners that didn't change since the last frame.
 353        for (type_id, listeners) in &mut prev_frame.mouse_listeners {
 354            let next_listeners = self.mouse_listeners.entry(*type_id).or_default();
 355            for (order, view_id, listener) in listeners.drain(..) {
 356                if self.reused_views.contains(&view_id) {
 357                    next_listeners.push((order, view_id, listener));
 358                }
 359            }
 360        }
 361
 362        // Reuse entries in the depth map that didn't change since the last frame.
 363        for (order, view_id, bounds) in prev_frame.depth_map.drain(..) {
 364            if self.reused_views.contains(&view_id) {
 365                self.depth_map.push((order, view_id, bounds));
 366            }
 367        }
 368        self.depth_map.sort_by(|a, b| a.0.cmp(&b.0));
 369
 370        // Retain element states for views that didn't change since the last frame.
 371        for (element_id, state) in prev_frame.element_states.drain() {
 372            if self.reused_views.contains(&state.parent_view_id) {
 373                self.element_states.entry(element_id).or_insert(state);
 374            }
 375        }
 376
 377        // Reuse geometry that didn't change since the last frame.
 378        self.scene
 379            .reuse_views(&self.reused_views, &mut prev_frame.scene);
 380    }
 381}
 382
 383impl Window {
 384    pub(crate) fn new(
 385        handle: AnyWindowHandle,
 386        options: WindowOptions,
 387        cx: &mut AppContext,
 388    ) -> Self {
 389        let platform_window = cx.platform.open_window(handle, options);
 390        let display_id = platform_window.display().id();
 391        let sprite_atlas = platform_window.sprite_atlas();
 392        let mouse_position = platform_window.mouse_position();
 393        let modifiers = platform_window.modifiers();
 394        let content_size = platform_window.content_size();
 395        let scale_factor = platform_window.scale_factor();
 396        let bounds = platform_window.bounds();
 397
 398        platform_window.on_request_frame(Box::new({
 399            let mut cx = cx.to_async();
 400            move || {
 401                handle.update(&mut cx, |_, cx| cx.draw()).log_err();
 402            }
 403        }));
 404        platform_window.on_resize(Box::new({
 405            let mut cx = cx.to_async();
 406            move |_, _| {
 407                handle
 408                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 409                    .log_err();
 410            }
 411        }));
 412        platform_window.on_moved(Box::new({
 413            let mut cx = cx.to_async();
 414            move || {
 415                handle
 416                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 417                    .log_err();
 418            }
 419        }));
 420        platform_window.on_active_status_change(Box::new({
 421            let mut cx = cx.to_async();
 422            move |active| {
 423                handle
 424                    .update(&mut cx, |_, cx| {
 425                        cx.window.active = active;
 426                        cx.window
 427                            .activation_observers
 428                            .clone()
 429                            .retain(&(), |callback| callback(cx));
 430                    })
 431                    .log_err();
 432            }
 433        }));
 434
 435        platform_window.on_input({
 436            let mut cx = cx.to_async();
 437            Box::new(move |event| {
 438                handle
 439                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 440                    .log_err()
 441                    .unwrap_or(false)
 442            })
 443        });
 444
 445        Window {
 446            handle,
 447            removed: false,
 448            platform_window,
 449            display_id,
 450            sprite_atlas,
 451            rem_size: px(16.),
 452            viewport_size: content_size,
 453            layout_engine: Some(TaffyLayoutEngine::new()),
 454            root_view: None,
 455            element_id_stack: GlobalElementId::default(),
 456            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 457            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 458            dirty_views: FxHashSet::default(),
 459            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 460            focus_listeners: SubscriberSet::new(),
 461            focus_lost_listeners: SubscriberSet::new(),
 462            default_prevented: true,
 463            mouse_position,
 464            modifiers,
 465            requested_cursor_style: None,
 466            scale_factor,
 467            bounds,
 468            bounds_observers: SubscriberSet::new(),
 469            active: false,
 470            dirty: false,
 471            refreshing: false,
 472            drawing: false,
 473            activation_observers: SubscriberSet::new(),
 474            focus: None,
 475            focus_enabled: true,
 476
 477            #[cfg(any(test, feature = "test-support"))]
 478            focus_invalidated: false,
 479        }
 480    }
 481}
 482
 483/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 484/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 485/// to leave room to support more complex shapes in the future.
 486#[derive(Clone, Debug, Default, PartialEq, Eq)]
 487#[repr(C)]
 488pub struct ContentMask<P: Clone + Default + Debug> {
 489    /// The bounds
 490    pub bounds: Bounds<P>,
 491}
 492
 493impl ContentMask<Pixels> {
 494    /// Scale the content mask's pixel units by the given scaling factor.
 495    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 496        ContentMask {
 497            bounds: self.bounds.scale(factor),
 498        }
 499    }
 500
 501    /// Intersect the content mask with the given content mask.
 502    pub fn intersect(&self, other: &Self) -> Self {
 503        let bounds = self.bounds.intersect(&other.bounds);
 504        ContentMask { bounds }
 505    }
 506}
 507
 508/// Provides access to application state in the context of a single window. Derefs
 509/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
 510/// an [`AppContext`] and call any [`AppContext`] methods.
 511pub struct WindowContext<'a> {
 512    pub(crate) app: &'a mut AppContext,
 513    pub(crate) window: &'a mut Window,
 514}
 515
 516impl<'a> WindowContext<'a> {
 517    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 518        Self { app, window }
 519    }
 520
 521    /// Obtain a handle to the window that belongs to this context.
 522    pub fn window_handle(&self) -> AnyWindowHandle {
 523        self.window.handle
 524    }
 525
 526    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 527    pub fn refresh(&mut self) {
 528        if !self.window.drawing {
 529            self.window.refreshing = true;
 530            self.window.dirty = true;
 531        }
 532    }
 533
 534    /// Close this window.
 535    pub fn remove_window(&mut self) {
 536        self.window.removed = true;
 537    }
 538
 539    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
 540    /// for elements rendered within this window.
 541    pub fn focus_handle(&mut self) -> FocusHandle {
 542        FocusHandle::new(&self.window.focus_handles)
 543    }
 544
 545    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
 546    pub fn focused(&self) -> Option<FocusHandle> {
 547        self.window
 548            .focus
 549            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 550    }
 551
 552    /// Move focus to the element associated with the given [`FocusHandle`].
 553    pub fn focus(&mut self, handle: &FocusHandle) {
 554        if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
 555            return;
 556        }
 557
 558        self.window.focus = Some(handle.id);
 559        self.window
 560            .rendered_frame
 561            .dispatch_tree
 562            .clear_pending_keystrokes();
 563
 564        #[cfg(any(test, feature = "test-support"))]
 565        {
 566            self.window.focus_invalidated = true;
 567        }
 568
 569        self.refresh();
 570    }
 571
 572    /// Remove focus from all elements within this context's window.
 573    pub fn blur(&mut self) {
 574        if !self.window.focus_enabled {
 575            return;
 576        }
 577
 578        self.window.focus = None;
 579        self.refresh();
 580    }
 581
 582    /// Blur the window and don't allow anything in it to be focused again.
 583    pub fn disable_focus(&mut self) {
 584        self.blur();
 585        self.window.focus_enabled = false;
 586    }
 587
 588    /// Dispatch the given action on the currently focused element.
 589    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 590        let focus_handle = self.focused();
 591
 592        self.defer(move |cx| {
 593            let node_id = focus_handle
 594                .and_then(|handle| {
 595                    cx.window
 596                        .rendered_frame
 597                        .dispatch_tree
 598                        .focusable_node_id(handle.id)
 599                })
 600                .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
 601
 602            cx.propagate_event = true;
 603            cx.dispatch_action_on_node(node_id, action);
 604        })
 605    }
 606
 607    pub(crate) fn dispatch_keystroke_observers(
 608        &mut self,
 609        event: &dyn Any,
 610        action: Option<Box<dyn Action>>,
 611    ) {
 612        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
 613            return;
 614        };
 615
 616        self.keystroke_observers
 617            .clone()
 618            .retain(&(), move |callback| {
 619                (callback)(
 620                    &KeystrokeEvent {
 621                        keystroke: key_down_event.keystroke.clone(),
 622                        action: action.as_ref().map(|action| action.boxed_clone()),
 623                    },
 624                    self,
 625                );
 626                true
 627            });
 628    }
 629
 630    pub(crate) fn clear_pending_keystrokes(&mut self) {
 631        self.window
 632            .rendered_frame
 633            .dispatch_tree
 634            .clear_pending_keystrokes();
 635        self.window
 636            .next_frame
 637            .dispatch_tree
 638            .clear_pending_keystrokes();
 639    }
 640
 641    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 642    /// that are currently on the stack to be returned to the app.
 643    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 644        let handle = self.window.handle;
 645        self.app.defer(move |cx| {
 646            handle.update(cx, |_, cx| f(cx)).ok();
 647        });
 648    }
 649
 650    /// Subscribe to events emitted by a model or view.
 651    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
 652    /// The callback will be invoked a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a window context for the current window.
 653    pub fn subscribe<Emitter, E, Evt>(
 654        &mut self,
 655        entity: &E,
 656        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
 657    ) -> Subscription
 658    where
 659        Emitter: EventEmitter<Evt>,
 660        E: Entity<Emitter>,
 661        Evt: 'static,
 662    {
 663        let entity_id = entity.entity_id();
 664        let entity = entity.downgrade();
 665        let window_handle = self.window.handle;
 666        let (subscription, activate) = self.app.event_listeners.insert(
 667            entity_id,
 668            (
 669                TypeId::of::<Evt>(),
 670                Box::new(move |event, cx| {
 671                    window_handle
 672                        .update(cx, |_, cx| {
 673                            if let Some(handle) = E::upgrade_from(&entity) {
 674                                let event = event.downcast_ref().expect("invalid event type");
 675                                on_event(handle, event, cx);
 676                                true
 677                            } else {
 678                                false
 679                            }
 680                        })
 681                        .unwrap_or(false)
 682                }),
 683            ),
 684        );
 685        self.app.defer(move |_| activate());
 686        subscription
 687    }
 688
 689    /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
 690    /// await points in async code.
 691    pub fn to_async(&self) -> AsyncWindowContext {
 692        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 693    }
 694
 695    /// Schedule the given closure to be run directly after the current frame is rendered.
 696    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
 697        let handle = self.window.handle;
 698        let display_id = self.window.display_id;
 699
 700        let mut frame_consumers = std::mem::take(&mut self.app.frame_consumers);
 701        if let Entry::Vacant(e) = frame_consumers.entry(display_id) {
 702            let (tx, mut rx) = mpsc::unbounded::<()>();
 703            self.platform.set_display_link_output_callback(
 704                display_id,
 705                Box::new(move |_current_time, _output_time| _ = tx.unbounded_send(())),
 706            );
 707
 708            let consumer_task = self.app.spawn(|cx| async move {
 709                while rx.next().await.is_some() {
 710                    cx.update(|cx| {
 711                        for callback in cx
 712                            .next_frame_callbacks
 713                            .get_mut(&display_id)
 714                            .unwrap()
 715                            .drain(..)
 716                            .collect::<SmallVec<[_; 32]>>()
 717                        {
 718                            callback(cx);
 719                        }
 720                    })
 721                    .ok();
 722
 723                    // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
 724
 725                    cx.update(|cx| {
 726                        if cx.next_frame_callbacks.is_empty() {
 727                            cx.platform.stop_display_link(display_id);
 728                        }
 729                    })
 730                    .ok();
 731                }
 732            });
 733            e.insert(consumer_task);
 734        }
 735        debug_assert!(self.app.frame_consumers.is_empty());
 736        self.app.frame_consumers = frame_consumers;
 737
 738        if self.next_frame_callbacks.is_empty() {
 739            self.platform.start_display_link(display_id);
 740        }
 741
 742        self.next_frame_callbacks
 743            .entry(display_id)
 744            .or_default()
 745            .push(Box::new(move |cx: &mut AppContext| {
 746                cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
 747            }));
 748    }
 749
 750    /// Spawn the future returned by the given closure on the application thread pool.
 751    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 752    /// use within your future.
 753    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 754    where
 755        R: 'static,
 756        Fut: Future<Output = R> + 'static,
 757    {
 758        self.app
 759            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 760    }
 761
 762    /// Update the global of the given type. The given closure is given simultaneous mutable
 763    /// access both to the global and the context.
 764    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 765    where
 766        G: 'static,
 767    {
 768        let mut global = self.app.lease_global::<G>();
 769        let result = f(&mut global, self);
 770        self.app.end_global_lease(global);
 771        result
 772    }
 773
 774    #[must_use]
 775    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 776    /// layout is being requested, along with the layout ids of any children. This method is called during
 777    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 778    pub fn request_layout(
 779        &mut self,
 780        style: &Style,
 781        children: impl IntoIterator<Item = LayoutId>,
 782    ) -> LayoutId {
 783        self.app.layout_id_buffer.clear();
 784        self.app.layout_id_buffer.extend(children);
 785        let rem_size = self.rem_size();
 786
 787        self.window.layout_engine.as_mut().unwrap().request_layout(
 788            style,
 789            rem_size,
 790            &self.app.layout_id_buffer,
 791        )
 792    }
 793
 794    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 795    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 796    /// determine the element's size. One place this is used internally is when measuring text.
 797    ///
 798    /// The given closure is invoked at layout time with the known dimensions and available space and
 799    /// returns a `Size`.
 800    pub fn request_measured_layout<
 801        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
 802            + 'static,
 803    >(
 804        &mut self,
 805        style: Style,
 806        measure: F,
 807    ) -> LayoutId {
 808        let rem_size = self.rem_size();
 809        self.window
 810            .layout_engine
 811            .as_mut()
 812            .unwrap()
 813            .request_measured_layout(style, rem_size, measure)
 814    }
 815
 816    pub(crate) fn layout_style(&self, layout_id: LayoutId) -> Option<&Style> {
 817        self.window
 818            .layout_engine
 819            .as_ref()
 820            .unwrap()
 821            .requested_style(layout_id)
 822    }
 823
 824    /// Compute the layout for the given id within the given available space.
 825    /// This method is called for its side effect, typically by the framework prior to painting.
 826    /// After calling it, you can request the bounds of the given layout node id or any descendant.
 827    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
 828        let mut layout_engine = self.window.layout_engine.take().unwrap();
 829        layout_engine.compute_layout(layout_id, available_space, self);
 830        self.window.layout_engine = Some(layout_engine);
 831    }
 832
 833    /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
 834    /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
 835    /// in order to pass your element its `Bounds` automatically.
 836    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
 837        let mut bounds = self
 838            .window
 839            .layout_engine
 840            .as_mut()
 841            .unwrap()
 842            .layout_bounds(layout_id)
 843            .map(Into::into);
 844        bounds.origin += self.element_offset();
 845        bounds
 846    }
 847
 848    fn window_bounds_changed(&mut self) {
 849        self.window.scale_factor = self.window.platform_window.scale_factor();
 850        self.window.viewport_size = self.window.platform_window.content_size();
 851        self.window.bounds = self.window.platform_window.bounds();
 852        self.window.display_id = self.window.platform_window.display().id();
 853        self.refresh();
 854
 855        self.window
 856            .bounds_observers
 857            .clone()
 858            .retain(&(), |callback| callback(self));
 859    }
 860
 861    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
 862    pub fn window_bounds(&self) -> WindowBounds {
 863        self.window.bounds
 864    }
 865
 866    /// Returns the size of the drawable area within the window.
 867    pub fn viewport_size(&self) -> Size<Pixels> {
 868        self.window.viewport_size
 869    }
 870
 871    /// Returns whether this window is focused by the operating system (receiving key events).
 872    pub fn is_window_active(&self) -> bool {
 873        self.window.active
 874    }
 875
 876    /// Toggle zoom on the window.
 877    pub fn zoom_window(&self) {
 878        self.window.platform_window.zoom();
 879    }
 880
 881    /// Update the window's title at the platform level.
 882    pub fn set_window_title(&mut self, title: &str) {
 883        self.window.platform_window.set_title(title);
 884    }
 885
 886    /// Mark the window as dirty at the platform level.
 887    pub fn set_window_edited(&mut self, edited: bool) {
 888        self.window.platform_window.set_edited(edited);
 889    }
 890
 891    /// Determine the display on which the window is visible.
 892    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 893        self.platform
 894            .displays()
 895            .into_iter()
 896            .find(|display| display.id() == self.window.display_id)
 897    }
 898
 899    /// Show the platform character palette.
 900    pub fn show_character_palette(&self) {
 901        self.window.platform_window.show_character_palette();
 902    }
 903
 904    /// The scale factor of the display associated with the window. For example, it could
 905    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 906    /// be rendered as two pixels on screen.
 907    pub fn scale_factor(&self) -> f32 {
 908        self.window.scale_factor
 909    }
 910
 911    /// The size of an em for the base font of the application. Adjusting this value allows the
 912    /// UI to scale, just like zooming a web page.
 913    pub fn rem_size(&self) -> Pixels {
 914        self.window.rem_size
 915    }
 916
 917    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 918    /// UI to scale, just like zooming a web page.
 919    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 920        self.window.rem_size = rem_size.into();
 921    }
 922
 923    /// The line height associated with the current text style.
 924    pub fn line_height(&self) -> Pixels {
 925        let rem_size = self.rem_size();
 926        let text_style = self.text_style();
 927        text_style
 928            .line_height
 929            .to_pixels(text_style.font_size, rem_size)
 930    }
 931
 932    /// Call to prevent the default action of an event. Currently only used to prevent
 933    /// parent elements from becoming focused on mouse down.
 934    pub fn prevent_default(&mut self) {
 935        self.window.default_prevented = true;
 936    }
 937
 938    /// Obtain whether default has been prevented for the event currently being dispatched.
 939    pub fn default_prevented(&self) -> bool {
 940        self.window.default_prevented
 941    }
 942
 943    /// Register a mouse event listener on the window for the next frame. The type of event
 944    /// is determined by the first parameter of the given listener. When the next frame is rendered
 945    /// the listener will be cleared.
 946    pub fn on_mouse_event<Event: 'static>(
 947        &mut self,
 948        mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
 949    ) {
 950        let view_id = self.parent_view_id().unwrap();
 951        let order = self.window.next_frame.z_index_stack.clone();
 952        self.window
 953            .next_frame
 954            .mouse_listeners
 955            .entry(TypeId::of::<Event>())
 956            .or_default()
 957            .push((
 958                order,
 959                view_id,
 960                Box::new(
 961                    move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
 962                        handler(event.downcast_ref().unwrap(), phase, cx)
 963                    },
 964                ),
 965            ))
 966    }
 967
 968    /// Register a key event listener on the window for the next frame. The type of event
 969    /// is determined by the first parameter of the given listener. When the next frame is rendered
 970    /// the listener will be cleared.
 971    ///
 972    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 973    /// a specific need to register a global listener.
 974    pub fn on_key_event<Event: 'static>(
 975        &mut self,
 976        listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 977    ) {
 978        self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
 979            move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
 980                if let Some(event) = event.downcast_ref::<Event>() {
 981                    listener(event, phase, cx)
 982                }
 983            },
 984        ));
 985    }
 986
 987    /// Register an action listener on the window for the next frame. The type of action
 988    /// is determined by the first parameter of the given listener. When the next frame is rendered
 989    /// the listener will be cleared.
 990    ///
 991    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
 992    /// a specific need to register a global listener.
 993    pub fn on_action(
 994        &mut self,
 995        action_type: TypeId,
 996        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
 997    ) {
 998        self.window
 999            .next_frame
1000            .dispatch_tree
1001            .on_action(action_type, Rc::new(listener));
1002    }
1003
1004    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1005    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1006        let target = self
1007            .focused()
1008            .and_then(|focused_handle| {
1009                self.window
1010                    .rendered_frame
1011                    .dispatch_tree
1012                    .focusable_node_id(focused_handle.id)
1013            })
1014            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1015        self.window
1016            .rendered_frame
1017            .dispatch_tree
1018            .is_action_available(action, target)
1019    }
1020
1021    /// The position of the mouse relative to the window.
1022    pub fn mouse_position(&self) -> Point<Pixels> {
1023        self.window.mouse_position
1024    }
1025
1026    /// The current state of the keyboard's modifiers
1027    pub fn modifiers(&self) -> Modifiers {
1028        self.window.modifiers
1029    }
1030
1031    /// Update the cursor style at the platform level.
1032    pub fn set_cursor_style(&mut self, style: CursorStyle) {
1033        self.window.requested_cursor_style = Some(style)
1034    }
1035
1036    /// Called during painting to track which z-index is on top at each pixel position
1037    pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
1038        let stacking_order = self.window.next_frame.z_index_stack.clone();
1039        let view_id = self.parent_view_id().unwrap();
1040        self.window
1041            .next_frame
1042            .depth_map
1043            .push((stacking_order, view_id, bounds));
1044    }
1045
1046    /// Returns true if there is no opaque layer containing the given point
1047    /// on top of the given level. Layers whose level is an extension of the
1048    /// level are not considered to be on top of the level.
1049    pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
1050        for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
1051            if level >= opaque_level {
1052                break;
1053            }
1054
1055            if bounds.contains(point) && !opaque_level.starts_with(level) {
1056                return false;
1057            }
1058        }
1059        true
1060    }
1061
1062    pub(crate) fn was_top_layer_under_active_drag(
1063        &self,
1064        point: &Point<Pixels>,
1065        level: &StackingOrder,
1066    ) -> bool {
1067        for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
1068            if level >= opaque_level {
1069                break;
1070            }
1071            if opaque_level.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
1072                continue;
1073            }
1074
1075            if bounds.contains(point) && !opaque_level.starts_with(level) {
1076                return false;
1077            }
1078        }
1079        true
1080    }
1081
1082    /// Called during painting to get the current stacking order.
1083    pub fn stacking_order(&self) -> &StackingOrder {
1084        &self.window.next_frame.z_index_stack
1085    }
1086
1087    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
1088    pub fn paint_shadows(
1089        &mut self,
1090        bounds: Bounds<Pixels>,
1091        corner_radii: Corners<Pixels>,
1092        shadows: &[BoxShadow],
1093    ) {
1094        let scale_factor = self.scale_factor();
1095        let content_mask = self.content_mask();
1096        let view_id = self.parent_view_id().unwrap();
1097        let window = &mut *self.window;
1098        for shadow in shadows {
1099            let mut shadow_bounds = bounds;
1100            shadow_bounds.origin += shadow.offset;
1101            shadow_bounds.dilate(shadow.spread_radius);
1102            window.next_frame.scene.insert(
1103                &window.next_frame.z_index_stack,
1104                Shadow {
1105                    view_id: view_id.into(),
1106                    layer_id: 0,
1107                    order: 0,
1108                    bounds: shadow_bounds.scale(scale_factor),
1109                    content_mask: content_mask.scale(scale_factor),
1110                    corner_radii: corner_radii.scale(scale_factor),
1111                    color: shadow.color,
1112                    blur_radius: shadow.blur_radius.scale(scale_factor),
1113                },
1114            );
1115        }
1116    }
1117
1118    /// Paint one or more quads into the scene for the next frame at the current stacking context.
1119    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
1120    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
1121    pub fn paint_quad(&mut self, quad: PaintQuad) {
1122        let scale_factor = self.scale_factor();
1123        let content_mask = self.content_mask();
1124        let view_id = self.parent_view_id().unwrap();
1125
1126        let window = &mut *self.window;
1127        window.next_frame.scene.insert(
1128            &window.next_frame.z_index_stack,
1129            Quad {
1130                view_id: view_id.into(),
1131                layer_id: 0,
1132                order: 0,
1133                bounds: quad.bounds.scale(scale_factor),
1134                content_mask: content_mask.scale(scale_factor),
1135                background: quad.background,
1136                border_color: quad.border_color,
1137                corner_radii: quad.corner_radii.scale(scale_factor),
1138                border_widths: quad.border_widths.scale(scale_factor),
1139            },
1140        );
1141    }
1142
1143    /// Paint the given `Path` into the scene for the next frame at the current z-index.
1144    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
1145        let scale_factor = self.scale_factor();
1146        let content_mask = self.content_mask();
1147        let view_id = self.parent_view_id().unwrap();
1148
1149        path.content_mask = content_mask;
1150        path.color = color.into();
1151        path.view_id = view_id.into();
1152        let window = &mut *self.window;
1153        window
1154            .next_frame
1155            .scene
1156            .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1157    }
1158
1159    /// Paint an underline into the scene for the next frame at the current z-index.
1160    pub fn paint_underline(
1161        &mut self,
1162        origin: Point<Pixels>,
1163        width: Pixels,
1164        style: &UnderlineStyle,
1165    ) {
1166        let scale_factor = self.scale_factor();
1167        let height = if style.wavy {
1168            style.thickness * 3.
1169        } else {
1170            style.thickness
1171        };
1172        let bounds = Bounds {
1173            origin,
1174            size: size(width, height),
1175        };
1176        let content_mask = self.content_mask();
1177        let view_id = self.parent_view_id().unwrap();
1178
1179        let window = &mut *self.window;
1180        window.next_frame.scene.insert(
1181            &window.next_frame.z_index_stack,
1182            Underline {
1183                view_id: view_id.into(),
1184                layer_id: 0,
1185                order: 0,
1186                bounds: bounds.scale(scale_factor),
1187                content_mask: content_mask.scale(scale_factor),
1188                thickness: style.thickness.scale(scale_factor),
1189                color: style.color.unwrap_or_default(),
1190                wavy: style.wavy,
1191            },
1192        );
1193    }
1194
1195    /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1196    /// The y component of the origin is the baseline of the glyph.
1197    pub fn paint_glyph(
1198        &mut self,
1199        origin: Point<Pixels>,
1200        font_id: FontId,
1201        glyph_id: GlyphId,
1202        font_size: Pixels,
1203        color: Hsla,
1204    ) -> Result<()> {
1205        let scale_factor = self.scale_factor();
1206        let glyph_origin = origin.scale(scale_factor);
1207        let subpixel_variant = Point {
1208            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1209            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1210        };
1211        let params = RenderGlyphParams {
1212            font_id,
1213            glyph_id,
1214            font_size,
1215            subpixel_variant,
1216            scale_factor,
1217            is_emoji: false,
1218        };
1219
1220        let raster_bounds = self.text_system().raster_bounds(&params)?;
1221        if !raster_bounds.is_zero() {
1222            let tile =
1223                self.window
1224                    .sprite_atlas
1225                    .get_or_insert_with(&params.clone().into(), &mut || {
1226                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1227                        Ok((size, Cow::Owned(bytes)))
1228                    })?;
1229            let bounds = Bounds {
1230                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1231                size: tile.bounds.size.map(Into::into),
1232            };
1233            let content_mask = self.content_mask().scale(scale_factor);
1234            let view_id = self.parent_view_id().unwrap();
1235            let window = &mut *self.window;
1236            window.next_frame.scene.insert(
1237                &window.next_frame.z_index_stack,
1238                MonochromeSprite {
1239                    view_id: view_id.into(),
1240                    layer_id: 0,
1241                    order: 0,
1242                    bounds,
1243                    content_mask,
1244                    color,
1245                    tile,
1246                },
1247            );
1248        }
1249        Ok(())
1250    }
1251
1252    /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1253    /// The y component of the origin is the baseline of the glyph.
1254    pub fn paint_emoji(
1255        &mut self,
1256        origin: Point<Pixels>,
1257        font_id: FontId,
1258        glyph_id: GlyphId,
1259        font_size: Pixels,
1260    ) -> Result<()> {
1261        let scale_factor = self.scale_factor();
1262        let glyph_origin = origin.scale(scale_factor);
1263        let params = RenderGlyphParams {
1264            font_id,
1265            glyph_id,
1266            font_size,
1267            // We don't render emojis with subpixel variants.
1268            subpixel_variant: Default::default(),
1269            scale_factor,
1270            is_emoji: true,
1271        };
1272
1273        let raster_bounds = self.text_system().raster_bounds(&params)?;
1274        if !raster_bounds.is_zero() {
1275            let tile =
1276                self.window
1277                    .sprite_atlas
1278                    .get_or_insert_with(&params.clone().into(), &mut || {
1279                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1280                        Ok((size, Cow::Owned(bytes)))
1281                    })?;
1282            let bounds = Bounds {
1283                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1284                size: tile.bounds.size.map(Into::into),
1285            };
1286            let content_mask = self.content_mask().scale(scale_factor);
1287            let view_id = self.parent_view_id().unwrap();
1288            let window = &mut *self.window;
1289
1290            window.next_frame.scene.insert(
1291                &window.next_frame.z_index_stack,
1292                PolychromeSprite {
1293                    view_id: view_id.into(),
1294                    layer_id: 0,
1295                    order: 0,
1296                    bounds,
1297                    corner_radii: Default::default(),
1298                    content_mask,
1299                    tile,
1300                    grayscale: false,
1301                },
1302            );
1303        }
1304        Ok(())
1305    }
1306
1307    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1308    pub fn paint_svg(
1309        &mut self,
1310        bounds: Bounds<Pixels>,
1311        path: SharedString,
1312        color: Hsla,
1313    ) -> Result<()> {
1314        let scale_factor = self.scale_factor();
1315        let bounds = bounds.scale(scale_factor);
1316        // Render the SVG at twice the size to get a higher quality result.
1317        let params = RenderSvgParams {
1318            path,
1319            size: bounds
1320                .size
1321                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1322        };
1323
1324        let tile =
1325            self.window
1326                .sprite_atlas
1327                .get_or_insert_with(&params.clone().into(), &mut || {
1328                    let bytes = self.svg_renderer.render(&params)?;
1329                    Ok((params.size, Cow::Owned(bytes)))
1330                })?;
1331        let content_mask = self.content_mask().scale(scale_factor);
1332        let view_id = self.parent_view_id().unwrap();
1333
1334        let window = &mut *self.window;
1335        window.next_frame.scene.insert(
1336            &window.next_frame.z_index_stack,
1337            MonochromeSprite {
1338                view_id: view_id.into(),
1339                layer_id: 0,
1340                order: 0,
1341                bounds,
1342                content_mask,
1343                color,
1344                tile,
1345            },
1346        );
1347
1348        Ok(())
1349    }
1350
1351    /// Paint an image into the scene for the next frame at the current z-index.
1352    pub fn paint_image(
1353        &mut self,
1354        bounds: Bounds<Pixels>,
1355        corner_radii: Corners<Pixels>,
1356        data: Arc<ImageData>,
1357        grayscale: bool,
1358    ) -> Result<()> {
1359        let scale_factor = self.scale_factor();
1360        let bounds = bounds.scale(scale_factor);
1361        let params = RenderImageParams { image_id: data.id };
1362
1363        let tile = self
1364            .window
1365            .sprite_atlas
1366            .get_or_insert_with(&params.clone().into(), &mut || {
1367                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1368            })?;
1369        let content_mask = self.content_mask().scale(scale_factor);
1370        let corner_radii = corner_radii.scale(scale_factor);
1371        let view_id = self.parent_view_id().unwrap();
1372
1373        let window = &mut *self.window;
1374        window.next_frame.scene.insert(
1375            &window.next_frame.z_index_stack,
1376            PolychromeSprite {
1377                view_id: view_id.into(),
1378                layer_id: 0,
1379                order: 0,
1380                bounds,
1381                content_mask,
1382                corner_radii,
1383                tile,
1384                grayscale,
1385            },
1386        );
1387        Ok(())
1388    }
1389
1390    /// Paint a surface into the scene for the next frame at the current z-index.
1391    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1392        let scale_factor = self.scale_factor();
1393        let bounds = bounds.scale(scale_factor);
1394        let content_mask = self.content_mask().scale(scale_factor);
1395        let view_id = self.parent_view_id().unwrap();
1396        let window = &mut *self.window;
1397        window.next_frame.scene.insert(
1398            &window.next_frame.z_index_stack,
1399            Surface {
1400                view_id: view_id.into(),
1401                layer_id: 0,
1402                order: 0,
1403                bounds,
1404                content_mask,
1405                image_buffer,
1406            },
1407        );
1408    }
1409
1410    pub(crate) fn reuse_view(&mut self) {
1411        let view_id = self.parent_view_id().unwrap();
1412        let window = &mut self.window;
1413        let grafted_view_ids = window
1414            .next_frame
1415            .dispatch_tree
1416            .graft(view_id, &mut window.rendered_frame.dispatch_tree);
1417        for view_id in grafted_view_ids {
1418            assert!(window.next_frame.reused_views.insert(view_id));
1419        }
1420    }
1421
1422    /// Draw pixels to the display for this window based on the contents of its scene.
1423    pub(crate) fn draw(&mut self) {
1424        self.window.dirty = false;
1425        self.window.drawing = true;
1426
1427        #[cfg(any(test, feature = "test-support"))]
1428        {
1429            self.window.focus_invalidated = false;
1430        }
1431
1432        self.text_system().start_frame();
1433        self.window.platform_window.clear_input_handler();
1434        self.window.layout_engine.as_mut().unwrap().clear();
1435        self.window.next_frame.clear();
1436        let root_view = self.window.root_view.take().unwrap();
1437
1438        self.with_z_index(0, |cx| {
1439            cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1440                for (action_type, action_listeners) in &cx.app.global_action_listeners {
1441                    for action_listener in action_listeners.iter().cloned() {
1442                        cx.window.next_frame.dispatch_tree.on_action(
1443                            *action_type,
1444                            Rc::new(move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1445                                action_listener(action, phase, cx)
1446                            }),
1447                        )
1448                    }
1449                }
1450
1451                let available_space = cx.window.viewport_size.map(Into::into);
1452                root_view.draw(Point::default(), available_space, cx);
1453            })
1454        });
1455
1456        if let Some(active_drag) = self.app.active_drag.take() {
1457            self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1458                let offset = cx.mouse_position() - active_drag.cursor_offset;
1459                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1460                active_drag.view.draw(offset, available_space, cx);
1461            });
1462            self.active_drag = Some(active_drag);
1463        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1464            self.with_z_index(1, |cx| {
1465                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1466                active_tooltip
1467                    .view
1468                    .draw(active_tooltip.cursor_offset, available_space, cx);
1469            });
1470        }
1471        self.window.dirty_views.clear();
1472
1473        self.window
1474            .next_frame
1475            .dispatch_tree
1476            .preserve_pending_keystrokes(
1477                &mut self.window.rendered_frame.dispatch_tree,
1478                self.window.focus,
1479            );
1480        self.window.next_frame.focus = self.window.focus;
1481        self.window.next_frame.window_active = self.window.active;
1482        self.window.root_view = Some(root_view);
1483
1484        self.window
1485            .next_frame
1486            .reuse_views(&mut self.window.rendered_frame);
1487        self.window.next_frame.scene.finish();
1488
1489        let previous_focus_path = self.window.rendered_frame.focus_path();
1490        let previous_window_active = self.window.rendered_frame.window_active;
1491        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1492        let current_focus_path = self.window.rendered_frame.focus_path();
1493        let current_window_active = self.window.rendered_frame.window_active;
1494
1495        // Set the cursor only if we're the active window.
1496        let cursor_style = self
1497            .window
1498            .requested_cursor_style
1499            .take()
1500            .unwrap_or(CursorStyle::Arrow);
1501        if self.is_window_active() {
1502            self.platform.set_cursor_style(cursor_style);
1503        }
1504
1505        self.window.refreshing = false;
1506        self.window.drawing = false;
1507        ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
1508
1509        if previous_focus_path != current_focus_path
1510            || previous_window_active != current_window_active
1511        {
1512            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1513                self.window
1514                    .focus_lost_listeners
1515                    .clone()
1516                    .retain(&(), |listener| listener(self));
1517            }
1518
1519            let event = FocusEvent {
1520                previous_focus_path: if previous_window_active {
1521                    previous_focus_path
1522                } else {
1523                    Default::default()
1524                },
1525                current_focus_path: if current_window_active {
1526                    current_focus_path
1527                } else {
1528                    Default::default()
1529                },
1530            };
1531            self.window
1532                .focus_listeners
1533                .clone()
1534                .retain(&(), |listener| listener(&event, self));
1535        }
1536
1537        self.window
1538            .platform_window
1539            .draw(&self.window.rendered_frame.scene);
1540    }
1541
1542    /// Dispatch a mouse or keyboard event on the window.
1543    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1544        // Handlers may set this to false by calling `stop_propagation`.
1545        self.app.propagate_event = true;
1546        // Handlers may set this to true by calling `prevent_default`.
1547        self.window.default_prevented = false;
1548
1549        let event = match event {
1550            // Track the mouse position with our own state, since accessing the platform
1551            // API for the mouse position can only occur on the main thread.
1552            InputEvent::MouseMove(mouse_move) => {
1553                self.window.mouse_position = mouse_move.position;
1554                self.window.modifiers = mouse_move.modifiers;
1555                InputEvent::MouseMove(mouse_move)
1556            }
1557            InputEvent::MouseDown(mouse_down) => {
1558                self.window.mouse_position = mouse_down.position;
1559                self.window.modifiers = mouse_down.modifiers;
1560                InputEvent::MouseDown(mouse_down)
1561            }
1562            InputEvent::MouseUp(mouse_up) => {
1563                self.window.mouse_position = mouse_up.position;
1564                self.window.modifiers = mouse_up.modifiers;
1565                InputEvent::MouseUp(mouse_up)
1566            }
1567            InputEvent::MouseExited(mouse_exited) => {
1568                self.window.modifiers = mouse_exited.modifiers;
1569                InputEvent::MouseExited(mouse_exited)
1570            }
1571            InputEvent::ModifiersChanged(modifiers_changed) => {
1572                self.window.modifiers = modifiers_changed.modifiers;
1573                InputEvent::ModifiersChanged(modifiers_changed)
1574            }
1575            InputEvent::ScrollWheel(scroll_wheel) => {
1576                self.window.mouse_position = scroll_wheel.position;
1577                self.window.modifiers = scroll_wheel.modifiers;
1578                InputEvent::ScrollWheel(scroll_wheel)
1579            }
1580            // Translate dragging and dropping of external files from the operating system
1581            // to internal drag and drop events.
1582            InputEvent::FileDrop(file_drop) => match file_drop {
1583                FileDropEvent::Entered { position, paths } => {
1584                    self.window.mouse_position = position;
1585                    if self.active_drag.is_none() {
1586                        self.active_drag = Some(AnyDrag {
1587                            value: Box::new(paths.clone()),
1588                            view: self.new_view(|_| paths).into(),
1589                            cursor_offset: position,
1590                        });
1591                    }
1592                    InputEvent::MouseMove(MouseMoveEvent {
1593                        position,
1594                        pressed_button: Some(MouseButton::Left),
1595                        modifiers: Modifiers::default(),
1596                    })
1597                }
1598                FileDropEvent::Pending { position } => {
1599                    self.window.mouse_position = position;
1600                    InputEvent::MouseMove(MouseMoveEvent {
1601                        position,
1602                        pressed_button: Some(MouseButton::Left),
1603                        modifiers: Modifiers::default(),
1604                    })
1605                }
1606                FileDropEvent::Submit { position } => {
1607                    self.activate(true);
1608                    self.window.mouse_position = position;
1609                    InputEvent::MouseUp(MouseUpEvent {
1610                        button: MouseButton::Left,
1611                        position,
1612                        modifiers: Modifiers::default(),
1613                        click_count: 1,
1614                    })
1615                }
1616                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1617                    button: MouseButton::Left,
1618                    position: Point::default(),
1619                    modifiers: Modifiers::default(),
1620                    click_count: 1,
1621                }),
1622            },
1623            InputEvent::KeyDown(_) | InputEvent::KeyUp(_) => event,
1624        };
1625
1626        if let Some(any_mouse_event) = event.mouse_event() {
1627            self.dispatch_mouse_event(any_mouse_event);
1628        } else if let Some(any_key_event) = event.keyboard_event() {
1629            self.dispatch_key_event(any_key_event);
1630        }
1631
1632        !self.app.propagate_event
1633    }
1634
1635    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1636        if let Some(mut handlers) = self
1637            .window
1638            .rendered_frame
1639            .mouse_listeners
1640            .remove(&event.type_id())
1641        {
1642            // Because handlers may add other handlers, we sort every time.
1643            handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
1644
1645            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1646            // special purposes, such as detecting events outside of a given Bounds.
1647            for (_, _, handler) in &mut handlers {
1648                handler(event, DispatchPhase::Capture, self);
1649                if !self.app.propagate_event {
1650                    break;
1651                }
1652            }
1653
1654            // Bubble phase, where most normal handlers do their work.
1655            if self.app.propagate_event {
1656                for (_, _, handler) in handlers.iter_mut().rev() {
1657                    handler(event, DispatchPhase::Bubble, self);
1658                    if !self.app.propagate_event {
1659                        break;
1660                    }
1661                }
1662            }
1663
1664            self.window
1665                .rendered_frame
1666                .mouse_listeners
1667                .insert(event.type_id(), handlers);
1668        }
1669
1670        if self.app.propagate_event && self.has_active_drag() {
1671            if event.is::<MouseMoveEvent>() {
1672                // If this was a mouse move event, redraw the window so that the
1673                // active drag can follow the mouse cursor.
1674                self.refresh();
1675            } else if event.is::<MouseUpEvent>() {
1676                // If this was a mouse up event, cancel the active drag and redraw
1677                // the window.
1678                self.active_drag = None;
1679                self.refresh();
1680            }
1681        }
1682    }
1683
1684    fn dispatch_key_event(&mut self, event: &dyn Any) {
1685        let node_id = self
1686            .window
1687            .focus
1688            .and_then(|focus_id| {
1689                self.window
1690                    .rendered_frame
1691                    .dispatch_tree
1692                    .focusable_node_id(focus_id)
1693            })
1694            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1695
1696        let dispatch_path = self
1697            .window
1698            .rendered_frame
1699            .dispatch_tree
1700            .dispatch_path(node_id);
1701
1702        let mut actions: Vec<Box<dyn Action>> = Vec::new();
1703
1704        let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1705        for node_id in &dispatch_path {
1706            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1707
1708            if let Some(context) = node.context.clone() {
1709                context_stack.push(context);
1710            }
1711        }
1712
1713        for node_id in dispatch_path.iter().rev() {
1714            // Match keystrokes
1715            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1716            if node.context.is_some() {
1717                if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1718                    let mut new_actions = self
1719                        .window
1720                        .rendered_frame
1721                        .dispatch_tree
1722                        .dispatch_key(&key_down_event.keystroke, &context_stack);
1723                    actions.append(&mut new_actions);
1724                }
1725
1726                context_stack.pop();
1727            }
1728        }
1729
1730        if !actions.is_empty() {
1731            self.clear_pending_keystrokes();
1732        }
1733
1734        self.propagate_event = true;
1735        for action in actions {
1736            self.dispatch_action_on_node(node_id, action.boxed_clone());
1737            if !self.propagate_event {
1738                self.dispatch_keystroke_observers(event, Some(action));
1739                return;
1740            }
1741        }
1742
1743        // Capture phase
1744        for node_id in &dispatch_path {
1745            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1746
1747            for key_listener in node.key_listeners.clone() {
1748                key_listener(event, DispatchPhase::Capture, self);
1749                if !self.propagate_event {
1750                    return;
1751                }
1752            }
1753        }
1754
1755        // Bubble phase
1756        for node_id in dispatch_path.iter().rev() {
1757            // Handle low level key events
1758            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1759            for key_listener in node.key_listeners.clone() {
1760                key_listener(event, DispatchPhase::Bubble, self);
1761                if !self.propagate_event {
1762                    return;
1763                }
1764            }
1765        }
1766
1767        self.dispatch_keystroke_observers(event, None);
1768    }
1769
1770    /// Determine whether a potential multi-stroke key binding is in progress on this window.
1771    pub fn has_pending_keystrokes(&self) -> bool {
1772        self.window
1773            .rendered_frame
1774            .dispatch_tree
1775            .has_pending_keystrokes()
1776    }
1777
1778    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1779        let dispatch_path = self
1780            .window
1781            .rendered_frame
1782            .dispatch_tree
1783            .dispatch_path(node_id);
1784
1785        // Capture phase
1786        for node_id in &dispatch_path {
1787            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1788            for DispatchActionListener {
1789                action_type,
1790                listener,
1791            } in node.action_listeners.clone()
1792            {
1793                let any_action = action.as_any();
1794                if action_type == any_action.type_id() {
1795                    listener(any_action, DispatchPhase::Capture, self);
1796                    if !self.propagate_event {
1797                        return;
1798                    }
1799                }
1800            }
1801        }
1802        // Bubble phase
1803        for node_id in dispatch_path.iter().rev() {
1804            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1805            for DispatchActionListener {
1806                action_type,
1807                listener,
1808            } in node.action_listeners.clone()
1809            {
1810                let any_action = action.as_any();
1811                if action_type == any_action.type_id() {
1812                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1813                    listener(any_action, DispatchPhase::Bubble, self);
1814                    if !self.propagate_event {
1815                        return;
1816                    }
1817                }
1818            }
1819        }
1820    }
1821
1822    /// Register the given handler to be invoked whenever the global of the given type
1823    /// is updated.
1824    pub fn observe_global<G: 'static>(
1825        &mut self,
1826        f: impl Fn(&mut WindowContext<'_>) + 'static,
1827    ) -> Subscription {
1828        let window_handle = self.window.handle;
1829        let (subscription, activate) = self.global_observers.insert(
1830            TypeId::of::<G>(),
1831            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1832        );
1833        self.app.defer(move |_| activate());
1834        subscription
1835    }
1836
1837    /// Focus the current window and bring it to the foreground at the platform level.
1838    pub fn activate_window(&self) {
1839        self.window.platform_window.activate();
1840    }
1841
1842    /// Minimize the current window at the platform level.
1843    pub fn minimize_window(&self) {
1844        self.window.platform_window.minimize();
1845    }
1846
1847    /// Toggle full screen status on the current window at the platform level.
1848    pub fn toggle_full_screen(&self) {
1849        self.window.platform_window.toggle_full_screen();
1850    }
1851
1852    /// Present a platform dialog.
1853    /// The provided message will be presented, along with buttons for each answer.
1854    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1855    pub fn prompt(
1856        &self,
1857        level: PromptLevel,
1858        message: &str,
1859        answers: &[&str],
1860    ) -> oneshot::Receiver<usize> {
1861        self.window.platform_window.prompt(level, message, answers)
1862    }
1863
1864    /// Returns all available actions for the focused element.
1865    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1866        let node_id = self
1867            .window
1868            .focus
1869            .and_then(|focus_id| {
1870                self.window
1871                    .rendered_frame
1872                    .dispatch_tree
1873                    .focusable_node_id(focus_id)
1874            })
1875            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1876
1877        self.window
1878            .rendered_frame
1879            .dispatch_tree
1880            .available_actions(node_id)
1881    }
1882
1883    /// Returns key bindings that invoke the given action on the currently focused element.
1884    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1885        self.window
1886            .rendered_frame
1887            .dispatch_tree
1888            .bindings_for_action(
1889                action,
1890                &self.window.rendered_frame.dispatch_tree.context_stack,
1891            )
1892    }
1893
1894    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1895    pub fn bindings_for_action_in(
1896        &self,
1897        action: &dyn Action,
1898        focus_handle: &FocusHandle,
1899    ) -> Vec<KeyBinding> {
1900        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1901
1902        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1903            return vec![];
1904        };
1905        let context_stack = dispatch_tree
1906            .dispatch_path(node_id)
1907            .into_iter()
1908            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1909            .collect();
1910        dispatch_tree.bindings_for_action(action, &context_stack)
1911    }
1912
1913    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1914    pub fn listener_for<V: Render, E>(
1915        &self,
1916        view: &View<V>,
1917        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1918    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1919        let view = view.downgrade();
1920        move |e: &E, cx: &mut WindowContext| {
1921            view.update(cx, |view, cx| f(view, e, cx)).ok();
1922        }
1923    }
1924
1925    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1926    pub fn handler_for<V: Render>(
1927        &self,
1928        view: &View<V>,
1929        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1930    ) -> impl Fn(&mut WindowContext) {
1931        let view = view.downgrade();
1932        move |cx: &mut WindowContext| {
1933            view.update(cx, |view, cx| f(view, cx)).ok();
1934        }
1935    }
1936
1937    /// Invoke the given function with the given focus handle present on the key dispatch stack.
1938    /// If you want an element to participate in key dispatch, use this method to push its key context and focus handle into the stack during paint.
1939    pub fn with_key_dispatch<R>(
1940        &mut self,
1941        context: Option<KeyContext>,
1942        focus_handle: Option<FocusHandle>,
1943        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1944    ) -> R {
1945        let parent_view_id = self.parent_view_id();
1946        let window = &mut self.window;
1947        let focus_id = focus_handle.as_ref().map(|handle| handle.id);
1948        window
1949            .next_frame
1950            .dispatch_tree
1951            .push_node(context.clone(), focus_id, parent_view_id);
1952
1953        let result = f(focus_handle, self);
1954
1955        self.window.next_frame.dispatch_tree.pop_node();
1956
1957        result
1958    }
1959
1960    pub(crate) fn with_view_id<R>(
1961        &mut self,
1962        view_id: EntityId,
1963        f: impl FnOnce(&mut Self) -> R,
1964    ) -> R {
1965        self.window.next_frame.view_stack.push(view_id);
1966        let result = f(self);
1967        self.window.next_frame.view_stack.pop();
1968        result
1969    }
1970
1971    /// Update or initialize state for an element with the given id that lives across multiple
1972    /// frames. If an element with this id existed in the rendered frame, its state will be passed
1973    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1974    /// when drawing the next frame.
1975    pub(crate) fn with_element_state<S, R>(
1976        &mut self,
1977        id: ElementId,
1978        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1979    ) -> R
1980    where
1981        S: 'static,
1982    {
1983        self.with_element_id(Some(id), |cx| {
1984            let global_id = cx.window().element_id_stack.clone();
1985
1986            if let Some(any) = cx
1987                .window_mut()
1988                .next_frame
1989                .element_states
1990                .remove(&global_id)
1991                .or_else(|| {
1992                    cx.window_mut()
1993                        .rendered_frame
1994                        .element_states
1995                        .remove(&global_id)
1996                })
1997            {
1998                let ElementStateBox {
1999                    inner,
2000                    parent_view_id,
2001                    #[cfg(debug_assertions)]
2002                    type_name
2003                } = any;
2004                // Using the extra inner option to avoid needing to reallocate a new box.
2005                let mut state_box = inner
2006                    .downcast::<Option<S>>()
2007                    .map_err(|_| {
2008                        #[cfg(debug_assertions)]
2009                        {
2010                            anyhow!(
2011                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2012                                std::any::type_name::<S>(),
2013                                type_name
2014                            )
2015                        }
2016
2017                        #[cfg(not(debug_assertions))]
2018                        {
2019                            anyhow!(
2020                                "invalid element state type for id, requested_type {:?}",
2021                                std::any::type_name::<S>(),
2022                            )
2023                        }
2024                    })
2025                    .unwrap();
2026
2027                // Actual: Option<AnyElement> <- View
2028                // Requested: () <- AnyElemet
2029                let state = state_box
2030                    .take()
2031                    .expect("element state is already on the stack");
2032                let (result, state) = f(Some(state), cx);
2033                state_box.replace(state);
2034                cx.window_mut()
2035                    .next_frame
2036                    .element_states
2037                    .insert(global_id, ElementStateBox {
2038                        inner: state_box,
2039                        parent_view_id,
2040                        #[cfg(debug_assertions)]
2041                        type_name
2042                    });
2043                result
2044            } else {
2045                let (result, state) = f(None, cx);
2046                let parent_view_id = cx.parent_view_id().unwrap();
2047                cx.window_mut()
2048                    .next_frame
2049                    .element_states
2050                    .insert(global_id,
2051                        ElementStateBox {
2052                            inner: Box::new(Some(state)),
2053                            parent_view_id,
2054                            #[cfg(debug_assertions)]
2055                            type_name: std::any::type_name::<S>()
2056                        }
2057
2058                    );
2059                result
2060            }
2061        })
2062    }
2063
2064    fn parent_view_id(&self) -> Option<EntityId> {
2065        self.window.next_frame.view_stack.last().copied()
2066    }
2067
2068    /// Set an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2069    /// platform to receive textual input with proper integration with concerns such
2070    /// as IME interactions.
2071    ///
2072    /// [element_input_handler]: crate::ElementInputHandler
2073    pub fn handle_input(
2074        &mut self,
2075        focus_handle: &FocusHandle,
2076        input_handler: impl PlatformInputHandler,
2077    ) {
2078        if focus_handle.is_focused(self) {
2079            self.window
2080                .platform_window
2081                .set_input_handler(Box::new(input_handler));
2082        }
2083    }
2084
2085    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
2086    /// If the callback returns false, the window won't be closed.
2087    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
2088        let mut this = self.to_async();
2089        self.window
2090            .platform_window
2091            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
2092    }
2093}
2094
2095impl Context for WindowContext<'_> {
2096    type Result<T> = T;
2097
2098    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
2099    where
2100        T: 'static,
2101    {
2102        let slot = self.app.entities.reserve();
2103        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
2104        self.entities.insert(slot, model)
2105    }
2106
2107    fn update_model<T: 'static, R>(
2108        &mut self,
2109        model: &Model<T>,
2110        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2111    ) -> R {
2112        let mut entity = self.entities.lease(model);
2113        let result = update(
2114            &mut *entity,
2115            &mut ModelContext::new(&mut *self.app, model.downgrade()),
2116        );
2117        self.entities.end_lease(entity);
2118        result
2119    }
2120
2121    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2122    where
2123        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2124    {
2125        if window == self.window.handle {
2126            let root_view = self.window.root_view.clone().unwrap();
2127            Ok(update(root_view, self))
2128        } else {
2129            window.update(self.app, update)
2130        }
2131    }
2132
2133    fn read_model<T, R>(
2134        &self,
2135        handle: &Model<T>,
2136        read: impl FnOnce(&T, &AppContext) -> R,
2137    ) -> Self::Result<R>
2138    where
2139        T: 'static,
2140    {
2141        let entity = self.entities.read(handle);
2142        read(entity, &*self.app)
2143    }
2144
2145    fn read_window<T, R>(
2146        &self,
2147        window: &WindowHandle<T>,
2148        read: impl FnOnce(View<T>, &AppContext) -> R,
2149    ) -> Result<R>
2150    where
2151        T: 'static,
2152    {
2153        if window.any_handle == self.window.handle {
2154            let root_view = self
2155                .window
2156                .root_view
2157                .clone()
2158                .unwrap()
2159                .downcast::<T>()
2160                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2161            Ok(read(root_view, self))
2162        } else {
2163            self.app.read_window(window, read)
2164        }
2165    }
2166}
2167
2168impl VisualContext for WindowContext<'_> {
2169    fn new_view<V>(
2170        &mut self,
2171        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2172    ) -> Self::Result<View<V>>
2173    where
2174        V: 'static + Render,
2175    {
2176        let slot = self.app.entities.reserve();
2177        let view = View {
2178            model: slot.clone(),
2179        };
2180        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
2181        let entity = build_view_state(&mut cx);
2182        cx.entities.insert(slot, entity);
2183
2184        cx.new_view_observers
2185            .clone()
2186            .retain(&TypeId::of::<V>(), |observer| {
2187                let any_view = AnyView::from(view.clone());
2188                (observer)(any_view, self);
2189                true
2190            });
2191
2192        view
2193    }
2194
2195    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
2196    fn update_view<T: 'static, R>(
2197        &mut self,
2198        view: &View<T>,
2199        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
2200    ) -> Self::Result<R> {
2201        let mut lease = self.app.entities.lease(&view.model);
2202        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
2203        let result = update(&mut *lease, &mut cx);
2204        cx.app.entities.end_lease(lease);
2205        result
2206    }
2207
2208    fn replace_root_view<V>(
2209        &mut self,
2210        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2211    ) -> Self::Result<View<V>>
2212    where
2213        V: 'static + Render,
2214    {
2215        let view = self.new_view(build_view);
2216        self.window.root_view = Some(view.clone().into());
2217        self.refresh();
2218        view
2219    }
2220
2221    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
2222        self.update_view(view, |view, cx| {
2223            view.focus_handle(cx).clone().focus(cx);
2224        })
2225    }
2226
2227    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
2228    where
2229        V: ManagedView,
2230    {
2231        self.update_view(view, |_, cx| cx.emit(DismissEvent))
2232    }
2233}
2234
2235impl<'a> std::ops::Deref for WindowContext<'a> {
2236    type Target = AppContext;
2237
2238    fn deref(&self) -> &Self::Target {
2239        self.app
2240    }
2241}
2242
2243impl<'a> std::ops::DerefMut for WindowContext<'a> {
2244    fn deref_mut(&mut self) -> &mut Self::Target {
2245        self.app
2246    }
2247}
2248
2249impl<'a> Borrow<AppContext> for WindowContext<'a> {
2250    fn borrow(&self) -> &AppContext {
2251        self.app
2252    }
2253}
2254
2255impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
2256    fn borrow_mut(&mut self) -> &mut AppContext {
2257        self.app
2258    }
2259}
2260
2261/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
2262pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2263    #[doc(hidden)]
2264    fn app_mut(&mut self) -> &mut AppContext {
2265        self.borrow_mut()
2266    }
2267
2268    #[doc(hidden)]
2269    fn app(&self) -> &AppContext {
2270        self.borrow()
2271    }
2272
2273    #[doc(hidden)]
2274    fn window(&self) -> &Window {
2275        self.borrow()
2276    }
2277
2278    #[doc(hidden)]
2279    fn window_mut(&mut self) -> &mut Window {
2280        self.borrow_mut()
2281    }
2282
2283    /// Pushes the given element id onto the global stack and invokes the given closure
2284    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
2285    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
2286    /// used to associate state with identified elements across separate frames.
2287    fn with_element_id<R>(
2288        &mut self,
2289        id: Option<impl Into<ElementId>>,
2290        f: impl FnOnce(&mut Self) -> R,
2291    ) -> R {
2292        if let Some(id) = id.map(Into::into) {
2293            let window = self.window_mut();
2294            window.element_id_stack.push(id);
2295            let result = f(self);
2296            let window: &mut Window = self.borrow_mut();
2297            window.element_id_stack.pop();
2298            result
2299        } else {
2300            f(self)
2301        }
2302    }
2303
2304    /// Invoke the given function with the given content mask after intersecting it
2305    /// with the current mask.
2306    fn with_content_mask<R>(
2307        &mut self,
2308        mask: Option<ContentMask<Pixels>>,
2309        f: impl FnOnce(&mut Self) -> R,
2310    ) -> R {
2311        if let Some(mask) = mask {
2312            let mask = mask.intersect(&self.content_mask());
2313            self.window_mut().next_frame.content_mask_stack.push(mask);
2314            let result = f(self);
2315            self.window_mut().next_frame.content_mask_stack.pop();
2316            result
2317        } else {
2318            f(self)
2319        }
2320    }
2321
2322    /// Invoke the given function with the content mask reset to that
2323    /// of the window.
2324    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2325        let mask = ContentMask {
2326            bounds: Bounds {
2327                origin: Point::default(),
2328                size: self.window().viewport_size,
2329            },
2330        };
2331        let new_stacking_order_id =
2332            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2333        let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
2334        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2335        self.window_mut().next_frame.content_mask_stack.push(mask);
2336        let result = f(self);
2337        self.window_mut().next_frame.content_mask_stack.pop();
2338        self.window_mut().next_frame.z_index_stack = old_stacking_order;
2339        result
2340    }
2341
2342    /// Called during painting to invoke the given closure in a new stacking context. The given
2343    /// z-index is interpreted relative to the previous call to `stack`.
2344    fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2345        let new_stacking_order_id =
2346            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2347        let old_stacking_order_id = mem::replace(
2348            &mut self.window_mut().next_frame.z_index_stack.id,
2349            new_stacking_order_id,
2350        );
2351        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2352        self.window_mut().next_frame.z_index_stack.push(z_index);
2353        let result = f(self);
2354        self.window_mut().next_frame.z_index_stack.id = old_stacking_order_id;
2355        self.window_mut().next_frame.z_index_stack.pop();
2356        result
2357    }
2358
2359    /// Update the global element offset relative to the current offset. This is used to implement
2360    /// scrolling.
2361    fn with_element_offset<R>(
2362        &mut self,
2363        offset: Point<Pixels>,
2364        f: impl FnOnce(&mut Self) -> R,
2365    ) -> R {
2366        if offset.is_zero() {
2367            return f(self);
2368        };
2369
2370        let abs_offset = self.element_offset() + offset;
2371        self.with_absolute_element_offset(abs_offset, f)
2372    }
2373
2374    /// Update the global element offset based on the given offset. This is used to implement
2375    /// drag handles and other manual painting of elements.
2376    fn with_absolute_element_offset<R>(
2377        &mut self,
2378        offset: Point<Pixels>,
2379        f: impl FnOnce(&mut Self) -> R,
2380    ) -> R {
2381        self.window_mut()
2382            .next_frame
2383            .element_offset_stack
2384            .push(offset);
2385        let result = f(self);
2386        self.window_mut().next_frame.element_offset_stack.pop();
2387        result
2388    }
2389
2390    /// Obtain the current element offset.
2391    fn element_offset(&self) -> Point<Pixels> {
2392        self.window()
2393            .next_frame
2394            .element_offset_stack
2395            .last()
2396            .copied()
2397            .unwrap_or_default()
2398    }
2399
2400    /// Obtain the current content mask.
2401    fn content_mask(&self) -> ContentMask<Pixels> {
2402        self.window()
2403            .next_frame
2404            .content_mask_stack
2405            .last()
2406            .cloned()
2407            .unwrap_or_else(|| ContentMask {
2408                bounds: Bounds {
2409                    origin: Point::default(),
2410                    size: self.window().viewport_size,
2411                },
2412            })
2413    }
2414
2415    /// The size of an em for the base font of the application. Adjusting this value allows the
2416    /// UI to scale, just like zooming a web page.
2417    fn rem_size(&self) -> Pixels {
2418        self.window().rem_size
2419    }
2420}
2421
2422impl Borrow<Window> for WindowContext<'_> {
2423    fn borrow(&self) -> &Window {
2424        self.window
2425    }
2426}
2427
2428impl BorrowMut<Window> for WindowContext<'_> {
2429    fn borrow_mut(&mut self) -> &mut Window {
2430        self.window
2431    }
2432}
2433
2434impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2435
2436/// Provides access to application state that is specialized for a particular [`View`].
2437/// Allows you to interact with focus, emit events, etc.
2438/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
2439/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
2440pub struct ViewContext<'a, V> {
2441    window_cx: WindowContext<'a>,
2442    view: &'a View<V>,
2443}
2444
2445impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2446    fn borrow(&self) -> &AppContext {
2447        &*self.window_cx.app
2448    }
2449}
2450
2451impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2452    fn borrow_mut(&mut self) -> &mut AppContext {
2453        &mut *self.window_cx.app
2454    }
2455}
2456
2457impl<V> Borrow<Window> for ViewContext<'_, V> {
2458    fn borrow(&self) -> &Window {
2459        &*self.window_cx.window
2460    }
2461}
2462
2463impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2464    fn borrow_mut(&mut self) -> &mut Window {
2465        &mut *self.window_cx.window
2466    }
2467}
2468
2469impl<'a, V: 'static> ViewContext<'a, V> {
2470    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2471        Self {
2472            window_cx: WindowContext::new(app, window),
2473            view,
2474        }
2475    }
2476
2477    /// Get the entity_id of this view.
2478    pub fn entity_id(&self) -> EntityId {
2479        self.view.entity_id()
2480    }
2481
2482    /// Get the view pointer underlying this context.
2483    pub fn view(&self) -> &View<V> {
2484        self.view
2485    }
2486
2487    /// Get the model underlying this view.
2488    pub fn model(&self) -> &Model<V> {
2489        &self.view.model
2490    }
2491
2492    /// Access the underlying window context.
2493    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2494        &mut self.window_cx
2495    }
2496
2497    /// Set a given callback to be run on the next frame.
2498    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2499    where
2500        V: 'static,
2501    {
2502        let view = self.view().clone();
2503        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2504    }
2505
2506    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2507    /// that are currently on the stack to be returned to the app.
2508    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2509        let view = self.view().downgrade();
2510        self.window_cx.defer(move |cx| {
2511            view.update(cx, f).ok();
2512        });
2513    }
2514
2515    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2516    pub fn observe<V2, E>(
2517        &mut self,
2518        entity: &E,
2519        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2520    ) -> Subscription
2521    where
2522        V2: 'static,
2523        V: 'static,
2524        E: Entity<V2>,
2525    {
2526        let view = self.view().downgrade();
2527        let entity_id = entity.entity_id();
2528        let entity = entity.downgrade();
2529        let window_handle = self.window.handle;
2530        let (subscription, activate) = self.app.observers.insert(
2531            entity_id,
2532            Box::new(move |cx| {
2533                window_handle
2534                    .update(cx, |_, cx| {
2535                        if let Some(handle) = E::upgrade_from(&entity) {
2536                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2537                                .is_ok()
2538                        } else {
2539                            false
2540                        }
2541                    })
2542                    .unwrap_or(false)
2543            }),
2544        );
2545        self.app.defer(move |_| activate());
2546        subscription
2547    }
2548
2549    /// Subscribe to events emitted by another model or view.
2550    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2551    /// The callback will be invoked with a reference to the current view, a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a view context for the current view.
2552    pub fn subscribe<V2, E, Evt>(
2553        &mut self,
2554        entity: &E,
2555        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2556    ) -> Subscription
2557    where
2558        V2: EventEmitter<Evt>,
2559        E: Entity<V2>,
2560        Evt: 'static,
2561    {
2562        let view = self.view().downgrade();
2563        let entity_id = entity.entity_id();
2564        let handle = entity.downgrade();
2565        let window_handle = self.window.handle;
2566        let (subscription, activate) = self.app.event_listeners.insert(
2567            entity_id,
2568            (
2569                TypeId::of::<Evt>(),
2570                Box::new(move |event, cx| {
2571                    window_handle
2572                        .update(cx, |_, cx| {
2573                            if let Some(handle) = E::upgrade_from(&handle) {
2574                                let event = event.downcast_ref().expect("invalid event type");
2575                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2576                                    .is_ok()
2577                            } else {
2578                                false
2579                            }
2580                        })
2581                        .unwrap_or(false)
2582                }),
2583            ),
2584        );
2585        self.app.defer(move |_| activate());
2586        subscription
2587    }
2588
2589    /// Register a callback to be invoked when the view is released.
2590    ///
2591    /// The callback receives a handle to the view's window. This handle may be
2592    /// invalid, if the window was closed before the view was released.
2593    pub fn on_release(
2594        &mut self,
2595        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2596    ) -> Subscription {
2597        let window_handle = self.window.handle;
2598        let (subscription, activate) = self.app.release_listeners.insert(
2599            self.view.model.entity_id,
2600            Box::new(move |this, cx| {
2601                let this = this.downcast_mut().expect("invalid entity type");
2602                on_release(this, window_handle, cx)
2603            }),
2604        );
2605        activate();
2606        subscription
2607    }
2608
2609    /// Register a callback to be invoked when the given Model or View is released.
2610    pub fn observe_release<V2, E>(
2611        &mut self,
2612        entity: &E,
2613        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2614    ) -> Subscription
2615    where
2616        V: 'static,
2617        V2: 'static,
2618        E: Entity<V2>,
2619    {
2620        let view = self.view().downgrade();
2621        let entity_id = entity.entity_id();
2622        let window_handle = self.window.handle;
2623        let (subscription, activate) = self.app.release_listeners.insert(
2624            entity_id,
2625            Box::new(move |entity, cx| {
2626                let entity = entity.downcast_mut().expect("invalid entity type");
2627                let _ = window_handle.update(cx, |_, cx| {
2628                    view.update(cx, |this, cx| on_release(this, entity, cx))
2629                });
2630            }),
2631        );
2632        activate();
2633        subscription
2634    }
2635
2636    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2637    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2638    pub fn notify(&mut self) {
2639        for view_id in self
2640            .window
2641            .rendered_frame
2642            .dispatch_tree
2643            .view_path(self.view.entity_id())
2644        {
2645            if !self.window.dirty_views.insert(view_id) {
2646                break;
2647            }
2648        }
2649
2650        if !self.window.drawing {
2651            self.window_cx.window.dirty = true;
2652            self.window_cx.app.push_effect(Effect::Notify {
2653                emitter: self.view.model.entity_id,
2654            });
2655        }
2656    }
2657
2658    /// Register a callback to be invoked when the window is resized.
2659    pub fn observe_window_bounds(
2660        &mut self,
2661        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2662    ) -> Subscription {
2663        let view = self.view.downgrade();
2664        let (subscription, activate) = self.window.bounds_observers.insert(
2665            (),
2666            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2667        );
2668        activate();
2669        subscription
2670    }
2671
2672    /// Register a callback to be invoked when the window is activated or deactivated.
2673    pub fn observe_window_activation(
2674        &mut self,
2675        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2676    ) -> Subscription {
2677        let view = self.view.downgrade();
2678        let (subscription, activate) = self.window.activation_observers.insert(
2679            (),
2680            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2681        );
2682        activate();
2683        subscription
2684    }
2685
2686    /// Register a listener to be called when the given focus handle receives focus.
2687    /// Returns a subscription and persists until the subscription is dropped.
2688    pub fn on_focus(
2689        &mut self,
2690        handle: &FocusHandle,
2691        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2692    ) -> Subscription {
2693        let view = self.view.downgrade();
2694        let focus_id = handle.id;
2695        let (subscription, activate) = self.window.focus_listeners.insert(
2696            (),
2697            Box::new(move |event, cx| {
2698                view.update(cx, |view, cx| {
2699                    if event.previous_focus_path.last() != Some(&focus_id)
2700                        && event.current_focus_path.last() == Some(&focus_id)
2701                    {
2702                        listener(view, cx)
2703                    }
2704                })
2705                .is_ok()
2706            }),
2707        );
2708        self.app.defer(move |_| activate());
2709        subscription
2710    }
2711
2712    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2713    /// Returns a subscription and persists until the subscription is dropped.
2714    pub fn on_focus_in(
2715        &mut self,
2716        handle: &FocusHandle,
2717        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2718    ) -> Subscription {
2719        let view = self.view.downgrade();
2720        let focus_id = handle.id;
2721        let (subscription, activate) = self.window.focus_listeners.insert(
2722            (),
2723            Box::new(move |event, cx| {
2724                view.update(cx, |view, cx| {
2725                    if !event.previous_focus_path.contains(&focus_id)
2726                        && event.current_focus_path.contains(&focus_id)
2727                    {
2728                        listener(view, cx)
2729                    }
2730                })
2731                .is_ok()
2732            }),
2733        );
2734        self.app.defer(move |_| activate());
2735        subscription
2736    }
2737
2738    /// Register a listener to be called when the given focus handle loses focus.
2739    /// Returns a subscription and persists until the subscription is dropped.
2740    pub fn on_blur(
2741        &mut self,
2742        handle: &FocusHandle,
2743        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2744    ) -> Subscription {
2745        let view = self.view.downgrade();
2746        let focus_id = handle.id;
2747        let (subscription, activate) = self.window.focus_listeners.insert(
2748            (),
2749            Box::new(move |event, cx| {
2750                view.update(cx, |view, cx| {
2751                    if event.previous_focus_path.last() == Some(&focus_id)
2752                        && event.current_focus_path.last() != Some(&focus_id)
2753                    {
2754                        listener(view, cx)
2755                    }
2756                })
2757                .is_ok()
2758            }),
2759        );
2760        self.app.defer(move |_| activate());
2761        subscription
2762    }
2763
2764    /// Register a listener to be called when nothing in the window has focus.
2765    /// This typically happens when the node that was focused is removed from the tree,
2766    /// and this callback lets you chose a default place to restore the users focus.
2767    /// Returns a subscription and persists until the subscription is dropped.
2768    pub fn on_focus_lost(
2769        &mut self,
2770        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2771    ) -> Subscription {
2772        let view = self.view.downgrade();
2773        let (subscription, activate) = self.window.focus_lost_listeners.insert(
2774            (),
2775            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2776        );
2777        activate();
2778        subscription
2779    }
2780
2781    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2782    /// Returns a subscription and persists until the subscription is dropped.
2783    pub fn on_focus_out(
2784        &mut self,
2785        handle: &FocusHandle,
2786        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2787    ) -> Subscription {
2788        let view = self.view.downgrade();
2789        let focus_id = handle.id;
2790        let (subscription, activate) = self.window.focus_listeners.insert(
2791            (),
2792            Box::new(move |event, cx| {
2793                view.update(cx, |view, cx| {
2794                    if event.previous_focus_path.contains(&focus_id)
2795                        && !event.current_focus_path.contains(&focus_id)
2796                    {
2797                        listener(view, cx)
2798                    }
2799                })
2800                .is_ok()
2801            }),
2802        );
2803        self.app.defer(move |_| activate());
2804        subscription
2805    }
2806
2807    /// Schedule a future to be run asynchronously.
2808    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2809    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2810    /// The returned future will be polled on the main thread.
2811    pub fn spawn<Fut, R>(
2812        &mut self,
2813        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2814    ) -> Task<R>
2815    where
2816        R: 'static,
2817        Fut: Future<Output = R> + 'static,
2818    {
2819        let view = self.view().downgrade();
2820        self.window_cx.spawn(|cx| f(view, cx))
2821    }
2822
2823    /// Update the global state of the given type.
2824    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2825    where
2826        G: 'static,
2827    {
2828        let mut global = self.app.lease_global::<G>();
2829        let result = f(&mut global, self);
2830        self.app.end_global_lease(global);
2831        result
2832    }
2833
2834    /// Register a callback to be invoked when the given global state changes.
2835    pub fn observe_global<G: 'static>(
2836        &mut self,
2837        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2838    ) -> Subscription {
2839        let window_handle = self.window.handle;
2840        let view = self.view().downgrade();
2841        let (subscription, activate) = self.global_observers.insert(
2842            TypeId::of::<G>(),
2843            Box::new(move |cx| {
2844                window_handle
2845                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2846                    .unwrap_or(false)
2847            }),
2848        );
2849        self.app.defer(move |_| activate());
2850        subscription
2851    }
2852
2853    /// Add a listener for any mouse event that occurs in the window.
2854    /// This is a fairly low level method.
2855    /// Typically, you'll want to use methods on UI elements, which perform bounds checking etc.
2856    pub fn on_mouse_event<Event: 'static>(
2857        &mut self,
2858        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2859    ) {
2860        let handle = self.view().clone();
2861        self.window_cx.on_mouse_event(move |event, phase, cx| {
2862            handle.update(cx, |view, cx| {
2863                handler(view, event, phase, cx);
2864            })
2865        });
2866    }
2867
2868    /// Register a callback to be invoked when the given Key Event is dispatched to the window.
2869    pub fn on_key_event<Event: 'static>(
2870        &mut self,
2871        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2872    ) {
2873        let handle = self.view().clone();
2874        self.window_cx.on_key_event(move |event, phase, cx| {
2875            handle.update(cx, |view, cx| {
2876                handler(view, event, phase, cx);
2877            })
2878        });
2879    }
2880
2881    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2882    pub fn on_action(
2883        &mut self,
2884        action_type: TypeId,
2885        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2886    ) {
2887        let handle = self.view().clone();
2888        self.window_cx
2889            .on_action(action_type, move |action, phase, cx| {
2890                handle.update(cx, |view, cx| {
2891                    listener(view, action, phase, cx);
2892                })
2893            });
2894    }
2895
2896    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2897    pub fn emit<Evt>(&mut self, event: Evt)
2898    where
2899        Evt: 'static,
2900        V: EventEmitter<Evt>,
2901    {
2902        let emitter = self.view.model.entity_id;
2903        self.app.push_effect(Effect::Emit {
2904            emitter,
2905            event_type: TypeId::of::<Evt>(),
2906            event: Box::new(event),
2907        });
2908    }
2909
2910    /// Move focus to the current view, assuming it implements [`FocusableView`].
2911    pub fn focus_self(&mut self)
2912    where
2913        V: FocusableView,
2914    {
2915        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2916    }
2917
2918    /// Convenience method for accessing view state in an event callback.
2919    ///
2920    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2921    /// but it's often useful to be able to access view state in these
2922    /// callbacks. This method provides a convenient way to do so.
2923    pub fn listener<E>(
2924        &self,
2925        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2926    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2927        let view = self.view().downgrade();
2928        move |e: &E, cx: &mut WindowContext| {
2929            view.update(cx, |view, cx| f(view, e, cx)).ok();
2930        }
2931    }
2932}
2933
2934impl<V> Context for ViewContext<'_, V> {
2935    type Result<U> = U;
2936
2937    fn new_model<T: 'static>(
2938        &mut self,
2939        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2940    ) -> Model<T> {
2941        self.window_cx.new_model(build_model)
2942    }
2943
2944    fn update_model<T: 'static, R>(
2945        &mut self,
2946        model: &Model<T>,
2947        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2948    ) -> R {
2949        self.window_cx.update_model(model, update)
2950    }
2951
2952    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2953    where
2954        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2955    {
2956        self.window_cx.update_window(window, update)
2957    }
2958
2959    fn read_model<T, R>(
2960        &self,
2961        handle: &Model<T>,
2962        read: impl FnOnce(&T, &AppContext) -> R,
2963    ) -> Self::Result<R>
2964    where
2965        T: 'static,
2966    {
2967        self.window_cx.read_model(handle, read)
2968    }
2969
2970    fn read_window<T, R>(
2971        &self,
2972        window: &WindowHandle<T>,
2973        read: impl FnOnce(View<T>, &AppContext) -> R,
2974    ) -> Result<R>
2975    where
2976        T: 'static,
2977    {
2978        self.window_cx.read_window(window, read)
2979    }
2980}
2981
2982impl<V: 'static> VisualContext for ViewContext<'_, V> {
2983    fn new_view<W: Render + 'static>(
2984        &mut self,
2985        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2986    ) -> Self::Result<View<W>> {
2987        self.window_cx.new_view(build_view_state)
2988    }
2989
2990    fn update_view<V2: 'static, R>(
2991        &mut self,
2992        view: &View<V2>,
2993        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2994    ) -> Self::Result<R> {
2995        self.window_cx.update_view(view, update)
2996    }
2997
2998    fn replace_root_view<W>(
2999        &mut self,
3000        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3001    ) -> Self::Result<View<W>>
3002    where
3003        W: 'static + Render,
3004    {
3005        self.window_cx.replace_root_view(build_view)
3006    }
3007
3008    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
3009        self.window_cx.focus_view(view)
3010    }
3011
3012    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
3013        self.window_cx.dismiss_view(view)
3014    }
3015}
3016
3017impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
3018    type Target = WindowContext<'a>;
3019
3020    fn deref(&self) -> &Self::Target {
3021        &self.window_cx
3022    }
3023}
3024
3025impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
3026    fn deref_mut(&mut self) -> &mut Self::Target {
3027        &mut self.window_cx
3028    }
3029}
3030
3031// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3032slotmap::new_key_type! {
3033    /// A unique identifier for a window.
3034    pub struct WindowId;
3035}
3036
3037impl WindowId {
3038    /// Converts this window ID to a `u64`.
3039    pub fn as_u64(&self) -> u64 {
3040        self.0.as_ffi()
3041    }
3042}
3043
3044/// A handle to a window with a specific root view type.
3045/// Note that this does not keep the window alive on its own.
3046#[derive(Deref, DerefMut)]
3047pub struct WindowHandle<V> {
3048    #[deref]
3049    #[deref_mut]
3050    pub(crate) any_handle: AnyWindowHandle,
3051    state_type: PhantomData<V>,
3052}
3053
3054impl<V: 'static + Render> WindowHandle<V> {
3055    /// Create a new handle from a window ID.
3056    /// This does not check if the root type of the window is `V`.
3057    pub fn new(id: WindowId) -> Self {
3058        WindowHandle {
3059            any_handle: AnyWindowHandle {
3060                id,
3061                state_type: TypeId::of::<V>(),
3062            },
3063            state_type: PhantomData,
3064        }
3065    }
3066
3067    /// Get the root view out of this window.
3068    ///
3069    /// This will fail if the window is closed or if the root view's type does not match `V`.
3070    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
3071    where
3072        C: Context,
3073    {
3074        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
3075            root_view
3076                .downcast::<V>()
3077                .map_err(|_| anyhow!("the type of the window's root view has changed"))
3078        }))
3079    }
3080
3081    /// Update the root view of this window.
3082    ///
3083    /// This will fail if the window has been closed or if the root view's type does not match
3084    pub fn update<C, R>(
3085        &self,
3086        cx: &mut C,
3087        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
3088    ) -> Result<R>
3089    where
3090        C: Context,
3091    {
3092        cx.update_window(self.any_handle, |root_view, cx| {
3093            let view = root_view
3094                .downcast::<V>()
3095                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3096            Ok(cx.update_view(&view, update))
3097        })?
3098    }
3099
3100    /// Read the root view out of this window.
3101    ///
3102    /// This will fail if the window is closed or if the root view's type does not match `V`.
3103    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
3104        let x = cx
3105            .windows
3106            .get(self.id)
3107            .and_then(|window| {
3108                window
3109                    .as_ref()
3110                    .and_then(|window| window.root_view.clone())
3111                    .map(|root_view| root_view.downcast::<V>())
3112            })
3113            .ok_or_else(|| anyhow!("window not found"))?
3114            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3115
3116        Ok(x.read(cx))
3117    }
3118
3119    /// Read the root view out of this window, with a callback
3120    ///
3121    /// This will fail if the window is closed or if the root view's type does not match `V`.
3122    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
3123    where
3124        C: Context,
3125    {
3126        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3127    }
3128
3129    /// Read the root view pointer off of this window.
3130    ///
3131    /// This will fail if the window is closed or if the root view's type does not match `V`.
3132    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
3133    where
3134        C: Context,
3135    {
3136        cx.read_window(self, |root_view, _cx| root_view.clone())
3137    }
3138
3139    /// Check if this window is 'active'.
3140    ///
3141    /// Will return `None` if the window is closed.
3142    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
3143        cx.windows
3144            .get(self.id)
3145            .and_then(|window| window.as_ref().map(|window| window.active))
3146    }
3147}
3148
3149impl<V> Copy for WindowHandle<V> {}
3150
3151impl<V> Clone for WindowHandle<V> {
3152    fn clone(&self) -> Self {
3153        *self
3154    }
3155}
3156
3157impl<V> PartialEq for WindowHandle<V> {
3158    fn eq(&self, other: &Self) -> bool {
3159        self.any_handle == other.any_handle
3160    }
3161}
3162
3163impl<V> Eq for WindowHandle<V> {}
3164
3165impl<V> Hash for WindowHandle<V> {
3166    fn hash<H: Hasher>(&self, state: &mut H) {
3167        self.any_handle.hash(state);
3168    }
3169}
3170
3171impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3172    fn from(val: WindowHandle<V>) -> Self {
3173        val.any_handle
3174    }
3175}
3176
3177/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3178#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3179pub struct AnyWindowHandle {
3180    pub(crate) id: WindowId,
3181    state_type: TypeId,
3182}
3183
3184impl AnyWindowHandle {
3185    /// Get the ID of this window.
3186    pub fn window_id(&self) -> WindowId {
3187        self.id
3188    }
3189
3190    /// Attempt to convert this handle to a window handle with a specific root view type.
3191    /// If the types do not match, this will return `None`.
3192    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3193        if TypeId::of::<T>() == self.state_type {
3194            Some(WindowHandle {
3195                any_handle: *self,
3196                state_type: PhantomData,
3197            })
3198        } else {
3199            None
3200        }
3201    }
3202
3203    /// Update the state of the root view of this window.
3204    ///
3205    /// This will fail if the window has been closed.
3206    pub fn update<C, R>(
3207        self,
3208        cx: &mut C,
3209        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
3210    ) -> Result<R>
3211    where
3212        C: Context,
3213    {
3214        cx.update_window(self, update)
3215    }
3216
3217    /// Read the state of the root view of this window.
3218    ///
3219    /// This will fail if the window has been closed.
3220    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
3221    where
3222        C: Context,
3223        T: 'static,
3224    {
3225        let view = self
3226            .downcast::<T>()
3227            .context("the type of the window's root view has changed")?;
3228
3229        cx.read_window(&view, read)
3230    }
3231}
3232
3233// #[cfg(any(test, feature = "test-support"))]
3234// impl From<SmallVec<[u32; 16]>> for StackingOrder {
3235//     fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
3236//         StackingOrder(small_vec)
3237//     }
3238// }
3239
3240/// An identifier for an [`Element`](crate::Element).
3241///
3242/// Can be constructed with a string, a number, or both, as well
3243/// as other internal representations.
3244#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3245pub enum ElementId {
3246    /// The ID of a View element
3247    View(EntityId),
3248    /// An integer ID.
3249    Integer(usize),
3250    /// A string based ID.
3251    Name(SharedString),
3252    /// An ID that's equated with a focus handle.
3253    FocusHandle(FocusId),
3254    /// A combination of a name and an integer.
3255    NamedInteger(SharedString, usize),
3256}
3257
3258impl ElementId {
3259    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3260        ElementId::View(entity_id)
3261    }
3262}
3263
3264impl TryInto<SharedString> for ElementId {
3265    type Error = anyhow::Error;
3266
3267    fn try_into(self) -> anyhow::Result<SharedString> {
3268        if let ElementId::Name(name) = self {
3269            Ok(name)
3270        } else {
3271            Err(anyhow!("element id is not string"))
3272        }
3273    }
3274}
3275
3276impl From<usize> for ElementId {
3277    fn from(id: usize) -> Self {
3278        ElementId::Integer(id)
3279    }
3280}
3281
3282impl From<i32> for ElementId {
3283    fn from(id: i32) -> Self {
3284        Self::Integer(id as usize)
3285    }
3286}
3287
3288impl From<SharedString> for ElementId {
3289    fn from(name: SharedString) -> Self {
3290        ElementId::Name(name)
3291    }
3292}
3293
3294impl From<&'static str> for ElementId {
3295    fn from(name: &'static str) -> Self {
3296        ElementId::Name(name.into())
3297    }
3298}
3299
3300impl<'a> From<&'a FocusHandle> for ElementId {
3301    fn from(handle: &'a FocusHandle) -> Self {
3302        ElementId::FocusHandle(handle.id)
3303    }
3304}
3305
3306impl From<(&'static str, EntityId)> for ElementId {
3307    fn from((name, id): (&'static str, EntityId)) -> Self {
3308        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3309    }
3310}
3311
3312impl From<(&'static str, usize)> for ElementId {
3313    fn from((name, id): (&'static str, usize)) -> Self {
3314        ElementId::NamedInteger(name.into(), id)
3315    }
3316}
3317
3318impl From<(&'static str, u64)> for ElementId {
3319    fn from((name, id): (&'static str, u64)) -> Self {
3320        ElementId::NamedInteger(name.into(), id as usize)
3321    }
3322}
3323
3324/// A rectangle to be rendered in the window at the given position and size.
3325/// Passed as an argument [`WindowContext::paint_quad`].
3326#[derive(Clone)]
3327pub struct PaintQuad {
3328    bounds: Bounds<Pixels>,
3329    corner_radii: Corners<Pixels>,
3330    background: Hsla,
3331    border_widths: Edges<Pixels>,
3332    border_color: Hsla,
3333}
3334
3335impl PaintQuad {
3336    /// Set the corner radii of the quad.
3337    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3338        PaintQuad {
3339            corner_radii: corner_radii.into(),
3340            ..self
3341        }
3342    }
3343
3344    /// Set the border widths of the quad.
3345    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3346        PaintQuad {
3347            border_widths: border_widths.into(),
3348            ..self
3349        }
3350    }
3351
3352    /// Set the border color of the quad.
3353    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3354        PaintQuad {
3355            border_color: border_color.into(),
3356            ..self
3357        }
3358    }
3359
3360    /// Set the background color of the quad.
3361    pub fn background(self, background: impl Into<Hsla>) -> Self {
3362        PaintQuad {
3363            background: background.into(),
3364            ..self
3365        }
3366    }
3367}
3368
3369/// Create a quad with the given parameters.
3370pub fn quad(
3371    bounds: Bounds<Pixels>,
3372    corner_radii: impl Into<Corners<Pixels>>,
3373    background: impl Into<Hsla>,
3374    border_widths: impl Into<Edges<Pixels>>,
3375    border_color: impl Into<Hsla>,
3376) -> PaintQuad {
3377    PaintQuad {
3378        bounds,
3379        corner_radii: corner_radii.into(),
3380        background: background.into(),
3381        border_widths: border_widths.into(),
3382        border_color: border_color.into(),
3383    }
3384}
3385
3386/// Create a filled quad with the given bounds and background color.
3387pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3388    PaintQuad {
3389        bounds: bounds.into(),
3390        corner_radii: (0.).into(),
3391        background: background.into(),
3392        border_widths: (0.).into(),
3393        border_color: transparent_black(),
3394    }
3395}
3396
3397/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3398pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3399    PaintQuad {
3400        bounds: bounds.into(),
3401        corner_radii: (0.).into(),
3402        background: transparent_black(),
3403        border_widths: (1.).into(),
3404        border_color: border_color.into(),
3405    }
3406}