window.rs

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