window.rs

   1use crate::{
   2    px, size, Action, AnyBox, AnyDrag, AnyView, AppContext, AsyncWindowContext, AvailableSpace,
   3    Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,
   4    Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,
   5    Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,
   6    Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent,
   7    MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow, Point, PolychromeSprite,
   8    PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels,
   9    SceneBuilder, Shadow, SharedString, Size, Style, SubscriberSet, Subscription,
  10    TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakView,
  11    WindowOptions, SUBPIXEL_VARIANTS,
  12};
  13use anyhow::{anyhow, Result};
  14use collections::HashMap;
  15use derive_more::{Deref, DerefMut};
  16use futures::channel::oneshot;
  17use parking_lot::RwLock;
  18use slotmap::SlotMap;
  19use smallvec::SmallVec;
  20use std::{
  21    any::{Any, TypeId},
  22    borrow::{Borrow, BorrowMut, Cow},
  23    fmt::Debug,
  24    future::Future,
  25    hash::{Hash, Hasher},
  26    marker::PhantomData,
  27    mem,
  28    sync::{
  29        atomic::{AtomicUsize, Ordering::SeqCst},
  30        Arc,
  31    },
  32};
  33use util::ResultExt;
  34
  35/// A global stacking order, which is created by stacking successive z-index values.
  36/// Each z-index will always be interpreted in the context of its parent z-index.
  37#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
  38pub(crate) struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
  39
  40/// Represents the two different phases when dispatching events.
  41#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  42pub enum DispatchPhase {
  43    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  44    /// invoked front to back and keyboard event listeners are invoked from the focused element
  45    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  46    /// registering event listeners.
  47    #[default]
  48    Bubble,
  49    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  50    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  51    /// is used for special purposes such as clearing the "pressed" state for click events. If
  52    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  53    /// outside of the immediate region may rely on detecting non-local events during this phase.
  54    Capture,
  55}
  56
  57type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
  58type AnyKeyListener = Box<
  59    dyn Fn(
  60            &dyn Any,
  61            &[&DispatchContext],
  62            DispatchPhase,
  63            &mut WindowContext,
  64        ) -> Option<Box<dyn Action>>
  65        + 'static,
  66>;
  67type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
  68type AnyFullScreenListener = Box<dyn FnMut(bool, &mut WindowContext) -> bool + 'static>;
  69
  70slotmap::new_key_type! { pub struct FocusId; }
  71
  72/// A handle which can be used to track and manipulate the focused element in a window.
  73pub struct FocusHandle {
  74    pub(crate) id: FocusId,
  75    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
  76}
  77
  78impl FocusHandle {
  79    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
  80        let id = handles.write().insert(AtomicUsize::new(1));
  81        Self {
  82            id,
  83            handles: handles.clone(),
  84        }
  85    }
  86
  87    pub(crate) fn for_id(
  88        id: FocusId,
  89        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
  90    ) -> Option<Self> {
  91        let lock = handles.read();
  92        let ref_count = lock.get(id)?;
  93        if ref_count.load(SeqCst) == 0 {
  94            None
  95        } else {
  96            ref_count.fetch_add(1, SeqCst);
  97            Some(Self {
  98                id,
  99                handles: handles.clone(),
 100            })
 101        }
 102    }
 103
 104    /// Obtains whether the element associated with this handle is currently focused.
 105    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 106        cx.window.focus == Some(self.id)
 107    }
 108
 109    /// Obtains whether the element associated with this handle contains the focused
 110    /// element or is itself focused.
 111    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 112        cx.focused()
 113            .map_or(false, |focused| self.contains(&focused, cx))
 114    }
 115
 116    /// Obtains whether the element associated with this handle is contained within the
 117    /// focused element or is itself focused.
 118    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 119        let focused = cx.focused();
 120        focused.map_or(false, |focused| focused.contains(self, cx))
 121    }
 122
 123    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 124    pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 125        let mut ancestor = Some(other.id);
 126        while let Some(ancestor_id) = ancestor {
 127            if self.id == ancestor_id {
 128                return true;
 129            } else {
 130                ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
 131            }
 132        }
 133        false
 134    }
 135}
 136
 137impl Clone for FocusHandle {
 138    fn clone(&self) -> Self {
 139        Self::for_id(self.id, &self.handles).unwrap()
 140    }
 141}
 142
 143impl PartialEq for FocusHandle {
 144    fn eq(&self, other: &Self) -> bool {
 145        self.id == other.id
 146    }
 147}
 148
 149impl Eq for FocusHandle {}
 150
 151impl Drop for FocusHandle {
 152    fn drop(&mut self) {
 153        self.handles
 154            .read()
 155            .get(self.id)
 156            .unwrap()
 157            .fetch_sub(1, SeqCst);
 158    }
 159}
 160
 161// Holds the state for a specific window.
 162pub struct Window {
 163    pub(crate) handle: AnyWindowHandle,
 164    platform_window: Box<dyn PlatformWindow>,
 165    display_id: DisplayId,
 166    sprite_atlas: Arc<dyn PlatformAtlas>,
 167    rem_size: Pixels,
 168    content_size: Size<Pixels>,
 169    pub(crate) layout_engine: TaffyLayoutEngine,
 170    pub(crate) root_view: Option<AnyView>,
 171    pub(crate) element_id_stack: GlobalElementId,
 172    prev_frame_element_states: HashMap<GlobalElementId, AnyBox>,
 173    element_states: HashMap<GlobalElementId, AnyBox>,
 174    prev_frame_key_matchers: HashMap<GlobalElementId, KeyMatcher>,
 175    key_matchers: HashMap<GlobalElementId, KeyMatcher>,
 176    z_index_stack: StackingOrder,
 177    content_mask_stack: Vec<ContentMask<Pixels>>,
 178    element_offset_stack: Vec<Point<Pixels>>,
 179    mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
 180    key_dispatch_stack: Vec<KeyDispatchStackFrame>,
 181    freeze_key_dispatch_stack: bool,
 182    focus_stack: Vec<FocusId>,
 183    focus_parents_by_child: HashMap<FocusId, FocusId>,
 184    pub(crate) focus_listeners: Vec<AnyFocusListener>,
 185    fullscreen_listeners: SubscriberSet<(), AnyFullScreenListener>,
 186    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 187    default_prevented: bool,
 188    mouse_position: Point<Pixels>,
 189    scale_factor: f32,
 190    fullscreen: bool,
 191    pub(crate) scene_builder: SceneBuilder,
 192    pub(crate) dirty: bool,
 193    pub(crate) last_blur: Option<Option<FocusId>>,
 194    pub(crate) focus: Option<FocusId>,
 195}
 196
 197impl Window {
 198    pub(crate) fn new(
 199        handle: AnyWindowHandle,
 200        options: WindowOptions,
 201        cx: &mut AppContext,
 202    ) -> Self {
 203        let platform_window = cx.platform.open_window(handle, options);
 204        let display_id = platform_window.display().id();
 205        let sprite_atlas = platform_window.sprite_atlas();
 206        let mouse_position = platform_window.mouse_position();
 207        let content_size = platform_window.content_size();
 208        let scale_factor = platform_window.scale_factor();
 209
 210        platform_window.on_resize(Box::new({
 211            let mut cx = cx.to_async();
 212            move |content_size, scale_factor| {
 213                handle
 214                    .update(&mut cx, |_, cx| {
 215                        cx.window.scale_factor = scale_factor;
 216                        cx.window.scene_builder = SceneBuilder::new();
 217                        cx.window.content_size = content_size;
 218                        cx.window.display_id = cx.window.platform_window.display().id();
 219                        cx.window.dirty = true;
 220                    })
 221                    .log_err();
 222            }
 223        }));
 224        platform_window.on_fullscreen(Box::new({
 225            let mut cx = cx.to_async();
 226            move |fullscreen| {
 227                handle
 228                    .update(&mut cx, |_, cx| {
 229                        cx.window.fullscreen = fullscreen;
 230                        cx.window
 231                            .fullscreen_listeners
 232                            .clone()
 233                            .retain(&(), |callback| callback(fullscreen, cx));
 234                        cx.window.dirty = true;
 235                    })
 236                    .log_err();
 237            }
 238        }));
 239
 240        platform_window.on_input({
 241            let mut cx = cx.to_async();
 242            Box::new(move |event| {
 243                handle
 244                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 245                    .log_err()
 246                    .unwrap_or(true)
 247            })
 248        });
 249
 250        Window {
 251            handle,
 252            platform_window,
 253            display_id,
 254            sprite_atlas,
 255            rem_size: px(16.),
 256            content_size,
 257            layout_engine: TaffyLayoutEngine::new(),
 258            root_view: None,
 259            element_id_stack: GlobalElementId::default(),
 260            prev_frame_element_states: HashMap::default(),
 261            element_states: HashMap::default(),
 262            prev_frame_key_matchers: HashMap::default(),
 263            key_matchers: HashMap::default(),
 264            z_index_stack: StackingOrder(SmallVec::new()),
 265            content_mask_stack: Vec::new(),
 266            element_offset_stack: Vec::new(),
 267            mouse_listeners: HashMap::default(),
 268            key_dispatch_stack: Vec::new(),
 269            freeze_key_dispatch_stack: false,
 270            focus_stack: Vec::new(),
 271            focus_parents_by_child: HashMap::default(),
 272            focus_listeners: Vec::new(),
 273            fullscreen_listeners: SubscriberSet::new(),
 274            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 275            default_prevented: true,
 276            mouse_position,
 277            scale_factor,
 278            fullscreen: false,
 279            scene_builder: SceneBuilder::new(),
 280            dirty: true,
 281            last_blur: None,
 282            focus: None,
 283        }
 284    }
 285}
 286
 287/// When constructing the element tree, we maintain a stack of key dispatch frames until we
 288/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
 289/// contexts when matching key events against the keymap.
 290enum KeyDispatchStackFrame {
 291    Listener {
 292        event_type: TypeId,
 293        listener: AnyKeyListener,
 294    },
 295    Context(DispatchContext),
 296}
 297
 298/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 299/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 300/// to leave room to support more complex shapes in the future.
 301#[derive(Clone, Debug, Default, PartialEq, Eq)]
 302#[repr(C)]
 303pub struct ContentMask<P: Clone + Default + Debug> {
 304    pub bounds: Bounds<P>,
 305}
 306
 307impl ContentMask<Pixels> {
 308    /// Scale the content mask's pixel units by the given scaling factor.
 309    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 310        ContentMask {
 311            bounds: self.bounds.scale(factor),
 312        }
 313    }
 314
 315    /// Intersect the content mask with the given content mask.
 316    pub fn intersect(&self, other: &Self) -> Self {
 317        let bounds = self.bounds.intersect(&other.bounds);
 318        ContentMask { bounds }
 319    }
 320}
 321
 322/// Provides access to application state in the context of a single window. Derefs
 323/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
 324/// an `AppContext` and call any `AppContext` methods.
 325pub struct WindowContext<'a> {
 326    pub(crate) app: &'a mut AppContext,
 327    pub(crate) window: &'a mut Window,
 328}
 329
 330impl<'a> WindowContext<'a> {
 331    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 332        Self { app, window }
 333    }
 334
 335    /// Obtain a handle to the window that belongs to this context.
 336    pub fn window_handle(&self) -> AnyWindowHandle {
 337        self.window.handle
 338    }
 339
 340    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 341    pub fn notify(&mut self) {
 342        self.window.dirty = true;
 343    }
 344
 345    /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
 346    /// for elements rendered within this window.
 347    pub fn focus_handle(&mut self) -> FocusHandle {
 348        FocusHandle::new(&self.window.focus_handles)
 349    }
 350
 351    /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
 352    pub fn focused(&self) -> Option<FocusHandle> {
 353        self.window
 354            .focus
 355            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 356    }
 357
 358    /// Move focus to the element associated with the given `FocusHandle`.
 359    pub fn focus(&mut self, handle: &FocusHandle) {
 360        if self.window.last_blur.is_none() {
 361            self.window.last_blur = Some(self.window.focus);
 362        }
 363
 364        self.window.focus = Some(handle.id);
 365        self.app.push_effect(Effect::FocusChanged {
 366            window_handle: self.window.handle,
 367            focused: Some(handle.id),
 368        });
 369        self.notify();
 370    }
 371
 372    /// Remove focus from all elements within this context's window.
 373    pub fn blur(&mut self) {
 374        if self.window.last_blur.is_none() {
 375            self.window.last_blur = Some(self.window.focus);
 376        }
 377
 378        self.window.focus = None;
 379        self.app.push_effect(Effect::FocusChanged {
 380            window_handle: self.window.handle,
 381            focused: None,
 382        });
 383        self.notify();
 384    }
 385
 386    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 387    /// that are currently on the stack to be returned to the app.
 388    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 389        let handle = self.window.handle;
 390        self.app.defer(move |cx| {
 391            handle.update(cx, |_, cx| f(cx)).ok();
 392        });
 393    }
 394
 395    pub fn subscribe<Emitter, E>(
 396        &mut self,
 397        entity: &E,
 398        mut on_event: impl FnMut(E, &Emitter::Event, &mut WindowContext<'_>) + 'static,
 399    ) -> Subscription
 400    where
 401        Emitter: EventEmitter,
 402        E: Entity<Emitter>,
 403    {
 404        let entity_id = entity.entity_id();
 405        let entity = entity.downgrade();
 406        let window_handle = self.window.handle;
 407        self.app.event_listeners.insert(
 408            entity_id,
 409            Box::new(move |event, cx| {
 410                window_handle
 411                    .update(cx, |_, cx| {
 412                        if let Some(handle) = E::upgrade_from(&entity) {
 413                            let event = event.downcast_ref().expect("invalid event type");
 414                            on_event(handle, event, cx);
 415                            true
 416                        } else {
 417                            false
 418                        }
 419                    })
 420                    .unwrap_or(false)
 421            }),
 422        )
 423    }
 424
 425    /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
 426    /// await points in async code.
 427    pub fn to_async(&self) -> AsyncWindowContext {
 428        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 429    }
 430
 431    /// Schedule the given closure to be run directly after the current frame is rendered.
 432    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 433        let f = Box::new(f);
 434        let display_id = self.window.display_id;
 435
 436        if let Some(callbacks) = self.next_frame_callbacks.get_mut(&display_id) {
 437            callbacks.push(f);
 438            // If there was already a callback, it means that we already scheduled a frame.
 439            if callbacks.len() > 1 {
 440                return;
 441            }
 442        } else {
 443            let mut async_cx = self.to_async();
 444            self.next_frame_callbacks.insert(display_id, vec![f]);
 445            self.platform.set_display_link_output_callback(
 446                display_id,
 447                Box::new(move |_current_time, _output_time| {
 448                    let _ = async_cx.update(|_, cx| {
 449                        let callbacks = cx
 450                            .next_frame_callbacks
 451                            .get_mut(&display_id)
 452                            .unwrap()
 453                            .drain(..)
 454                            .collect::<Vec<_>>();
 455                        for callback in callbacks {
 456                            callback(cx);
 457                        }
 458
 459                        if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
 460                            cx.platform.stop_display_link(display_id);
 461                        }
 462                    });
 463                }),
 464            );
 465        }
 466
 467        self.platform.start_display_link(display_id);
 468    }
 469
 470    /// Spawn the future returned by the given closure on the application thread pool.
 471    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 472    /// use within your future.
 473    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 474    where
 475        R: 'static,
 476        Fut: Future<Output = R> + 'static,
 477    {
 478        self.app
 479            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 480    }
 481
 482    /// Update the global of the given type. The given closure is given simultaneous mutable
 483    /// access both to the global and the context.
 484    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 485    where
 486        G: 'static,
 487    {
 488        let mut global = self.app.lease_global::<G>();
 489        let result = f(&mut global, self);
 490        self.app.end_global_lease(global);
 491        result
 492    }
 493
 494    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 495    /// layout is being requested, along with the layout ids of any children. This method is called during
 496    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 497    pub fn request_layout(
 498        &mut self,
 499        style: &Style,
 500        children: impl IntoIterator<Item = LayoutId>,
 501    ) -> LayoutId {
 502        self.app.layout_id_buffer.clear();
 503        self.app.layout_id_buffer.extend(children.into_iter());
 504        let rem_size = self.rem_size();
 505
 506        self.window
 507            .layout_engine
 508            .request_layout(style, rem_size, &self.app.layout_id_buffer)
 509    }
 510
 511    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 512    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 513    /// determine the element's size. One place this is used internally is when measuring text.
 514    ///
 515    /// The given closure is invoked at layout time with the known dimensions and available space and
 516    /// returns a `Size`.
 517    pub fn request_measured_layout<
 518        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
 519    >(
 520        &mut self,
 521        style: Style,
 522        rem_size: Pixels,
 523        measure: F,
 524    ) -> LayoutId {
 525        self.window
 526            .layout_engine
 527            .request_measured_layout(style, rem_size, measure)
 528    }
 529
 530    /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
 531    /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
 532    /// in order to pass your element its `Bounds` automatically.
 533    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
 534        let mut bounds = self
 535            .window
 536            .layout_engine
 537            .layout_bounds(layout_id)
 538            .map(Into::into);
 539        bounds.origin += self.element_offset();
 540        bounds
 541    }
 542
 543    /// The scale factor of the display associated with the window. For example, it could
 544    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 545    /// be rendered as two pixels on screen.
 546    pub fn scale_factor(&self) -> f32 {
 547        self.window.scale_factor
 548    }
 549
 550    /// The size of an em for the base font of the application. Adjusting this value allows the
 551    /// UI to scale, just like zooming a web page.
 552    pub fn rem_size(&self) -> Pixels {
 553        self.window.rem_size
 554    }
 555
 556    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 557    /// UI to scale, just like zooming a web page.
 558    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 559        self.window.rem_size = rem_size.into();
 560    }
 561
 562    /// The line height associated with the current text style.
 563    pub fn line_height(&self) -> Pixels {
 564        let rem_size = self.rem_size();
 565        let text_style = self.text_style();
 566        text_style
 567            .line_height
 568            .to_pixels(text_style.font_size.into(), rem_size)
 569    }
 570
 571    /// Call to prevent the default action of an event. Currently only used to prevent
 572    /// parent elements from becoming focused on mouse down.
 573    pub fn prevent_default(&mut self) {
 574        self.window.default_prevented = true;
 575    }
 576
 577    /// Obtain whether default has been prevented for the event currently being dispatched.
 578    pub fn default_prevented(&self) -> bool {
 579        self.window.default_prevented
 580    }
 581
 582    /// Register a mouse event listener on the window for the current frame. The type of event
 583    /// is determined by the first parameter of the given listener. When the next frame is rendered
 584    /// the listener will be cleared.
 585    ///
 586    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 587    /// a specific need to register a global listener.
 588    pub fn on_mouse_event<Event: 'static>(
 589        &mut self,
 590        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 591    ) {
 592        let order = self.window.z_index_stack.clone();
 593        self.window
 594            .mouse_listeners
 595            .entry(TypeId::of::<Event>())
 596            .or_default()
 597            .push((
 598                order,
 599                Box::new(move |event: &dyn Any, phase, cx| {
 600                    handler(event.downcast_ref().unwrap(), phase, cx)
 601                }),
 602            ))
 603    }
 604
 605    /// The position of the mouse relative to the window.
 606    pub fn mouse_position(&self) -> Point<Pixels> {
 607        self.window.mouse_position
 608    }
 609
 610    /// Called during painting to invoke the given closure in a new stacking context. The given
 611    /// z-index is interpreted relative to the previous call to `stack`.
 612    pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
 613        self.window.z_index_stack.push(z_index);
 614        let result = f(self);
 615        self.window.z_index_stack.pop();
 616        result
 617    }
 618
 619    /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
 620    pub fn paint_shadows(
 621        &mut self,
 622        bounds: Bounds<Pixels>,
 623        corner_radii: Corners<Pixels>,
 624        shadows: &[BoxShadow],
 625    ) {
 626        let scale_factor = self.scale_factor();
 627        let content_mask = self.content_mask();
 628        let window = &mut *self.window;
 629        for shadow in shadows {
 630            let mut shadow_bounds = bounds;
 631            shadow_bounds.origin += shadow.offset;
 632            shadow_bounds.dilate(shadow.spread_radius);
 633            window.scene_builder.insert(
 634                &window.z_index_stack,
 635                Shadow {
 636                    order: 0,
 637                    bounds: shadow_bounds.scale(scale_factor),
 638                    content_mask: content_mask.scale(scale_factor),
 639                    corner_radii: corner_radii.scale(scale_factor),
 640                    color: shadow.color,
 641                    blur_radius: shadow.blur_radius.scale(scale_factor),
 642                },
 643            );
 644        }
 645    }
 646
 647    /// Paint one or more quads into the scene for the current frame at the current stacking context.
 648    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 649    pub fn paint_quad(
 650        &mut self,
 651        bounds: Bounds<Pixels>,
 652        corner_radii: Corners<Pixels>,
 653        background: impl Into<Hsla>,
 654        border_widths: Edges<Pixels>,
 655        border_color: impl Into<Hsla>,
 656    ) {
 657        let scale_factor = self.scale_factor();
 658        let content_mask = self.content_mask();
 659
 660        let window = &mut *self.window;
 661        window.scene_builder.insert(
 662            &window.z_index_stack,
 663            Quad {
 664                order: 0,
 665                bounds: bounds.scale(scale_factor),
 666                content_mask: content_mask.scale(scale_factor),
 667                background: background.into(),
 668                border_color: border_color.into(),
 669                corner_radii: corner_radii.scale(scale_factor),
 670                border_widths: border_widths.scale(scale_factor),
 671            },
 672        );
 673    }
 674
 675    /// Paint the given `Path` into the scene for the current frame at the current z-index.
 676    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 677        let scale_factor = self.scale_factor();
 678        let content_mask = self.content_mask();
 679        path.content_mask = content_mask;
 680        path.color = color.into();
 681        let window = &mut *self.window;
 682        window
 683            .scene_builder
 684            .insert(&window.z_index_stack, path.scale(scale_factor));
 685    }
 686
 687    /// Paint an underline into the scene for the current frame at the current z-index.
 688    pub fn paint_underline(
 689        &mut self,
 690        origin: Point<Pixels>,
 691        width: Pixels,
 692        style: &UnderlineStyle,
 693    ) -> Result<()> {
 694        let scale_factor = self.scale_factor();
 695        let height = if style.wavy {
 696            style.thickness * 3.
 697        } else {
 698            style.thickness
 699        };
 700        let bounds = Bounds {
 701            origin,
 702            size: size(width, height),
 703        };
 704        let content_mask = self.content_mask();
 705        let window = &mut *self.window;
 706        window.scene_builder.insert(
 707            &window.z_index_stack,
 708            Underline {
 709                order: 0,
 710                bounds: bounds.scale(scale_factor),
 711                content_mask: content_mask.scale(scale_factor),
 712                thickness: style.thickness.scale(scale_factor),
 713                color: style.color.unwrap_or_default(),
 714                wavy: style.wavy,
 715            },
 716        );
 717        Ok(())
 718    }
 719
 720    /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
 721    pub fn paint_glyph(
 722        &mut self,
 723        origin: Point<Pixels>,
 724        font_id: FontId,
 725        glyph_id: GlyphId,
 726        font_size: Pixels,
 727        color: Hsla,
 728    ) -> Result<()> {
 729        let scale_factor = self.scale_factor();
 730        let glyph_origin = origin.scale(scale_factor);
 731        let subpixel_variant = Point {
 732            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 733            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 734        };
 735        let params = RenderGlyphParams {
 736            font_id,
 737            glyph_id,
 738            font_size,
 739            subpixel_variant,
 740            scale_factor,
 741            is_emoji: false,
 742        };
 743
 744        let raster_bounds = self.text_system().raster_bounds(&params)?;
 745        if !raster_bounds.is_zero() {
 746            let tile =
 747                self.window
 748                    .sprite_atlas
 749                    .get_or_insert_with(&params.clone().into(), &mut || {
 750                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 751                        Ok((size, Cow::Owned(bytes)))
 752                    })?;
 753            let bounds = Bounds {
 754                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 755                size: tile.bounds.size.map(Into::into),
 756            };
 757            let content_mask = self.content_mask().scale(scale_factor);
 758            let window = &mut *self.window;
 759            window.scene_builder.insert(
 760                &window.z_index_stack,
 761                MonochromeSprite {
 762                    order: 0,
 763                    bounds,
 764                    content_mask,
 765                    color,
 766                    tile,
 767                },
 768            );
 769        }
 770        Ok(())
 771    }
 772
 773    /// Paint an emoji glyph into the scene for the current frame at the current z-index.
 774    pub fn paint_emoji(
 775        &mut self,
 776        origin: Point<Pixels>,
 777        font_id: FontId,
 778        glyph_id: GlyphId,
 779        font_size: Pixels,
 780    ) -> Result<()> {
 781        let scale_factor = self.scale_factor();
 782        let glyph_origin = origin.scale(scale_factor);
 783        let params = RenderGlyphParams {
 784            font_id,
 785            glyph_id,
 786            font_size,
 787            // We don't render emojis with subpixel variants.
 788            subpixel_variant: Default::default(),
 789            scale_factor,
 790            is_emoji: true,
 791        };
 792
 793        let raster_bounds = self.text_system().raster_bounds(&params)?;
 794        if !raster_bounds.is_zero() {
 795            let tile =
 796                self.window
 797                    .sprite_atlas
 798                    .get_or_insert_with(&params.clone().into(), &mut || {
 799                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 800                        Ok((size, Cow::Owned(bytes)))
 801                    })?;
 802            let bounds = Bounds {
 803                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 804                size: tile.bounds.size.map(Into::into),
 805            };
 806            let content_mask = self.content_mask().scale(scale_factor);
 807            let window = &mut *self.window;
 808
 809            window.scene_builder.insert(
 810                &window.z_index_stack,
 811                PolychromeSprite {
 812                    order: 0,
 813                    bounds,
 814                    corner_radii: Default::default(),
 815                    content_mask,
 816                    tile,
 817                    grayscale: false,
 818                },
 819            );
 820        }
 821        Ok(())
 822    }
 823
 824    /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
 825    pub fn paint_svg(
 826        &mut self,
 827        bounds: Bounds<Pixels>,
 828        path: SharedString,
 829        color: Hsla,
 830    ) -> Result<()> {
 831        let scale_factor = self.scale_factor();
 832        let bounds = bounds.scale(scale_factor);
 833        // Render the SVG at twice the size to get a higher quality result.
 834        let params = RenderSvgParams {
 835            path,
 836            size: bounds
 837                .size
 838                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 839        };
 840
 841        let tile =
 842            self.window
 843                .sprite_atlas
 844                .get_or_insert_with(&params.clone().into(), &mut || {
 845                    let bytes = self.svg_renderer.render(&params)?;
 846                    Ok((params.size, Cow::Owned(bytes)))
 847                })?;
 848        let content_mask = self.content_mask().scale(scale_factor);
 849
 850        let window = &mut *self.window;
 851        window.scene_builder.insert(
 852            &window.z_index_stack,
 853            MonochromeSprite {
 854                order: 0,
 855                bounds,
 856                content_mask,
 857                color,
 858                tile,
 859            },
 860        );
 861
 862        Ok(())
 863    }
 864
 865    /// Paint an image into the scene for the current frame at the current z-index.
 866    pub fn paint_image(
 867        &mut self,
 868        bounds: Bounds<Pixels>,
 869        corner_radii: Corners<Pixels>,
 870        data: Arc<ImageData>,
 871        grayscale: bool,
 872    ) -> Result<()> {
 873        let scale_factor = self.scale_factor();
 874        let bounds = bounds.scale(scale_factor);
 875        let params = RenderImageParams { image_id: data.id };
 876
 877        let tile = self
 878            .window
 879            .sprite_atlas
 880            .get_or_insert_with(&params.clone().into(), &mut || {
 881                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
 882            })?;
 883        let content_mask = self.content_mask().scale(scale_factor);
 884        let corner_radii = corner_radii.scale(scale_factor);
 885
 886        let window = &mut *self.window;
 887        window.scene_builder.insert(
 888            &window.z_index_stack,
 889            PolychromeSprite {
 890                order: 0,
 891                bounds,
 892                content_mask,
 893                corner_radii,
 894                tile,
 895                grayscale,
 896            },
 897        );
 898        Ok(())
 899    }
 900
 901    /// Draw pixels to the display for this window based on the contents of its scene.
 902    pub(crate) fn draw(&mut self) {
 903        let root_view = self.window.root_view.take().unwrap();
 904
 905        self.start_frame();
 906
 907        self.stack(0, |cx| {
 908            let available_space = cx.window.content_size.map(Into::into);
 909            root_view.draw(available_space, cx);
 910        });
 911
 912        if let Some(active_drag) = self.app.active_drag.take() {
 913            self.stack(1, |cx| {
 914                let offset = cx.mouse_position() - active_drag.cursor_offset;
 915                cx.with_element_offset(Some(offset), |cx| {
 916                    let available_space =
 917                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 918                    active_drag.view.draw(available_space, cx);
 919                    cx.active_drag = Some(active_drag);
 920                });
 921            });
 922        }
 923
 924        self.window.root_view = Some(root_view);
 925        let scene = self.window.scene_builder.build();
 926
 927        self.window.platform_window.draw(scene);
 928        self.window.dirty = false;
 929    }
 930
 931    fn start_frame(&mut self) {
 932        self.text_system().start_frame();
 933
 934        let window = &mut *self.window;
 935
 936        // Move the current frame element states to the previous frame.
 937        // The new empty element states map will be populated for any element states we
 938        // reference during the upcoming frame.
 939        mem::swap(
 940            &mut window.element_states,
 941            &mut window.prev_frame_element_states,
 942        );
 943        window.element_states.clear();
 944
 945        // Make the current key matchers the previous, and then clear the current.
 946        // An empty key matcher map will be created for every identified element in the
 947        // upcoming frame.
 948        mem::swap(
 949            &mut window.key_matchers,
 950            &mut window.prev_frame_key_matchers,
 951        );
 952        window.key_matchers.clear();
 953
 954        // Clear mouse event listeners, because elements add new element listeners
 955        // when the upcoming frame is painted.
 956        window.mouse_listeners.values_mut().for_each(Vec::clear);
 957
 958        // Clear focus state, because we determine what is focused when the new elements
 959        // in the upcoming frame are initialized.
 960        window.focus_listeners.clear();
 961        window.key_dispatch_stack.clear();
 962        window.focus_parents_by_child.clear();
 963        window.freeze_key_dispatch_stack = false;
 964    }
 965
 966    /// Dispatch a mouse or keyboard event on the window.
 967    fn dispatch_event(&mut self, event: InputEvent) -> bool {
 968        let event = match event {
 969            // Track the mouse position with our own state, since accessing the platform
 970            // API for the mouse position can only occur on the main thread.
 971            InputEvent::MouseMove(mouse_move) => {
 972                self.window.mouse_position = mouse_move.position;
 973                InputEvent::MouseMove(mouse_move)
 974            }
 975            // Translate dragging and dropping of external files from the operating system
 976            // to internal drag and drop events.
 977            InputEvent::FileDrop(file_drop) => match file_drop {
 978                FileDropEvent::Entered { position, files } => {
 979                    self.window.mouse_position = position;
 980                    if self.active_drag.is_none() {
 981                        self.active_drag = Some(AnyDrag {
 982                            view: self.build_view(|_| files).into(),
 983                            cursor_offset: position,
 984                        });
 985                    }
 986                    InputEvent::MouseDown(MouseDownEvent {
 987                        position,
 988                        button: MouseButton::Left,
 989                        click_count: 1,
 990                        modifiers: Modifiers::default(),
 991                    })
 992                }
 993                FileDropEvent::Pending { position } => {
 994                    self.window.mouse_position = position;
 995                    InputEvent::MouseMove(MouseMoveEvent {
 996                        position,
 997                        pressed_button: Some(MouseButton::Left),
 998                        modifiers: Modifiers::default(),
 999                    })
1000                }
1001                FileDropEvent::Submit { position } => {
1002                    self.window.mouse_position = position;
1003                    InputEvent::MouseUp(MouseUpEvent {
1004                        button: MouseButton::Left,
1005                        position,
1006                        modifiers: Modifiers::default(),
1007                        click_count: 1,
1008                    })
1009                }
1010                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1011                    button: MouseButton::Left,
1012                    position: Point::default(),
1013                    modifiers: Modifiers::default(),
1014                    click_count: 1,
1015                }),
1016            },
1017            _ => event,
1018        };
1019
1020        if let Some(any_mouse_event) = event.mouse_event() {
1021            // Handlers may set this to false by calling `stop_propagation`
1022            self.app.propagate_event = true;
1023            self.window.default_prevented = false;
1024
1025            if let Some(mut handlers) = self
1026                .window
1027                .mouse_listeners
1028                .remove(&any_mouse_event.type_id())
1029            {
1030                // Because handlers may add other handlers, we sort every time.
1031                handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1032
1033                // Capture phase, events bubble from back to front. Handlers for this phase are used for
1034                // special purposes, such as detecting events outside of a given Bounds.
1035                for (_, handler) in &handlers {
1036                    handler(any_mouse_event, DispatchPhase::Capture, self);
1037                    if !self.app.propagate_event {
1038                        break;
1039                    }
1040                }
1041
1042                // Bubble phase, where most normal handlers do their work.
1043                if self.app.propagate_event {
1044                    for (_, handler) in handlers.iter().rev() {
1045                        handler(any_mouse_event, DispatchPhase::Bubble, self);
1046                        if !self.app.propagate_event {
1047                            break;
1048                        }
1049                    }
1050                }
1051
1052                if self.app.propagate_event
1053                    && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1054                {
1055                    self.active_drag = None;
1056                }
1057
1058                // Just in case any handlers added new handlers, which is weird, but possible.
1059                handlers.extend(
1060                    self.window
1061                        .mouse_listeners
1062                        .get_mut(&any_mouse_event.type_id())
1063                        .into_iter()
1064                        .flat_map(|handlers| handlers.drain(..)),
1065                );
1066                self.window
1067                    .mouse_listeners
1068                    .insert(any_mouse_event.type_id(), handlers);
1069            }
1070        } else if let Some(any_key_event) = event.keyboard_event() {
1071            let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1072            let key_event_type = any_key_event.type_id();
1073            let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1074
1075            for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1076                match frame {
1077                    KeyDispatchStackFrame::Listener {
1078                        event_type,
1079                        listener,
1080                    } => {
1081                        if key_event_type == *event_type {
1082                            if let Some(action) = listener(
1083                                any_key_event,
1084                                &context_stack,
1085                                DispatchPhase::Capture,
1086                                self,
1087                            ) {
1088                                self.dispatch_action(action, &key_dispatch_stack[..ix]);
1089                            }
1090                            if !self.app.propagate_event {
1091                                break;
1092                            }
1093                        }
1094                    }
1095                    KeyDispatchStackFrame::Context(context) => {
1096                        context_stack.push(&context);
1097                    }
1098                }
1099            }
1100
1101            if self.app.propagate_event {
1102                for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1103                    match frame {
1104                        KeyDispatchStackFrame::Listener {
1105                            event_type,
1106                            listener,
1107                        } => {
1108                            if key_event_type == *event_type {
1109                                if let Some(action) = listener(
1110                                    any_key_event,
1111                                    &context_stack,
1112                                    DispatchPhase::Bubble,
1113                                    self,
1114                                ) {
1115                                    self.dispatch_action(action, &key_dispatch_stack[..ix]);
1116                                }
1117
1118                                if !self.app.propagate_event {
1119                                    break;
1120                                }
1121                            }
1122                        }
1123                        KeyDispatchStackFrame::Context(_) => {
1124                            context_stack.pop();
1125                        }
1126                    }
1127                }
1128            }
1129
1130            drop(context_stack);
1131            self.window.key_dispatch_stack = key_dispatch_stack;
1132        }
1133
1134        true
1135    }
1136
1137    /// Attempt to map a keystroke to an action based on the keymap.
1138    pub fn match_keystroke(
1139        &mut self,
1140        element_id: &GlobalElementId,
1141        keystroke: &Keystroke,
1142        context_stack: &[&DispatchContext],
1143    ) -> KeyMatch {
1144        let key_match = self
1145            .window
1146            .key_matchers
1147            .get_mut(element_id)
1148            .unwrap()
1149            .match_keystroke(keystroke, context_stack);
1150
1151        if key_match.is_some() {
1152            for matcher in self.window.key_matchers.values_mut() {
1153                matcher.clear_pending();
1154            }
1155        }
1156
1157        key_match
1158    }
1159
1160    /// Register the given handler to be invoked whenever the global of the given type
1161    /// is updated.
1162    pub fn observe_global<G: 'static>(
1163        &mut self,
1164        f: impl Fn(&mut WindowContext<'_>) + 'static,
1165    ) -> Subscription {
1166        let window_handle = self.window.handle;
1167        self.global_observers.insert(
1168            TypeId::of::<G>(),
1169            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1170        )
1171    }
1172
1173    pub fn activate_window(&self) {
1174        self.window.platform_window.activate();
1175    }
1176
1177    pub fn prompt(
1178        &self,
1179        level: PromptLevel,
1180        msg: &str,
1181        answers: &[&str],
1182    ) -> oneshot::Receiver<usize> {
1183        self.window.platform_window.prompt(level, msg, answers)
1184    }
1185
1186    fn dispatch_action(
1187        &mut self,
1188        action: Box<dyn Action>,
1189        dispatch_stack: &[KeyDispatchStackFrame],
1190    ) {
1191        let action_type = action.as_any().type_id();
1192
1193        if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1194            for listener in &global_listeners {
1195                listener(action.as_ref(), DispatchPhase::Capture, self);
1196                if !self.app.propagate_event {
1197                    break;
1198                }
1199            }
1200            global_listeners.extend(
1201                self.global_action_listeners
1202                    .remove(&action_type)
1203                    .unwrap_or_default(),
1204            );
1205            self.global_action_listeners
1206                .insert(action_type, global_listeners);
1207        }
1208
1209        if self.app.propagate_event {
1210            for stack_frame in dispatch_stack {
1211                if let KeyDispatchStackFrame::Listener {
1212                    event_type,
1213                    listener,
1214                } = stack_frame
1215                {
1216                    if action_type == *event_type {
1217                        listener(action.as_any(), &[], DispatchPhase::Capture, self);
1218                        if !self.app.propagate_event {
1219                            break;
1220                        }
1221                    }
1222                }
1223            }
1224        }
1225
1226        if self.app.propagate_event {
1227            for stack_frame in dispatch_stack.iter().rev() {
1228                if let KeyDispatchStackFrame::Listener {
1229                    event_type,
1230                    listener,
1231                } = stack_frame
1232                {
1233                    if action_type == *event_type {
1234                        listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1235                        if !self.app.propagate_event {
1236                            break;
1237                        }
1238                    }
1239                }
1240            }
1241        }
1242
1243        if self.app.propagate_event {
1244            if let Some(mut global_listeners) =
1245                self.app.global_action_listeners.remove(&action_type)
1246            {
1247                for listener in global_listeners.iter().rev() {
1248                    listener(action.as_ref(), DispatchPhase::Bubble, self);
1249                    if !self.app.propagate_event {
1250                        break;
1251                    }
1252                }
1253                global_listeners.extend(
1254                    self.global_action_listeners
1255                        .remove(&action_type)
1256                        .unwrap_or_default(),
1257                );
1258                self.global_action_listeners
1259                    .insert(action_type, global_listeners);
1260            }
1261        }
1262    }
1263}
1264
1265impl Context for WindowContext<'_> {
1266    type Result<T> = T;
1267
1268    fn build_model<T>(
1269        &mut self,
1270        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1271    ) -> Model<T>
1272    where
1273        T: 'static,
1274    {
1275        let slot = self.app.entities.reserve();
1276        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1277        self.entities.insert(slot, model)
1278    }
1279
1280    fn update_model<T: 'static, R>(
1281        &mut self,
1282        model: &Model<T>,
1283        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1284    ) -> R {
1285        let mut entity = self.entities.lease(model);
1286        let result = update(
1287            &mut *entity,
1288            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1289        );
1290        self.entities.end_lease(entity);
1291        result
1292    }
1293
1294    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1295    where
1296        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1297    {
1298        if window == self.window.handle {
1299            let root_view = self.window.root_view.clone().unwrap();
1300            Ok(update(root_view, self))
1301        } else {
1302            window.update(self.app, update)
1303        }
1304    }
1305}
1306
1307impl VisualContext for WindowContext<'_> {
1308    fn build_view<V>(
1309        &mut self,
1310        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1311    ) -> Self::Result<View<V>>
1312    where
1313        V: 'static,
1314    {
1315        let slot = self.app.entities.reserve();
1316        let view = View {
1317            model: slot.clone(),
1318        };
1319        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1320        let entity = build_view_state(&mut cx);
1321        self.entities.insert(slot, entity);
1322        view
1323    }
1324
1325    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1326    fn update_view<T: 'static, R>(
1327        &mut self,
1328        view: &View<T>,
1329        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1330    ) -> Self::Result<R> {
1331        let mut lease = self.app.entities.lease(&view.model);
1332        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1333        let result = update(&mut *lease, &mut cx);
1334        cx.app.entities.end_lease(lease);
1335        result
1336    }
1337
1338    fn replace_root_view<V>(
1339        &mut self,
1340        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1341    ) -> Self::Result<View<V>>
1342    where
1343        V: Render,
1344    {
1345        let slot = self.app.entities.reserve();
1346        let view = View {
1347            model: slot.clone(),
1348        };
1349        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1350        let entity = build_view(&mut cx);
1351        self.entities.insert(slot, entity);
1352        self.window.root_view = Some(view.clone().into());
1353        view
1354    }
1355}
1356
1357impl<'a> std::ops::Deref for WindowContext<'a> {
1358    type Target = AppContext;
1359
1360    fn deref(&self) -> &Self::Target {
1361        &self.app
1362    }
1363}
1364
1365impl<'a> std::ops::DerefMut for WindowContext<'a> {
1366    fn deref_mut(&mut self) -> &mut Self::Target {
1367        &mut self.app
1368    }
1369}
1370
1371impl<'a> Borrow<AppContext> for WindowContext<'a> {
1372    fn borrow(&self) -> &AppContext {
1373        &self.app
1374    }
1375}
1376
1377impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1378    fn borrow_mut(&mut self) -> &mut AppContext {
1379        &mut self.app
1380    }
1381}
1382
1383pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1384    fn app_mut(&mut self) -> &mut AppContext {
1385        self.borrow_mut()
1386    }
1387
1388    fn window(&self) -> &Window {
1389        self.borrow()
1390    }
1391
1392    fn window_mut(&mut self) -> &mut Window {
1393        self.borrow_mut()
1394    }
1395
1396    /// Pushes the given element id onto the global stack and invokes the given closure
1397    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1398    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1399    /// used to associate state with identified elements across separate frames.
1400    fn with_element_id<R>(
1401        &mut self,
1402        id: impl Into<ElementId>,
1403        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1404    ) -> R {
1405        let keymap = self.app_mut().keymap.clone();
1406        let window = self.window_mut();
1407        window.element_id_stack.push(id.into());
1408        let global_id = window.element_id_stack.clone();
1409
1410        if window.key_matchers.get(&global_id).is_none() {
1411            window.key_matchers.insert(
1412                global_id.clone(),
1413                window
1414                    .prev_frame_key_matchers
1415                    .remove(&global_id)
1416                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1417            );
1418        }
1419
1420        let result = f(global_id, self);
1421        let window: &mut Window = self.borrow_mut();
1422        window.element_id_stack.pop();
1423        result
1424    }
1425
1426    /// Invoke the given function with the given content mask after intersecting it
1427    /// with the current mask.
1428    fn with_content_mask<R>(
1429        &mut self,
1430        mask: ContentMask<Pixels>,
1431        f: impl FnOnce(&mut Self) -> R,
1432    ) -> R {
1433        let mask = mask.intersect(&self.content_mask());
1434        self.window_mut().content_mask_stack.push(mask);
1435        let result = f(self);
1436        self.window_mut().content_mask_stack.pop();
1437        result
1438    }
1439
1440    /// Update the global element offset based on the given offset. This is used to implement
1441    /// scrolling and position drag handles.
1442    fn with_element_offset<R>(
1443        &mut self,
1444        offset: Option<Point<Pixels>>,
1445        f: impl FnOnce(&mut Self) -> R,
1446    ) -> R {
1447        let Some(offset) = offset else {
1448            return f(self);
1449        };
1450
1451        let offset = self.element_offset() + offset;
1452        self.window_mut().element_offset_stack.push(offset);
1453        let result = f(self);
1454        self.window_mut().element_offset_stack.pop();
1455        result
1456    }
1457
1458    /// Obtain the current element offset.
1459    fn element_offset(&self) -> Point<Pixels> {
1460        self.window()
1461            .element_offset_stack
1462            .last()
1463            .copied()
1464            .unwrap_or_default()
1465    }
1466
1467    /// Update or intialize state for an element with the given id that lives across multiple
1468    /// frames. If an element with this id existed in the previous frame, its state will be passed
1469    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1470    /// when drawing the next frame.
1471    fn with_element_state<S, R>(
1472        &mut self,
1473        id: ElementId,
1474        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1475    ) -> R
1476    where
1477        S: 'static,
1478    {
1479        self.with_element_id(id, |global_id, cx| {
1480            if let Some(any) = cx
1481                .window_mut()
1482                .element_states
1483                .remove(&global_id)
1484                .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1485            {
1486                // Using the extra inner option to avoid needing to reallocate a new box.
1487                let mut state_box = any
1488                    .downcast::<Option<S>>()
1489                    .expect("invalid element state type for id");
1490                let state = state_box
1491                    .take()
1492                    .expect("element state is already on the stack");
1493                let (result, state) = f(Some(state), cx);
1494                state_box.replace(state);
1495                cx.window_mut().element_states.insert(global_id, state_box);
1496                result
1497            } else {
1498                let (result, state) = f(None, cx);
1499                cx.window_mut()
1500                    .element_states
1501                    .insert(global_id, Box::new(Some(state)));
1502                result
1503            }
1504        })
1505    }
1506
1507    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1508    /// id is `None`, no state will be retrieved or stored.
1509    fn with_optional_element_state<S, R>(
1510        &mut self,
1511        element_id: Option<ElementId>,
1512        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1513    ) -> R
1514    where
1515        S: 'static,
1516    {
1517        if let Some(element_id) = element_id {
1518            self.with_element_state(element_id, f)
1519        } else {
1520            f(None, self).0
1521        }
1522    }
1523
1524    /// Obtain the current content mask.
1525    fn content_mask(&self) -> ContentMask<Pixels> {
1526        self.window()
1527            .content_mask_stack
1528            .last()
1529            .cloned()
1530            .unwrap_or_else(|| ContentMask {
1531                bounds: Bounds {
1532                    origin: Point::default(),
1533                    size: self.window().content_size,
1534                },
1535            })
1536    }
1537
1538    /// The size of an em for the base font of the application. Adjusting this value allows the
1539    /// UI to scale, just like zooming a web page.
1540    fn rem_size(&self) -> Pixels {
1541        self.window().rem_size
1542    }
1543}
1544
1545impl Borrow<Window> for WindowContext<'_> {
1546    fn borrow(&self) -> &Window {
1547        &self.window
1548    }
1549}
1550
1551impl BorrowMut<Window> for WindowContext<'_> {
1552    fn borrow_mut(&mut self) -> &mut Window {
1553        &mut self.window
1554    }
1555}
1556
1557impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1558
1559pub struct ViewContext<'a, V> {
1560    window_cx: WindowContext<'a>,
1561    view: &'a View<V>,
1562}
1563
1564impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1565    fn borrow(&self) -> &AppContext {
1566        &*self.window_cx.app
1567    }
1568}
1569
1570impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1571    fn borrow_mut(&mut self) -> &mut AppContext {
1572        &mut *self.window_cx.app
1573    }
1574}
1575
1576impl<V> Borrow<Window> for ViewContext<'_, V> {
1577    fn borrow(&self) -> &Window {
1578        &*self.window_cx.window
1579    }
1580}
1581
1582impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1583    fn borrow_mut(&mut self) -> &mut Window {
1584        &mut *self.window_cx.window
1585    }
1586}
1587
1588impl<'a, V: 'static> ViewContext<'a, V> {
1589    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1590        Self {
1591            window_cx: WindowContext::new(app, window),
1592            view,
1593        }
1594    }
1595
1596    pub fn view(&self) -> View<V> {
1597        self.view.clone()
1598    }
1599
1600    pub fn model(&self) -> Model<V> {
1601        self.view.model.clone()
1602    }
1603
1604    pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1605        self.window.z_index_stack.push(order);
1606        let result = f(self);
1607        self.window.z_index_stack.pop();
1608        result
1609    }
1610
1611    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1612    where
1613        V: 'static,
1614    {
1615        let view = self.view();
1616        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1617    }
1618
1619    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1620    /// that are currently on the stack to be returned to the app.
1621    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1622        let view = self.view().downgrade();
1623        self.window_cx.defer(move |cx| {
1624            view.update(cx, f).ok();
1625        });
1626    }
1627
1628    pub fn observe<V2, E>(
1629        &mut self,
1630        entity: &E,
1631        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1632    ) -> Subscription
1633    where
1634        V2: 'static,
1635        V: 'static,
1636        E: Entity<V2>,
1637    {
1638        let view = self.view().downgrade();
1639        let entity_id = entity.entity_id();
1640        let entity = entity.downgrade();
1641        let window_handle = self.window.handle;
1642        self.app.observers.insert(
1643            entity_id,
1644            Box::new(move |cx| {
1645                window_handle
1646                    .update(cx, |_, cx| {
1647                        if let Some(handle) = E::upgrade_from(&entity) {
1648                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1649                                .is_ok()
1650                        } else {
1651                            false
1652                        }
1653                    })
1654                    .unwrap_or(false)
1655            }),
1656        )
1657    }
1658
1659    pub fn subscribe<V2, E>(
1660        &mut self,
1661        entity: &E,
1662        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + 'static,
1663    ) -> Subscription
1664    where
1665        V2: EventEmitter,
1666        E: Entity<V2>,
1667    {
1668        let view = self.view().downgrade();
1669        let entity_id = entity.entity_id();
1670        let handle = entity.downgrade();
1671        let window_handle = self.window.handle;
1672        self.app.event_listeners.insert(
1673            entity_id,
1674            Box::new(move |event, cx| {
1675                window_handle
1676                    .update(cx, |_, cx| {
1677                        if let Some(handle) = E::upgrade_from(&handle) {
1678                            let event = event.downcast_ref().expect("invalid event type");
1679                            view.update(cx, |this, cx| on_event(this, handle, event, cx))
1680                                .is_ok()
1681                        } else {
1682                            false
1683                        }
1684                    })
1685                    .unwrap_or(false)
1686            }),
1687        )
1688    }
1689
1690    pub fn on_release(
1691        &mut self,
1692        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1693    ) -> Subscription {
1694        let window_handle = self.window.handle;
1695        self.app.release_listeners.insert(
1696            self.view.model.entity_id,
1697            Box::new(move |this, cx| {
1698                let this = this.downcast_mut().expect("invalid entity type");
1699                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1700            }),
1701        )
1702    }
1703
1704    pub fn observe_release<V2, E>(
1705        &mut self,
1706        entity: &E,
1707        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1708    ) -> Subscription
1709    where
1710        V: 'static,
1711        V2: 'static,
1712        E: Entity<V2>,
1713    {
1714        let view = self.view().downgrade();
1715        let entity_id = entity.entity_id();
1716        let window_handle = self.window.handle;
1717        self.app.release_listeners.insert(
1718            entity_id,
1719            Box::new(move |entity, cx| {
1720                let entity = entity.downcast_mut().expect("invalid entity type");
1721                let _ = window_handle.update(cx, |_, cx| {
1722                    view.update(cx, |this, cx| on_release(this, entity, cx))
1723                });
1724            }),
1725        )
1726    }
1727
1728    pub fn notify(&mut self) {
1729        self.window_cx.notify();
1730        self.window_cx.app.push_effect(Effect::Notify {
1731            emitter: self.view.model.entity_id,
1732        });
1733    }
1734
1735    pub fn observe_fullscreen(
1736        &mut self,
1737        mut callback: impl FnMut(&mut V, bool, &mut ViewContext<V>) + 'static,
1738    ) -> Subscription {
1739        let view = self.view.downgrade();
1740        self.window.fullscreen_listeners.insert(
1741            (),
1742            Box::new(move |fullscreen, cx| {
1743                view.update(cx, |view, cx| callback(view, fullscreen, cx))
1744                    .is_ok()
1745            }),
1746        )
1747    }
1748
1749    // fn observe_window_activation(&mut self) -> Subscription {}
1750
1751    // fn observe_window_bounds(&mut self) -> Subscription {}
1752
1753    pub fn on_focus_changed(
1754        &mut self,
1755        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
1756    ) {
1757        let handle = self.view().downgrade();
1758        self.window.focus_listeners.push(Box::new(move |event, cx| {
1759            handle
1760                .update(cx, |view, cx| listener(view, event, cx))
1761                .log_err();
1762        }));
1763    }
1764
1765    pub fn with_key_listeners<R>(
1766        &mut self,
1767        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1768        f: impl FnOnce(&mut Self) -> R,
1769    ) -> R {
1770        let old_stack_len = self.window.key_dispatch_stack.len();
1771        if !self.window.freeze_key_dispatch_stack {
1772            for (event_type, listener) in key_listeners {
1773                let handle = self.view().downgrade();
1774                let listener = Box::new(
1775                    move |event: &dyn Any,
1776                          context_stack: &[&DispatchContext],
1777                          phase: DispatchPhase,
1778                          cx: &mut WindowContext<'_>| {
1779                        handle
1780                            .update(cx, |view, cx| {
1781                                listener(view, event, context_stack, phase, cx)
1782                            })
1783                            .log_err()
1784                            .flatten()
1785                    },
1786                );
1787                self.window
1788                    .key_dispatch_stack
1789                    .push(KeyDispatchStackFrame::Listener {
1790                        event_type,
1791                        listener,
1792                    });
1793            }
1794        }
1795
1796        let result = f(self);
1797
1798        if !self.window.freeze_key_dispatch_stack {
1799            self.window.key_dispatch_stack.truncate(old_stack_len);
1800        }
1801
1802        result
1803    }
1804
1805    pub fn with_key_dispatch_context<R>(
1806        &mut self,
1807        context: DispatchContext,
1808        f: impl FnOnce(&mut Self) -> R,
1809    ) -> R {
1810        if context.is_empty() {
1811            return f(self);
1812        }
1813
1814        if !self.window.freeze_key_dispatch_stack {
1815            self.window
1816                .key_dispatch_stack
1817                .push(KeyDispatchStackFrame::Context(context));
1818        }
1819
1820        let result = f(self);
1821
1822        if !self.window.freeze_key_dispatch_stack {
1823            self.window.key_dispatch_stack.pop();
1824        }
1825
1826        result
1827    }
1828
1829    pub fn with_focus<R>(
1830        &mut self,
1831        focus_handle: FocusHandle,
1832        f: impl FnOnce(&mut Self) -> R,
1833    ) -> R {
1834        if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1835            self.window
1836                .focus_parents_by_child
1837                .insert(focus_handle.id, parent_focus_id);
1838        }
1839        self.window.focus_stack.push(focus_handle.id);
1840
1841        if Some(focus_handle.id) == self.window.focus {
1842            self.window.freeze_key_dispatch_stack = true;
1843        }
1844
1845        let result = f(self);
1846
1847        self.window.focus_stack.pop();
1848        result
1849    }
1850
1851    pub fn spawn<Fut, R>(
1852        &mut self,
1853        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1854    ) -> Task<R>
1855    where
1856        R: 'static,
1857        Fut: Future<Output = R> + 'static,
1858    {
1859        let view = self.view().downgrade();
1860        self.window_cx.spawn(|cx| f(view, cx))
1861    }
1862
1863    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1864    where
1865        G: 'static,
1866    {
1867        let mut global = self.app.lease_global::<G>();
1868        let result = f(&mut global, self);
1869        self.app.end_global_lease(global);
1870        result
1871    }
1872
1873    pub fn observe_global<G: 'static>(
1874        &mut self,
1875        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
1876    ) -> Subscription {
1877        let window_handle = self.window.handle;
1878        let view = self.view().downgrade();
1879        self.global_observers.insert(
1880            TypeId::of::<G>(),
1881            Box::new(move |cx| {
1882                window_handle
1883                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
1884                    .unwrap_or(false)
1885            }),
1886        )
1887    }
1888
1889    pub fn on_mouse_event<Event: 'static>(
1890        &mut self,
1891        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
1892    ) {
1893        let handle = self.view();
1894        self.window_cx.on_mouse_event(move |event, phase, cx| {
1895            handle.update(cx, |view, cx| {
1896                handler(view, event, phase, cx);
1897            })
1898        });
1899    }
1900}
1901
1902impl<V> ViewContext<'_, V>
1903where
1904    V: EventEmitter,
1905    V::Event: 'static,
1906{
1907    pub fn emit(&mut self, event: V::Event) {
1908        let emitter = self.view.model.entity_id;
1909        self.app.push_effect(Effect::Emit {
1910            emitter,
1911            event: Box::new(event),
1912        });
1913    }
1914}
1915
1916impl<V> Context for ViewContext<'_, V> {
1917    type Result<U> = U;
1918
1919    fn build_model<T: 'static>(
1920        &mut self,
1921        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1922    ) -> Model<T> {
1923        self.window_cx.build_model(build_model)
1924    }
1925
1926    fn update_model<T: 'static, R>(
1927        &mut self,
1928        model: &Model<T>,
1929        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1930    ) -> R {
1931        self.window_cx.update_model(model, update)
1932    }
1933
1934    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1935    where
1936        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1937    {
1938        self.window_cx.update_window(window, update)
1939    }
1940}
1941
1942impl<V: 'static> VisualContext for ViewContext<'_, V> {
1943    fn build_view<W: 'static>(
1944        &mut self,
1945        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
1946    ) -> Self::Result<View<W>> {
1947        self.window_cx.build_view(build_view)
1948    }
1949
1950    fn update_view<V2: 'static, R>(
1951        &mut self,
1952        view: &View<V2>,
1953        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
1954    ) -> Self::Result<R> {
1955        self.window_cx.update_view(view, update)
1956    }
1957
1958    fn replace_root_view<W>(
1959        &mut self,
1960        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
1961    ) -> Self::Result<View<W>>
1962    where
1963        W: Render,
1964    {
1965        self.window_cx.replace_root_view(build_view)
1966    }
1967}
1968
1969impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
1970    type Target = WindowContext<'a>;
1971
1972    fn deref(&self) -> &Self::Target {
1973        &self.window_cx
1974    }
1975}
1976
1977impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
1978    fn deref_mut(&mut self) -> &mut Self::Target {
1979        &mut self.window_cx
1980    }
1981}
1982
1983// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
1984slotmap::new_key_type! { pub struct WindowId; }
1985
1986impl WindowId {
1987    pub fn as_u64(&self) -> u64 {
1988        self.0.as_ffi()
1989    }
1990}
1991
1992#[derive(Deref, DerefMut)]
1993pub struct WindowHandle<V> {
1994    #[deref]
1995    #[deref_mut]
1996    pub(crate) any_handle: AnyWindowHandle,
1997    state_type: PhantomData<V>,
1998}
1999
2000impl<V: 'static + Render> WindowHandle<V> {
2001    pub fn new(id: WindowId) -> Self {
2002        WindowHandle {
2003            any_handle: AnyWindowHandle {
2004                id,
2005                state_type: TypeId::of::<V>(),
2006            },
2007            state_type: PhantomData,
2008        }
2009    }
2010
2011    pub fn update<C, R>(
2012        self,
2013        cx: &mut C,
2014        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2015    ) -> Result<R>
2016    where
2017        C: Context,
2018    {
2019        cx.update_window(self.any_handle, |root_view, cx| {
2020            let view = root_view
2021                .downcast::<V>()
2022                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2023            Ok(cx.update_view(&view, update))
2024        })?
2025    }
2026}
2027
2028impl<V> Copy for WindowHandle<V> {}
2029
2030impl<V> Clone for WindowHandle<V> {
2031    fn clone(&self) -> Self {
2032        WindowHandle {
2033            any_handle: self.any_handle,
2034            state_type: PhantomData,
2035        }
2036    }
2037}
2038
2039impl<V> PartialEq for WindowHandle<V> {
2040    fn eq(&self, other: &Self) -> bool {
2041        self.any_handle == other.any_handle
2042    }
2043}
2044
2045impl<V> Eq for WindowHandle<V> {}
2046
2047impl<V> Hash for WindowHandle<V> {
2048    fn hash<H: Hasher>(&self, state: &mut H) {
2049        self.any_handle.hash(state);
2050    }
2051}
2052
2053impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2054    fn into(self) -> AnyWindowHandle {
2055        self.any_handle
2056    }
2057}
2058
2059#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2060pub struct AnyWindowHandle {
2061    pub(crate) id: WindowId,
2062    state_type: TypeId,
2063}
2064
2065impl AnyWindowHandle {
2066    pub fn window_id(&self) -> WindowId {
2067        self.id
2068    }
2069
2070    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2071        if TypeId::of::<T>() == self.state_type {
2072            Some(WindowHandle {
2073                any_handle: *self,
2074                state_type: PhantomData,
2075            })
2076        } else {
2077            None
2078        }
2079    }
2080
2081    pub fn update<C, R>(
2082        self,
2083        cx: &mut C,
2084        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2085    ) -> Result<R>
2086    where
2087        C: Context,
2088    {
2089        cx.update_window(self, update)
2090    }
2091}
2092
2093#[cfg(any(test, feature = "test-support"))]
2094impl From<SmallVec<[u32; 16]>> for StackingOrder {
2095    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2096        StackingOrder(small_vec)
2097    }
2098}
2099
2100#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2101pub enum ElementId {
2102    View(EntityId),
2103    Number(usize),
2104    Name(SharedString),
2105    FocusHandle(FocusId),
2106}
2107
2108impl From<EntityId> for ElementId {
2109    fn from(id: EntityId) -> Self {
2110        ElementId::View(id)
2111    }
2112}
2113
2114impl From<usize> for ElementId {
2115    fn from(id: usize) -> Self {
2116        ElementId::Number(id)
2117    }
2118}
2119
2120impl From<i32> for ElementId {
2121    fn from(id: i32) -> Self {
2122        Self::Number(id as usize)
2123    }
2124}
2125
2126impl From<SharedString> for ElementId {
2127    fn from(name: SharedString) -> Self {
2128        ElementId::Name(name)
2129    }
2130}
2131
2132impl From<&'static str> for ElementId {
2133    fn from(name: &'static str) -> Self {
2134        ElementId::Name(name.into())
2135    }
2136}
2137
2138impl<'a> From<&'a FocusHandle> for ElementId {
2139    fn from(handle: &'a FocusHandle) -> Self {
2140        ElementId::FocusHandle(handle.id)
2141    }
2142}