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