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