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            let mut actions = self
1495                .window
1496                .current_frame
1497                .dispatch_tree
1498                .available_actions(focus_id);
1499            actions.extend(
1500                self.app
1501                    .global_action_listeners
1502                    .keys()
1503                    .filter_map(|type_id| self.app.actions.build_action_type(type_id).ok()),
1504            );
1505            actions
1506        } else {
1507            Vec::new()
1508        }
1509    }
1510
1511    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1512        self.window
1513            .previous_frame
1514            .dispatch_tree
1515            .bindings_for_action(
1516                action,
1517                &self.window.previous_frame.dispatch_tree.context_stack,
1518            )
1519    }
1520
1521    pub fn bindings_for_action_in(
1522        &self,
1523        action: &dyn Action,
1524        focus_handle: &FocusHandle,
1525    ) -> Vec<KeyBinding> {
1526        let dispatch_tree = &self.window.previous_frame.dispatch_tree;
1527
1528        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1529            return vec![];
1530        };
1531        let context_stack = dispatch_tree
1532            .dispatch_path(node_id)
1533            .into_iter()
1534            .map(|node_id| dispatch_tree.node(node_id).context.clone())
1535            .collect();
1536        dispatch_tree.bindings_for_action(action, &context_stack)
1537    }
1538
1539    pub fn listener_for<V: Render, E>(
1540        &self,
1541        view: &View<V>,
1542        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1543    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1544        let view = view.downgrade();
1545        move |e: &E, cx: &mut WindowContext| {
1546            view.update(cx, |view, cx| f(view, e, cx)).ok();
1547        }
1548    }
1549
1550    pub fn handler_for<V: Render>(
1551        &self,
1552        view: &View<V>,
1553        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1554    ) -> impl Fn(&mut WindowContext) {
1555        let view = view.downgrade();
1556        move |cx: &mut WindowContext| {
1557            view.update(cx, |view, cx| f(view, cx)).ok();
1558        }
1559    }
1560
1561    //========== ELEMENT RELATED FUNCTIONS ===========
1562    pub fn with_key_dispatch<R>(
1563        &mut self,
1564        context: KeyContext,
1565        focus_handle: Option<FocusHandle>,
1566        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1567    ) -> R {
1568        let window = &mut self.window;
1569        window
1570            .current_frame
1571            .dispatch_tree
1572            .push_node(context.clone());
1573        if let Some(focus_handle) = focus_handle.as_ref() {
1574            window
1575                .current_frame
1576                .dispatch_tree
1577                .make_focusable(focus_handle.id);
1578        }
1579        let result = f(focus_handle, self);
1580
1581        self.window.current_frame.dispatch_tree.pop_node();
1582
1583        result
1584    }
1585
1586    /// Register a focus listener for the current frame only. It will be cleared
1587    /// on the next frame render. You should use this method only from within elements,
1588    /// and we may want to enforce that better via a different context type.
1589    // todo!() Move this to `FrameContext` to emphasize its individuality?
1590    pub fn on_focus_changed(
1591        &mut self,
1592        listener: impl Fn(&FocusEvent, &mut WindowContext) + 'static,
1593    ) {
1594        self.window
1595            .current_frame
1596            .focus_listeners
1597            .push(Box::new(move |event, cx| {
1598                listener(event, cx);
1599            }));
1600    }
1601
1602    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1603    /// platform to receive textual input with proper integration with concerns such
1604    /// as IME interactions.
1605    pub fn handle_input(
1606        &mut self,
1607        focus_handle: &FocusHandle,
1608        input_handler: impl PlatformInputHandler,
1609    ) {
1610        if focus_handle.is_focused(self) {
1611            self.window
1612                .platform_window
1613                .set_input_handler(Box::new(input_handler));
1614        }
1615    }
1616
1617    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1618        let mut this = self.to_async();
1619        self.window
1620            .platform_window
1621            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1622    }
1623}
1624
1625impl Context for WindowContext<'_> {
1626    type Result<T> = T;
1627
1628    fn build_model<T>(
1629        &mut self,
1630        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1631    ) -> Model<T>
1632    where
1633        T: 'static,
1634    {
1635        let slot = self.app.entities.reserve();
1636        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1637        self.entities.insert(slot, model)
1638    }
1639
1640    fn update_model<T: 'static, R>(
1641        &mut self,
1642        model: &Model<T>,
1643        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1644    ) -> R {
1645        let mut entity = self.entities.lease(model);
1646        let result = update(
1647            &mut *entity,
1648            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1649        );
1650        self.entities.end_lease(entity);
1651        result
1652    }
1653
1654    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1655    where
1656        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1657    {
1658        if window == self.window.handle {
1659            let root_view = self.window.root_view.clone().unwrap();
1660            Ok(update(root_view, self))
1661        } else {
1662            window.update(self.app, update)
1663        }
1664    }
1665
1666    fn read_model<T, R>(
1667        &self,
1668        handle: &Model<T>,
1669        read: impl FnOnce(&T, &AppContext) -> R,
1670    ) -> Self::Result<R>
1671    where
1672        T: 'static,
1673    {
1674        let entity = self.entities.read(handle);
1675        read(&*entity, &*self.app)
1676    }
1677
1678    fn read_window<T, R>(
1679        &self,
1680        window: &WindowHandle<T>,
1681        read: impl FnOnce(View<T>, &AppContext) -> R,
1682    ) -> Result<R>
1683    where
1684        T: 'static,
1685    {
1686        if window.any_handle == self.window.handle {
1687            let root_view = self
1688                .window
1689                .root_view
1690                .clone()
1691                .unwrap()
1692                .downcast::<T>()
1693                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1694            Ok(read(root_view, self))
1695        } else {
1696            self.app.read_window(window, read)
1697        }
1698    }
1699}
1700
1701impl VisualContext for WindowContext<'_> {
1702    fn build_view<V>(
1703        &mut self,
1704        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1705    ) -> Self::Result<View<V>>
1706    where
1707        V: 'static + Render,
1708    {
1709        let slot = self.app.entities.reserve();
1710        let view = View {
1711            model: slot.clone(),
1712        };
1713        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1714        let entity = build_view_state(&mut cx);
1715        cx.entities.insert(slot, entity);
1716
1717        cx.new_view_observers
1718            .clone()
1719            .retain(&TypeId::of::<V>(), |observer| {
1720                let any_view = AnyView::from(view.clone());
1721                (observer)(any_view, self);
1722                true
1723            });
1724
1725        view
1726    }
1727
1728    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1729    fn update_view<T: 'static, R>(
1730        &mut self,
1731        view: &View<T>,
1732        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1733    ) -> Self::Result<R> {
1734        let mut lease = self.app.entities.lease(&view.model);
1735        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1736        let result = update(&mut *lease, &mut cx);
1737        cx.app.entities.end_lease(lease);
1738        result
1739    }
1740
1741    fn replace_root_view<V>(
1742        &mut self,
1743        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1744    ) -> Self::Result<View<V>>
1745    where
1746        V: 'static + Render,
1747    {
1748        let slot = self.app.entities.reserve();
1749        let view = View {
1750            model: slot.clone(),
1751        };
1752        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1753        let entity = build_view(&mut cx);
1754        self.entities.insert(slot, entity);
1755        self.window.root_view = Some(view.clone().into());
1756        view
1757    }
1758
1759    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1760        self.update_view(view, |view, cx| {
1761            view.focus_handle(cx).clone().focus(cx);
1762        })
1763    }
1764
1765    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1766    where
1767        V: ManagedView,
1768    {
1769        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1770    }
1771}
1772
1773impl<'a> std::ops::Deref for WindowContext<'a> {
1774    type Target = AppContext;
1775
1776    fn deref(&self) -> &Self::Target {
1777        &self.app
1778    }
1779}
1780
1781impl<'a> std::ops::DerefMut for WindowContext<'a> {
1782    fn deref_mut(&mut self) -> &mut Self::Target {
1783        &mut self.app
1784    }
1785}
1786
1787impl<'a> Borrow<AppContext> for WindowContext<'a> {
1788    fn borrow(&self) -> &AppContext {
1789        &self.app
1790    }
1791}
1792
1793impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1794    fn borrow_mut(&mut self) -> &mut AppContext {
1795        &mut self.app
1796    }
1797}
1798
1799pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1800    fn app_mut(&mut self) -> &mut AppContext {
1801        self.borrow_mut()
1802    }
1803
1804    fn app(&self) -> &AppContext {
1805        self.borrow()
1806    }
1807
1808    fn window(&self) -> &Window {
1809        self.borrow()
1810    }
1811
1812    fn window_mut(&mut self) -> &mut Window {
1813        self.borrow_mut()
1814    }
1815
1816    /// Pushes the given element id onto the global stack and invokes the given closure
1817    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1818    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1819    /// used to associate state with identified elements across separate frames.
1820    fn with_element_id<R>(
1821        &mut self,
1822        id: Option<impl Into<ElementId>>,
1823        f: impl FnOnce(&mut Self) -> R,
1824    ) -> R {
1825        if let Some(id) = id.map(Into::into) {
1826            let window = self.window_mut();
1827            window.element_id_stack.push(id.into());
1828            let result = f(self);
1829            let window: &mut Window = self.borrow_mut();
1830            window.element_id_stack.pop();
1831            result
1832        } else {
1833            f(self)
1834        }
1835    }
1836
1837    /// Invoke the given function with the given content mask after intersecting it
1838    /// with the current mask.
1839    fn with_content_mask<R>(
1840        &mut self,
1841        mask: Option<ContentMask<Pixels>>,
1842        f: impl FnOnce(&mut Self) -> R,
1843    ) -> R {
1844        if let Some(mask) = mask {
1845            let mask = mask.intersect(&self.content_mask());
1846            self.window_mut()
1847                .current_frame
1848                .content_mask_stack
1849                .push(mask);
1850            let result = f(self);
1851            self.window_mut().current_frame.content_mask_stack.pop();
1852            result
1853        } else {
1854            f(self)
1855        }
1856    }
1857
1858    /// Invoke the given function with the content mask reset to that
1859    /// of the window.
1860    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1861        let mask = ContentMask {
1862            bounds: Bounds {
1863                origin: Point::default(),
1864                size: self.window().viewport_size,
1865            },
1866        };
1867        self.window_mut()
1868            .current_frame
1869            .content_mask_stack
1870            .push(mask);
1871        let result = f(self);
1872        self.window_mut().current_frame.content_mask_stack.pop();
1873        result
1874    }
1875
1876    /// Update the global element offset relative to the current offset. This is used to implement
1877    /// scrolling.
1878    fn with_element_offset<R>(
1879        &mut self,
1880        offset: Point<Pixels>,
1881        f: impl FnOnce(&mut Self) -> R,
1882    ) -> R {
1883        if offset.is_zero() {
1884            return f(self);
1885        };
1886
1887        let abs_offset = self.element_offset() + offset;
1888        self.with_absolute_element_offset(abs_offset, f)
1889    }
1890
1891    /// Update the global element offset based on the given offset. This is used to implement
1892    /// drag handles and other manual painting of elements.
1893    fn with_absolute_element_offset<R>(
1894        &mut self,
1895        offset: Point<Pixels>,
1896        f: impl FnOnce(&mut Self) -> R,
1897    ) -> R {
1898        self.window_mut()
1899            .current_frame
1900            .element_offset_stack
1901            .push(offset);
1902        let result = f(self);
1903        self.window_mut().current_frame.element_offset_stack.pop();
1904        result
1905    }
1906
1907    /// Obtain the current element offset.
1908    fn element_offset(&self) -> Point<Pixels> {
1909        self.window()
1910            .current_frame
1911            .element_offset_stack
1912            .last()
1913            .copied()
1914            .unwrap_or_default()
1915    }
1916
1917    /// Update or intialize state for an element with the given id that lives across multiple
1918    /// frames. If an element with this id existed in the previous frame, its state will be passed
1919    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1920    /// when drawing the next frame.
1921    fn with_element_state<S, R>(
1922        &mut self,
1923        id: ElementId,
1924        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1925    ) -> R
1926    where
1927        S: 'static,
1928    {
1929        self.with_element_id(Some(id), |cx| {
1930            let global_id = cx.window().element_id_stack.clone();
1931
1932            if let Some(any) = cx
1933                .window_mut()
1934                .current_frame
1935                .element_states
1936                .remove(&global_id)
1937                .or_else(|| {
1938                    cx.window_mut()
1939                        .previous_frame
1940                        .element_states
1941                        .remove(&global_id)
1942                })
1943            {
1944                let ElementStateBox {
1945                    inner,
1946
1947                    #[cfg(debug_assertions)]
1948                    type_name
1949                } = any;
1950                // Using the extra inner option to avoid needing to reallocate a new box.
1951                let mut state_box = inner
1952                    .downcast::<Option<S>>()
1953                    .map_err(|_| {
1954                        #[cfg(debug_assertions)]
1955                        {
1956                            anyhow!(
1957                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
1958                                std::any::type_name::<S>(),
1959                                type_name
1960                            )
1961                        }
1962
1963                        #[cfg(not(debug_assertions))]
1964                        {
1965                            anyhow!(
1966                                "invalid element state type for id, requested_type {:?}",
1967                                std::any::type_name::<S>(),
1968                            )
1969                        }
1970                    })
1971                    .unwrap();
1972
1973                // Actual: Option<AnyElement> <- View
1974                // Requested: () <- AnyElemet
1975                let state = state_box
1976                    .take()
1977                    .expect("element state is already on the stack");
1978                let (result, state) = f(Some(state), cx);
1979                state_box.replace(state);
1980                cx.window_mut()
1981                    .current_frame
1982                    .element_states
1983                    .insert(global_id, ElementStateBox {
1984                        inner: state_box,
1985
1986                        #[cfg(debug_assertions)]
1987                        type_name
1988                    });
1989                result
1990            } else {
1991                let (result, state) = f(None, cx);
1992                cx.window_mut()
1993                    .current_frame
1994                    .element_states
1995                    .insert(global_id,
1996                        ElementStateBox {
1997                            inner: Box::new(Some(state)),
1998
1999                            #[cfg(debug_assertions)]
2000                            type_name: std::any::type_name::<S>()
2001                        }
2002
2003                    );
2004                result
2005            }
2006        })
2007    }
2008
2009    /// Obtain the current content mask.
2010    fn content_mask(&self) -> ContentMask<Pixels> {
2011        self.window()
2012            .current_frame
2013            .content_mask_stack
2014            .last()
2015            .cloned()
2016            .unwrap_or_else(|| ContentMask {
2017                bounds: Bounds {
2018                    origin: Point::default(),
2019                    size: self.window().viewport_size,
2020                },
2021            })
2022    }
2023
2024    /// The size of an em for the base font of the application. Adjusting this value allows the
2025    /// UI to scale, just like zooming a web page.
2026    fn rem_size(&self) -> Pixels {
2027        self.window().rem_size
2028    }
2029}
2030
2031impl Borrow<Window> for WindowContext<'_> {
2032    fn borrow(&self) -> &Window {
2033        &self.window
2034    }
2035}
2036
2037impl BorrowMut<Window> for WindowContext<'_> {
2038    fn borrow_mut(&mut self) -> &mut Window {
2039        &mut self.window
2040    }
2041}
2042
2043impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2044
2045pub struct ViewContext<'a, V> {
2046    window_cx: WindowContext<'a>,
2047    view: &'a View<V>,
2048}
2049
2050impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2051    fn borrow(&self) -> &AppContext {
2052        &*self.window_cx.app
2053    }
2054}
2055
2056impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2057    fn borrow_mut(&mut self) -> &mut AppContext {
2058        &mut *self.window_cx.app
2059    }
2060}
2061
2062impl<V> Borrow<Window> for ViewContext<'_, V> {
2063    fn borrow(&self) -> &Window {
2064        &*self.window_cx.window
2065    }
2066}
2067
2068impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2069    fn borrow_mut(&mut self) -> &mut Window {
2070        &mut *self.window_cx.window
2071    }
2072}
2073
2074impl<'a, V: 'static> ViewContext<'a, V> {
2075    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2076        Self {
2077            window_cx: WindowContext::new(app, window),
2078            view,
2079        }
2080    }
2081
2082    pub fn entity_id(&self) -> EntityId {
2083        self.view.entity_id()
2084    }
2085
2086    pub fn view(&self) -> &View<V> {
2087        self.view
2088    }
2089
2090    pub fn model(&self) -> &Model<V> {
2091        &self.view.model
2092    }
2093
2094    /// Access the underlying window context.
2095    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2096        &mut self.window_cx
2097    }
2098
2099    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
2100        self.window.current_frame.z_index_stack.push(z_index);
2101        let result = f(self);
2102        self.window.current_frame.z_index_stack.pop();
2103        result
2104    }
2105
2106    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2107    where
2108        V: 'static,
2109    {
2110        let view = self.view().clone();
2111        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2112    }
2113
2114    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2115    /// that are currently on the stack to be returned to the app.
2116    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2117        let view = self.view().downgrade();
2118        self.window_cx.defer(move |cx| {
2119            view.update(cx, f).ok();
2120        });
2121    }
2122
2123    pub fn observe<V2, E>(
2124        &mut self,
2125        entity: &E,
2126        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2127    ) -> Subscription
2128    where
2129        V2: 'static,
2130        V: 'static,
2131        E: Entity<V2>,
2132    {
2133        let view = self.view().downgrade();
2134        let entity_id = entity.entity_id();
2135        let entity = entity.downgrade();
2136        let window_handle = self.window.handle;
2137        let (subscription, activate) = self.app.observers.insert(
2138            entity_id,
2139            Box::new(move |cx| {
2140                window_handle
2141                    .update(cx, |_, cx| {
2142                        if let Some(handle) = E::upgrade_from(&entity) {
2143                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2144                                .is_ok()
2145                        } else {
2146                            false
2147                        }
2148                    })
2149                    .unwrap_or(false)
2150            }),
2151        );
2152        self.app.defer(move |_| activate());
2153        subscription
2154    }
2155
2156    pub fn subscribe<V2, E, Evt>(
2157        &mut self,
2158        entity: &E,
2159        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2160    ) -> Subscription
2161    where
2162        V2: EventEmitter<Evt>,
2163        E: Entity<V2>,
2164        Evt: 'static,
2165    {
2166        let view = self.view().downgrade();
2167        let entity_id = entity.entity_id();
2168        let handle = entity.downgrade();
2169        let window_handle = self.window.handle;
2170        let (subscription, activate) = self.app.event_listeners.insert(
2171            entity_id,
2172            (
2173                TypeId::of::<Evt>(),
2174                Box::new(move |event, cx| {
2175                    window_handle
2176                        .update(cx, |_, cx| {
2177                            if let Some(handle) = E::upgrade_from(&handle) {
2178                                let event = event.downcast_ref().expect("invalid event type");
2179                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2180                                    .is_ok()
2181                            } else {
2182                                false
2183                            }
2184                        })
2185                        .unwrap_or(false)
2186                }),
2187            ),
2188        );
2189        self.app.defer(move |_| activate());
2190        subscription
2191    }
2192
2193    pub fn on_release(
2194        &mut self,
2195        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2196    ) -> Subscription {
2197        let window_handle = self.window.handle;
2198        let (subscription, activate) = self.app.release_listeners.insert(
2199            self.view.model.entity_id,
2200            Box::new(move |this, cx| {
2201                let this = this.downcast_mut().expect("invalid entity type");
2202                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2203            }),
2204        );
2205        activate();
2206        subscription
2207    }
2208
2209    pub fn observe_release<V2, E>(
2210        &mut self,
2211        entity: &E,
2212        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2213    ) -> Subscription
2214    where
2215        V: 'static,
2216        V2: 'static,
2217        E: Entity<V2>,
2218    {
2219        let view = self.view().downgrade();
2220        let entity_id = entity.entity_id();
2221        let window_handle = self.window.handle;
2222        let (subscription, activate) = self.app.release_listeners.insert(
2223            entity_id,
2224            Box::new(move |entity, cx| {
2225                let entity = entity.downcast_mut().expect("invalid entity type");
2226                let _ = window_handle.update(cx, |_, cx| {
2227                    view.update(cx, |this, cx| on_release(this, entity, cx))
2228                });
2229            }),
2230        );
2231        activate();
2232        subscription
2233    }
2234
2235    pub fn notify(&mut self) {
2236        self.window_cx.notify();
2237        self.window_cx.app.push_effect(Effect::Notify {
2238            emitter: self.view.model.entity_id,
2239        });
2240    }
2241
2242    pub fn observe_window_bounds(
2243        &mut self,
2244        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2245    ) -> Subscription {
2246        let view = self.view.downgrade();
2247        let (subscription, activate) = self.window.bounds_observers.insert(
2248            (),
2249            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2250        );
2251        activate();
2252        subscription
2253    }
2254
2255    pub fn observe_window_activation(
2256        &mut self,
2257        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2258    ) -> Subscription {
2259        let view = self.view.downgrade();
2260        let (subscription, activate) = self.window.activation_observers.insert(
2261            (),
2262            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2263        );
2264        activate();
2265        subscription
2266    }
2267
2268    /// Register a listener to be called when the given focus handle receives focus.
2269    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2270    /// is dropped.
2271    pub fn on_focus(
2272        &mut self,
2273        handle: &FocusHandle,
2274        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2275    ) -> Subscription {
2276        let view = self.view.downgrade();
2277        let focus_id = handle.id;
2278        let (subscription, activate) = self.window.focus_listeners.insert(
2279            (),
2280            Box::new(move |event, cx| {
2281                view.update(cx, |view, cx| {
2282                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2283                        listener(view, cx)
2284                    }
2285                })
2286                .is_ok()
2287            }),
2288        );
2289        self.app.defer(move |_| activate());
2290        subscription
2291    }
2292
2293    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2294    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2295    /// is dropped.
2296    pub fn on_focus_in(
2297        &mut self,
2298        handle: &FocusHandle,
2299        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2300    ) -> Subscription {
2301        let view = self.view.downgrade();
2302        let focus_id = handle.id;
2303        let (subscription, activate) = self.window.focus_listeners.insert(
2304            (),
2305            Box::new(move |event, cx| {
2306                view.update(cx, |view, cx| {
2307                    if event
2308                        .focused
2309                        .as_ref()
2310                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
2311                    {
2312                        listener(view, cx)
2313                    }
2314                })
2315                .is_ok()
2316            }),
2317        );
2318        self.app.defer(move |_| activate());
2319        subscription
2320    }
2321
2322    /// Register a listener to be called when the given focus handle loses focus.
2323    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2324    /// is dropped.
2325    pub fn on_blur(
2326        &mut self,
2327        handle: &FocusHandle,
2328        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2329    ) -> Subscription {
2330        let view = self.view.downgrade();
2331        let focus_id = handle.id;
2332        let (subscription, activate) = self.window.focus_listeners.insert(
2333            (),
2334            Box::new(move |event, cx| {
2335                view.update(cx, |view, cx| {
2336                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2337                        listener(view, cx)
2338                    }
2339                })
2340                .is_ok()
2341            }),
2342        );
2343        self.app.defer(move |_| activate());
2344        subscription
2345    }
2346
2347    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2348    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2349    /// is dropped.
2350    pub fn on_focus_out(
2351        &mut self,
2352        handle: &FocusHandle,
2353        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2354    ) -> Subscription {
2355        let view = self.view.downgrade();
2356        let focus_id = handle.id;
2357        let (subscription, activate) = self.window.focus_listeners.insert(
2358            (),
2359            Box::new(move |event, cx| {
2360                view.update(cx, |view, cx| {
2361                    if event
2362                        .blurred
2363                        .as_ref()
2364                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2365                    {
2366                        listener(view, cx)
2367                    }
2368                })
2369                .is_ok()
2370            }),
2371        );
2372        self.app.defer(move |_| activate());
2373        subscription
2374    }
2375
2376    pub fn spawn<Fut, R>(
2377        &mut self,
2378        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2379    ) -> Task<R>
2380    where
2381        R: 'static,
2382        Fut: Future<Output = R> + 'static,
2383    {
2384        let view = self.view().downgrade();
2385        self.window_cx.spawn(|cx| f(view, cx))
2386    }
2387
2388    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2389    where
2390        G: 'static,
2391    {
2392        let mut global = self.app.lease_global::<G>();
2393        let result = f(&mut global, self);
2394        self.app.end_global_lease(global);
2395        result
2396    }
2397
2398    pub fn observe_global<G: 'static>(
2399        &mut self,
2400        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2401    ) -> Subscription {
2402        let window_handle = self.window.handle;
2403        let view = self.view().downgrade();
2404        let (subscription, activate) = self.global_observers.insert(
2405            TypeId::of::<G>(),
2406            Box::new(move |cx| {
2407                window_handle
2408                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2409                    .unwrap_or(false)
2410            }),
2411        );
2412        self.app.defer(move |_| activate());
2413        subscription
2414    }
2415
2416    pub fn on_mouse_event<Event: 'static>(
2417        &mut self,
2418        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2419    ) {
2420        let handle = self.view().clone();
2421        self.window_cx.on_mouse_event(move |event, phase, cx| {
2422            handle.update(cx, |view, cx| {
2423                handler(view, event, phase, cx);
2424            })
2425        });
2426    }
2427
2428    pub fn on_key_event<Event: 'static>(
2429        &mut self,
2430        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2431    ) {
2432        let handle = self.view().clone();
2433        self.window_cx.on_key_event(move |event, phase, cx| {
2434            handle.update(cx, |view, cx| {
2435                handler(view, event, phase, cx);
2436            })
2437        });
2438    }
2439
2440    pub fn on_action(
2441        &mut self,
2442        action_type: TypeId,
2443        handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2444    ) {
2445        let handle = self.view().clone();
2446        self.window_cx
2447            .on_action(action_type, move |action, phase, cx| {
2448                handle.update(cx, |view, cx| {
2449                    handler(view, action, phase, cx);
2450                })
2451            });
2452    }
2453
2454    pub fn emit<Evt>(&mut self, event: Evt)
2455    where
2456        Evt: 'static,
2457        V: EventEmitter<Evt>,
2458    {
2459        let emitter = self.view.model.entity_id;
2460        self.app.push_effect(Effect::Emit {
2461            emitter,
2462            event_type: TypeId::of::<Evt>(),
2463            event: Box::new(event),
2464        });
2465    }
2466
2467    pub fn focus_self(&mut self)
2468    where
2469        V: FocusableView,
2470    {
2471        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2472    }
2473
2474    pub fn dismiss_self(&mut self)
2475    where
2476        V: ManagedView,
2477    {
2478        self.defer(|_, cx| cx.emit(DismissEvent))
2479    }
2480
2481    pub fn listener<E>(
2482        &self,
2483        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2484    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2485        let view = self.view().downgrade();
2486        move |e: &E, cx: &mut WindowContext| {
2487            view.update(cx, |view, cx| f(view, e, cx)).ok();
2488        }
2489    }
2490}
2491
2492impl<V> Context for ViewContext<'_, V> {
2493    type Result<U> = U;
2494
2495    fn build_model<T: 'static>(
2496        &mut self,
2497        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2498    ) -> Model<T> {
2499        self.window_cx.build_model(build_model)
2500    }
2501
2502    fn update_model<T: 'static, R>(
2503        &mut self,
2504        model: &Model<T>,
2505        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2506    ) -> R {
2507        self.window_cx.update_model(model, update)
2508    }
2509
2510    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2511    where
2512        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2513    {
2514        self.window_cx.update_window(window, update)
2515    }
2516
2517    fn read_model<T, R>(
2518        &self,
2519        handle: &Model<T>,
2520        read: impl FnOnce(&T, &AppContext) -> R,
2521    ) -> Self::Result<R>
2522    where
2523        T: 'static,
2524    {
2525        self.window_cx.read_model(handle, read)
2526    }
2527
2528    fn read_window<T, R>(
2529        &self,
2530        window: &WindowHandle<T>,
2531        read: impl FnOnce(View<T>, &AppContext) -> R,
2532    ) -> Result<R>
2533    where
2534        T: 'static,
2535    {
2536        self.window_cx.read_window(window, read)
2537    }
2538}
2539
2540impl<V: 'static> VisualContext for ViewContext<'_, V> {
2541    fn build_view<W: Render + 'static>(
2542        &mut self,
2543        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2544    ) -> Self::Result<View<W>> {
2545        self.window_cx.build_view(build_view_state)
2546    }
2547
2548    fn update_view<V2: 'static, R>(
2549        &mut self,
2550        view: &View<V2>,
2551        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2552    ) -> Self::Result<R> {
2553        self.window_cx.update_view(view, update)
2554    }
2555
2556    fn replace_root_view<W>(
2557        &mut self,
2558        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2559    ) -> Self::Result<View<W>>
2560    where
2561        W: 'static + Render,
2562    {
2563        self.window_cx.replace_root_view(build_view)
2564    }
2565
2566    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2567        self.window_cx.focus_view(view)
2568    }
2569
2570    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2571        self.window_cx.dismiss_view(view)
2572    }
2573}
2574
2575impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2576    type Target = WindowContext<'a>;
2577
2578    fn deref(&self) -> &Self::Target {
2579        &self.window_cx
2580    }
2581}
2582
2583impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2584    fn deref_mut(&mut self) -> &mut Self::Target {
2585        &mut self.window_cx
2586    }
2587}
2588
2589// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2590slotmap::new_key_type! { pub struct WindowId; }
2591
2592impl WindowId {
2593    pub fn as_u64(&self) -> u64 {
2594        self.0.as_ffi()
2595    }
2596}
2597
2598#[derive(Deref, DerefMut)]
2599pub struct WindowHandle<V> {
2600    #[deref]
2601    #[deref_mut]
2602    pub(crate) any_handle: AnyWindowHandle,
2603    state_type: PhantomData<V>,
2604}
2605
2606impl<V: 'static + Render> WindowHandle<V> {
2607    pub fn new(id: WindowId) -> Self {
2608        WindowHandle {
2609            any_handle: AnyWindowHandle {
2610                id,
2611                state_type: TypeId::of::<V>(),
2612            },
2613            state_type: PhantomData,
2614        }
2615    }
2616
2617    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2618    where
2619        C: Context,
2620    {
2621        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2622            root_view
2623                .downcast::<V>()
2624                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2625        }))
2626    }
2627
2628    pub fn update<C, R>(
2629        &self,
2630        cx: &mut C,
2631        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2632    ) -> Result<R>
2633    where
2634        C: Context,
2635    {
2636        cx.update_window(self.any_handle, |root_view, cx| {
2637            let view = root_view
2638                .downcast::<V>()
2639                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2640            Ok(cx.update_view(&view, update))
2641        })?
2642    }
2643
2644    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2645        let x = cx
2646            .windows
2647            .get(self.id)
2648            .and_then(|window| {
2649                window
2650                    .as_ref()
2651                    .and_then(|window| window.root_view.clone())
2652                    .map(|root_view| root_view.downcast::<V>())
2653            })
2654            .ok_or_else(|| anyhow!("window not found"))?
2655            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2656
2657        Ok(x.read(cx))
2658    }
2659
2660    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2661    where
2662        C: Context,
2663    {
2664        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2665    }
2666
2667    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2668    where
2669        C: Context,
2670    {
2671        cx.read_window(self, |root_view, _cx| root_view.clone())
2672    }
2673
2674    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2675        cx.windows
2676            .get(self.id)
2677            .and_then(|window| window.as_ref().map(|window| window.active))
2678    }
2679}
2680
2681impl<V> Copy for WindowHandle<V> {}
2682
2683impl<V> Clone for WindowHandle<V> {
2684    fn clone(&self) -> Self {
2685        WindowHandle {
2686            any_handle: self.any_handle,
2687            state_type: PhantomData,
2688        }
2689    }
2690}
2691
2692impl<V> PartialEq for WindowHandle<V> {
2693    fn eq(&self, other: &Self) -> bool {
2694        self.any_handle == other.any_handle
2695    }
2696}
2697
2698impl<V> Eq for WindowHandle<V> {}
2699
2700impl<V> Hash for WindowHandle<V> {
2701    fn hash<H: Hasher>(&self, state: &mut H) {
2702        self.any_handle.hash(state);
2703    }
2704}
2705
2706impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2707    fn into(self) -> AnyWindowHandle {
2708        self.any_handle
2709    }
2710}
2711
2712#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2713pub struct AnyWindowHandle {
2714    pub(crate) id: WindowId,
2715    state_type: TypeId,
2716}
2717
2718impl AnyWindowHandle {
2719    pub fn window_id(&self) -> WindowId {
2720        self.id
2721    }
2722
2723    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2724        if TypeId::of::<T>() == self.state_type {
2725            Some(WindowHandle {
2726                any_handle: *self,
2727                state_type: PhantomData,
2728            })
2729        } else {
2730            None
2731        }
2732    }
2733
2734    pub fn update<C, R>(
2735        self,
2736        cx: &mut C,
2737        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2738    ) -> Result<R>
2739    where
2740        C: Context,
2741    {
2742        cx.update_window(self, update)
2743    }
2744
2745    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2746    where
2747        C: Context,
2748        T: 'static,
2749    {
2750        let view = self
2751            .downcast::<T>()
2752            .context("the type of the window's root view has changed")?;
2753
2754        cx.read_window(&view, read)
2755    }
2756}
2757
2758#[cfg(any(test, feature = "test-support"))]
2759impl From<SmallVec<[u32; 16]>> for StackingOrder {
2760    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2761        StackingOrder(small_vec)
2762    }
2763}
2764
2765#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2766pub enum ElementId {
2767    View(EntityId),
2768    Integer(usize),
2769    Name(SharedString),
2770    FocusHandle(FocusId),
2771    NamedInteger(SharedString, usize),
2772}
2773
2774impl ElementId {
2775    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2776        ElementId::View(entity_id)
2777    }
2778}
2779
2780impl TryInto<SharedString> for ElementId {
2781    type Error = anyhow::Error;
2782
2783    fn try_into(self) -> anyhow::Result<SharedString> {
2784        if let ElementId::Name(name) = self {
2785            Ok(name)
2786        } else {
2787            Err(anyhow!("element id is not string"))
2788        }
2789    }
2790}
2791
2792impl From<usize> for ElementId {
2793    fn from(id: usize) -> Self {
2794        ElementId::Integer(id)
2795    }
2796}
2797
2798impl From<i32> for ElementId {
2799    fn from(id: i32) -> Self {
2800        Self::Integer(id as usize)
2801    }
2802}
2803
2804impl From<SharedString> for ElementId {
2805    fn from(name: SharedString) -> Self {
2806        ElementId::Name(name)
2807    }
2808}
2809
2810impl From<&'static str> for ElementId {
2811    fn from(name: &'static str) -> Self {
2812        ElementId::Name(name.into())
2813    }
2814}
2815
2816impl<'a> From<&'a FocusHandle> for ElementId {
2817    fn from(handle: &'a FocusHandle) -> Self {
2818        ElementId::FocusHandle(handle.id)
2819    }
2820}
2821
2822impl From<(&'static str, EntityId)> for ElementId {
2823    fn from((name, id): (&'static str, EntityId)) -> Self {
2824        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2825    }
2826}
2827
2828impl From<(&'static str, usize)> for ElementId {
2829    fn from((name, id): (&'static str, usize)) -> Self {
2830        ElementId::NamedInteger(name.into(), id)
2831    }
2832}