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