window.rs

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