window.rs

   1use crate::{
   2    key_dispatch::DispatchActionListener, px, size, Action, AnyDrag, AnyView, AppContext,
   3    AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle,
   4    DevicePixels, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId,
   5    EventEmitter, FileDropEvent, Flatten, FocusEvent, FontId, GlobalElementId, GlyphId, Hsla,
   6    ImageData, InputEvent, IsZero, KeyBinding, KeyContext, KeyDownEvent, LayoutId, Model,
   7    ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent,
   8    MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler,
   9    PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams,
  10    RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size,
  11    Style, SubscriberSet, Subscription, Surface, TaffyLayoutEngine, Task, Underline,
  12    UnderlineStyle, View, VisualContext, WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
  13};
  14use anyhow::{anyhow, Context as _, Result};
  15use collections::HashMap;
  16use derive_more::{Deref, DerefMut};
  17use futures::{
  18    channel::{mpsc, oneshot},
  19    StreamExt,
  20};
  21use media::core_video::CVImageBuffer;
  22use parking_lot::RwLock;
  23use slotmap::SlotMap;
  24use smallvec::SmallVec;
  25use std::{
  26    any::{Any, TypeId},
  27    borrow::{Borrow, BorrowMut, Cow},
  28    fmt::Debug,
  29    future::Future,
  30    hash::{Hash, Hasher},
  31    marker::PhantomData,
  32    mem,
  33    rc::Rc,
  34    sync::{
  35        atomic::{AtomicUsize, Ordering::SeqCst},
  36        Arc,
  37    },
  38};
  39use util::ResultExt;
  40
  41/// A global stacking order, which is created by stacking successive z-index values.
  42/// Each z-index will always be interpreted in the context of its parent z-index.
  43#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default, Debug)]
  44pub struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
  45
  46/// Represents the two different phases when dispatching events.
  47#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  48pub enum DispatchPhase {
  49    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  50    /// invoked front to back and keyboard event listeners are invoked from the focused element
  51    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  52    /// registering event listeners.
  53    #[default]
  54    Bubble,
  55    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  56    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  57    /// is used for special purposes such as clearing the "pressed" state for click events. If
  58    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  59    /// outside of the immediate region may rely on detecting non-local events during this phase.
  60    Capture,
  61}
  62
  63type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  64type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
  65type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
  66type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
  67
  68slotmap::new_key_type! { pub struct FocusId; }
  69
  70impl FocusId {
  71    /// Obtains whether the element associated with this handle is currently focused.
  72    pub fn is_focused(&self, cx: &WindowContext) -> bool {
  73        cx.window.focus == Some(*self)
  74    }
  75
  76    /// Obtains whether the element associated with this handle contains the focused
  77    /// element or is itself focused.
  78    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
  79        cx.focused()
  80            .map_or(false, |focused| self.contains(focused.id, cx))
  81    }
  82
  83    /// Obtains whether the element associated with this handle is contained within the
  84    /// focused element or is itself focused.
  85    pub fn within_focused(&self, cx: &WindowContext) -> bool {
  86        let focused = cx.focused();
  87        focused.map_or(false, |focused| focused.id.contains(*self, cx))
  88    }
  89
  90    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
  91    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
  92        cx.window
  93            .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::MouseDown(MouseDownEvent {
1273                        position,
1274                        button: MouseButton::Left,
1275                        click_count: 1,
1276                        modifiers: Modifiers::default(),
1277                    })
1278                }
1279                FileDropEvent::Pending { position } => {
1280                    self.window.mouse_position = position;
1281                    InputEvent::MouseMove(MouseMoveEvent {
1282                        position,
1283                        pressed_button: Some(MouseButton::Left),
1284                        modifiers: Modifiers::default(),
1285                    })
1286                }
1287                FileDropEvent::Submit { position } => {
1288                    self.window.mouse_position = position;
1289                    InputEvent::MouseUp(MouseUpEvent {
1290                        button: MouseButton::Left,
1291                        position,
1292                        modifiers: Modifiers::default(),
1293                        click_count: 1,
1294                    })
1295                }
1296                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1297                    button: MouseButton::Left,
1298                    position: Point::default(),
1299                    modifiers: Modifiers::default(),
1300                    click_count: 1,
1301                }),
1302            },
1303            _ => event,
1304        };
1305
1306        if let Some(any_mouse_event) = event.mouse_event() {
1307            self.dispatch_mouse_event(any_mouse_event);
1308        } else if let Some(any_key_event) = event.keyboard_event() {
1309            self.dispatch_key_event(any_key_event);
1310        }
1311
1312        !self.app.propagate_event
1313    }
1314
1315    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1316        if let Some(mut handlers) = self
1317            .window
1318            .rendered_frame
1319            .mouse_listeners
1320            .remove(&event.type_id())
1321        {
1322            // Because handlers may add other handlers, we sort every time.
1323            handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1324
1325            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1326            // special purposes, such as detecting events outside of a given Bounds.
1327            for (_, handler) in &mut handlers {
1328                handler(event, DispatchPhase::Capture, self);
1329                if !self.app.propagate_event {
1330                    break;
1331                }
1332            }
1333
1334            // Bubble phase, where most normal handlers do their work.
1335            if self.app.propagate_event {
1336                for (_, handler) in handlers.iter_mut().rev() {
1337                    handler(event, DispatchPhase::Bubble, self);
1338                    if !self.app.propagate_event {
1339                        break;
1340                    }
1341                }
1342            }
1343
1344            if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1345                self.active_drag = None;
1346            }
1347
1348            self.window
1349                .rendered_frame
1350                .mouse_listeners
1351                .insert(event.type_id(), handlers);
1352        }
1353    }
1354
1355    fn dispatch_key_event(&mut self, event: &dyn Any) {
1356        let node_id = self
1357            .window
1358            .focus
1359            .and_then(|focus_id| {
1360                self.window
1361                    .rendered_frame
1362                    .dispatch_tree
1363                    .focusable_node_id(focus_id)
1364            })
1365            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1366
1367        let dispatch_path = self
1368            .window
1369            .rendered_frame
1370            .dispatch_tree
1371            .dispatch_path(node_id);
1372
1373        let mut actions: Vec<Box<dyn Action>> = Vec::new();
1374
1375        // Capture phase
1376        let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1377        self.propagate_event = true;
1378
1379        for node_id in &dispatch_path {
1380            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1381
1382            if let Some(context) = node.context.clone() {
1383                context_stack.push(context);
1384            }
1385
1386            for key_listener in node.key_listeners.clone() {
1387                key_listener(event, DispatchPhase::Capture, self);
1388                if !self.propagate_event {
1389                    return;
1390                }
1391            }
1392        }
1393
1394        // Bubble phase
1395        for node_id in dispatch_path.iter().rev() {
1396            // Handle low level key events
1397            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1398            for key_listener in node.key_listeners.clone() {
1399                key_listener(event, DispatchPhase::Bubble, self);
1400                if !self.propagate_event {
1401                    return;
1402                }
1403            }
1404
1405            // Match keystrokes
1406            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1407            if node.context.is_some() {
1408                if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1409                    if let Some(found) = self
1410                        .window
1411                        .rendered_frame
1412                        .dispatch_tree
1413                        .dispatch_key(&key_down_event.keystroke, &context_stack)
1414                    {
1415                        actions.push(found.boxed_clone())
1416                    }
1417                }
1418
1419                context_stack.pop();
1420            }
1421        }
1422
1423        for action in actions {
1424            self.dispatch_action_on_node(node_id, action);
1425            if !self.propagate_event {
1426                return;
1427            }
1428        }
1429    }
1430
1431    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1432        let dispatch_path = self
1433            .window
1434            .rendered_frame
1435            .dispatch_tree
1436            .dispatch_path(node_id);
1437
1438        // Capture phase
1439        for node_id in &dispatch_path {
1440            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1441            for DispatchActionListener {
1442                action_type,
1443                listener,
1444            } in node.action_listeners.clone()
1445            {
1446                let any_action = action.as_any();
1447                if action_type == any_action.type_id() {
1448                    listener(any_action, DispatchPhase::Capture, self);
1449                    if !self.propagate_event {
1450                        return;
1451                    }
1452                }
1453            }
1454        }
1455        // Bubble phase
1456        for node_id in dispatch_path.iter().rev() {
1457            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1458            for DispatchActionListener {
1459                action_type,
1460                listener,
1461            } in node.action_listeners.clone()
1462            {
1463                let any_action = action.as_any();
1464                if action_type == any_action.type_id() {
1465                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1466                    listener(any_action, DispatchPhase::Bubble, self);
1467                    if !self.propagate_event {
1468                        return;
1469                    }
1470                }
1471            }
1472        }
1473    }
1474
1475    /// Register the given handler to be invoked whenever the global of the given type
1476    /// is updated.
1477    pub fn observe_global<G: 'static>(
1478        &mut self,
1479        f: impl Fn(&mut WindowContext<'_>) + 'static,
1480    ) -> Subscription {
1481        let window_handle = self.window.handle;
1482        let (subscription, activate) = self.global_observers.insert(
1483            TypeId::of::<G>(),
1484            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1485        );
1486        self.app.defer(move |_| activate());
1487        subscription
1488    }
1489
1490    pub fn activate_window(&self) {
1491        self.window.platform_window.activate();
1492    }
1493
1494    pub fn minimize_window(&self) {
1495        self.window.platform_window.minimize();
1496    }
1497
1498    pub fn toggle_full_screen(&self) {
1499        self.window.platform_window.toggle_full_screen();
1500    }
1501
1502    pub fn prompt(
1503        &self,
1504        level: PromptLevel,
1505        msg: &str,
1506        answers: &[&str],
1507    ) -> oneshot::Receiver<usize> {
1508        self.window.platform_window.prompt(level, msg, answers)
1509    }
1510
1511    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1512        let node_id = self
1513            .window
1514            .focus
1515            .and_then(|focus_id| {
1516                self.window
1517                    .rendered_frame
1518                    .dispatch_tree
1519                    .focusable_node_id(focus_id)
1520            })
1521            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1522
1523        self.window
1524            .rendered_frame
1525            .dispatch_tree
1526            .available_actions(node_id)
1527    }
1528
1529    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1530        self.window
1531            .rendered_frame
1532            .dispatch_tree
1533            .bindings_for_action(
1534                action,
1535                &self.window.rendered_frame.dispatch_tree.context_stack,
1536            )
1537    }
1538
1539    pub fn bindings_for_action_in(
1540        &self,
1541        action: &dyn Action,
1542        focus_handle: &FocusHandle,
1543    ) -> Vec<KeyBinding> {
1544        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1545
1546        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1547            return vec![];
1548        };
1549        let context_stack = dispatch_tree
1550            .dispatch_path(node_id)
1551            .into_iter()
1552            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1553            .collect();
1554        dispatch_tree.bindings_for_action(action, &context_stack)
1555    }
1556
1557    pub fn listener_for<V: Render, E>(
1558        &self,
1559        view: &View<V>,
1560        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1561    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1562        let view = view.downgrade();
1563        move |e: &E, cx: &mut WindowContext| {
1564            view.update(cx, |view, cx| f(view, e, cx)).ok();
1565        }
1566    }
1567
1568    pub fn handler_for<V: Render>(
1569        &self,
1570        view: &View<V>,
1571        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1572    ) -> impl Fn(&mut WindowContext) {
1573        let view = view.downgrade();
1574        move |cx: &mut WindowContext| {
1575            view.update(cx, |view, cx| f(view, cx)).ok();
1576        }
1577    }
1578
1579    //========== ELEMENT RELATED FUNCTIONS ===========
1580    pub fn with_key_dispatch<R>(
1581        &mut self,
1582        context: Option<KeyContext>,
1583        focus_handle: Option<FocusHandle>,
1584        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1585    ) -> R {
1586        let window = &mut self.window;
1587        window.next_frame.dispatch_tree.push_node(context.clone());
1588        if let Some(focus_handle) = focus_handle.as_ref() {
1589            window
1590                .next_frame
1591                .dispatch_tree
1592                .make_focusable(focus_handle.id);
1593        }
1594        let result = f(focus_handle, self);
1595
1596        self.window.next_frame.dispatch_tree.pop_node();
1597
1598        result
1599    }
1600
1601    /// Register a focus listener for the next frame only. It will be cleared
1602    /// on the next frame render. You should use this method only from within elements,
1603    /// and we may want to enforce that better via a different context type.
1604    // todo!() Move this to `FrameContext` to emphasize its individuality?
1605    pub fn on_focus_changed(
1606        &mut self,
1607        listener: impl Fn(&FocusEvent, &mut WindowContext) + 'static,
1608    ) {
1609        self.window
1610            .next_frame
1611            .focus_listeners
1612            .push(Box::new(move |event, cx| {
1613                listener(event, cx);
1614            }));
1615    }
1616
1617    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1618    /// platform to receive textual input with proper integration with concerns such
1619    /// as IME interactions.
1620    pub fn handle_input(
1621        &mut self,
1622        focus_handle: &FocusHandle,
1623        input_handler: impl PlatformInputHandler,
1624    ) {
1625        if focus_handle.is_focused(self) {
1626            self.window
1627                .platform_window
1628                .set_input_handler(Box::new(input_handler));
1629        }
1630    }
1631
1632    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1633        let mut this = self.to_async();
1634        self.window
1635            .platform_window
1636            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1637    }
1638}
1639
1640impl Context for WindowContext<'_> {
1641    type Result<T> = T;
1642
1643    fn build_model<T>(
1644        &mut self,
1645        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1646    ) -> Model<T>
1647    where
1648        T: 'static,
1649    {
1650        let slot = self.app.entities.reserve();
1651        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1652        self.entities.insert(slot, model)
1653    }
1654
1655    fn update_model<T: 'static, R>(
1656        &mut self,
1657        model: &Model<T>,
1658        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1659    ) -> R {
1660        let mut entity = self.entities.lease(model);
1661        let result = update(
1662            &mut *entity,
1663            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1664        );
1665        self.entities.end_lease(entity);
1666        result
1667    }
1668
1669    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1670    where
1671        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1672    {
1673        if window == self.window.handle {
1674            let root_view = self.window.root_view.clone().unwrap();
1675            Ok(update(root_view, self))
1676        } else {
1677            window.update(self.app, update)
1678        }
1679    }
1680
1681    fn read_model<T, R>(
1682        &self,
1683        handle: &Model<T>,
1684        read: impl FnOnce(&T, &AppContext) -> R,
1685    ) -> Self::Result<R>
1686    where
1687        T: 'static,
1688    {
1689        let entity = self.entities.read(handle);
1690        read(&*entity, &*self.app)
1691    }
1692
1693    fn read_window<T, R>(
1694        &self,
1695        window: &WindowHandle<T>,
1696        read: impl FnOnce(View<T>, &AppContext) -> R,
1697    ) -> Result<R>
1698    where
1699        T: 'static,
1700    {
1701        if window.any_handle == self.window.handle {
1702            let root_view = self
1703                .window
1704                .root_view
1705                .clone()
1706                .unwrap()
1707                .downcast::<T>()
1708                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1709            Ok(read(root_view, self))
1710        } else {
1711            self.app.read_window(window, read)
1712        }
1713    }
1714}
1715
1716impl VisualContext for WindowContext<'_> {
1717    fn build_view<V>(
1718        &mut self,
1719        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1720    ) -> Self::Result<View<V>>
1721    where
1722        V: 'static + Render,
1723    {
1724        let slot = self.app.entities.reserve();
1725        let view = View {
1726            model: slot.clone(),
1727        };
1728        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1729        let entity = build_view_state(&mut cx);
1730        cx.entities.insert(slot, entity);
1731
1732        cx.new_view_observers
1733            .clone()
1734            .retain(&TypeId::of::<V>(), |observer| {
1735                let any_view = AnyView::from(view.clone());
1736                (observer)(any_view, self);
1737                true
1738            });
1739
1740        view
1741    }
1742
1743    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1744    fn update_view<T: 'static, R>(
1745        &mut self,
1746        view: &View<T>,
1747        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1748    ) -> Self::Result<R> {
1749        let mut lease = self.app.entities.lease(&view.model);
1750        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1751        let result = update(&mut *lease, &mut cx);
1752        cx.app.entities.end_lease(lease);
1753        result
1754    }
1755
1756    fn replace_root_view<V>(
1757        &mut self,
1758        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1759    ) -> Self::Result<View<V>>
1760    where
1761        V: 'static + Render,
1762    {
1763        let slot = self.app.entities.reserve();
1764        let view = View {
1765            model: slot.clone(),
1766        };
1767        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1768        let entity = build_view(&mut cx);
1769        self.entities.insert(slot, entity);
1770        self.window.root_view = Some(view.clone().into());
1771        view
1772    }
1773
1774    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1775        self.update_view(view, |view, cx| {
1776            view.focus_handle(cx).clone().focus(cx);
1777        })
1778    }
1779
1780    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1781    where
1782        V: ManagedView,
1783    {
1784        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1785    }
1786}
1787
1788impl<'a> std::ops::Deref for WindowContext<'a> {
1789    type Target = AppContext;
1790
1791    fn deref(&self) -> &Self::Target {
1792        &self.app
1793    }
1794}
1795
1796impl<'a> std::ops::DerefMut for WindowContext<'a> {
1797    fn deref_mut(&mut self) -> &mut Self::Target {
1798        &mut self.app
1799    }
1800}
1801
1802impl<'a> Borrow<AppContext> for WindowContext<'a> {
1803    fn borrow(&self) -> &AppContext {
1804        &self.app
1805    }
1806}
1807
1808impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1809    fn borrow_mut(&mut self) -> &mut AppContext {
1810        &mut self.app
1811    }
1812}
1813
1814pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1815    fn app_mut(&mut self) -> &mut AppContext {
1816        self.borrow_mut()
1817    }
1818
1819    fn app(&self) -> &AppContext {
1820        self.borrow()
1821    }
1822
1823    fn window(&self) -> &Window {
1824        self.borrow()
1825    }
1826
1827    fn window_mut(&mut self) -> &mut Window {
1828        self.borrow_mut()
1829    }
1830
1831    /// Pushes the given element id onto the global stack and invokes the given closure
1832    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1833    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1834    /// used to associate state with identified elements across separate frames.
1835    fn with_element_id<R>(
1836        &mut self,
1837        id: Option<impl Into<ElementId>>,
1838        f: impl FnOnce(&mut Self) -> R,
1839    ) -> R {
1840        if let Some(id) = id.map(Into::into) {
1841            let window = self.window_mut();
1842            window.element_id_stack.push(id.into());
1843            let result = f(self);
1844            let window: &mut Window = self.borrow_mut();
1845            window.element_id_stack.pop();
1846            result
1847        } else {
1848            f(self)
1849        }
1850    }
1851
1852    /// Invoke the given function with the given content mask after intersecting it
1853    /// with the current mask.
1854    fn with_content_mask<R>(
1855        &mut self,
1856        mask: Option<ContentMask<Pixels>>,
1857        f: impl FnOnce(&mut Self) -> R,
1858    ) -> R {
1859        if let Some(mask) = mask {
1860            let mask = mask.intersect(&self.content_mask());
1861            self.window_mut().next_frame.content_mask_stack.push(mask);
1862            let result = f(self);
1863            self.window_mut().next_frame.content_mask_stack.pop();
1864            result
1865        } else {
1866            f(self)
1867        }
1868    }
1869
1870    /// Invoke the given function with the content mask reset to that
1871    /// of the window.
1872    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1873        let mask = ContentMask {
1874            bounds: Bounds {
1875                origin: Point::default(),
1876                size: self.window().viewport_size,
1877            },
1878        };
1879        self.window_mut().next_frame.content_mask_stack.push(mask);
1880        let result = f(self);
1881        self.window_mut().next_frame.content_mask_stack.pop();
1882        result
1883    }
1884
1885    /// Update the global element offset relative to the current offset. This is used to implement
1886    /// scrolling.
1887    fn with_element_offset<R>(
1888        &mut self,
1889        offset: Point<Pixels>,
1890        f: impl FnOnce(&mut Self) -> R,
1891    ) -> R {
1892        if offset.is_zero() {
1893            return f(self);
1894        };
1895
1896        let abs_offset = self.element_offset() + offset;
1897        self.with_absolute_element_offset(abs_offset, f)
1898    }
1899
1900    /// Update the global element offset based on the given offset. This is used to implement
1901    /// drag handles and other manual painting of elements.
1902    fn with_absolute_element_offset<R>(
1903        &mut self,
1904        offset: Point<Pixels>,
1905        f: impl FnOnce(&mut Self) -> R,
1906    ) -> R {
1907        self.window_mut()
1908            .next_frame
1909            .element_offset_stack
1910            .push(offset);
1911        let result = f(self);
1912        self.window_mut().next_frame.element_offset_stack.pop();
1913        result
1914    }
1915
1916    /// Obtain the current element offset.
1917    fn element_offset(&self) -> Point<Pixels> {
1918        self.window()
1919            .next_frame
1920            .element_offset_stack
1921            .last()
1922            .copied()
1923            .unwrap_or_default()
1924    }
1925
1926    /// Update or initialize state for an element with the given id that lives across multiple
1927    /// frames. If an element with this id existed in the rendered frame, its state will be passed
1928    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1929    /// when drawing the next frame.
1930    fn with_element_state<S, R>(
1931        &mut self,
1932        id: ElementId,
1933        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1934    ) -> R
1935    where
1936        S: 'static,
1937    {
1938        self.with_element_id(Some(id), |cx| {
1939            let global_id = cx.window().element_id_stack.clone();
1940
1941            if let Some(any) = cx
1942                .window_mut()
1943                .next_frame
1944                .element_states
1945                .remove(&global_id)
1946                .or_else(|| {
1947                    cx.window_mut()
1948                        .rendered_frame
1949                        .element_states
1950                        .remove(&global_id)
1951                })
1952            {
1953                let ElementStateBox {
1954                    inner,
1955
1956                    #[cfg(debug_assertions)]
1957                    type_name
1958                } = any;
1959                // Using the extra inner option to avoid needing to reallocate a new box.
1960                let mut state_box = inner
1961                    .downcast::<Option<S>>()
1962                    .map_err(|_| {
1963                        #[cfg(debug_assertions)]
1964                        {
1965                            anyhow!(
1966                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
1967                                std::any::type_name::<S>(),
1968                                type_name
1969                            )
1970                        }
1971
1972                        #[cfg(not(debug_assertions))]
1973                        {
1974                            anyhow!(
1975                                "invalid element state type for id, requested_type {:?}",
1976                                std::any::type_name::<S>(),
1977                            )
1978                        }
1979                    })
1980                    .unwrap();
1981
1982                // Actual: Option<AnyElement> <- View
1983                // Requested: () <- AnyElemet
1984                let state = state_box
1985                    .take()
1986                    .expect("element state is already on the stack");
1987                let (result, state) = f(Some(state), cx);
1988                state_box.replace(state);
1989                cx.window_mut()
1990                    .next_frame
1991                    .element_states
1992                    .insert(global_id, ElementStateBox {
1993                        inner: state_box,
1994
1995                        #[cfg(debug_assertions)]
1996                        type_name
1997                    });
1998                result
1999            } else {
2000                let (result, state) = f(None, cx);
2001                cx.window_mut()
2002                    .next_frame
2003                    .element_states
2004                    .insert(global_id,
2005                        ElementStateBox {
2006                            inner: Box::new(Some(state)),
2007
2008                            #[cfg(debug_assertions)]
2009                            type_name: std::any::type_name::<S>()
2010                        }
2011
2012                    );
2013                result
2014            }
2015        })
2016    }
2017
2018    /// Obtain the current content mask.
2019    fn content_mask(&self) -> ContentMask<Pixels> {
2020        self.window()
2021            .next_frame
2022            .content_mask_stack
2023            .last()
2024            .cloned()
2025            .unwrap_or_else(|| ContentMask {
2026                bounds: Bounds {
2027                    origin: Point::default(),
2028                    size: self.window().viewport_size,
2029                },
2030            })
2031    }
2032
2033    /// The size of an em for the base font of the application. Adjusting this value allows the
2034    /// UI to scale, just like zooming a web page.
2035    fn rem_size(&self) -> Pixels {
2036        self.window().rem_size
2037    }
2038}
2039
2040impl Borrow<Window> for WindowContext<'_> {
2041    fn borrow(&self) -> &Window {
2042        &self.window
2043    }
2044}
2045
2046impl BorrowMut<Window> for WindowContext<'_> {
2047    fn borrow_mut(&mut self) -> &mut Window {
2048        &mut self.window
2049    }
2050}
2051
2052impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2053
2054pub struct ViewContext<'a, V> {
2055    window_cx: WindowContext<'a>,
2056    view: &'a View<V>,
2057}
2058
2059impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2060    fn borrow(&self) -> &AppContext {
2061        &*self.window_cx.app
2062    }
2063}
2064
2065impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2066    fn borrow_mut(&mut self) -> &mut AppContext {
2067        &mut *self.window_cx.app
2068    }
2069}
2070
2071impl<V> Borrow<Window> for ViewContext<'_, V> {
2072    fn borrow(&self) -> &Window {
2073        &*self.window_cx.window
2074    }
2075}
2076
2077impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2078    fn borrow_mut(&mut self) -> &mut Window {
2079        &mut *self.window_cx.window
2080    }
2081}
2082
2083impl<'a, V: 'static> ViewContext<'a, V> {
2084    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2085        Self {
2086            window_cx: WindowContext::new(app, window),
2087            view,
2088        }
2089    }
2090
2091    pub fn entity_id(&self) -> EntityId {
2092        self.view.entity_id()
2093    }
2094
2095    pub fn view(&self) -> &View<V> {
2096        self.view
2097    }
2098
2099    pub fn model(&self) -> &Model<V> {
2100        &self.view.model
2101    }
2102
2103    /// Access the underlying window context.
2104    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2105        &mut self.window_cx
2106    }
2107
2108    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
2109        self.window.next_frame.z_index_stack.push(z_index);
2110        let result = f(self);
2111        self.window.next_frame.z_index_stack.pop();
2112        result
2113    }
2114
2115    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2116    where
2117        V: 'static,
2118    {
2119        let view = self.view().clone();
2120        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2121    }
2122
2123    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2124    /// that are currently on the stack to be returned to the app.
2125    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2126        let view = self.view().downgrade();
2127        self.window_cx.defer(move |cx| {
2128            view.update(cx, f).ok();
2129        });
2130    }
2131
2132    pub fn observe<V2, E>(
2133        &mut self,
2134        entity: &E,
2135        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2136    ) -> Subscription
2137    where
2138        V2: 'static,
2139        V: 'static,
2140        E: Entity<V2>,
2141    {
2142        let view = self.view().downgrade();
2143        let entity_id = entity.entity_id();
2144        let entity = entity.downgrade();
2145        let window_handle = self.window.handle;
2146        let (subscription, activate) = self.app.observers.insert(
2147            entity_id,
2148            Box::new(move |cx| {
2149                window_handle
2150                    .update(cx, |_, cx| {
2151                        if let Some(handle) = E::upgrade_from(&entity) {
2152                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2153                                .is_ok()
2154                        } else {
2155                            false
2156                        }
2157                    })
2158                    .unwrap_or(false)
2159            }),
2160        );
2161        self.app.defer(move |_| activate());
2162        subscription
2163    }
2164
2165    pub fn subscribe<V2, E, Evt>(
2166        &mut self,
2167        entity: &E,
2168        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2169    ) -> Subscription
2170    where
2171        V2: EventEmitter<Evt>,
2172        E: Entity<V2>,
2173        Evt: 'static,
2174    {
2175        let view = self.view().downgrade();
2176        let entity_id = entity.entity_id();
2177        let handle = entity.downgrade();
2178        let window_handle = self.window.handle;
2179        let (subscription, activate) = self.app.event_listeners.insert(
2180            entity_id,
2181            (
2182                TypeId::of::<Evt>(),
2183                Box::new(move |event, cx| {
2184                    window_handle
2185                        .update(cx, |_, cx| {
2186                            if let Some(handle) = E::upgrade_from(&handle) {
2187                                let event = event.downcast_ref().expect("invalid event type");
2188                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2189                                    .is_ok()
2190                            } else {
2191                                false
2192                            }
2193                        })
2194                        .unwrap_or(false)
2195                }),
2196            ),
2197        );
2198        self.app.defer(move |_| activate());
2199        subscription
2200    }
2201
2202    pub fn on_release(
2203        &mut self,
2204        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2205    ) -> Subscription {
2206        let window_handle = self.window.handle;
2207        let (subscription, activate) = self.app.release_listeners.insert(
2208            self.view.model.entity_id,
2209            Box::new(move |this, cx| {
2210                let this = this.downcast_mut().expect("invalid entity type");
2211                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2212            }),
2213        );
2214        activate();
2215        subscription
2216    }
2217
2218    pub fn observe_release<V2, E>(
2219        &mut self,
2220        entity: &E,
2221        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2222    ) -> Subscription
2223    where
2224        V: 'static,
2225        V2: 'static,
2226        E: Entity<V2>,
2227    {
2228        let view = self.view().downgrade();
2229        let entity_id = entity.entity_id();
2230        let window_handle = self.window.handle;
2231        let (subscription, activate) = self.app.release_listeners.insert(
2232            entity_id,
2233            Box::new(move |entity, cx| {
2234                let entity = entity.downcast_mut().expect("invalid entity type");
2235                let _ = window_handle.update(cx, |_, cx| {
2236                    view.update(cx, |this, cx| on_release(this, entity, cx))
2237                });
2238            }),
2239        );
2240        activate();
2241        subscription
2242    }
2243
2244    pub fn notify(&mut self) {
2245        self.window_cx.notify();
2246        self.window_cx.app.push_effect(Effect::Notify {
2247            emitter: self.view.model.entity_id,
2248        });
2249    }
2250
2251    pub fn observe_window_bounds(
2252        &mut self,
2253        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2254    ) -> Subscription {
2255        let view = self.view.downgrade();
2256        let (subscription, activate) = self.window.bounds_observers.insert(
2257            (),
2258            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2259        );
2260        activate();
2261        subscription
2262    }
2263
2264    pub fn observe_window_activation(
2265        &mut self,
2266        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2267    ) -> Subscription {
2268        let view = self.view.downgrade();
2269        let (subscription, activate) = self.window.activation_observers.insert(
2270            (),
2271            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2272        );
2273        activate();
2274        subscription
2275    }
2276
2277    /// Register a listener to be called when the given focus handle receives focus.
2278    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2279    /// is dropped.
2280    pub fn on_focus(
2281        &mut self,
2282        handle: &FocusHandle,
2283        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2284    ) -> Subscription {
2285        let view = self.view.downgrade();
2286        let focus_id = handle.id;
2287        let (subscription, activate) = self.window.focus_listeners.insert(
2288            (),
2289            Box::new(move |event, cx| {
2290                view.update(cx, |view, cx| {
2291                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2292                        listener(view, cx)
2293                    }
2294                })
2295                .is_ok()
2296            }),
2297        );
2298        self.app.defer(move |_| activate());
2299        subscription
2300    }
2301
2302    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2303    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2304    /// is dropped.
2305    pub fn on_focus_in(
2306        &mut self,
2307        handle: &FocusHandle,
2308        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2309    ) -> Subscription {
2310        let view = self.view.downgrade();
2311        let focus_id = handle.id;
2312        let (subscription, activate) = self.window.focus_listeners.insert(
2313            (),
2314            Box::new(move |event, cx| {
2315                view.update(cx, |view, cx| {
2316                    if event
2317                        .focused
2318                        .as_ref()
2319                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
2320                    {
2321                        listener(view, cx)
2322                    }
2323                })
2324                .is_ok()
2325            }),
2326        );
2327        self.app.defer(move |_| activate());
2328        subscription
2329    }
2330
2331    /// Register a listener to be called when the given focus handle loses focus.
2332    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2333    /// is dropped.
2334    pub fn on_blur(
2335        &mut self,
2336        handle: &FocusHandle,
2337        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2338    ) -> Subscription {
2339        let view = self.view.downgrade();
2340        let focus_id = handle.id;
2341        let (subscription, activate) = self.window.focus_listeners.insert(
2342            (),
2343            Box::new(move |event, cx| {
2344                view.update(cx, |view, cx| {
2345                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2346                        listener(view, cx)
2347                    }
2348                })
2349                .is_ok()
2350            }),
2351        );
2352        self.app.defer(move |_| activate());
2353        subscription
2354    }
2355
2356    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2357    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2358    /// is dropped.
2359    pub fn on_focus_out(
2360        &mut self,
2361        handle: &FocusHandle,
2362        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2363    ) -> Subscription {
2364        let view = self.view.downgrade();
2365        let focus_id = handle.id;
2366        let (subscription, activate) = self.window.focus_listeners.insert(
2367            (),
2368            Box::new(move |event, cx| {
2369                view.update(cx, |view, cx| {
2370                    if event
2371                        .blurred
2372                        .as_ref()
2373                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2374                    {
2375                        listener(view, cx)
2376                    }
2377                })
2378                .is_ok()
2379            }),
2380        );
2381        self.app.defer(move |_| activate());
2382        subscription
2383    }
2384
2385    pub fn spawn<Fut, R>(
2386        &mut self,
2387        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2388    ) -> Task<R>
2389    where
2390        R: 'static,
2391        Fut: Future<Output = R> + 'static,
2392    {
2393        let view = self.view().downgrade();
2394        self.window_cx.spawn(|cx| f(view, cx))
2395    }
2396
2397    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2398    where
2399        G: 'static,
2400    {
2401        let mut global = self.app.lease_global::<G>();
2402        let result = f(&mut global, self);
2403        self.app.end_global_lease(global);
2404        result
2405    }
2406
2407    pub fn observe_global<G: 'static>(
2408        &mut self,
2409        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2410    ) -> Subscription {
2411        let window_handle = self.window.handle;
2412        let view = self.view().downgrade();
2413        let (subscription, activate) = self.global_observers.insert(
2414            TypeId::of::<G>(),
2415            Box::new(move |cx| {
2416                window_handle
2417                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2418                    .unwrap_or(false)
2419            }),
2420        );
2421        self.app.defer(move |_| activate());
2422        subscription
2423    }
2424
2425    pub fn on_mouse_event<Event: 'static>(
2426        &mut self,
2427        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2428    ) {
2429        let handle = self.view().clone();
2430        self.window_cx.on_mouse_event(move |event, phase, cx| {
2431            handle.update(cx, |view, cx| {
2432                handler(view, event, phase, cx);
2433            })
2434        });
2435    }
2436
2437    pub fn on_key_event<Event: 'static>(
2438        &mut self,
2439        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2440    ) {
2441        let handle = self.view().clone();
2442        self.window_cx.on_key_event(move |event, phase, cx| {
2443            handle.update(cx, |view, cx| {
2444                handler(view, event, phase, cx);
2445            })
2446        });
2447    }
2448
2449    pub fn on_action(
2450        &mut self,
2451        action_type: TypeId,
2452        handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2453    ) {
2454        let handle = self.view().clone();
2455        self.window_cx
2456            .on_action(action_type, move |action, phase, cx| {
2457                handle.update(cx, |view, cx| {
2458                    handler(view, action, phase, cx);
2459                })
2460            });
2461    }
2462
2463    pub fn emit<Evt>(&mut self, event: Evt)
2464    where
2465        Evt: 'static,
2466        V: EventEmitter<Evt>,
2467    {
2468        let emitter = self.view.model.entity_id;
2469        self.app.push_effect(Effect::Emit {
2470            emitter,
2471            event_type: TypeId::of::<Evt>(),
2472            event: Box::new(event),
2473        });
2474    }
2475
2476    pub fn focus_self(&mut self)
2477    where
2478        V: FocusableView,
2479    {
2480        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2481    }
2482
2483    pub fn dismiss_self(&mut self)
2484    where
2485        V: ManagedView,
2486    {
2487        self.defer(|_, cx| cx.emit(DismissEvent))
2488    }
2489
2490    pub fn listener<E>(
2491        &self,
2492        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2493    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2494        let view = self.view().downgrade();
2495        move |e: &E, cx: &mut WindowContext| {
2496            view.update(cx, |view, cx| f(view, e, cx)).ok();
2497        }
2498    }
2499}
2500
2501impl<V> Context for ViewContext<'_, V> {
2502    type Result<U> = U;
2503
2504    fn build_model<T: 'static>(
2505        &mut self,
2506        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2507    ) -> Model<T> {
2508        self.window_cx.build_model(build_model)
2509    }
2510
2511    fn update_model<T: 'static, R>(
2512        &mut self,
2513        model: &Model<T>,
2514        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2515    ) -> R {
2516        self.window_cx.update_model(model, update)
2517    }
2518
2519    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2520    where
2521        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2522    {
2523        self.window_cx.update_window(window, update)
2524    }
2525
2526    fn read_model<T, R>(
2527        &self,
2528        handle: &Model<T>,
2529        read: impl FnOnce(&T, &AppContext) -> R,
2530    ) -> Self::Result<R>
2531    where
2532        T: 'static,
2533    {
2534        self.window_cx.read_model(handle, read)
2535    }
2536
2537    fn read_window<T, R>(
2538        &self,
2539        window: &WindowHandle<T>,
2540        read: impl FnOnce(View<T>, &AppContext) -> R,
2541    ) -> Result<R>
2542    where
2543        T: 'static,
2544    {
2545        self.window_cx.read_window(window, read)
2546    }
2547}
2548
2549impl<V: 'static> VisualContext for ViewContext<'_, V> {
2550    fn build_view<W: Render + 'static>(
2551        &mut self,
2552        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2553    ) -> Self::Result<View<W>> {
2554        self.window_cx.build_view(build_view_state)
2555    }
2556
2557    fn update_view<V2: 'static, R>(
2558        &mut self,
2559        view: &View<V2>,
2560        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2561    ) -> Self::Result<R> {
2562        self.window_cx.update_view(view, update)
2563    }
2564
2565    fn replace_root_view<W>(
2566        &mut self,
2567        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2568    ) -> Self::Result<View<W>>
2569    where
2570        W: 'static + Render,
2571    {
2572        self.window_cx.replace_root_view(build_view)
2573    }
2574
2575    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2576        self.window_cx.focus_view(view)
2577    }
2578
2579    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2580        self.window_cx.dismiss_view(view)
2581    }
2582}
2583
2584impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2585    type Target = WindowContext<'a>;
2586
2587    fn deref(&self) -> &Self::Target {
2588        &self.window_cx
2589    }
2590}
2591
2592impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2593    fn deref_mut(&mut self) -> &mut Self::Target {
2594        &mut self.window_cx
2595    }
2596}
2597
2598// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2599slotmap::new_key_type! { pub struct WindowId; }
2600
2601impl WindowId {
2602    pub fn as_u64(&self) -> u64 {
2603        self.0.as_ffi()
2604    }
2605}
2606
2607#[derive(Deref, DerefMut)]
2608pub struct WindowHandle<V> {
2609    #[deref]
2610    #[deref_mut]
2611    pub(crate) any_handle: AnyWindowHandle,
2612    state_type: PhantomData<V>,
2613}
2614
2615impl<V: 'static + Render> WindowHandle<V> {
2616    pub fn new(id: WindowId) -> Self {
2617        WindowHandle {
2618            any_handle: AnyWindowHandle {
2619                id,
2620                state_type: TypeId::of::<V>(),
2621            },
2622            state_type: PhantomData,
2623        }
2624    }
2625
2626    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2627    where
2628        C: Context,
2629    {
2630        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2631            root_view
2632                .downcast::<V>()
2633                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2634        }))
2635    }
2636
2637    pub fn update<C, R>(
2638        &self,
2639        cx: &mut C,
2640        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2641    ) -> Result<R>
2642    where
2643        C: Context,
2644    {
2645        cx.update_window(self.any_handle, |root_view, cx| {
2646            let view = root_view
2647                .downcast::<V>()
2648                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2649            Ok(cx.update_view(&view, update))
2650        })?
2651    }
2652
2653    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2654        let x = cx
2655            .windows
2656            .get(self.id)
2657            .and_then(|window| {
2658                window
2659                    .as_ref()
2660                    .and_then(|window| window.root_view.clone())
2661                    .map(|root_view| root_view.downcast::<V>())
2662            })
2663            .ok_or_else(|| anyhow!("window not found"))?
2664            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2665
2666        Ok(x.read(cx))
2667    }
2668
2669    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2670    where
2671        C: Context,
2672    {
2673        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2674    }
2675
2676    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2677    where
2678        C: Context,
2679    {
2680        cx.read_window(self, |root_view, _cx| root_view.clone())
2681    }
2682
2683    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2684        cx.windows
2685            .get(self.id)
2686            .and_then(|window| window.as_ref().map(|window| window.active))
2687    }
2688}
2689
2690impl<V> Copy for WindowHandle<V> {}
2691
2692impl<V> Clone for WindowHandle<V> {
2693    fn clone(&self) -> Self {
2694        WindowHandle {
2695            any_handle: self.any_handle,
2696            state_type: PhantomData,
2697        }
2698    }
2699}
2700
2701impl<V> PartialEq for WindowHandle<V> {
2702    fn eq(&self, other: &Self) -> bool {
2703        self.any_handle == other.any_handle
2704    }
2705}
2706
2707impl<V> Eq for WindowHandle<V> {}
2708
2709impl<V> Hash for WindowHandle<V> {
2710    fn hash<H: Hasher>(&self, state: &mut H) {
2711        self.any_handle.hash(state);
2712    }
2713}
2714
2715impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2716    fn into(self) -> AnyWindowHandle {
2717        self.any_handle
2718    }
2719}
2720
2721#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2722pub struct AnyWindowHandle {
2723    pub(crate) id: WindowId,
2724    state_type: TypeId,
2725}
2726
2727impl AnyWindowHandle {
2728    pub fn window_id(&self) -> WindowId {
2729        self.id
2730    }
2731
2732    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2733        if TypeId::of::<T>() == self.state_type {
2734            Some(WindowHandle {
2735                any_handle: *self,
2736                state_type: PhantomData,
2737            })
2738        } else {
2739            None
2740        }
2741    }
2742
2743    pub fn update<C, R>(
2744        self,
2745        cx: &mut C,
2746        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2747    ) -> Result<R>
2748    where
2749        C: Context,
2750    {
2751        cx.update_window(self, update)
2752    }
2753
2754    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2755    where
2756        C: Context,
2757        T: 'static,
2758    {
2759        let view = self
2760            .downcast::<T>()
2761            .context("the type of the window's root view has changed")?;
2762
2763        cx.read_window(&view, read)
2764    }
2765}
2766
2767#[cfg(any(test, feature = "test-support"))]
2768impl From<SmallVec<[u32; 16]>> for StackingOrder {
2769    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2770        StackingOrder(small_vec)
2771    }
2772}
2773
2774#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2775pub enum ElementId {
2776    View(EntityId),
2777    Integer(usize),
2778    Name(SharedString),
2779    FocusHandle(FocusId),
2780    NamedInteger(SharedString, usize),
2781}
2782
2783impl ElementId {
2784    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2785        ElementId::View(entity_id)
2786    }
2787}
2788
2789impl TryInto<SharedString> for ElementId {
2790    type Error = anyhow::Error;
2791
2792    fn try_into(self) -> anyhow::Result<SharedString> {
2793        if let ElementId::Name(name) = self {
2794            Ok(name)
2795        } else {
2796            Err(anyhow!("element id is not string"))
2797        }
2798    }
2799}
2800
2801impl From<usize> for ElementId {
2802    fn from(id: usize) -> Self {
2803        ElementId::Integer(id)
2804    }
2805}
2806
2807impl From<i32> for ElementId {
2808    fn from(id: i32) -> Self {
2809        Self::Integer(id as usize)
2810    }
2811}
2812
2813impl From<SharedString> for ElementId {
2814    fn from(name: SharedString) -> Self {
2815        ElementId::Name(name)
2816    }
2817}
2818
2819impl From<&'static str> for ElementId {
2820    fn from(name: &'static str) -> Self {
2821        ElementId::Name(name.into())
2822    }
2823}
2824
2825impl<'a> From<&'a FocusHandle> for ElementId {
2826    fn from(handle: &'a FocusHandle) -> Self {
2827        ElementId::FocusHandle(handle.id)
2828    }
2829}
2830
2831impl From<(&'static str, EntityId)> for ElementId {
2832    fn from((name, id): (&'static str, EntityId)) -> Self {
2833        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2834    }
2835}
2836
2837impl From<(&'static str, usize)> for ElementId {
2838    fn from((name, id): (&'static str, usize)) -> Self {
2839        ElementId::NamedInteger(name.into(), id)
2840    }
2841}