window.rs

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