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                self.window.modifiers = mouse_exited.modifiers;
1478                InputEvent::MouseExited(mouse_exited)
1479            }
1480            InputEvent::ModifiersChanged(modifiers_changed) => {
1481                self.window.modifiers = modifiers_changed.modifiers;
1482                InputEvent::ModifiersChanged(modifiers_changed)
1483            }
1484            InputEvent::ScrollWheel(scroll_wheel) => {
1485                self.window.mouse_position = scroll_wheel.position;
1486                self.window.modifiers = scroll_wheel.modifiers;
1487                InputEvent::ScrollWheel(scroll_wheel)
1488            }
1489            // Translate dragging and dropping of external files from the operating system
1490            // to internal drag and drop events.
1491            InputEvent::FileDrop(file_drop) => match file_drop {
1492                FileDropEvent::Entered { position, paths } => {
1493                    self.window.mouse_position = position;
1494                    if self.active_drag.is_none() {
1495                        self.active_drag = Some(AnyDrag {
1496                            value: Box::new(paths.clone()),
1497                            view: self.new_view(|_| paths).into(),
1498                            cursor_offset: position,
1499                        });
1500                    }
1501                    InputEvent::MouseMove(MouseMoveEvent {
1502                        position,
1503                        pressed_button: Some(MouseButton::Left),
1504                        modifiers: Modifiers::default(),
1505                    })
1506                }
1507                FileDropEvent::Pending { position } => {
1508                    self.window.mouse_position = position;
1509                    InputEvent::MouseMove(MouseMoveEvent {
1510                        position,
1511                        pressed_button: Some(MouseButton::Left),
1512                        modifiers: Modifiers::default(),
1513                    })
1514                }
1515                FileDropEvent::Submit { position } => {
1516                    self.activate(true);
1517                    self.window.mouse_position = position;
1518                    InputEvent::MouseUp(MouseUpEvent {
1519                        button: MouseButton::Left,
1520                        position,
1521                        modifiers: Modifiers::default(),
1522                        click_count: 1,
1523                    })
1524                }
1525                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1526                    button: MouseButton::Left,
1527                    position: Point::default(),
1528                    modifiers: Modifiers::default(),
1529                    click_count: 1,
1530                }),
1531            },
1532            InputEvent::KeyDown(_) | InputEvent::KeyUp(_) => event,
1533        };
1534
1535        if let Some(any_mouse_event) = event.mouse_event() {
1536            self.dispatch_mouse_event(any_mouse_event);
1537        } else if let Some(any_key_event) = event.keyboard_event() {
1538            self.dispatch_key_event(any_key_event);
1539        }
1540
1541        !self.app.propagate_event
1542    }
1543
1544    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1545        if let Some(mut handlers) = self
1546            .window
1547            .rendered_frame
1548            .mouse_listeners
1549            .remove(&event.type_id())
1550        {
1551            // Because handlers may add other handlers, we sort every time.
1552            handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1553
1554            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1555            // special purposes, such as detecting events outside of a given Bounds.
1556            for (_, handler) in &mut handlers {
1557                handler(event, DispatchPhase::Capture, self);
1558                if !self.app.propagate_event {
1559                    break;
1560                }
1561            }
1562
1563            // Bubble phase, where most normal handlers do their work.
1564            if self.app.propagate_event {
1565                for (_, handler) in handlers.iter_mut().rev() {
1566                    handler(event, DispatchPhase::Bubble, self);
1567                    if !self.app.propagate_event {
1568                        break;
1569                    }
1570                }
1571            }
1572
1573            self.window
1574                .rendered_frame
1575                .mouse_listeners
1576                .insert(event.type_id(), handlers);
1577        }
1578
1579        if self.app.propagate_event && self.has_active_drag() {
1580            if event.is::<MouseMoveEvent>() {
1581                // If this was a mouse move event, redraw the window so that the
1582                // active drag can follow the mouse cursor.
1583                self.notify();
1584            } else if event.is::<MouseUpEvent>() {
1585                // If this was a mouse up event, cancel the active drag and redraw
1586                // the window.
1587                self.active_drag = None;
1588                self.notify();
1589            }
1590        }
1591    }
1592
1593    fn dispatch_key_event(&mut self, event: &dyn Any) {
1594        let node_id = self
1595            .window
1596            .focus
1597            .and_then(|focus_id| {
1598                self.window
1599                    .rendered_frame
1600                    .dispatch_tree
1601                    .focusable_node_id(focus_id)
1602            })
1603            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1604
1605        let dispatch_path = self
1606            .window
1607            .rendered_frame
1608            .dispatch_tree
1609            .dispatch_path(node_id);
1610
1611        let mut actions: Vec<Box<dyn Action>> = Vec::new();
1612
1613        let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1614        for node_id in &dispatch_path {
1615            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1616
1617            if let Some(context) = node.context.clone() {
1618                context_stack.push(context);
1619            }
1620        }
1621
1622        for node_id in dispatch_path.iter().rev() {
1623            // Match keystrokes
1624            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1625            if node.context.is_some() {
1626                if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1627                    let mut new_actions = self
1628                        .window
1629                        .rendered_frame
1630                        .dispatch_tree
1631                        .dispatch_key(&key_down_event.keystroke, &context_stack);
1632                    actions.append(&mut new_actions);
1633                }
1634
1635                context_stack.pop();
1636            }
1637        }
1638
1639        if !actions.is_empty() {
1640            self.clear_pending_keystrokes();
1641        }
1642
1643        self.propagate_event = true;
1644        for action in actions {
1645            self.dispatch_action_on_node(node_id, action.boxed_clone());
1646            if !self.propagate_event {
1647                self.dispatch_keystroke_observers(event, Some(action));
1648                return;
1649            }
1650        }
1651
1652        // Capture phase
1653        for node_id in &dispatch_path {
1654            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1655
1656            for key_listener in node.key_listeners.clone() {
1657                key_listener(event, DispatchPhase::Capture, self);
1658                if !self.propagate_event {
1659                    return;
1660                }
1661            }
1662        }
1663
1664        // Bubble phase
1665        for node_id in dispatch_path.iter().rev() {
1666            // Handle low level key events
1667            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1668            for key_listener in node.key_listeners.clone() {
1669                key_listener(event, DispatchPhase::Bubble, self);
1670                if !self.propagate_event {
1671                    return;
1672                }
1673            }
1674        }
1675
1676        self.dispatch_keystroke_observers(event, None);
1677    }
1678
1679    /// Determine whether a potential multi-stroke key binding is in progress on this window.
1680    pub fn has_pending_keystrokes(&self) -> bool {
1681        self.window
1682            .rendered_frame
1683            .dispatch_tree
1684            .has_pending_keystrokes()
1685    }
1686
1687    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1688        let dispatch_path = self
1689            .window
1690            .rendered_frame
1691            .dispatch_tree
1692            .dispatch_path(node_id);
1693
1694        // Capture phase
1695        for node_id in &dispatch_path {
1696            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1697            for DispatchActionListener {
1698                action_type,
1699                listener,
1700            } in node.action_listeners.clone()
1701            {
1702                let any_action = action.as_any();
1703                if action_type == any_action.type_id() {
1704                    listener(any_action, DispatchPhase::Capture, self);
1705                    if !self.propagate_event {
1706                        return;
1707                    }
1708                }
1709            }
1710        }
1711        // Bubble phase
1712        for node_id in dispatch_path.iter().rev() {
1713            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1714            for DispatchActionListener {
1715                action_type,
1716                listener,
1717            } in node.action_listeners.clone()
1718            {
1719                let any_action = action.as_any();
1720                if action_type == any_action.type_id() {
1721                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1722                    listener(any_action, DispatchPhase::Bubble, self);
1723                    if !self.propagate_event {
1724                        return;
1725                    }
1726                }
1727            }
1728        }
1729    }
1730
1731    /// Register the given handler to be invoked whenever the global of the given type
1732    /// is updated.
1733    pub fn observe_global<G: 'static>(
1734        &mut self,
1735        f: impl Fn(&mut WindowContext<'_>) + 'static,
1736    ) -> Subscription {
1737        let window_handle = self.window.handle;
1738        let (subscription, activate) = self.global_observers.insert(
1739            TypeId::of::<G>(),
1740            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1741        );
1742        self.app.defer(move |_| activate());
1743        subscription
1744    }
1745
1746    /// Focus the current window and bring it to the foreground at the platform level.
1747    pub fn activate_window(&self) {
1748        self.window.platform_window.activate();
1749    }
1750
1751    /// Minimize the current window at the platform level.
1752    pub fn minimize_window(&self) {
1753        self.window.platform_window.minimize();
1754    }
1755
1756    /// Toggle full screen status on the current window at the platform level.
1757    pub fn toggle_full_screen(&self) {
1758        self.window.platform_window.toggle_full_screen();
1759    }
1760
1761    /// Present a platform dialog.
1762    /// The provided message will be presented, along with buttons for each answer.
1763    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1764    pub fn prompt(
1765        &self,
1766        level: PromptLevel,
1767        message: &str,
1768        answers: &[&str],
1769    ) -> oneshot::Receiver<usize> {
1770        self.window.platform_window.prompt(level, message, answers)
1771    }
1772
1773    /// Returns all available actions for the focused element.
1774    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1775        let node_id = self
1776            .window
1777            .focus
1778            .and_then(|focus_id| {
1779                self.window
1780                    .rendered_frame
1781                    .dispatch_tree
1782                    .focusable_node_id(focus_id)
1783            })
1784            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1785
1786        self.window
1787            .rendered_frame
1788            .dispatch_tree
1789            .available_actions(node_id)
1790    }
1791
1792    /// Returns key bindings that invoke the given action on the currently focused element.
1793    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1794        self.window
1795            .rendered_frame
1796            .dispatch_tree
1797            .bindings_for_action(
1798                action,
1799                &self.window.rendered_frame.dispatch_tree.context_stack,
1800            )
1801    }
1802
1803    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1804    pub fn bindings_for_action_in(
1805        &self,
1806        action: &dyn Action,
1807        focus_handle: &FocusHandle,
1808    ) -> Vec<KeyBinding> {
1809        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1810
1811        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1812            return vec![];
1813        };
1814        let context_stack = dispatch_tree
1815            .dispatch_path(node_id)
1816            .into_iter()
1817            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1818            .collect();
1819        dispatch_tree.bindings_for_action(action, &context_stack)
1820    }
1821
1822    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1823    pub fn listener_for<V: Render, E>(
1824        &self,
1825        view: &View<V>,
1826        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1827    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1828        let view = view.downgrade();
1829        move |e: &E, cx: &mut WindowContext| {
1830            view.update(cx, |view, cx| f(view, e, cx)).ok();
1831        }
1832    }
1833
1834    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1835    pub fn handler_for<V: Render>(
1836        &self,
1837        view: &View<V>,
1838        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1839    ) -> impl Fn(&mut WindowContext) {
1840        let view = view.downgrade();
1841        move |cx: &mut WindowContext| {
1842            view.update(cx, |view, cx| f(view, cx)).ok();
1843        }
1844    }
1845
1846    /// Invoke the given function with the given focus handle present on the key dispatch stack.
1847    /// 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.
1848    pub fn with_key_dispatch<R>(
1849        &mut self,
1850        context: Option<KeyContext>,
1851        focus_handle: Option<FocusHandle>,
1852        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1853    ) -> R {
1854        let window = &mut self.window;
1855        window.next_frame.dispatch_tree.push_node(context.clone());
1856        if let Some(focus_handle) = focus_handle.as_ref() {
1857            window
1858                .next_frame
1859                .dispatch_tree
1860                .make_focusable(focus_handle.id);
1861        }
1862        let result = f(focus_handle, self);
1863
1864        self.window.next_frame.dispatch_tree.pop_node();
1865
1866        result
1867    }
1868
1869    /// Set an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
1870    /// platform to receive textual input with proper integration with concerns such
1871    /// as IME interactions.
1872    ///
1873    /// [element_input_handler]: crate::ElementInputHandler
1874    pub fn handle_input(
1875        &mut self,
1876        focus_handle: &FocusHandle,
1877        input_handler: impl PlatformInputHandler,
1878    ) {
1879        if focus_handle.is_focused(self) {
1880            self.window
1881                .platform_window
1882                .set_input_handler(Box::new(input_handler));
1883        }
1884    }
1885
1886    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1887    /// If the callback returns false, the window won't be closed.
1888    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1889        let mut this = self.to_async();
1890        self.window
1891            .platform_window
1892            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1893    }
1894}
1895
1896impl Context for WindowContext<'_> {
1897    type Result<T> = T;
1898
1899    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1900    where
1901        T: 'static,
1902    {
1903        let slot = self.app.entities.reserve();
1904        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1905        self.entities.insert(slot, model)
1906    }
1907
1908    fn update_model<T: 'static, R>(
1909        &mut self,
1910        model: &Model<T>,
1911        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1912    ) -> R {
1913        let mut entity = self.entities.lease(model);
1914        let result = update(
1915            &mut *entity,
1916            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1917        );
1918        self.entities.end_lease(entity);
1919        result
1920    }
1921
1922    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1923    where
1924        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1925    {
1926        if window == self.window.handle {
1927            let root_view = self.window.root_view.clone().unwrap();
1928            Ok(update(root_view, self))
1929        } else {
1930            window.update(self.app, update)
1931        }
1932    }
1933
1934    fn read_model<T, R>(
1935        &self,
1936        handle: &Model<T>,
1937        read: impl FnOnce(&T, &AppContext) -> R,
1938    ) -> Self::Result<R>
1939    where
1940        T: 'static,
1941    {
1942        let entity = self.entities.read(handle);
1943        read(entity, &*self.app)
1944    }
1945
1946    fn read_window<T, R>(
1947        &self,
1948        window: &WindowHandle<T>,
1949        read: impl FnOnce(View<T>, &AppContext) -> R,
1950    ) -> Result<R>
1951    where
1952        T: 'static,
1953    {
1954        if window.any_handle == self.window.handle {
1955            let root_view = self
1956                .window
1957                .root_view
1958                .clone()
1959                .unwrap()
1960                .downcast::<T>()
1961                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1962            Ok(read(root_view, self))
1963        } else {
1964            self.app.read_window(window, read)
1965        }
1966    }
1967}
1968
1969impl VisualContext for WindowContext<'_> {
1970    fn new_view<V>(
1971        &mut self,
1972        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1973    ) -> Self::Result<View<V>>
1974    where
1975        V: 'static + Render,
1976    {
1977        let slot = self.app.entities.reserve();
1978        let view = View {
1979            model: slot.clone(),
1980        };
1981        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1982        let entity = build_view_state(&mut cx);
1983        cx.entities.insert(slot, entity);
1984
1985        cx.new_view_observers
1986            .clone()
1987            .retain(&TypeId::of::<V>(), |observer| {
1988                let any_view = AnyView::from(view.clone());
1989                (observer)(any_view, self);
1990                true
1991            });
1992
1993        view
1994    }
1995
1996    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1997    fn update_view<T: 'static, R>(
1998        &mut self,
1999        view: &View<T>,
2000        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
2001    ) -> Self::Result<R> {
2002        let mut lease = self.app.entities.lease(&view.model);
2003        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
2004        let result = update(&mut *lease, &mut cx);
2005        cx.app.entities.end_lease(lease);
2006        result
2007    }
2008
2009    fn replace_root_view<V>(
2010        &mut self,
2011        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2012    ) -> Self::Result<View<V>>
2013    where
2014        V: 'static + Render,
2015    {
2016        let view = self.new_view(build_view);
2017        self.window.root_view = Some(view.clone().into());
2018        self.notify();
2019        view
2020    }
2021
2022    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
2023        self.update_view(view, |view, cx| {
2024            view.focus_handle(cx).clone().focus(cx);
2025        })
2026    }
2027
2028    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
2029    where
2030        V: ManagedView,
2031    {
2032        self.update_view(view, |_, cx| cx.emit(DismissEvent))
2033    }
2034}
2035
2036impl<'a> std::ops::Deref for WindowContext<'a> {
2037    type Target = AppContext;
2038
2039    fn deref(&self) -> &Self::Target {
2040        self.app
2041    }
2042}
2043
2044impl<'a> std::ops::DerefMut for WindowContext<'a> {
2045    fn deref_mut(&mut self) -> &mut Self::Target {
2046        self.app
2047    }
2048}
2049
2050impl<'a> Borrow<AppContext> for WindowContext<'a> {
2051    fn borrow(&self) -> &AppContext {
2052        self.app
2053    }
2054}
2055
2056impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
2057    fn borrow_mut(&mut self) -> &mut AppContext {
2058        self.app
2059    }
2060}
2061
2062/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
2063pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2064    #[doc(hidden)]
2065    fn app_mut(&mut self) -> &mut AppContext {
2066        self.borrow_mut()
2067    }
2068
2069    #[doc(hidden)]
2070    fn app(&self) -> &AppContext {
2071        self.borrow()
2072    }
2073
2074    #[doc(hidden)]
2075    fn window(&self) -> &Window {
2076        self.borrow()
2077    }
2078
2079    #[doc(hidden)]
2080    fn window_mut(&mut self) -> &mut Window {
2081        self.borrow_mut()
2082    }
2083
2084    /// Pushes the given element id onto the global stack and invokes the given closure
2085    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
2086    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
2087    /// used to associate state with identified elements across separate frames.
2088    fn with_element_id<R>(
2089        &mut self,
2090        id: Option<impl Into<ElementId>>,
2091        f: impl FnOnce(&mut Self) -> R,
2092    ) -> R {
2093        if let Some(id) = id.map(Into::into) {
2094            let window = self.window_mut();
2095            window.element_id_stack.push(id);
2096            let result = f(self);
2097            let window: &mut Window = self.borrow_mut();
2098            window.element_id_stack.pop();
2099            result
2100        } else {
2101            f(self)
2102        }
2103    }
2104
2105    /// Invoke the given function with the given content mask after intersecting it
2106    /// with the current mask.
2107    fn with_content_mask<R>(
2108        &mut self,
2109        mask: Option<ContentMask<Pixels>>,
2110        f: impl FnOnce(&mut Self) -> R,
2111    ) -> R {
2112        if let Some(mask) = mask {
2113            let mask = mask.intersect(&self.content_mask());
2114            self.window_mut().next_frame.content_mask_stack.push(mask);
2115            let result = f(self);
2116            self.window_mut().next_frame.content_mask_stack.pop();
2117            result
2118        } else {
2119            f(self)
2120        }
2121    }
2122
2123    /// Invoke the given function with the content mask reset to that
2124    /// of the window.
2125    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2126        let mask = ContentMask {
2127            bounds: Bounds {
2128                origin: Point::default(),
2129                size: self.window().viewport_size,
2130            },
2131        };
2132        let new_stacking_order_id =
2133            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2134        let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
2135        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2136        self.window_mut().next_frame.content_mask_stack.push(mask);
2137        let result = f(self);
2138        self.window_mut().next_frame.content_mask_stack.pop();
2139        self.window_mut().next_frame.z_index_stack = old_stacking_order;
2140        result
2141    }
2142
2143    /// Called during painting to invoke the given closure in a new stacking context. The given
2144    /// z-index is interpreted relative to the previous call to `stack`.
2145    fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2146        let new_stacking_order_id =
2147            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2148        let old_stacking_order_id = mem::replace(
2149            &mut self.window_mut().next_frame.z_index_stack.id,
2150            new_stacking_order_id,
2151        );
2152        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2153        self.window_mut().next_frame.z_index_stack.push(z_index);
2154        let result = f(self);
2155        self.window_mut().next_frame.z_index_stack.id = old_stacking_order_id;
2156        self.window_mut().next_frame.z_index_stack.pop();
2157        result
2158    }
2159
2160    /// Update the global element offset relative to the current offset. This is used to implement
2161    /// scrolling.
2162    fn with_element_offset<R>(
2163        &mut self,
2164        offset: Point<Pixels>,
2165        f: impl FnOnce(&mut Self) -> R,
2166    ) -> R {
2167        if offset.is_zero() {
2168            return f(self);
2169        };
2170
2171        let abs_offset = self.element_offset() + offset;
2172        self.with_absolute_element_offset(abs_offset, f)
2173    }
2174
2175    /// Update the global element offset based on the given offset. This is used to implement
2176    /// drag handles and other manual painting of elements.
2177    fn with_absolute_element_offset<R>(
2178        &mut self,
2179        offset: Point<Pixels>,
2180        f: impl FnOnce(&mut Self) -> R,
2181    ) -> R {
2182        self.window_mut()
2183            .next_frame
2184            .element_offset_stack
2185            .push(offset);
2186        let result = f(self);
2187        self.window_mut().next_frame.element_offset_stack.pop();
2188        result
2189    }
2190
2191    /// Obtain the current element offset.
2192    fn element_offset(&self) -> Point<Pixels> {
2193        self.window()
2194            .next_frame
2195            .element_offset_stack
2196            .last()
2197            .copied()
2198            .unwrap_or_default()
2199    }
2200
2201    /// Update or initialize state for an element with the given id that lives across multiple
2202    /// frames. If an element with this id existed in the rendered frame, its state will be passed
2203    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2204    /// when drawing the next frame.
2205    fn with_element_state<S, R>(
2206        &mut self,
2207        id: ElementId,
2208        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2209    ) -> R
2210    where
2211        S: 'static,
2212    {
2213        self.with_element_id(Some(id), |cx| {
2214            let global_id = cx.window().element_id_stack.clone();
2215
2216            if let Some(any) = cx
2217                .window_mut()
2218                .next_frame
2219                .element_states
2220                .remove(&global_id)
2221                .or_else(|| {
2222                    cx.window_mut()
2223                        .rendered_frame
2224                        .element_states
2225                        .remove(&global_id)
2226                })
2227            {
2228                let ElementStateBox {
2229                    inner,
2230
2231                    #[cfg(debug_assertions)]
2232                    type_name
2233                } = any;
2234                // Using the extra inner option to avoid needing to reallocate a new box.
2235                let mut state_box = inner
2236                    .downcast::<Option<S>>()
2237                    .map_err(|_| {
2238                        #[cfg(debug_assertions)]
2239                        {
2240                            anyhow!(
2241                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2242                                std::any::type_name::<S>(),
2243                                type_name
2244                            )
2245                        }
2246
2247                        #[cfg(not(debug_assertions))]
2248                        {
2249                            anyhow!(
2250                                "invalid element state type for id, requested_type {:?}",
2251                                std::any::type_name::<S>(),
2252                            )
2253                        }
2254                    })
2255                    .unwrap();
2256
2257                // Actual: Option<AnyElement> <- View
2258                // Requested: () <- AnyElemet
2259                let state = state_box
2260                    .take()
2261                    .expect("element state is already on the stack");
2262                let (result, state) = f(Some(state), cx);
2263                state_box.replace(state);
2264                cx.window_mut()
2265                    .next_frame
2266                    .element_states
2267                    .insert(global_id, ElementStateBox {
2268                        inner: state_box,
2269
2270                        #[cfg(debug_assertions)]
2271                        type_name
2272                    });
2273                result
2274            } else {
2275                let (result, state) = f(None, cx);
2276                cx.window_mut()
2277                    .next_frame
2278                    .element_states
2279                    .insert(global_id,
2280                        ElementStateBox {
2281                            inner: Box::new(Some(state)),
2282
2283                            #[cfg(debug_assertions)]
2284                            type_name: std::any::type_name::<S>()
2285                        }
2286
2287                    );
2288                result
2289            }
2290        })
2291    }
2292
2293    /// Obtain the current content mask.
2294    fn content_mask(&self) -> ContentMask<Pixels> {
2295        self.window()
2296            .next_frame
2297            .content_mask_stack
2298            .last()
2299            .cloned()
2300            .unwrap_or_else(|| ContentMask {
2301                bounds: Bounds {
2302                    origin: Point::default(),
2303                    size: self.window().viewport_size,
2304                },
2305            })
2306    }
2307
2308    /// The size of an em for the base font of the application. Adjusting this value allows the
2309    /// UI to scale, just like zooming a web page.
2310    fn rem_size(&self) -> Pixels {
2311        self.window().rem_size
2312    }
2313}
2314
2315impl Borrow<Window> for WindowContext<'_> {
2316    fn borrow(&self) -> &Window {
2317        self.window
2318    }
2319}
2320
2321impl BorrowMut<Window> for WindowContext<'_> {
2322    fn borrow_mut(&mut self) -> &mut Window {
2323        self.window
2324    }
2325}
2326
2327impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2328
2329/// Provides access to application state that is specialized for a particular [`View`].
2330/// Allows you to interact with focus, emit events, etc.
2331/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
2332/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
2333pub struct ViewContext<'a, V> {
2334    window_cx: WindowContext<'a>,
2335    view: &'a View<V>,
2336}
2337
2338impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2339    fn borrow(&self) -> &AppContext {
2340        &*self.window_cx.app
2341    }
2342}
2343
2344impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2345    fn borrow_mut(&mut self) -> &mut AppContext {
2346        &mut *self.window_cx.app
2347    }
2348}
2349
2350impl<V> Borrow<Window> for ViewContext<'_, V> {
2351    fn borrow(&self) -> &Window {
2352        &*self.window_cx.window
2353    }
2354}
2355
2356impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2357    fn borrow_mut(&mut self) -> &mut Window {
2358        &mut *self.window_cx.window
2359    }
2360}
2361
2362impl<'a, V: 'static> ViewContext<'a, V> {
2363    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2364        Self {
2365            window_cx: WindowContext::new(app, window),
2366            view,
2367        }
2368    }
2369
2370    /// Get the entity_id of this view.
2371    pub fn entity_id(&self) -> EntityId {
2372        self.view.entity_id()
2373    }
2374
2375    /// Get the view pointer underlying this context.
2376    pub fn view(&self) -> &View<V> {
2377        self.view
2378    }
2379
2380    /// Get the model underlying this view.
2381    pub fn model(&self) -> &Model<V> {
2382        &self.view.model
2383    }
2384
2385    /// Access the underlying window context.
2386    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2387        &mut self.window_cx
2388    }
2389
2390    /// Set a given callback to be run on the next frame.
2391    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2392    where
2393        V: 'static,
2394    {
2395        let view = self.view().clone();
2396        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2397    }
2398
2399    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2400    /// that are currently on the stack to be returned to the app.
2401    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2402        let view = self.view().downgrade();
2403        self.window_cx.defer(move |cx| {
2404            view.update(cx, f).ok();
2405        });
2406    }
2407
2408    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2409    pub fn observe<V2, E>(
2410        &mut self,
2411        entity: &E,
2412        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2413    ) -> Subscription
2414    where
2415        V2: 'static,
2416        V: 'static,
2417        E: Entity<V2>,
2418    {
2419        let view = self.view().downgrade();
2420        let entity_id = entity.entity_id();
2421        let entity = entity.downgrade();
2422        let window_handle = self.window.handle;
2423        let (subscription, activate) = self.app.observers.insert(
2424            entity_id,
2425            Box::new(move |cx| {
2426                window_handle
2427                    .update(cx, |_, cx| {
2428                        if let Some(handle) = E::upgrade_from(&entity) {
2429                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2430                                .is_ok()
2431                        } else {
2432                            false
2433                        }
2434                    })
2435                    .unwrap_or(false)
2436            }),
2437        );
2438        self.app.defer(move |_| activate());
2439        subscription
2440    }
2441
2442    /// Subscribe to events emitted by another model or view.
2443    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2444    /// 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.
2445    pub fn subscribe<V2, E, Evt>(
2446        &mut self,
2447        entity: &E,
2448        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2449    ) -> Subscription
2450    where
2451        V2: EventEmitter<Evt>,
2452        E: Entity<V2>,
2453        Evt: 'static,
2454    {
2455        let view = self.view().downgrade();
2456        let entity_id = entity.entity_id();
2457        let handle = entity.downgrade();
2458        let window_handle = self.window.handle;
2459        let (subscription, activate) = self.app.event_listeners.insert(
2460            entity_id,
2461            (
2462                TypeId::of::<Evt>(),
2463                Box::new(move |event, cx| {
2464                    window_handle
2465                        .update(cx, |_, cx| {
2466                            if let Some(handle) = E::upgrade_from(&handle) {
2467                                let event = event.downcast_ref().expect("invalid event type");
2468                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2469                                    .is_ok()
2470                            } else {
2471                                false
2472                            }
2473                        })
2474                        .unwrap_or(false)
2475                }),
2476            ),
2477        );
2478        self.app.defer(move |_| activate());
2479        subscription
2480    }
2481
2482    /// Register a callback to be invoked when the view is released.
2483    ///
2484    /// The callback receives a handle to the view's window. This handle may be
2485    /// invalid, if the window was closed before the view was released.
2486    pub fn on_release(
2487        &mut self,
2488        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2489    ) -> Subscription {
2490        let window_handle = self.window.handle;
2491        let (subscription, activate) = self.app.release_listeners.insert(
2492            self.view.model.entity_id,
2493            Box::new(move |this, cx| {
2494                let this = this.downcast_mut().expect("invalid entity type");
2495                on_release(this, window_handle, cx)
2496            }),
2497        );
2498        activate();
2499        subscription
2500    }
2501
2502    /// Register a callback to be invoked when the given Model or View is released.
2503    pub fn observe_release<V2, E>(
2504        &mut self,
2505        entity: &E,
2506        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2507    ) -> Subscription
2508    where
2509        V: 'static,
2510        V2: 'static,
2511        E: Entity<V2>,
2512    {
2513        let view = self.view().downgrade();
2514        let entity_id = entity.entity_id();
2515        let window_handle = self.window.handle;
2516        let (subscription, activate) = self.app.release_listeners.insert(
2517            entity_id,
2518            Box::new(move |entity, cx| {
2519                let entity = entity.downcast_mut().expect("invalid entity type");
2520                let _ = window_handle.update(cx, |_, cx| {
2521                    view.update(cx, |this, cx| on_release(this, entity, cx))
2522                });
2523            }),
2524        );
2525        activate();
2526        subscription
2527    }
2528
2529    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2530    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2531    pub fn notify(&mut self) {
2532        if !self.window.drawing {
2533            self.window_cx.notify();
2534            self.window_cx.app.push_effect(Effect::Notify {
2535                emitter: self.view.model.entity_id,
2536            });
2537        }
2538    }
2539
2540    /// Register a callback to be invoked when the window is resized.
2541    pub fn observe_window_bounds(
2542        &mut self,
2543        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2544    ) -> Subscription {
2545        let view = self.view.downgrade();
2546        let (subscription, activate) = self.window.bounds_observers.insert(
2547            (),
2548            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2549        );
2550        activate();
2551        subscription
2552    }
2553
2554    /// Register a callback to be invoked when the window is activated or deactivated.
2555    pub fn observe_window_activation(
2556        &mut self,
2557        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2558    ) -> Subscription {
2559        let view = self.view.downgrade();
2560        let (subscription, activate) = self.window.activation_observers.insert(
2561            (),
2562            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2563        );
2564        activate();
2565        subscription
2566    }
2567
2568    /// Register a listener to be called when the given focus handle receives focus.
2569    /// Returns a subscription and persists until the subscription is dropped.
2570    pub fn on_focus(
2571        &mut self,
2572        handle: &FocusHandle,
2573        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2574    ) -> Subscription {
2575        let view = self.view.downgrade();
2576        let focus_id = handle.id;
2577        let (subscription, activate) = self.window.focus_listeners.insert(
2578            (),
2579            Box::new(move |event, cx| {
2580                view.update(cx, |view, cx| {
2581                    if event.previous_focus_path.last() != Some(&focus_id)
2582                        && event.current_focus_path.last() == Some(&focus_id)
2583                    {
2584                        listener(view, cx)
2585                    }
2586                })
2587                .is_ok()
2588            }),
2589        );
2590        self.app.defer(move |_| activate());
2591        subscription
2592    }
2593
2594    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2595    /// Returns a subscription and persists until the subscription is dropped.
2596    pub fn on_focus_in(
2597        &mut self,
2598        handle: &FocusHandle,
2599        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2600    ) -> Subscription {
2601        let view = self.view.downgrade();
2602        let focus_id = handle.id;
2603        let (subscription, activate) = self.window.focus_listeners.insert(
2604            (),
2605            Box::new(move |event, cx| {
2606                view.update(cx, |view, cx| {
2607                    if !event.previous_focus_path.contains(&focus_id)
2608                        && event.current_focus_path.contains(&focus_id)
2609                    {
2610                        listener(view, cx)
2611                    }
2612                })
2613                .is_ok()
2614            }),
2615        );
2616        self.app.defer(move |_| activate());
2617        subscription
2618    }
2619
2620    /// Register a listener to be called when the given focus handle loses focus.
2621    /// Returns a subscription and persists until the subscription is dropped.
2622    pub fn on_blur(
2623        &mut self,
2624        handle: &FocusHandle,
2625        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2626    ) -> Subscription {
2627        let view = self.view.downgrade();
2628        let focus_id = handle.id;
2629        let (subscription, activate) = self.window.focus_listeners.insert(
2630            (),
2631            Box::new(move |event, cx| {
2632                view.update(cx, |view, cx| {
2633                    if event.previous_focus_path.last() == Some(&focus_id)
2634                        && event.current_focus_path.last() != Some(&focus_id)
2635                    {
2636                        listener(view, cx)
2637                    }
2638                })
2639                .is_ok()
2640            }),
2641        );
2642        self.app.defer(move |_| activate());
2643        subscription
2644    }
2645
2646    /// Register a listener to be called when the window loses focus.
2647    /// Returns a subscription and persists until the subscription is dropped.
2648    pub fn on_blur_window(
2649        &mut self,
2650        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2651    ) -> Subscription {
2652        let view = self.view.downgrade();
2653        let (subscription, activate) = self.window.blur_listeners.insert(
2654            (),
2655            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2656        );
2657        activate();
2658        subscription
2659    }
2660
2661    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2662    /// Returns a subscription and persists until the subscription is dropped.
2663    pub fn on_focus_out(
2664        &mut self,
2665        handle: &FocusHandle,
2666        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2667    ) -> Subscription {
2668        let view = self.view.downgrade();
2669        let focus_id = handle.id;
2670        let (subscription, activate) = self.window.focus_listeners.insert(
2671            (),
2672            Box::new(move |event, cx| {
2673                view.update(cx, |view, cx| {
2674                    if event.previous_focus_path.contains(&focus_id)
2675                        && !event.current_focus_path.contains(&focus_id)
2676                    {
2677                        listener(view, cx)
2678                    }
2679                })
2680                .is_ok()
2681            }),
2682        );
2683        self.app.defer(move |_| activate());
2684        subscription
2685    }
2686
2687    /// Schedule a future to be run asynchronously.
2688    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2689    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2690    /// The returned future will be polled on the main thread.
2691    pub fn spawn<Fut, R>(
2692        &mut self,
2693        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2694    ) -> Task<R>
2695    where
2696        R: 'static,
2697        Fut: Future<Output = R> + 'static,
2698    {
2699        let view = self.view().downgrade();
2700        self.window_cx.spawn(|cx| f(view, cx))
2701    }
2702
2703    /// Update the global state of the given type.
2704    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2705    where
2706        G: 'static,
2707    {
2708        let mut global = self.app.lease_global::<G>();
2709        let result = f(&mut global, self);
2710        self.app.end_global_lease(global);
2711        result
2712    }
2713
2714    /// Register a callback to be invoked when the given global state changes.
2715    pub fn observe_global<G: 'static>(
2716        &mut self,
2717        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2718    ) -> Subscription {
2719        let window_handle = self.window.handle;
2720        let view = self.view().downgrade();
2721        let (subscription, activate) = self.global_observers.insert(
2722            TypeId::of::<G>(),
2723            Box::new(move |cx| {
2724                window_handle
2725                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2726                    .unwrap_or(false)
2727            }),
2728        );
2729        self.app.defer(move |_| activate());
2730        subscription
2731    }
2732
2733    /// Add a listener for any mouse event that occurs in the window.
2734    /// This is a fairly low level method.
2735    /// Typically, you'll want to use methods on UI elements, which perform bounds checking etc.
2736    pub fn on_mouse_event<Event: 'static>(
2737        &mut self,
2738        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2739    ) {
2740        let handle = self.view().clone();
2741        self.window_cx.on_mouse_event(move |event, phase, cx| {
2742            handle.update(cx, |view, cx| {
2743                handler(view, event, phase, cx);
2744            })
2745        });
2746    }
2747
2748    /// Register a callback to be invoked when the given Key Event is dispatched to the window.
2749    pub fn on_key_event<Event: 'static>(
2750        &mut self,
2751        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2752    ) {
2753        let handle = self.view().clone();
2754        self.window_cx.on_key_event(move |event, phase, cx| {
2755            handle.update(cx, |view, cx| {
2756                handler(view, event, phase, cx);
2757            })
2758        });
2759    }
2760
2761    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2762    pub fn on_action(
2763        &mut self,
2764        action_type: TypeId,
2765        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2766    ) {
2767        let handle = self.view().clone();
2768        self.window_cx
2769            .on_action(action_type, move |action, phase, cx| {
2770                handle.update(cx, |view, cx| {
2771                    listener(view, action, phase, cx);
2772                })
2773            });
2774    }
2775
2776    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2777    pub fn emit<Evt>(&mut self, event: Evt)
2778    where
2779        Evt: 'static,
2780        V: EventEmitter<Evt>,
2781    {
2782        let emitter = self.view.model.entity_id;
2783        self.app.push_effect(Effect::Emit {
2784            emitter,
2785            event_type: TypeId::of::<Evt>(),
2786            event: Box::new(event),
2787        });
2788    }
2789
2790    /// Move focus to the current view, assuming it implements [`FocusableView`].
2791    pub fn focus_self(&mut self)
2792    where
2793        V: FocusableView,
2794    {
2795        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2796    }
2797
2798    /// Convenience method for accessing view state in an event callback.
2799    ///
2800    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2801    /// but it's often useful to be able to access view state in these
2802    /// callbacks. This method provides a convenient way to do so.
2803    pub fn listener<E>(
2804        &self,
2805        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2806    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2807        let view = self.view().downgrade();
2808        move |e: &E, cx: &mut WindowContext| {
2809            view.update(cx, |view, cx| f(view, e, cx)).ok();
2810        }
2811    }
2812}
2813
2814impl<V> Context for ViewContext<'_, V> {
2815    type Result<U> = U;
2816
2817    fn new_model<T: 'static>(
2818        &mut self,
2819        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2820    ) -> Model<T> {
2821        self.window_cx.new_model(build_model)
2822    }
2823
2824    fn update_model<T: 'static, R>(
2825        &mut self,
2826        model: &Model<T>,
2827        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2828    ) -> R {
2829        self.window_cx.update_model(model, update)
2830    }
2831
2832    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2833    where
2834        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2835    {
2836        self.window_cx.update_window(window, update)
2837    }
2838
2839    fn read_model<T, R>(
2840        &self,
2841        handle: &Model<T>,
2842        read: impl FnOnce(&T, &AppContext) -> R,
2843    ) -> Self::Result<R>
2844    where
2845        T: 'static,
2846    {
2847        self.window_cx.read_model(handle, read)
2848    }
2849
2850    fn read_window<T, R>(
2851        &self,
2852        window: &WindowHandle<T>,
2853        read: impl FnOnce(View<T>, &AppContext) -> R,
2854    ) -> Result<R>
2855    where
2856        T: 'static,
2857    {
2858        self.window_cx.read_window(window, read)
2859    }
2860}
2861
2862impl<V: 'static> VisualContext for ViewContext<'_, V> {
2863    fn new_view<W: Render + 'static>(
2864        &mut self,
2865        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2866    ) -> Self::Result<View<W>> {
2867        self.window_cx.new_view(build_view_state)
2868    }
2869
2870    fn update_view<V2: 'static, R>(
2871        &mut self,
2872        view: &View<V2>,
2873        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2874    ) -> Self::Result<R> {
2875        self.window_cx.update_view(view, update)
2876    }
2877
2878    fn replace_root_view<W>(
2879        &mut self,
2880        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2881    ) -> Self::Result<View<W>>
2882    where
2883        W: 'static + Render,
2884    {
2885        self.window_cx.replace_root_view(build_view)
2886    }
2887
2888    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2889        self.window_cx.focus_view(view)
2890    }
2891
2892    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2893        self.window_cx.dismiss_view(view)
2894    }
2895}
2896
2897impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2898    type Target = WindowContext<'a>;
2899
2900    fn deref(&self) -> &Self::Target {
2901        &self.window_cx
2902    }
2903}
2904
2905impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2906    fn deref_mut(&mut self) -> &mut Self::Target {
2907        &mut self.window_cx
2908    }
2909}
2910
2911// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2912slotmap::new_key_type! {
2913    /// A unique identifier for a window.
2914    pub struct WindowId;
2915}
2916
2917impl WindowId {
2918    /// Converts this window ID to a `u64`.
2919    pub fn as_u64(&self) -> u64 {
2920        self.0.as_ffi()
2921    }
2922}
2923
2924/// A handle to a window with a specific root view type.
2925/// Note that this does not keep the window alive on its own.
2926#[derive(Deref, DerefMut)]
2927pub struct WindowHandle<V> {
2928    #[deref]
2929    #[deref_mut]
2930    pub(crate) any_handle: AnyWindowHandle,
2931    state_type: PhantomData<V>,
2932}
2933
2934impl<V: 'static + Render> WindowHandle<V> {
2935    /// Create a new handle from a window ID.
2936    /// This does not check if the root type of the window is `V`.
2937    pub fn new(id: WindowId) -> Self {
2938        WindowHandle {
2939            any_handle: AnyWindowHandle {
2940                id,
2941                state_type: TypeId::of::<V>(),
2942            },
2943            state_type: PhantomData,
2944        }
2945    }
2946
2947    /// Get the root view out of this window.
2948    ///
2949    /// This will fail if the window is closed or if the root view's type does not match `V`.
2950    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2951    where
2952        C: Context,
2953    {
2954        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2955            root_view
2956                .downcast::<V>()
2957                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2958        }))
2959    }
2960
2961    /// Update the root view of this window.
2962    ///
2963    /// This will fail if the window has been closed or if the root view's type does not match
2964    pub fn update<C, R>(
2965        &self,
2966        cx: &mut C,
2967        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2968    ) -> Result<R>
2969    where
2970        C: Context,
2971    {
2972        cx.update_window(self.any_handle, |root_view, cx| {
2973            let view = root_view
2974                .downcast::<V>()
2975                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2976            Ok(cx.update_view(&view, update))
2977        })?
2978    }
2979
2980    /// Read the root view out of this window.
2981    ///
2982    /// This will fail if the window is closed or if the root view's type does not match `V`.
2983    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2984        let x = cx
2985            .windows
2986            .get(self.id)
2987            .and_then(|window| {
2988                window
2989                    .as_ref()
2990                    .and_then(|window| window.root_view.clone())
2991                    .map(|root_view| root_view.downcast::<V>())
2992            })
2993            .ok_or_else(|| anyhow!("window not found"))?
2994            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2995
2996        Ok(x.read(cx))
2997    }
2998
2999    /// Read the root view out of this window, with a callback
3000    ///
3001    /// This will fail if the window is closed or if the root view's type does not match `V`.
3002    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
3003    where
3004        C: Context,
3005    {
3006        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3007    }
3008
3009    /// Read the root view pointer off of this window.
3010    ///
3011    /// This will fail if the window is closed or if the root view's type does not match `V`.
3012    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
3013    where
3014        C: Context,
3015    {
3016        cx.read_window(self, |root_view, _cx| root_view.clone())
3017    }
3018
3019    /// Check if this window is 'active'.
3020    ///
3021    /// Will return `None` if the window is closed.
3022    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
3023        cx.windows
3024            .get(self.id)
3025            .and_then(|window| window.as_ref().map(|window| window.active))
3026    }
3027}
3028
3029impl<V> Copy for WindowHandle<V> {}
3030
3031impl<V> Clone for WindowHandle<V> {
3032    fn clone(&self) -> Self {
3033        *self
3034    }
3035}
3036
3037impl<V> PartialEq for WindowHandle<V> {
3038    fn eq(&self, other: &Self) -> bool {
3039        self.any_handle == other.any_handle
3040    }
3041}
3042
3043impl<V> Eq for WindowHandle<V> {}
3044
3045impl<V> Hash for WindowHandle<V> {
3046    fn hash<H: Hasher>(&self, state: &mut H) {
3047        self.any_handle.hash(state);
3048    }
3049}
3050
3051impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3052    fn from(val: WindowHandle<V>) -> Self {
3053        val.any_handle
3054    }
3055}
3056
3057/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3058#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3059pub struct AnyWindowHandle {
3060    pub(crate) id: WindowId,
3061    state_type: TypeId,
3062}
3063
3064impl AnyWindowHandle {
3065    /// Get the ID of this window.
3066    pub fn window_id(&self) -> WindowId {
3067        self.id
3068    }
3069
3070    /// Attempt to convert this handle to a window handle with a specific root view type.
3071    /// If the types do not match, this will return `None`.
3072    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3073        if TypeId::of::<T>() == self.state_type {
3074            Some(WindowHandle {
3075                any_handle: *self,
3076                state_type: PhantomData,
3077            })
3078        } else {
3079            None
3080        }
3081    }
3082
3083    /// Update the state of the root view of this window.
3084    ///
3085    /// This will fail if the window has been closed.
3086    pub fn update<C, R>(
3087        self,
3088        cx: &mut C,
3089        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
3090    ) -> Result<R>
3091    where
3092        C: Context,
3093    {
3094        cx.update_window(self, update)
3095    }
3096
3097    /// Read the state of the root view of this window.
3098    ///
3099    /// This will fail if the window has been closed.
3100    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
3101    where
3102        C: Context,
3103        T: 'static,
3104    {
3105        let view = self
3106            .downcast::<T>()
3107            .context("the type of the window's root view has changed")?;
3108
3109        cx.read_window(&view, read)
3110    }
3111}
3112
3113// #[cfg(any(test, feature = "test-support"))]
3114// impl From<SmallVec<[u32; 16]>> for StackingOrder {
3115//     fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
3116//         StackingOrder(small_vec)
3117//     }
3118// }
3119
3120/// An identifier for an [`Element`](crate::Element).
3121///
3122/// Can be constructed with a string, a number, or both, as well
3123/// as other internal representations.
3124#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3125pub enum ElementId {
3126    /// The ID of a View element
3127    View(EntityId),
3128    /// An integer ID.
3129    Integer(usize),
3130    /// A string based ID.
3131    Name(SharedString),
3132    /// An ID that's equated with a focus handle.
3133    FocusHandle(FocusId),
3134    /// A combination of a name and an integer.
3135    NamedInteger(SharedString, usize),
3136}
3137
3138impl ElementId {
3139    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3140        ElementId::View(entity_id)
3141    }
3142}
3143
3144impl TryInto<SharedString> for ElementId {
3145    type Error = anyhow::Error;
3146
3147    fn try_into(self) -> anyhow::Result<SharedString> {
3148        if let ElementId::Name(name) = self {
3149            Ok(name)
3150        } else {
3151            Err(anyhow!("element id is not string"))
3152        }
3153    }
3154}
3155
3156impl From<usize> for ElementId {
3157    fn from(id: usize) -> Self {
3158        ElementId::Integer(id)
3159    }
3160}
3161
3162impl From<i32> for ElementId {
3163    fn from(id: i32) -> Self {
3164        Self::Integer(id as usize)
3165    }
3166}
3167
3168impl From<SharedString> for ElementId {
3169    fn from(name: SharedString) -> Self {
3170        ElementId::Name(name)
3171    }
3172}
3173
3174impl From<&'static str> for ElementId {
3175    fn from(name: &'static str) -> Self {
3176        ElementId::Name(name.into())
3177    }
3178}
3179
3180impl<'a> From<&'a FocusHandle> for ElementId {
3181    fn from(handle: &'a FocusHandle) -> Self {
3182        ElementId::FocusHandle(handle.id)
3183    }
3184}
3185
3186impl From<(&'static str, EntityId)> for ElementId {
3187    fn from((name, id): (&'static str, EntityId)) -> Self {
3188        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3189    }
3190}
3191
3192impl From<(&'static str, usize)> for ElementId {
3193    fn from((name, id): (&'static str, usize)) -> Self {
3194        ElementId::NamedInteger(name.into(), id)
3195    }
3196}
3197
3198impl From<(&'static str, u64)> for ElementId {
3199    fn from((name, id): (&'static str, u64)) -> Self {
3200        ElementId::NamedInteger(name.into(), id as usize)
3201    }
3202}
3203
3204/// A rectangle to be rendered in the window at the given position and size.
3205/// Passed as an argument [`WindowContext::paint_quad`].
3206#[derive(Clone)]
3207pub struct PaintQuad {
3208    bounds: Bounds<Pixels>,
3209    corner_radii: Corners<Pixels>,
3210    background: Hsla,
3211    border_widths: Edges<Pixels>,
3212    border_color: Hsla,
3213}
3214
3215impl PaintQuad {
3216    /// Set the corner radii of the quad.
3217    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3218        PaintQuad {
3219            corner_radii: corner_radii.into(),
3220            ..self
3221        }
3222    }
3223
3224    /// Set the border widths of the quad.
3225    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3226        PaintQuad {
3227            border_widths: border_widths.into(),
3228            ..self
3229        }
3230    }
3231
3232    /// Set the border color of the quad.
3233    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3234        PaintQuad {
3235            border_color: border_color.into(),
3236            ..self
3237        }
3238    }
3239
3240    /// Set the background color of the quad.
3241    pub fn background(self, background: impl Into<Hsla>) -> Self {
3242        PaintQuad {
3243            background: background.into(),
3244            ..self
3245        }
3246    }
3247}
3248
3249/// Create a quad with the given parameters.
3250pub fn quad(
3251    bounds: Bounds<Pixels>,
3252    corner_radii: impl Into<Corners<Pixels>>,
3253    background: impl Into<Hsla>,
3254    border_widths: impl Into<Edges<Pixels>>,
3255    border_color: impl Into<Hsla>,
3256) -> PaintQuad {
3257    PaintQuad {
3258        bounds,
3259        corner_radii: corner_radii.into(),
3260        background: background.into(),
3261        border_widths: border_widths.into(),
3262        border_color: border_color.into(),
3263    }
3264}
3265
3266/// Create a filled quad with the given bounds and background color.
3267pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3268    PaintQuad {
3269        bounds: bounds.into(),
3270        corner_radii: (0.).into(),
3271        background: background.into(),
3272        border_widths: (0.).into(),
3273        border_color: transparent_black(),
3274    }
3275}
3276
3277/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3278pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3279    PaintQuad {
3280        bounds: bounds.into(),
3281        corner_radii: (0.).into(),
3282        background: transparent_black(),
3283        border_widths: (1.).into(),
3284        border_color: border_color.into(),
3285    }
3286}