window.rs

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