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