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