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