window.rs

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