window.rs

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