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    pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1668        self.window.z_index_stack.push(order);
1669        let result = f(self);
1670        self.window.z_index_stack.pop();
1671        result
1672    }
1673
1674    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1675    where
1676        V: 'static,
1677    {
1678        let view = self.view();
1679        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1680    }
1681
1682    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1683    /// that are currently on the stack to be returned to the app.
1684    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1685        let view = self.view().downgrade();
1686        self.window_cx.defer(move |cx| {
1687            view.update(cx, f).ok();
1688        });
1689    }
1690
1691    pub fn observe<V2, E>(
1692        &mut self,
1693        entity: &E,
1694        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1695    ) -> Subscription
1696    where
1697        V2: 'static,
1698        V: 'static,
1699        E: Entity<V2>,
1700    {
1701        let view = self.view().downgrade();
1702        let entity_id = entity.entity_id();
1703        let entity = entity.downgrade();
1704        let window_handle = self.window.handle;
1705        self.app.observers.insert(
1706            entity_id,
1707            Box::new(move |cx| {
1708                window_handle
1709                    .update(cx, |_, cx| {
1710                        if let Some(handle) = E::upgrade_from(&entity) {
1711                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1712                                .is_ok()
1713                        } else {
1714                            false
1715                        }
1716                    })
1717                    .unwrap_or(false)
1718            }),
1719        )
1720    }
1721
1722    pub fn subscribe<V2, E>(
1723        &mut self,
1724        entity: &E,
1725        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + 'static,
1726    ) -> Subscription
1727    where
1728        V2: EventEmitter,
1729        E: Entity<V2>,
1730    {
1731        let view = self.view().downgrade();
1732        let entity_id = entity.entity_id();
1733        let handle = entity.downgrade();
1734        let window_handle = self.window.handle;
1735        self.app.event_listeners.insert(
1736            entity_id,
1737            Box::new(move |event, cx| {
1738                window_handle
1739                    .update(cx, |_, cx| {
1740                        if let Some(handle) = E::upgrade_from(&handle) {
1741                            let event = event.downcast_ref().expect("invalid event type");
1742                            view.update(cx, |this, cx| on_event(this, handle, event, cx))
1743                                .is_ok()
1744                        } else {
1745                            false
1746                        }
1747                    })
1748                    .unwrap_or(false)
1749            }),
1750        )
1751    }
1752
1753    pub fn on_release(
1754        &mut self,
1755        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1756    ) -> Subscription {
1757        let window_handle = self.window.handle;
1758        self.app.release_listeners.insert(
1759            self.view.model.entity_id,
1760            Box::new(move |this, cx| {
1761                let this = this.downcast_mut().expect("invalid entity type");
1762                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1763            }),
1764        )
1765    }
1766
1767    pub fn observe_release<V2, E>(
1768        &mut self,
1769        entity: &E,
1770        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1771    ) -> Subscription
1772    where
1773        V: 'static,
1774        V2: 'static,
1775        E: Entity<V2>,
1776    {
1777        let view = self.view().downgrade();
1778        let entity_id = entity.entity_id();
1779        let window_handle = self.window.handle;
1780        self.app.release_listeners.insert(
1781            entity_id,
1782            Box::new(move |entity, cx| {
1783                let entity = entity.downcast_mut().expect("invalid entity type");
1784                let _ = window_handle.update(cx, |_, cx| {
1785                    view.update(cx, |this, cx| on_release(this, entity, cx))
1786                });
1787            }),
1788        )
1789    }
1790
1791    pub fn notify(&mut self) {
1792        self.window_cx.notify();
1793        self.window_cx.app.push_effect(Effect::Notify {
1794            emitter: self.view.model.entity_id,
1795        });
1796    }
1797
1798    pub fn observe_window_bounds(
1799        &mut self,
1800        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1801    ) -> Subscription {
1802        let view = self.view.downgrade();
1803        self.window.bounds_observers.insert(
1804            (),
1805            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1806        )
1807    }
1808
1809    pub fn observe_window_activation(
1810        &mut self,
1811        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1812    ) -> Subscription {
1813        let view = self.view.downgrade();
1814        self.window.activation_observers.insert(
1815            (),
1816            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1817        )
1818    }
1819
1820    pub fn on_focus_changed(
1821        &mut self,
1822        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
1823    ) {
1824        let handle = self.view().downgrade();
1825        self.window.focus_listeners.push(Box::new(move |event, cx| {
1826            handle
1827                .update(cx, |view, cx| listener(view, event, cx))
1828                .log_err();
1829        }));
1830    }
1831
1832    pub fn with_key_listeners<R>(
1833        &mut self,
1834        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1835        f: impl FnOnce(&mut Self) -> R,
1836    ) -> R {
1837        let old_stack_len = self.window.key_dispatch_stack.len();
1838        if !self.window.freeze_key_dispatch_stack {
1839            for (event_type, listener) in key_listeners {
1840                let handle = self.view().downgrade();
1841                let listener = Box::new(
1842                    move |event: &dyn Any,
1843                          context_stack: &[&DispatchContext],
1844                          phase: DispatchPhase,
1845                          cx: &mut WindowContext<'_>| {
1846                        handle
1847                            .update(cx, |view, cx| {
1848                                listener(view, event, context_stack, phase, cx)
1849                            })
1850                            .log_err()
1851                            .flatten()
1852                    },
1853                );
1854                self.window
1855                    .key_dispatch_stack
1856                    .push(KeyDispatchStackFrame::Listener {
1857                        event_type,
1858                        listener,
1859                    });
1860            }
1861        }
1862
1863        let result = f(self);
1864
1865        if !self.window.freeze_key_dispatch_stack {
1866            self.window.key_dispatch_stack.truncate(old_stack_len);
1867        }
1868
1869        result
1870    }
1871
1872    pub fn with_key_dispatch_context<R>(
1873        &mut self,
1874        context: DispatchContext,
1875        f: impl FnOnce(&mut Self) -> R,
1876    ) -> R {
1877        if context.is_empty() {
1878            return f(self);
1879        }
1880
1881        if !self.window.freeze_key_dispatch_stack {
1882            self.window
1883                .key_dispatch_stack
1884                .push(KeyDispatchStackFrame::Context(context));
1885        }
1886
1887        let result = f(self);
1888
1889        if !self.window.freeze_key_dispatch_stack {
1890            self.window.key_dispatch_stack.pop();
1891        }
1892
1893        result
1894    }
1895
1896    pub fn with_focus<R>(
1897        &mut self,
1898        focus_handle: FocusHandle,
1899        f: impl FnOnce(&mut Self) -> R,
1900    ) -> R {
1901        if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1902            self.window
1903                .focus_parents_by_child
1904                .insert(focus_handle.id, parent_focus_id);
1905        }
1906        self.window.focus_stack.push(focus_handle.id);
1907
1908        if Some(focus_handle.id) == self.window.focus {
1909            self.window.freeze_key_dispatch_stack = true;
1910        }
1911
1912        let result = f(self);
1913
1914        self.window.focus_stack.pop();
1915        result
1916    }
1917
1918    pub fn spawn<Fut, R>(
1919        &mut self,
1920        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1921    ) -> Task<R>
1922    where
1923        R: 'static,
1924        Fut: Future<Output = R> + 'static,
1925    {
1926        let view = self.view().downgrade();
1927        self.window_cx.spawn(|cx| f(view, cx))
1928    }
1929
1930    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1931    where
1932        G: 'static,
1933    {
1934        let mut global = self.app.lease_global::<G>();
1935        let result = f(&mut global, self);
1936        self.app.end_global_lease(global);
1937        result
1938    }
1939
1940    pub fn observe_global<G: 'static>(
1941        &mut self,
1942        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
1943    ) -> Subscription {
1944        let window_handle = self.window.handle;
1945        let view = self.view().downgrade();
1946        self.global_observers.insert(
1947            TypeId::of::<G>(),
1948            Box::new(move |cx| {
1949                window_handle
1950                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
1951                    .unwrap_or(false)
1952            }),
1953        )
1954    }
1955
1956    pub fn on_mouse_event<Event: 'static>(
1957        &mut self,
1958        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
1959    ) {
1960        let handle = self.view();
1961        self.window_cx.on_mouse_event(move |event, phase, cx| {
1962            handle.update(cx, |view, cx| {
1963                handler(view, event, phase, cx);
1964            })
1965        });
1966    }
1967}
1968
1969impl<V> ViewContext<'_, V>
1970where
1971    V: EventEmitter,
1972    V::Event: 'static,
1973{
1974    pub fn emit(&mut self, event: V::Event) {
1975        let emitter = self.view.model.entity_id;
1976        self.app.push_effect(Effect::Emit {
1977            emitter,
1978            event: Box::new(event),
1979        });
1980    }
1981}
1982
1983impl<V> Context for ViewContext<'_, V> {
1984    type Result<U> = U;
1985
1986    fn build_model<T: 'static>(
1987        &mut self,
1988        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1989    ) -> Model<T> {
1990        self.window_cx.build_model(build_model)
1991    }
1992
1993    fn update_model<T: 'static, R>(
1994        &mut self,
1995        model: &Model<T>,
1996        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1997    ) -> R {
1998        self.window_cx.update_model(model, update)
1999    }
2000
2001    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2002    where
2003        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2004    {
2005        self.window_cx.update_window(window, update)
2006    }
2007}
2008
2009impl<V: 'static> VisualContext for ViewContext<'_, V> {
2010    fn build_view<W: 'static>(
2011        &mut self,
2012        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2013    ) -> Self::Result<View<W>> {
2014        self.window_cx.build_view(build_view)
2015    }
2016
2017    fn update_view<V2: 'static, R>(
2018        &mut self,
2019        view: &View<V2>,
2020        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2021    ) -> Self::Result<R> {
2022        self.window_cx.update_view(view, update)
2023    }
2024
2025    fn replace_root_view<W>(
2026        &mut self,
2027        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2028    ) -> Self::Result<View<W>>
2029    where
2030        W: Render,
2031    {
2032        self.window_cx.replace_root_view(build_view)
2033    }
2034}
2035
2036impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2037    type Target = WindowContext<'a>;
2038
2039    fn deref(&self) -> &Self::Target {
2040        &self.window_cx
2041    }
2042}
2043
2044impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2045    fn deref_mut(&mut self) -> &mut Self::Target {
2046        &mut self.window_cx
2047    }
2048}
2049
2050// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2051slotmap::new_key_type! { pub struct WindowId; }
2052
2053impl WindowId {
2054    pub fn as_u64(&self) -> u64 {
2055        self.0.as_ffi()
2056    }
2057}
2058
2059#[derive(Deref, DerefMut)]
2060pub struct WindowHandle<V> {
2061    #[deref]
2062    #[deref_mut]
2063    pub(crate) any_handle: AnyWindowHandle,
2064    state_type: PhantomData<V>,
2065}
2066
2067impl<V: 'static + Render> WindowHandle<V> {
2068    pub fn new(id: WindowId) -> Self {
2069        WindowHandle {
2070            any_handle: AnyWindowHandle {
2071                id,
2072                state_type: TypeId::of::<V>(),
2073            },
2074            state_type: PhantomData,
2075        }
2076    }
2077
2078    pub fn update<C, R>(
2079        self,
2080        cx: &mut C,
2081        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2082    ) -> Result<R>
2083    where
2084        C: Context,
2085    {
2086        cx.update_window(self.any_handle, |root_view, cx| {
2087            let view = root_view
2088                .downcast::<V>()
2089                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2090            Ok(cx.update_view(&view, update))
2091        })?
2092    }
2093}
2094
2095impl<V> Copy for WindowHandle<V> {}
2096
2097impl<V> Clone for WindowHandle<V> {
2098    fn clone(&self) -> Self {
2099        WindowHandle {
2100            any_handle: self.any_handle,
2101            state_type: PhantomData,
2102        }
2103    }
2104}
2105
2106impl<V> PartialEq for WindowHandle<V> {
2107    fn eq(&self, other: &Self) -> bool {
2108        self.any_handle == other.any_handle
2109    }
2110}
2111
2112impl<V> Eq for WindowHandle<V> {}
2113
2114impl<V> Hash for WindowHandle<V> {
2115    fn hash<H: Hasher>(&self, state: &mut H) {
2116        self.any_handle.hash(state);
2117    }
2118}
2119
2120impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2121    fn into(self) -> AnyWindowHandle {
2122        self.any_handle
2123    }
2124}
2125
2126#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2127pub struct AnyWindowHandle {
2128    pub(crate) id: WindowId,
2129    state_type: TypeId,
2130}
2131
2132impl AnyWindowHandle {
2133    pub fn window_id(&self) -> WindowId {
2134        self.id
2135    }
2136
2137    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2138        if TypeId::of::<T>() == self.state_type {
2139            Some(WindowHandle {
2140                any_handle: *self,
2141                state_type: PhantomData,
2142            })
2143        } else {
2144            None
2145        }
2146    }
2147
2148    pub fn update<C, R>(
2149        self,
2150        cx: &mut C,
2151        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2152    ) -> Result<R>
2153    where
2154        C: Context,
2155    {
2156        cx.update_window(self, update)
2157    }
2158}
2159
2160#[cfg(any(test, feature = "test-support"))]
2161impl From<SmallVec<[u32; 16]>> for StackingOrder {
2162    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2163        StackingOrder(small_vec)
2164    }
2165}
2166
2167#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2168pub enum ElementId {
2169    View(EntityId),
2170    Number(usize),
2171    Name(SharedString),
2172    FocusHandle(FocusId),
2173}
2174
2175impl From<EntityId> for ElementId {
2176    fn from(id: EntityId) -> Self {
2177        ElementId::View(id)
2178    }
2179}
2180
2181impl From<usize> for ElementId {
2182    fn from(id: usize) -> Self {
2183        ElementId::Number(id)
2184    }
2185}
2186
2187impl From<i32> for ElementId {
2188    fn from(id: i32) -> Self {
2189        Self::Number(id as usize)
2190    }
2191}
2192
2193impl From<SharedString> for ElementId {
2194    fn from(name: SharedString) -> Self {
2195        ElementId::Name(name)
2196    }
2197}
2198
2199impl From<&'static str> for ElementId {
2200    fn from(name: &'static str) -> Self {
2201        ElementId::Name(name.into())
2202    }
2203}
2204
2205impl<'a> From<&'a FocusHandle> for ElementId {
2206    fn from(handle: &'a FocusHandle) -> Self {
2207        ElementId::FocusHandle(handle.id)
2208    }
2209}