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