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        }
 991
 992        self.window.root_view = Some(root_view);
 993        let scene = self.window.scene_builder.build();
 994
 995        self.window.platform_window.draw(scene);
 996        let cursor_style = self
 997            .window
 998            .requested_cursor_style
 999            .take()
1000            .unwrap_or(CursorStyle::Arrow);
1001        self.platform.set_cursor_style(cursor_style);
1002
1003        self.window.dirty = false;
1004    }
1005
1006    fn start_frame(&mut self) {
1007        self.text_system().start_frame();
1008
1009        let window = &mut *self.window;
1010
1011        // Move the current frame element states to the previous frame.
1012        // The new empty element states map will be populated for any element states we
1013        // reference during the upcoming frame.
1014        mem::swap(
1015            &mut window.element_states,
1016            &mut window.prev_frame_element_states,
1017        );
1018        window.element_states.clear();
1019
1020        // Make the current key matchers the previous, and then clear the current.
1021        // An empty key matcher map will be created for every identified element in the
1022        // upcoming frame.
1023        mem::swap(
1024            &mut window.key_matchers,
1025            &mut window.prev_frame_key_matchers,
1026        );
1027        window.key_matchers.clear();
1028
1029        // Clear mouse event listeners, because elements add new element listeners
1030        // when the upcoming frame is painted.
1031        window.mouse_listeners.values_mut().for_each(Vec::clear);
1032
1033        // Clear focus state, because we determine what is focused when the new elements
1034        // in the upcoming frame are initialized.
1035        window.focus_listeners.clear();
1036        window.key_dispatch_stack.clear();
1037        window.focus_parents_by_child.clear();
1038        window.freeze_key_dispatch_stack = false;
1039    }
1040
1041    /// Dispatch a mouse or keyboard event on the window.
1042    fn dispatch_event(&mut self, event: InputEvent) -> bool {
1043        let event = match event {
1044            // Track the mouse position with our own state, since accessing the platform
1045            // API for the mouse position can only occur on the main thread.
1046            InputEvent::MouseMove(mouse_move) => {
1047                self.window.mouse_position = mouse_move.position;
1048                InputEvent::MouseMove(mouse_move)
1049            }
1050            // Translate dragging and dropping of external files from the operating system
1051            // to internal drag and drop events.
1052            InputEvent::FileDrop(file_drop) => match file_drop {
1053                FileDropEvent::Entered { position, files } => {
1054                    self.window.mouse_position = position;
1055                    if self.active_drag.is_none() {
1056                        self.active_drag = Some(AnyDrag {
1057                            view: self.build_view(|_| files).into(),
1058                            cursor_offset: position,
1059                        });
1060                    }
1061                    InputEvent::MouseDown(MouseDownEvent {
1062                        position,
1063                        button: MouseButton::Left,
1064                        click_count: 1,
1065                        modifiers: Modifiers::default(),
1066                    })
1067                }
1068                FileDropEvent::Pending { position } => {
1069                    self.window.mouse_position = position;
1070                    InputEvent::MouseMove(MouseMoveEvent {
1071                        position,
1072                        pressed_button: Some(MouseButton::Left),
1073                        modifiers: Modifiers::default(),
1074                    })
1075                }
1076                FileDropEvent::Submit { position } => {
1077                    self.window.mouse_position = position;
1078                    InputEvent::MouseUp(MouseUpEvent {
1079                        button: MouseButton::Left,
1080                        position,
1081                        modifiers: Modifiers::default(),
1082                        click_count: 1,
1083                    })
1084                }
1085                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1086                    button: MouseButton::Left,
1087                    position: Point::default(),
1088                    modifiers: Modifiers::default(),
1089                    click_count: 1,
1090                }),
1091            },
1092            _ => event,
1093        };
1094
1095        if let Some(any_mouse_event) = event.mouse_event() {
1096            // Handlers may set this to false by calling `stop_propagation`
1097            self.app.propagate_event = true;
1098            self.window.default_prevented = false;
1099
1100            if let Some(mut handlers) = self
1101                .window
1102                .mouse_listeners
1103                .remove(&any_mouse_event.type_id())
1104            {
1105                // Because handlers may add other handlers, we sort every time.
1106                handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1107
1108                // Capture phase, events bubble from back to front. Handlers for this phase are used for
1109                // special purposes, such as detecting events outside of a given Bounds.
1110                for (_, handler) in &handlers {
1111                    handler(any_mouse_event, DispatchPhase::Capture, self);
1112                    if !self.app.propagate_event {
1113                        break;
1114                    }
1115                }
1116
1117                // Bubble phase, where most normal handlers do their work.
1118                if self.app.propagate_event {
1119                    for (_, handler) in handlers.iter().rev() {
1120                        handler(any_mouse_event, DispatchPhase::Bubble, self);
1121                        if !self.app.propagate_event {
1122                            break;
1123                        }
1124                    }
1125                }
1126
1127                if self.app.propagate_event
1128                    && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1129                {
1130                    self.active_drag = None;
1131                }
1132
1133                // Just in case any handlers added new handlers, which is weird, but possible.
1134                handlers.extend(
1135                    self.window
1136                        .mouse_listeners
1137                        .get_mut(&any_mouse_event.type_id())
1138                        .into_iter()
1139                        .flat_map(|handlers| handlers.drain(..)),
1140                );
1141                self.window
1142                    .mouse_listeners
1143                    .insert(any_mouse_event.type_id(), handlers);
1144            }
1145        } else if let Some(any_key_event) = event.keyboard_event() {
1146            let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1147            let key_event_type = any_key_event.type_id();
1148            let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1149
1150            for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1151                match frame {
1152                    KeyDispatchStackFrame::Listener {
1153                        event_type,
1154                        listener,
1155                    } => {
1156                        if key_event_type == *event_type {
1157                            if let Some(action) = listener(
1158                                any_key_event,
1159                                &context_stack,
1160                                DispatchPhase::Capture,
1161                                self,
1162                            ) {
1163                                self.dispatch_action(action, &key_dispatch_stack[..ix]);
1164                            }
1165                            if !self.app.propagate_event {
1166                                break;
1167                            }
1168                        }
1169                    }
1170                    KeyDispatchStackFrame::Context(context) => {
1171                        context_stack.push(&context);
1172                    }
1173                }
1174            }
1175
1176            if self.app.propagate_event {
1177                for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1178                    match frame {
1179                        KeyDispatchStackFrame::Listener {
1180                            event_type,
1181                            listener,
1182                        } => {
1183                            if key_event_type == *event_type {
1184                                if let Some(action) = listener(
1185                                    any_key_event,
1186                                    &context_stack,
1187                                    DispatchPhase::Bubble,
1188                                    self,
1189                                ) {
1190                                    self.dispatch_action(action, &key_dispatch_stack[..ix]);
1191                                }
1192
1193                                if !self.app.propagate_event {
1194                                    break;
1195                                }
1196                            }
1197                        }
1198                        KeyDispatchStackFrame::Context(_) => {
1199                            context_stack.pop();
1200                        }
1201                    }
1202                }
1203            }
1204
1205            drop(context_stack);
1206            self.window.key_dispatch_stack = key_dispatch_stack;
1207        }
1208
1209        true
1210    }
1211
1212    /// Attempt to map a keystroke to an action based on the keymap.
1213    pub fn match_keystroke(
1214        &mut self,
1215        element_id: &GlobalElementId,
1216        keystroke: &Keystroke,
1217        context_stack: &[&DispatchContext],
1218    ) -> KeyMatch {
1219        let key_match = self
1220            .window
1221            .key_matchers
1222            .get_mut(element_id)
1223            .unwrap()
1224            .match_keystroke(keystroke, context_stack);
1225
1226        if key_match.is_some() {
1227            for matcher in self.window.key_matchers.values_mut() {
1228                matcher.clear_pending();
1229            }
1230        }
1231
1232        key_match
1233    }
1234
1235    /// Register the given handler to be invoked whenever the global of the given type
1236    /// is updated.
1237    pub fn observe_global<G: 'static>(
1238        &mut self,
1239        f: impl Fn(&mut WindowContext<'_>) + 'static,
1240    ) -> Subscription {
1241        let window_handle = self.window.handle;
1242        self.global_observers.insert(
1243            TypeId::of::<G>(),
1244            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1245        )
1246    }
1247
1248    pub fn activate_window(&self) {
1249        self.window.platform_window.activate();
1250    }
1251
1252    pub fn prompt(
1253        &self,
1254        level: PromptLevel,
1255        msg: &str,
1256        answers: &[&str],
1257    ) -> oneshot::Receiver<usize> {
1258        self.window.platform_window.prompt(level, msg, answers)
1259    }
1260
1261    fn dispatch_action(
1262        &mut self,
1263        action: Box<dyn Action>,
1264        dispatch_stack: &[KeyDispatchStackFrame],
1265    ) {
1266        let action_type = action.as_any().type_id();
1267
1268        if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1269            for listener in &global_listeners {
1270                listener(action.as_ref(), DispatchPhase::Capture, self);
1271                if !self.app.propagate_event {
1272                    break;
1273                }
1274            }
1275            global_listeners.extend(
1276                self.global_action_listeners
1277                    .remove(&action_type)
1278                    .unwrap_or_default(),
1279            );
1280            self.global_action_listeners
1281                .insert(action_type, global_listeners);
1282        }
1283
1284        if self.app.propagate_event {
1285            for stack_frame in dispatch_stack {
1286                if let KeyDispatchStackFrame::Listener {
1287                    event_type,
1288                    listener,
1289                } = stack_frame
1290                {
1291                    if action_type == *event_type {
1292                        listener(action.as_any(), &[], DispatchPhase::Capture, self);
1293                        if !self.app.propagate_event {
1294                            break;
1295                        }
1296                    }
1297                }
1298            }
1299        }
1300
1301        if self.app.propagate_event {
1302            for stack_frame in dispatch_stack.iter().rev() {
1303                if let KeyDispatchStackFrame::Listener {
1304                    event_type,
1305                    listener,
1306                } = stack_frame
1307                {
1308                    if action_type == *event_type {
1309                        listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1310                        if !self.app.propagate_event {
1311                            break;
1312                        }
1313                    }
1314                }
1315            }
1316        }
1317
1318        if self.app.propagate_event {
1319            if let Some(mut global_listeners) =
1320                self.app.global_action_listeners.remove(&action_type)
1321            {
1322                for listener in global_listeners.iter().rev() {
1323                    listener(action.as_ref(), DispatchPhase::Bubble, self);
1324                    if !self.app.propagate_event {
1325                        break;
1326                    }
1327                }
1328                global_listeners.extend(
1329                    self.global_action_listeners
1330                        .remove(&action_type)
1331                        .unwrap_or_default(),
1332                );
1333                self.global_action_listeners
1334                    .insert(action_type, global_listeners);
1335            }
1336        }
1337    }
1338}
1339
1340impl Context for WindowContext<'_> {
1341    type Result<T> = T;
1342
1343    fn build_model<T>(
1344        &mut self,
1345        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1346    ) -> Model<T>
1347    where
1348        T: 'static,
1349    {
1350        let slot = self.app.entities.reserve();
1351        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1352        self.entities.insert(slot, model)
1353    }
1354
1355    fn update_model<T: 'static, R>(
1356        &mut self,
1357        model: &Model<T>,
1358        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1359    ) -> R {
1360        let mut entity = self.entities.lease(model);
1361        let result = update(
1362            &mut *entity,
1363            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1364        );
1365        self.entities.end_lease(entity);
1366        result
1367    }
1368
1369    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1370    where
1371        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1372    {
1373        if window == self.window.handle {
1374            let root_view = self.window.root_view.clone().unwrap();
1375            Ok(update(root_view, self))
1376        } else {
1377            window.update(self.app, update)
1378        }
1379    }
1380}
1381
1382impl VisualContext for WindowContext<'_> {
1383    fn build_view<V>(
1384        &mut self,
1385        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1386    ) -> Self::Result<View<V>>
1387    where
1388        V: 'static,
1389    {
1390        let slot = self.app.entities.reserve();
1391        let view = View {
1392            model: slot.clone(),
1393        };
1394        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1395        let entity = build_view_state(&mut cx);
1396        self.entities.insert(slot, entity);
1397        view
1398    }
1399
1400    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1401    fn update_view<T: 'static, R>(
1402        &mut self,
1403        view: &View<T>,
1404        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1405    ) -> Self::Result<R> {
1406        let mut lease = self.app.entities.lease(&view.model);
1407        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1408        let result = update(&mut *lease, &mut cx);
1409        cx.app.entities.end_lease(lease);
1410        result
1411    }
1412
1413    fn replace_root_view<V>(
1414        &mut self,
1415        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1416    ) -> Self::Result<View<V>>
1417    where
1418        V: Render,
1419    {
1420        let slot = self.app.entities.reserve();
1421        let view = View {
1422            model: slot.clone(),
1423        };
1424        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1425        let entity = build_view(&mut cx);
1426        self.entities.insert(slot, entity);
1427        self.window.root_view = Some(view.clone().into());
1428        view
1429    }
1430}
1431
1432impl<'a> std::ops::Deref for WindowContext<'a> {
1433    type Target = AppContext;
1434
1435    fn deref(&self) -> &Self::Target {
1436        &self.app
1437    }
1438}
1439
1440impl<'a> std::ops::DerefMut for WindowContext<'a> {
1441    fn deref_mut(&mut self) -> &mut Self::Target {
1442        &mut self.app
1443    }
1444}
1445
1446impl<'a> Borrow<AppContext> for WindowContext<'a> {
1447    fn borrow(&self) -> &AppContext {
1448        &self.app
1449    }
1450}
1451
1452impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1453    fn borrow_mut(&mut self) -> &mut AppContext {
1454        &mut self.app
1455    }
1456}
1457
1458pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1459    fn app_mut(&mut self) -> &mut AppContext {
1460        self.borrow_mut()
1461    }
1462
1463    fn window(&self) -> &Window {
1464        self.borrow()
1465    }
1466
1467    fn window_mut(&mut self) -> &mut Window {
1468        self.borrow_mut()
1469    }
1470
1471    /// Pushes the given element id onto the global stack and invokes the given closure
1472    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1473    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1474    /// used to associate state with identified elements across separate frames.
1475    fn with_element_id<R>(
1476        &mut self,
1477        id: impl Into<ElementId>,
1478        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1479    ) -> R {
1480        let keymap = self.app_mut().keymap.clone();
1481        let window = self.window_mut();
1482        window.element_id_stack.push(id.into());
1483        let global_id = window.element_id_stack.clone();
1484
1485        if window.key_matchers.get(&global_id).is_none() {
1486            window.key_matchers.insert(
1487                global_id.clone(),
1488                window
1489                    .prev_frame_key_matchers
1490                    .remove(&global_id)
1491                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1492            );
1493        }
1494
1495        let result = f(global_id, self);
1496        let window: &mut Window = self.borrow_mut();
1497        window.element_id_stack.pop();
1498        result
1499    }
1500
1501    /// Invoke the given function with the given content mask after intersecting it
1502    /// with the current mask.
1503    fn with_content_mask<R>(
1504        &mut self,
1505        mask: ContentMask<Pixels>,
1506        f: impl FnOnce(&mut Self) -> R,
1507    ) -> R {
1508        let mask = mask.intersect(&self.content_mask());
1509        self.window_mut().content_mask_stack.push(mask);
1510        let result = f(self);
1511        self.window_mut().content_mask_stack.pop();
1512        result
1513    }
1514
1515    /// Update the global element offset based on the given offset. This is used to implement
1516    /// scrolling and position drag handles.
1517    fn with_element_offset<R>(
1518        &mut self,
1519        offset: Option<Point<Pixels>>,
1520        f: impl FnOnce(&mut Self) -> R,
1521    ) -> R {
1522        let Some(offset) = offset else {
1523            return f(self);
1524        };
1525
1526        let offset = self.element_offset() + offset;
1527        self.window_mut().element_offset_stack.push(offset);
1528        let result = f(self);
1529        self.window_mut().element_offset_stack.pop();
1530        result
1531    }
1532
1533    /// Obtain the current element offset.
1534    fn element_offset(&self) -> Point<Pixels> {
1535        self.window()
1536            .element_offset_stack
1537            .last()
1538            .copied()
1539            .unwrap_or_default()
1540    }
1541
1542    /// Update or intialize state for an element with the given id that lives across multiple
1543    /// frames. If an element with this id existed in the previous frame, its state will be passed
1544    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1545    /// when drawing the next frame.
1546    fn with_element_state<S, R>(
1547        &mut self,
1548        id: ElementId,
1549        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1550    ) -> R
1551    where
1552        S: 'static,
1553    {
1554        self.with_element_id(id, |global_id, cx| {
1555            if let Some(any) = cx
1556                .window_mut()
1557                .element_states
1558                .remove(&global_id)
1559                .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1560            {
1561                // Using the extra inner option to avoid needing to reallocate a new box.
1562                let mut state_box = any
1563                    .downcast::<Option<S>>()
1564                    .expect("invalid element state type for id");
1565                let state = state_box
1566                    .take()
1567                    .expect("element state is already on the stack");
1568                let (result, state) = f(Some(state), cx);
1569                state_box.replace(state);
1570                cx.window_mut().element_states.insert(global_id, state_box);
1571                result
1572            } else {
1573                let (result, state) = f(None, cx);
1574                cx.window_mut()
1575                    .element_states
1576                    .insert(global_id, Box::new(Some(state)));
1577                result
1578            }
1579        })
1580    }
1581
1582    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1583    /// id is `None`, no state will be retrieved or stored.
1584    fn with_optional_element_state<S, R>(
1585        &mut self,
1586        element_id: Option<ElementId>,
1587        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1588    ) -> R
1589    where
1590        S: 'static,
1591    {
1592        if let Some(element_id) = element_id {
1593            self.with_element_state(element_id, f)
1594        } else {
1595            f(None, self).0
1596        }
1597    }
1598
1599    /// Obtain the current content mask.
1600    fn content_mask(&self) -> ContentMask<Pixels> {
1601        self.window()
1602            .content_mask_stack
1603            .last()
1604            .cloned()
1605            .unwrap_or_else(|| ContentMask {
1606                bounds: Bounds {
1607                    origin: Point::default(),
1608                    size: self.window().content_size,
1609                },
1610            })
1611    }
1612
1613    /// The size of an em for the base font of the application. Adjusting this value allows the
1614    /// UI to scale, just like zooming a web page.
1615    fn rem_size(&self) -> Pixels {
1616        self.window().rem_size
1617    }
1618}
1619
1620impl Borrow<Window> for WindowContext<'_> {
1621    fn borrow(&self) -> &Window {
1622        &self.window
1623    }
1624}
1625
1626impl BorrowMut<Window> for WindowContext<'_> {
1627    fn borrow_mut(&mut self) -> &mut Window {
1628        &mut self.window
1629    }
1630}
1631
1632impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1633
1634pub struct ViewContext<'a, V> {
1635    window_cx: WindowContext<'a>,
1636    view: &'a View<V>,
1637}
1638
1639impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1640    fn borrow(&self) -> &AppContext {
1641        &*self.window_cx.app
1642    }
1643}
1644
1645impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1646    fn borrow_mut(&mut self) -> &mut AppContext {
1647        &mut *self.window_cx.app
1648    }
1649}
1650
1651impl<V> Borrow<Window> for ViewContext<'_, V> {
1652    fn borrow(&self) -> &Window {
1653        &*self.window_cx.window
1654    }
1655}
1656
1657impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1658    fn borrow_mut(&mut self) -> &mut Window {
1659        &mut *self.window_cx.window
1660    }
1661}
1662
1663impl<'a, V: 'static> ViewContext<'a, V> {
1664    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1665        Self {
1666            window_cx: WindowContext::new(app, window),
1667            view,
1668        }
1669    }
1670
1671    // todo!("change this to return a reference");
1672    pub fn view(&self) -> View<V> {
1673        self.view.clone()
1674    }
1675
1676    pub fn model(&self) -> Model<V> {
1677        self.view.model.clone()
1678    }
1679
1680    /// Access the underlying window context.
1681    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1682        &mut self.window_cx
1683    }
1684
1685    pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1686        self.window.z_index_stack.push(order);
1687        let result = f(self);
1688        self.window.z_index_stack.pop();
1689        result
1690    }
1691
1692    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1693    where
1694        V: 'static,
1695    {
1696        let view = self.view();
1697        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1698    }
1699
1700    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1701    /// that are currently on the stack to be returned to the app.
1702    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1703        let view = self.view().downgrade();
1704        self.window_cx.defer(move |cx| {
1705            view.update(cx, f).ok();
1706        });
1707    }
1708
1709    pub fn observe<V2, E>(
1710        &mut self,
1711        entity: &E,
1712        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1713    ) -> Subscription
1714    where
1715        V2: 'static,
1716        V: 'static,
1717        E: Entity<V2>,
1718    {
1719        let view = self.view().downgrade();
1720        let entity_id = entity.entity_id();
1721        let entity = entity.downgrade();
1722        let window_handle = self.window.handle;
1723        self.app.observers.insert(
1724            entity_id,
1725            Box::new(move |cx| {
1726                window_handle
1727                    .update(cx, |_, cx| {
1728                        if let Some(handle) = E::upgrade_from(&entity) {
1729                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1730                                .is_ok()
1731                        } else {
1732                            false
1733                        }
1734                    })
1735                    .unwrap_or(false)
1736            }),
1737        )
1738    }
1739
1740    pub fn subscribe<V2, E>(
1741        &mut self,
1742        entity: &E,
1743        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + 'static,
1744    ) -> Subscription
1745    where
1746        V2: EventEmitter,
1747        E: Entity<V2>,
1748    {
1749        let view = self.view().downgrade();
1750        let entity_id = entity.entity_id();
1751        let handle = entity.downgrade();
1752        let window_handle = self.window.handle;
1753        self.app.event_listeners.insert(
1754            entity_id,
1755            Box::new(move |event, cx| {
1756                window_handle
1757                    .update(cx, |_, cx| {
1758                        if let Some(handle) = E::upgrade_from(&handle) {
1759                            let event = event.downcast_ref().expect("invalid event type");
1760                            view.update(cx, |this, cx| on_event(this, handle, event, cx))
1761                                .is_ok()
1762                        } else {
1763                            false
1764                        }
1765                    })
1766                    .unwrap_or(false)
1767            }),
1768        )
1769    }
1770
1771    pub fn on_release(
1772        &mut self,
1773        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1774    ) -> Subscription {
1775        let window_handle = self.window.handle;
1776        self.app.release_listeners.insert(
1777            self.view.model.entity_id,
1778            Box::new(move |this, cx| {
1779                let this = this.downcast_mut().expect("invalid entity type");
1780                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1781            }),
1782        )
1783    }
1784
1785    pub fn observe_release<V2, E>(
1786        &mut self,
1787        entity: &E,
1788        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1789    ) -> Subscription
1790    where
1791        V: 'static,
1792        V2: 'static,
1793        E: Entity<V2>,
1794    {
1795        let view = self.view().downgrade();
1796        let entity_id = entity.entity_id();
1797        let window_handle = self.window.handle;
1798        self.app.release_listeners.insert(
1799            entity_id,
1800            Box::new(move |entity, cx| {
1801                let entity = entity.downcast_mut().expect("invalid entity type");
1802                let _ = window_handle.update(cx, |_, cx| {
1803                    view.update(cx, |this, cx| on_release(this, entity, cx))
1804                });
1805            }),
1806        )
1807    }
1808
1809    pub fn notify(&mut self) {
1810        self.window_cx.notify();
1811        self.window_cx.app.push_effect(Effect::Notify {
1812            emitter: self.view.model.entity_id,
1813        });
1814    }
1815
1816    pub fn observe_window_bounds(
1817        &mut self,
1818        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1819    ) -> Subscription {
1820        let view = self.view.downgrade();
1821        self.window.bounds_observers.insert(
1822            (),
1823            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1824        )
1825    }
1826
1827    pub fn observe_window_activation(
1828        &mut self,
1829        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1830    ) -> Subscription {
1831        let view = self.view.downgrade();
1832        self.window.activation_observers.insert(
1833            (),
1834            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1835        )
1836    }
1837
1838    pub fn on_focus_changed(
1839        &mut self,
1840        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
1841    ) {
1842        let handle = self.view().downgrade();
1843        self.window.focus_listeners.push(Box::new(move |event, cx| {
1844            handle
1845                .update(cx, |view, cx| listener(view, event, cx))
1846                .log_err();
1847        }));
1848    }
1849
1850    pub fn with_key_listeners<R>(
1851        &mut self,
1852        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1853        f: impl FnOnce(&mut Self) -> R,
1854    ) -> R {
1855        let old_stack_len = self.window.key_dispatch_stack.len();
1856        if !self.window.freeze_key_dispatch_stack {
1857            for (event_type, listener) in key_listeners {
1858                let handle = self.view().downgrade();
1859                let listener = Box::new(
1860                    move |event: &dyn Any,
1861                          context_stack: &[&DispatchContext],
1862                          phase: DispatchPhase,
1863                          cx: &mut WindowContext<'_>| {
1864                        handle
1865                            .update(cx, |view, cx| {
1866                                listener(view, event, context_stack, phase, cx)
1867                            })
1868                            .log_err()
1869                            .flatten()
1870                    },
1871                );
1872                self.window
1873                    .key_dispatch_stack
1874                    .push(KeyDispatchStackFrame::Listener {
1875                        event_type,
1876                        listener,
1877                    });
1878            }
1879        }
1880
1881        let result = f(self);
1882
1883        if !self.window.freeze_key_dispatch_stack {
1884            self.window.key_dispatch_stack.truncate(old_stack_len);
1885        }
1886
1887        result
1888    }
1889
1890    pub fn with_key_dispatch_context<R>(
1891        &mut self,
1892        context: DispatchContext,
1893        f: impl FnOnce(&mut Self) -> R,
1894    ) -> R {
1895        if context.is_empty() {
1896            return f(self);
1897        }
1898
1899        if !self.window.freeze_key_dispatch_stack {
1900            self.window
1901                .key_dispatch_stack
1902                .push(KeyDispatchStackFrame::Context(context));
1903        }
1904
1905        let result = f(self);
1906
1907        if !self.window.freeze_key_dispatch_stack {
1908            self.window.key_dispatch_stack.pop();
1909        }
1910
1911        result
1912    }
1913
1914    pub fn with_focus<R>(
1915        &mut self,
1916        focus_handle: FocusHandle,
1917        f: impl FnOnce(&mut Self) -> R,
1918    ) -> R {
1919        if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1920            self.window
1921                .focus_parents_by_child
1922                .insert(focus_handle.id, parent_focus_id);
1923        }
1924        self.window.focus_stack.push(focus_handle.id);
1925
1926        if Some(focus_handle.id) == self.window.focus {
1927            self.window.freeze_key_dispatch_stack = true;
1928        }
1929
1930        let result = f(self);
1931
1932        self.window.focus_stack.pop();
1933        result
1934    }
1935
1936    pub fn spawn<Fut, R>(
1937        &mut self,
1938        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1939    ) -> Task<R>
1940    where
1941        R: 'static,
1942        Fut: Future<Output = R> + 'static,
1943    {
1944        let view = self.view().downgrade();
1945        self.window_cx.spawn(|cx| f(view, cx))
1946    }
1947
1948    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1949    where
1950        G: 'static,
1951    {
1952        let mut global = self.app.lease_global::<G>();
1953        let result = f(&mut global, self);
1954        self.app.end_global_lease(global);
1955        result
1956    }
1957
1958    pub fn observe_global<G: 'static>(
1959        &mut self,
1960        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
1961    ) -> Subscription {
1962        let window_handle = self.window.handle;
1963        let view = self.view().downgrade();
1964        self.global_observers.insert(
1965            TypeId::of::<G>(),
1966            Box::new(move |cx| {
1967                window_handle
1968                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
1969                    .unwrap_or(false)
1970            }),
1971        )
1972    }
1973
1974    pub fn on_mouse_event<Event: 'static>(
1975        &mut self,
1976        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
1977    ) {
1978        let handle = self.view();
1979        self.window_cx.on_mouse_event(move |event, phase, cx| {
1980            handle.update(cx, |view, cx| {
1981                handler(view, event, phase, cx);
1982            })
1983        });
1984    }
1985}
1986
1987impl<V> ViewContext<'_, V>
1988where
1989    V: EventEmitter,
1990    V::Event: 'static,
1991{
1992    pub fn emit(&mut self, event: V::Event) {
1993        let emitter = self.view.model.entity_id;
1994        self.app.push_effect(Effect::Emit {
1995            emitter,
1996            event: Box::new(event),
1997        });
1998    }
1999}
2000
2001impl<V> Context for ViewContext<'_, V> {
2002    type Result<U> = U;
2003
2004    fn build_model<T: 'static>(
2005        &mut self,
2006        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2007    ) -> Model<T> {
2008        self.window_cx.build_model(build_model)
2009    }
2010
2011    fn update_model<T: 'static, R>(
2012        &mut self,
2013        model: &Model<T>,
2014        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2015    ) -> R {
2016        self.window_cx.update_model(model, update)
2017    }
2018
2019    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2020    where
2021        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2022    {
2023        self.window_cx.update_window(window, update)
2024    }
2025}
2026
2027impl<V: 'static> VisualContext for ViewContext<'_, V> {
2028    fn build_view<W: 'static>(
2029        &mut self,
2030        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2031    ) -> Self::Result<View<W>> {
2032        self.window_cx.build_view(build_view)
2033    }
2034
2035    fn update_view<V2: 'static, R>(
2036        &mut self,
2037        view: &View<V2>,
2038        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2039    ) -> Self::Result<R> {
2040        self.window_cx.update_view(view, update)
2041    }
2042
2043    fn replace_root_view<W>(
2044        &mut self,
2045        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2046    ) -> Self::Result<View<W>>
2047    where
2048        W: Render,
2049    {
2050        self.window_cx.replace_root_view(build_view)
2051    }
2052}
2053
2054impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2055    type Target = WindowContext<'a>;
2056
2057    fn deref(&self) -> &Self::Target {
2058        &self.window_cx
2059    }
2060}
2061
2062impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2063    fn deref_mut(&mut self) -> &mut Self::Target {
2064        &mut self.window_cx
2065    }
2066}
2067
2068// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2069slotmap::new_key_type! { pub struct WindowId; }
2070
2071impl WindowId {
2072    pub fn as_u64(&self) -> u64 {
2073        self.0.as_ffi()
2074    }
2075}
2076
2077#[derive(Deref, DerefMut)]
2078pub struct WindowHandle<V> {
2079    #[deref]
2080    #[deref_mut]
2081    pub(crate) any_handle: AnyWindowHandle,
2082    state_type: PhantomData<V>,
2083}
2084
2085impl<V: 'static + Render> WindowHandle<V> {
2086    pub fn new(id: WindowId) -> Self {
2087        WindowHandle {
2088            any_handle: AnyWindowHandle {
2089                id,
2090                state_type: TypeId::of::<V>(),
2091            },
2092            state_type: PhantomData,
2093        }
2094    }
2095
2096    pub fn update<C, R>(
2097        self,
2098        cx: &mut C,
2099        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2100    ) -> Result<R>
2101    where
2102        C: Context,
2103    {
2104        cx.update_window(self.any_handle, |root_view, cx| {
2105            let view = root_view
2106                .downcast::<V>()
2107                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2108            Ok(cx.update_view(&view, update))
2109        })?
2110    }
2111}
2112
2113impl<V> Copy for WindowHandle<V> {}
2114
2115impl<V> Clone for WindowHandle<V> {
2116    fn clone(&self) -> Self {
2117        WindowHandle {
2118            any_handle: self.any_handle,
2119            state_type: PhantomData,
2120        }
2121    }
2122}
2123
2124impl<V> PartialEq for WindowHandle<V> {
2125    fn eq(&self, other: &Self) -> bool {
2126        self.any_handle == other.any_handle
2127    }
2128}
2129
2130impl<V> Eq for WindowHandle<V> {}
2131
2132impl<V> Hash for WindowHandle<V> {
2133    fn hash<H: Hasher>(&self, state: &mut H) {
2134        self.any_handle.hash(state);
2135    }
2136}
2137
2138impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2139    fn into(self) -> AnyWindowHandle {
2140        self.any_handle
2141    }
2142}
2143
2144#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2145pub struct AnyWindowHandle {
2146    pub(crate) id: WindowId,
2147    state_type: TypeId,
2148}
2149
2150impl AnyWindowHandle {
2151    pub fn window_id(&self) -> WindowId {
2152        self.id
2153    }
2154
2155    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2156        if TypeId::of::<T>() == self.state_type {
2157            Some(WindowHandle {
2158                any_handle: *self,
2159                state_type: PhantomData,
2160            })
2161        } else {
2162            None
2163        }
2164    }
2165
2166    pub fn update<C, R>(
2167        self,
2168        cx: &mut C,
2169        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2170    ) -> Result<R>
2171    where
2172        C: Context,
2173    {
2174        cx.update_window(self, update)
2175    }
2176}
2177
2178#[cfg(any(test, feature = "test-support"))]
2179impl From<SmallVec<[u32; 16]>> for StackingOrder {
2180    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2181        StackingOrder(small_vec)
2182    }
2183}
2184
2185#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2186pub enum ElementId {
2187    View(EntityId),
2188    Number(usize),
2189    Name(SharedString),
2190    FocusHandle(FocusId),
2191}
2192
2193impl From<EntityId> for ElementId {
2194    fn from(id: EntityId) -> Self {
2195        ElementId::View(id)
2196    }
2197}
2198
2199impl From<usize> for ElementId {
2200    fn from(id: usize) -> Self {
2201        ElementId::Number(id)
2202    }
2203}
2204
2205impl From<i32> for ElementId {
2206    fn from(id: i32) -> Self {
2207        Self::Number(id as usize)
2208    }
2209}
2210
2211impl From<SharedString> for ElementId {
2212    fn from(name: SharedString) -> Self {
2213        ElementId::Name(name)
2214    }
2215}
2216
2217impl From<&'static str> for ElementId {
2218    fn from(name: &'static str) -> Self {
2219        ElementId::Name(name.into())
2220    }
2221}
2222
2223impl<'a> From<&'a FocusHandle> for ElementId {
2224    fn from(handle: &'a FocusHandle) -> Self {
2225        ElementId::FocusHandle(handle.id)
2226    }
2227}