window.rs

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