window.rs

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