window.rs

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