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    /// The scale factor of the display associated with the window. For example, it could
 612    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 613    /// be rendered as two pixels on screen.
 614    pub fn scale_factor(&self) -> f32 {
 615        self.window.scale_factor
 616    }
 617
 618    /// The size of an em for the base font of the application. Adjusting this value allows the
 619    /// UI to scale, just like zooming a web page.
 620    pub fn rem_size(&self) -> Pixels {
 621        self.window.rem_size
 622    }
 623
 624    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 625    /// UI to scale, just like zooming a web page.
 626    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 627        self.window.rem_size = rem_size.into();
 628    }
 629
 630    /// The line height associated with the current text style.
 631    pub fn line_height(&self) -> Pixels {
 632        let rem_size = self.rem_size();
 633        let text_style = self.text_style();
 634        text_style
 635            .line_height
 636            .to_pixels(text_style.font_size.into(), rem_size)
 637    }
 638
 639    /// Call to prevent the default action of an event. Currently only used to prevent
 640    /// parent elements from becoming focused on mouse down.
 641    pub fn prevent_default(&mut self) {
 642        self.window.default_prevented = true;
 643    }
 644
 645    /// Obtain whether default has been prevented for the event currently being dispatched.
 646    pub fn default_prevented(&self) -> bool {
 647        self.window.default_prevented
 648    }
 649
 650    /// Register a mouse event listener on the window for the current frame. The type of event
 651    /// is determined by the first parameter of the given listener. When the next frame is rendered
 652    /// the listener will be cleared.
 653    ///
 654    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 655    /// a specific need to register a global listener.
 656    pub fn on_mouse_event<Event: 'static>(
 657        &mut self,
 658        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 659    ) {
 660        let order = self.window.z_index_stack.clone();
 661        self.window
 662            .mouse_listeners
 663            .entry(TypeId::of::<Event>())
 664            .or_default()
 665            .push((
 666                order,
 667                Box::new(move |event: &dyn Any, phase, cx| {
 668                    handler(event.downcast_ref().unwrap(), phase, cx)
 669                }),
 670            ))
 671    }
 672
 673    /// The position of the mouse relative to the window.
 674    pub fn mouse_position(&self) -> Point<Pixels> {
 675        self.window.mouse_position
 676    }
 677
 678    pub fn set_cursor_style(&mut self, style: CursorStyle) {
 679        self.window.requested_cursor_style = Some(style)
 680    }
 681
 682    /// Called during painting to invoke the given closure in a new stacking context. The given
 683    /// z-index is interpreted relative to the previous call to `stack`.
 684    pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
 685        self.window.z_index_stack.push(z_index);
 686        let result = f(self);
 687        self.window.z_index_stack.pop();
 688        result
 689    }
 690
 691    /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
 692    pub fn paint_shadows(
 693        &mut self,
 694        bounds: Bounds<Pixels>,
 695        corner_radii: Corners<Pixels>,
 696        shadows: &[BoxShadow],
 697    ) {
 698        let scale_factor = self.scale_factor();
 699        let content_mask = self.content_mask();
 700        let window = &mut *self.window;
 701        for shadow in shadows {
 702            let mut shadow_bounds = bounds;
 703            shadow_bounds.origin += shadow.offset;
 704            shadow_bounds.dilate(shadow.spread_radius);
 705            window.scene_builder.insert(
 706                &window.z_index_stack,
 707                Shadow {
 708                    order: 0,
 709                    bounds: shadow_bounds.scale(scale_factor),
 710                    content_mask: content_mask.scale(scale_factor),
 711                    corner_radii: corner_radii.scale(scale_factor),
 712                    color: shadow.color,
 713                    blur_radius: shadow.blur_radius.scale(scale_factor),
 714                },
 715            );
 716        }
 717    }
 718
 719    /// Paint one or more quads into the scene for the current frame at the current stacking context.
 720    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 721    pub fn paint_quad(
 722        &mut self,
 723        bounds: Bounds<Pixels>,
 724        corner_radii: Corners<Pixels>,
 725        background: impl Into<Hsla>,
 726        border_widths: Edges<Pixels>,
 727        border_color: impl Into<Hsla>,
 728    ) {
 729        let scale_factor = self.scale_factor();
 730        let content_mask = self.content_mask();
 731
 732        let window = &mut *self.window;
 733        window.scene_builder.insert(
 734            &window.z_index_stack,
 735            Quad {
 736                order: 0,
 737                bounds: bounds.scale(scale_factor),
 738                content_mask: content_mask.scale(scale_factor),
 739                background: background.into(),
 740                border_color: border_color.into(),
 741                corner_radii: corner_radii.scale(scale_factor),
 742                border_widths: border_widths.scale(scale_factor),
 743            },
 744        );
 745    }
 746
 747    /// Paint the given `Path` into the scene for the current frame at the current z-index.
 748    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 749        let scale_factor = self.scale_factor();
 750        let content_mask = self.content_mask();
 751        path.content_mask = content_mask;
 752        path.color = color.into();
 753        let window = &mut *self.window;
 754        window
 755            .scene_builder
 756            .insert(&window.z_index_stack, path.scale(scale_factor));
 757    }
 758
 759    /// Paint an underline into the scene for the current frame at the current z-index.
 760    pub fn paint_underline(
 761        &mut self,
 762        origin: Point<Pixels>,
 763        width: Pixels,
 764        style: &UnderlineStyle,
 765    ) -> Result<()> {
 766        let scale_factor = self.scale_factor();
 767        let height = if style.wavy {
 768            style.thickness * 3.
 769        } else {
 770            style.thickness
 771        };
 772        let bounds = Bounds {
 773            origin,
 774            size: size(width, height),
 775        };
 776        let content_mask = self.content_mask();
 777        let window = &mut *self.window;
 778        window.scene_builder.insert(
 779            &window.z_index_stack,
 780            Underline {
 781                order: 0,
 782                bounds: bounds.scale(scale_factor),
 783                content_mask: content_mask.scale(scale_factor),
 784                thickness: style.thickness.scale(scale_factor),
 785                color: style.color.unwrap_or_default(),
 786                wavy: style.wavy,
 787            },
 788        );
 789        Ok(())
 790    }
 791
 792    /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
 793    pub fn paint_glyph(
 794        &mut self,
 795        origin: Point<Pixels>,
 796        font_id: FontId,
 797        glyph_id: GlyphId,
 798        font_size: Pixels,
 799        color: Hsla,
 800    ) -> Result<()> {
 801        let scale_factor = self.scale_factor();
 802        let glyph_origin = origin.scale(scale_factor);
 803        let subpixel_variant = Point {
 804            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 805            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 806        };
 807        let params = RenderGlyphParams {
 808            font_id,
 809            glyph_id,
 810            font_size,
 811            subpixel_variant,
 812            scale_factor,
 813            is_emoji: false,
 814        };
 815
 816        let raster_bounds = self.text_system().raster_bounds(&params)?;
 817        if !raster_bounds.is_zero() {
 818            let tile =
 819                self.window
 820                    .sprite_atlas
 821                    .get_or_insert_with(&params.clone().into(), &mut || {
 822                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 823                        Ok((size, Cow::Owned(bytes)))
 824                    })?;
 825            let bounds = Bounds {
 826                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 827                size: tile.bounds.size.map(Into::into),
 828            };
 829            let content_mask = self.content_mask().scale(scale_factor);
 830            let window = &mut *self.window;
 831            window.scene_builder.insert(
 832                &window.z_index_stack,
 833                MonochromeSprite {
 834                    order: 0,
 835                    bounds,
 836                    content_mask,
 837                    color,
 838                    tile,
 839                },
 840            );
 841        }
 842        Ok(())
 843    }
 844
 845    /// Paint an emoji glyph into the scene for the current frame at the current z-index.
 846    pub fn paint_emoji(
 847        &mut self,
 848        origin: Point<Pixels>,
 849        font_id: FontId,
 850        glyph_id: GlyphId,
 851        font_size: Pixels,
 852    ) -> Result<()> {
 853        let scale_factor = self.scale_factor();
 854        let glyph_origin = origin.scale(scale_factor);
 855        let params = RenderGlyphParams {
 856            font_id,
 857            glyph_id,
 858            font_size,
 859            // We don't render emojis with subpixel variants.
 860            subpixel_variant: Default::default(),
 861            scale_factor,
 862            is_emoji: true,
 863        };
 864
 865        let raster_bounds = self.text_system().raster_bounds(&params)?;
 866        if !raster_bounds.is_zero() {
 867            let tile =
 868                self.window
 869                    .sprite_atlas
 870                    .get_or_insert_with(&params.clone().into(), &mut || {
 871                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 872                        Ok((size, Cow::Owned(bytes)))
 873                    })?;
 874            let bounds = Bounds {
 875                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 876                size: tile.bounds.size.map(Into::into),
 877            };
 878            let content_mask = self.content_mask().scale(scale_factor);
 879            let window = &mut *self.window;
 880
 881            window.scene_builder.insert(
 882                &window.z_index_stack,
 883                PolychromeSprite {
 884                    order: 0,
 885                    bounds,
 886                    corner_radii: Default::default(),
 887                    content_mask,
 888                    tile,
 889                    grayscale: false,
 890                },
 891            );
 892        }
 893        Ok(())
 894    }
 895
 896    /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
 897    pub fn paint_svg(
 898        &mut self,
 899        bounds: Bounds<Pixels>,
 900        path: SharedString,
 901        color: Hsla,
 902    ) -> Result<()> {
 903        let scale_factor = self.scale_factor();
 904        let bounds = bounds.scale(scale_factor);
 905        // Render the SVG at twice the size to get a higher quality result.
 906        let params = RenderSvgParams {
 907            path,
 908            size: bounds
 909                .size
 910                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 911        };
 912
 913        let tile =
 914            self.window
 915                .sprite_atlas
 916                .get_or_insert_with(&params.clone().into(), &mut || {
 917                    let bytes = self.svg_renderer.render(&params)?;
 918                    Ok((params.size, Cow::Owned(bytes)))
 919                })?;
 920        let content_mask = self.content_mask().scale(scale_factor);
 921
 922        let window = &mut *self.window;
 923        window.scene_builder.insert(
 924            &window.z_index_stack,
 925            MonochromeSprite {
 926                order: 0,
 927                bounds,
 928                content_mask,
 929                color,
 930                tile,
 931            },
 932        );
 933
 934        Ok(())
 935    }
 936
 937    /// Paint an image into the scene for the current frame at the current z-index.
 938    pub fn paint_image(
 939        &mut self,
 940        bounds: Bounds<Pixels>,
 941        corner_radii: Corners<Pixels>,
 942        data: Arc<ImageData>,
 943        grayscale: bool,
 944    ) -> Result<()> {
 945        let scale_factor = self.scale_factor();
 946        let bounds = bounds.scale(scale_factor);
 947        let params = RenderImageParams { image_id: data.id };
 948
 949        let tile = self
 950            .window
 951            .sprite_atlas
 952            .get_or_insert_with(&params.clone().into(), &mut || {
 953                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
 954            })?;
 955        let content_mask = self.content_mask().scale(scale_factor);
 956        let corner_radii = corner_radii.scale(scale_factor);
 957
 958        let window = &mut *self.window;
 959        window.scene_builder.insert(
 960            &window.z_index_stack,
 961            PolychromeSprite {
 962                order: 0,
 963                bounds,
 964                content_mask,
 965                corner_radii,
 966                tile,
 967                grayscale,
 968            },
 969        );
 970        Ok(())
 971    }
 972
 973    /// Draw pixels to the display for this window based on the contents of its scene.
 974    pub(crate) fn draw(&mut self) {
 975        let root_view = self.window.root_view.take().unwrap();
 976
 977        self.start_frame();
 978
 979        self.stack(0, |cx| {
 980            let available_space = cx.window.content_size.map(Into::into);
 981            root_view.draw(available_space, cx);
 982        });
 983
 984        if let Some(active_drag) = self.app.active_drag.take() {
 985            self.stack(1, |cx| {
 986                let offset = cx.mouse_position() - active_drag.cursor_offset;
 987                cx.with_element_offset(Some(offset), |cx| {
 988                    let available_space =
 989                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 990                    active_drag.view.draw(available_space, cx);
 991                    cx.active_drag = Some(active_drag);
 992                });
 993            });
 994        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
 995            self.stack(1, |cx| {
 996                cx.with_element_offset(Some(active_tooltip.cursor_offset), |cx| {
 997                    let available_space =
 998                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 999                    active_tooltip.view.draw(available_space, cx);
1000                });
1001            });
1002        }
1003
1004        self.window.root_view = Some(root_view);
1005        let scene = self.window.scene_builder.build();
1006
1007        self.window.platform_window.draw(scene);
1008        let cursor_style = self
1009            .window
1010            .requested_cursor_style
1011            .take()
1012            .unwrap_or(CursorStyle::Arrow);
1013        self.platform.set_cursor_style(cursor_style);
1014        if let Some(handler) = self.window.requested_input_handler.take() {
1015            self.window.platform_window.set_input_handler(handler);
1016        }
1017
1018        self.window.dirty = false;
1019    }
1020
1021    fn start_frame(&mut self) {
1022        self.text_system().start_frame();
1023
1024        let window = &mut *self.window;
1025
1026        // Move the current frame element states to the previous frame.
1027        // The new empty element states map will be populated for any element states we
1028        // reference during the upcoming frame.
1029        mem::swap(
1030            &mut window.element_states,
1031            &mut window.prev_frame_element_states,
1032        );
1033        window.element_states.clear();
1034
1035        // Make the current key matchers the previous, and then clear the current.
1036        // An empty key matcher map will be created for every identified element in the
1037        // upcoming frame.
1038        mem::swap(
1039            &mut window.key_matchers,
1040            &mut window.prev_frame_key_matchers,
1041        );
1042        window.key_matchers.clear();
1043
1044        // Clear mouse event listeners, because elements add new element listeners
1045        // when the upcoming frame is painted.
1046        window.mouse_listeners.values_mut().for_each(Vec::clear);
1047
1048        // Clear focus state, because we determine what is focused when the new elements
1049        // in the upcoming frame are initialized.
1050        window.focus_listeners.clear();
1051        window.key_dispatch_stack.clear();
1052        window.focus_parents_by_child.clear();
1053        window.freeze_key_dispatch_stack = false;
1054    }
1055
1056    /// Dispatch a mouse or keyboard event on the window.
1057    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1058        // Handlers may set this to false by calling `stop_propagation`
1059        self.app.propagate_event = true;
1060        self.window.default_prevented = false;
1061
1062        let event = match event {
1063            // Track the mouse position with our own state, since accessing the platform
1064            // API for the mouse position can only occur on the main thread.
1065            InputEvent::MouseMove(mouse_move) => {
1066                self.window.mouse_position = mouse_move.position;
1067                InputEvent::MouseMove(mouse_move)
1068            }
1069            // Translate dragging and dropping of external files from the operating system
1070            // to internal drag and drop events.
1071            InputEvent::FileDrop(file_drop) => match file_drop {
1072                FileDropEvent::Entered { position, files } => {
1073                    self.window.mouse_position = position;
1074                    if self.active_drag.is_none() {
1075                        self.active_drag = Some(AnyDrag {
1076                            view: self.build_view(|_| files).into(),
1077                            cursor_offset: position,
1078                        });
1079                    }
1080                    InputEvent::MouseDown(MouseDownEvent {
1081                        position,
1082                        button: MouseButton::Left,
1083                        click_count: 1,
1084                        modifiers: Modifiers::default(),
1085                    })
1086                }
1087                FileDropEvent::Pending { position } => {
1088                    self.window.mouse_position = position;
1089                    InputEvent::MouseMove(MouseMoveEvent {
1090                        position,
1091                        pressed_button: Some(MouseButton::Left),
1092                        modifiers: Modifiers::default(),
1093                    })
1094                }
1095                FileDropEvent::Submit { position } => {
1096                    self.window.mouse_position = position;
1097                    InputEvent::MouseUp(MouseUpEvent {
1098                        button: MouseButton::Left,
1099                        position,
1100                        modifiers: Modifiers::default(),
1101                        click_count: 1,
1102                    })
1103                }
1104                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1105                    button: MouseButton::Left,
1106                    position: Point::default(),
1107                    modifiers: Modifiers::default(),
1108                    click_count: 1,
1109                }),
1110            },
1111            _ => event,
1112        };
1113
1114        if let Some(any_mouse_event) = event.mouse_event() {
1115            if let Some(mut handlers) = self
1116                .window
1117                .mouse_listeners
1118                .remove(&any_mouse_event.type_id())
1119            {
1120                // Because handlers may add other handlers, we sort every time.
1121                handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1122
1123                // Capture phase, events bubble from back to front. Handlers for this phase are used for
1124                // special purposes, such as detecting events outside of a given Bounds.
1125                for (_, handler) in &handlers {
1126                    handler(any_mouse_event, DispatchPhase::Capture, self);
1127                    if !self.app.propagate_event {
1128                        break;
1129                    }
1130                }
1131
1132                // Bubble phase, where most normal handlers do their work.
1133                if self.app.propagate_event {
1134                    for (_, handler) in handlers.iter().rev() {
1135                        handler(any_mouse_event, DispatchPhase::Bubble, self);
1136                        if !self.app.propagate_event {
1137                            break;
1138                        }
1139                    }
1140                }
1141
1142                if self.app.propagate_event
1143                    && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1144                {
1145                    self.active_drag = None;
1146                }
1147
1148                // Just in case any handlers added new handlers, which is weird, but possible.
1149                handlers.extend(
1150                    self.window
1151                        .mouse_listeners
1152                        .get_mut(&any_mouse_event.type_id())
1153                        .into_iter()
1154                        .flat_map(|handlers| handlers.drain(..)),
1155                );
1156                self.window
1157                    .mouse_listeners
1158                    .insert(any_mouse_event.type_id(), handlers);
1159            }
1160        } else if let Some(any_key_event) = event.keyboard_event() {
1161            let mut did_handle_action = false;
1162            let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1163            let key_event_type = any_key_event.type_id();
1164            let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1165
1166            for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1167                match frame {
1168                    KeyDispatchStackFrame::Listener {
1169                        event_type,
1170                        listener,
1171                    } => {
1172                        if key_event_type == *event_type {
1173                            if let Some(action) = listener(
1174                                any_key_event,
1175                                &context_stack,
1176                                DispatchPhase::Capture,
1177                                self,
1178                            ) {
1179                                self.dispatch_action(action, &key_dispatch_stack[..ix]);
1180                            }
1181                            if !self.app.propagate_event {
1182                                did_handle_action = true;
1183                                break;
1184                            }
1185                        }
1186                    }
1187                    KeyDispatchStackFrame::Context(context) => {
1188                        context_stack.push(&context);
1189                    }
1190                }
1191            }
1192
1193            if self.app.propagate_event {
1194                for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1195                    match frame {
1196                        KeyDispatchStackFrame::Listener {
1197                            event_type,
1198                            listener,
1199                        } => {
1200                            if key_event_type == *event_type {
1201                                if let Some(action) = listener(
1202                                    any_key_event,
1203                                    &context_stack,
1204                                    DispatchPhase::Bubble,
1205                                    self,
1206                                ) {
1207                                    self.dispatch_action(action, &key_dispatch_stack[..ix]);
1208                                }
1209
1210                                if !self.app.propagate_event {
1211                                    did_handle_action = true;
1212                                    break;
1213                                }
1214                            }
1215                        }
1216                        KeyDispatchStackFrame::Context(_) => {
1217                            context_stack.pop();
1218                        }
1219                    }
1220                }
1221            }
1222
1223            drop(context_stack);
1224            self.window.key_dispatch_stack = key_dispatch_stack;
1225            return did_handle_action;
1226        }
1227
1228        true
1229    }
1230
1231    /// Attempt to map a keystroke to an action based on the keymap.
1232    pub fn match_keystroke(
1233        &mut self,
1234        element_id: &GlobalElementId,
1235        keystroke: &Keystroke,
1236        context_stack: &[&DispatchContext],
1237    ) -> KeyMatch {
1238        let key_match = self
1239            .window
1240            .key_matchers
1241            .get_mut(element_id)
1242            .unwrap()
1243            .match_keystroke(keystroke, context_stack);
1244
1245        if key_match.is_some() {
1246            for matcher in self.window.key_matchers.values_mut() {
1247                matcher.clear_pending();
1248            }
1249        }
1250
1251        key_match
1252    }
1253
1254    /// Register the given handler to be invoked whenever the global of the given type
1255    /// is updated.
1256    pub fn observe_global<G: 'static>(
1257        &mut self,
1258        f: impl Fn(&mut WindowContext<'_>) + 'static,
1259    ) -> Subscription {
1260        let window_handle = self.window.handle;
1261        self.global_observers.insert(
1262            TypeId::of::<G>(),
1263            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1264        )
1265    }
1266
1267    pub fn activate_window(&self) {
1268        self.window.platform_window.activate();
1269    }
1270
1271    pub fn prompt(
1272        &self,
1273        level: PromptLevel,
1274        msg: &str,
1275        answers: &[&str],
1276    ) -> oneshot::Receiver<usize> {
1277        self.window.platform_window.prompt(level, msg, answers)
1278    }
1279
1280    fn dispatch_action(
1281        &mut self,
1282        action: Box<dyn Action>,
1283        dispatch_stack: &[KeyDispatchStackFrame],
1284    ) {
1285        let action_type = action.as_any().type_id();
1286
1287        if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1288            for listener in &global_listeners {
1289                listener(action.as_ref(), DispatchPhase::Capture, self);
1290                if !self.app.propagate_event {
1291                    break;
1292                }
1293            }
1294            global_listeners.extend(
1295                self.global_action_listeners
1296                    .remove(&action_type)
1297                    .unwrap_or_default(),
1298            );
1299            self.global_action_listeners
1300                .insert(action_type, global_listeners);
1301        }
1302
1303        if self.app.propagate_event {
1304            for stack_frame in dispatch_stack {
1305                if let KeyDispatchStackFrame::Listener {
1306                    event_type,
1307                    listener,
1308                } = stack_frame
1309                {
1310                    if action_type == *event_type {
1311                        listener(action.as_any(), &[], DispatchPhase::Capture, self);
1312                        if !self.app.propagate_event {
1313                            break;
1314                        }
1315                    }
1316                }
1317            }
1318        }
1319
1320        if self.app.propagate_event {
1321            for stack_frame in dispatch_stack.iter().rev() {
1322                if let KeyDispatchStackFrame::Listener {
1323                    event_type,
1324                    listener,
1325                } = stack_frame
1326                {
1327                    if action_type == *event_type {
1328                        self.app.propagate_event = false;
1329                        listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1330                        if !self.app.propagate_event {
1331                            break;
1332                        }
1333                    }
1334                }
1335            }
1336        }
1337
1338        if self.app.propagate_event {
1339            if let Some(mut global_listeners) =
1340                self.app.global_action_listeners.remove(&action_type)
1341            {
1342                for listener in global_listeners.iter().rev() {
1343                    self.app.propagate_event = false;
1344                    listener(action.as_ref(), DispatchPhase::Bubble, self);
1345                    if !self.app.propagate_event {
1346                        break;
1347                    }
1348                }
1349                global_listeners.extend(
1350                    self.global_action_listeners
1351                        .remove(&action_type)
1352                        .unwrap_or_default(),
1353                );
1354                self.global_action_listeners
1355                    .insert(action_type, global_listeners);
1356            }
1357        }
1358    }
1359}
1360
1361impl Context for WindowContext<'_> {
1362    type Result<T> = T;
1363
1364    fn build_model<T>(
1365        &mut self,
1366        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1367    ) -> Model<T>
1368    where
1369        T: 'static,
1370    {
1371        let slot = self.app.entities.reserve();
1372        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1373        self.entities.insert(slot, model)
1374    }
1375
1376    fn update_model<T: 'static, R>(
1377        &mut self,
1378        model: &Model<T>,
1379        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1380    ) -> R {
1381        let mut entity = self.entities.lease(model);
1382        let result = update(
1383            &mut *entity,
1384            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1385        );
1386        self.entities.end_lease(entity);
1387        result
1388    }
1389
1390    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1391    where
1392        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1393    {
1394        if window == self.window.handle {
1395            let root_view = self.window.root_view.clone().unwrap();
1396            Ok(update(root_view, self))
1397        } else {
1398            window.update(self.app, update)
1399        }
1400    }
1401}
1402
1403impl VisualContext for WindowContext<'_> {
1404    fn build_view<V>(
1405        &mut self,
1406        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1407    ) -> Self::Result<View<V>>
1408    where
1409        V: 'static,
1410    {
1411        let slot = self.app.entities.reserve();
1412        let view = View {
1413            model: slot.clone(),
1414        };
1415        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1416        let entity = build_view_state(&mut cx);
1417        self.entities.insert(slot, entity);
1418        view
1419    }
1420
1421    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1422    fn update_view<T: 'static, R>(
1423        &mut self,
1424        view: &View<T>,
1425        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1426    ) -> Self::Result<R> {
1427        let mut lease = self.app.entities.lease(&view.model);
1428        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1429        let result = update(&mut *lease, &mut cx);
1430        cx.app.entities.end_lease(lease);
1431        result
1432    }
1433
1434    fn replace_root_view<V>(
1435        &mut self,
1436        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1437    ) -> Self::Result<View<V>>
1438    where
1439        V: Render,
1440    {
1441        let slot = self.app.entities.reserve();
1442        let view = View {
1443            model: slot.clone(),
1444        };
1445        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1446        let entity = build_view(&mut cx);
1447        self.entities.insert(slot, entity);
1448        self.window.root_view = Some(view.clone().into());
1449        view
1450    }
1451}
1452
1453impl<'a> std::ops::Deref for WindowContext<'a> {
1454    type Target = AppContext;
1455
1456    fn deref(&self) -> &Self::Target {
1457        &self.app
1458    }
1459}
1460
1461impl<'a> std::ops::DerefMut for WindowContext<'a> {
1462    fn deref_mut(&mut self) -> &mut Self::Target {
1463        &mut self.app
1464    }
1465}
1466
1467impl<'a> Borrow<AppContext> for WindowContext<'a> {
1468    fn borrow(&self) -> &AppContext {
1469        &self.app
1470    }
1471}
1472
1473impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1474    fn borrow_mut(&mut self) -> &mut AppContext {
1475        &mut self.app
1476    }
1477}
1478
1479pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1480    fn app_mut(&mut self) -> &mut AppContext {
1481        self.borrow_mut()
1482    }
1483
1484    fn window(&self) -> &Window {
1485        self.borrow()
1486    }
1487
1488    fn window_mut(&mut self) -> &mut Window {
1489        self.borrow_mut()
1490    }
1491
1492    /// Pushes the given element id onto the global stack and invokes the given closure
1493    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1494    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1495    /// used to associate state with identified elements across separate frames.
1496    fn with_element_id<R>(
1497        &mut self,
1498        id: impl Into<ElementId>,
1499        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1500    ) -> R {
1501        let keymap = self.app_mut().keymap.clone();
1502        let window = self.window_mut();
1503        window.element_id_stack.push(id.into());
1504        let global_id = window.element_id_stack.clone();
1505
1506        if window.key_matchers.get(&global_id).is_none() {
1507            window.key_matchers.insert(
1508                global_id.clone(),
1509                window
1510                    .prev_frame_key_matchers
1511                    .remove(&global_id)
1512                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1513            );
1514        }
1515
1516        let result = f(global_id, self);
1517        let window: &mut Window = self.borrow_mut();
1518        window.element_id_stack.pop();
1519        result
1520    }
1521
1522    /// Invoke the given function with the given content mask after intersecting it
1523    /// with the current mask.
1524    fn with_content_mask<R>(
1525        &mut self,
1526        mask: ContentMask<Pixels>,
1527        f: impl FnOnce(&mut Self) -> R,
1528    ) -> R {
1529        let mask = mask.intersect(&self.content_mask());
1530        self.window_mut().content_mask_stack.push(mask);
1531        let result = f(self);
1532        self.window_mut().content_mask_stack.pop();
1533        result
1534    }
1535
1536    /// Update the global element offset based on the given offset. This is used to implement
1537    /// scrolling and position drag handles.
1538    fn with_element_offset<R>(
1539        &mut self,
1540        offset: Option<Point<Pixels>>,
1541        f: impl FnOnce(&mut Self) -> R,
1542    ) -> R {
1543        let Some(offset) = offset else {
1544            return f(self);
1545        };
1546
1547        let offset = self.element_offset() + offset;
1548        self.window_mut().element_offset_stack.push(offset);
1549        let result = f(self);
1550        self.window_mut().element_offset_stack.pop();
1551        result
1552    }
1553
1554    /// Obtain the current element offset.
1555    fn element_offset(&self) -> Point<Pixels> {
1556        self.window()
1557            .element_offset_stack
1558            .last()
1559            .copied()
1560            .unwrap_or_default()
1561    }
1562
1563    /// Update or intialize state for an element with the given id that lives across multiple
1564    /// frames. If an element with this id existed in the previous frame, its state will be passed
1565    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1566    /// when drawing the next frame.
1567    fn with_element_state<S, R>(
1568        &mut self,
1569        id: ElementId,
1570        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1571    ) -> R
1572    where
1573        S: 'static,
1574    {
1575        self.with_element_id(id, |global_id, cx| {
1576            if let Some(any) = cx
1577                .window_mut()
1578                .element_states
1579                .remove(&global_id)
1580                .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1581            {
1582                // Using the extra inner option to avoid needing to reallocate a new box.
1583                let mut state_box = any
1584                    .downcast::<Option<S>>()
1585                    .expect("invalid element state type for id");
1586                let state = state_box
1587                    .take()
1588                    .expect("element state is already on the stack");
1589                let (result, state) = f(Some(state), cx);
1590                state_box.replace(state);
1591                cx.window_mut().element_states.insert(global_id, state_box);
1592                result
1593            } else {
1594                let (result, state) = f(None, cx);
1595                cx.window_mut()
1596                    .element_states
1597                    .insert(global_id, Box::new(Some(state)));
1598                result
1599            }
1600        })
1601    }
1602
1603    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1604    /// id is `None`, no state will be retrieved or stored.
1605    fn with_optional_element_state<S, R>(
1606        &mut self,
1607        element_id: Option<ElementId>,
1608        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1609    ) -> R
1610    where
1611        S: 'static,
1612    {
1613        if let Some(element_id) = element_id {
1614            self.with_element_state(element_id, f)
1615        } else {
1616            f(None, self).0
1617        }
1618    }
1619
1620    /// Obtain the current content mask.
1621    fn content_mask(&self) -> ContentMask<Pixels> {
1622        self.window()
1623            .content_mask_stack
1624            .last()
1625            .cloned()
1626            .unwrap_or_else(|| ContentMask {
1627                bounds: Bounds {
1628                    origin: Point::default(),
1629                    size: self.window().content_size,
1630                },
1631            })
1632    }
1633
1634    /// The size of an em for the base font of the application. Adjusting this value allows the
1635    /// UI to scale, just like zooming a web page.
1636    fn rem_size(&self) -> Pixels {
1637        self.window().rem_size
1638    }
1639}
1640
1641impl Borrow<Window> for WindowContext<'_> {
1642    fn borrow(&self) -> &Window {
1643        &self.window
1644    }
1645}
1646
1647impl BorrowMut<Window> for WindowContext<'_> {
1648    fn borrow_mut(&mut self) -> &mut Window {
1649        &mut self.window
1650    }
1651}
1652
1653impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1654
1655pub struct ViewContext<'a, V> {
1656    window_cx: WindowContext<'a>,
1657    view: &'a View<V>,
1658}
1659
1660impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1661    fn borrow(&self) -> &AppContext {
1662        &*self.window_cx.app
1663    }
1664}
1665
1666impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1667    fn borrow_mut(&mut self) -> &mut AppContext {
1668        &mut *self.window_cx.app
1669    }
1670}
1671
1672impl<V> Borrow<Window> for ViewContext<'_, V> {
1673    fn borrow(&self) -> &Window {
1674        &*self.window_cx.window
1675    }
1676}
1677
1678impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1679    fn borrow_mut(&mut self) -> &mut Window {
1680        &mut *self.window_cx.window
1681    }
1682}
1683
1684impl<'a, V: 'static> ViewContext<'a, V> {
1685    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1686        Self {
1687            window_cx: WindowContext::new(app, window),
1688            view,
1689        }
1690    }
1691
1692    // todo!("change this to return a reference");
1693    pub fn view(&self) -> View<V> {
1694        self.view.clone()
1695    }
1696
1697    pub fn model(&self) -> Model<V> {
1698        self.view.model.clone()
1699    }
1700
1701    /// Access the underlying window context.
1702    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1703        &mut self.window_cx
1704    }
1705
1706    pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1707        self.window.z_index_stack.push(order);
1708        let result = f(self);
1709        self.window.z_index_stack.pop();
1710        result
1711    }
1712
1713    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1714    where
1715        V: 'static,
1716    {
1717        let view = self.view();
1718        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1719    }
1720
1721    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1722    /// that are currently on the stack to be returned to the app.
1723    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1724        let view = self.view().downgrade();
1725        self.window_cx.defer(move |cx| {
1726            view.update(cx, f).ok();
1727        });
1728    }
1729
1730    pub fn observe<V2, E>(
1731        &mut self,
1732        entity: &E,
1733        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1734    ) -> Subscription
1735    where
1736        V2: 'static,
1737        V: 'static,
1738        E: Entity<V2>,
1739    {
1740        let view = self.view().downgrade();
1741        let entity_id = entity.entity_id();
1742        let entity = entity.downgrade();
1743        let window_handle = self.window.handle;
1744        self.app.observers.insert(
1745            entity_id,
1746            Box::new(move |cx| {
1747                window_handle
1748                    .update(cx, |_, cx| {
1749                        if let Some(handle) = E::upgrade_from(&entity) {
1750                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1751                                .is_ok()
1752                        } else {
1753                            false
1754                        }
1755                    })
1756                    .unwrap_or(false)
1757            }),
1758        )
1759    }
1760
1761    pub fn subscribe<V2, E>(
1762        &mut self,
1763        entity: &E,
1764        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + 'static,
1765    ) -> Subscription
1766    where
1767        V2: EventEmitter,
1768        E: Entity<V2>,
1769    {
1770        let view = self.view().downgrade();
1771        let entity_id = entity.entity_id();
1772        let handle = entity.downgrade();
1773        let window_handle = self.window.handle;
1774        self.app.event_listeners.insert(
1775            entity_id,
1776            Box::new(move |event, cx| {
1777                window_handle
1778                    .update(cx, |_, cx| {
1779                        if let Some(handle) = E::upgrade_from(&handle) {
1780                            let event = event.downcast_ref().expect("invalid event type");
1781                            view.update(cx, |this, cx| on_event(this, handle, event, cx))
1782                                .is_ok()
1783                        } else {
1784                            false
1785                        }
1786                    })
1787                    .unwrap_or(false)
1788            }),
1789        )
1790    }
1791
1792    pub fn on_release(
1793        &mut self,
1794        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1795    ) -> Subscription {
1796        let window_handle = self.window.handle;
1797        self.app.release_listeners.insert(
1798            self.view.model.entity_id,
1799            Box::new(move |this, cx| {
1800                let this = this.downcast_mut().expect("invalid entity type");
1801                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1802            }),
1803        )
1804    }
1805
1806    pub fn observe_release<V2, E>(
1807        &mut self,
1808        entity: &E,
1809        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1810    ) -> Subscription
1811    where
1812        V: 'static,
1813        V2: 'static,
1814        E: Entity<V2>,
1815    {
1816        let view = self.view().downgrade();
1817        let entity_id = entity.entity_id();
1818        let window_handle = self.window.handle;
1819        self.app.release_listeners.insert(
1820            entity_id,
1821            Box::new(move |entity, cx| {
1822                let entity = entity.downcast_mut().expect("invalid entity type");
1823                let _ = window_handle.update(cx, |_, cx| {
1824                    view.update(cx, |this, cx| on_release(this, entity, cx))
1825                });
1826            }),
1827        )
1828    }
1829
1830    pub fn notify(&mut self) {
1831        self.window_cx.notify();
1832        self.window_cx.app.push_effect(Effect::Notify {
1833            emitter: self.view.model.entity_id,
1834        });
1835    }
1836
1837    pub fn observe_window_bounds(
1838        &mut self,
1839        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1840    ) -> Subscription {
1841        let view = self.view.downgrade();
1842        self.window.bounds_observers.insert(
1843            (),
1844            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1845        )
1846    }
1847
1848    pub fn observe_window_activation(
1849        &mut self,
1850        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1851    ) -> Subscription {
1852        let view = self.view.downgrade();
1853        self.window.activation_observers.insert(
1854            (),
1855            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1856        )
1857    }
1858
1859    pub fn on_focus_changed(
1860        &mut self,
1861        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
1862    ) {
1863        let handle = self.view().downgrade();
1864        self.window.focus_listeners.push(Box::new(move |event, cx| {
1865            handle
1866                .update(cx, |view, cx| listener(view, event, cx))
1867                .log_err();
1868        }));
1869    }
1870
1871    pub fn with_key_listeners<R>(
1872        &mut self,
1873        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1874        f: impl FnOnce(&mut Self) -> R,
1875    ) -> R {
1876        let old_stack_len = self.window.key_dispatch_stack.len();
1877        if !self.window.freeze_key_dispatch_stack {
1878            for (event_type, listener) in key_listeners {
1879                let handle = self.view().downgrade();
1880                let listener = Box::new(
1881                    move |event: &dyn Any,
1882                          context_stack: &[&DispatchContext],
1883                          phase: DispatchPhase,
1884                          cx: &mut WindowContext<'_>| {
1885                        handle
1886                            .update(cx, |view, cx| {
1887                                listener(view, event, context_stack, phase, cx)
1888                            })
1889                            .log_err()
1890                            .flatten()
1891                    },
1892                );
1893                self.window
1894                    .key_dispatch_stack
1895                    .push(KeyDispatchStackFrame::Listener {
1896                        event_type,
1897                        listener,
1898                    });
1899            }
1900        }
1901
1902        let result = f(self);
1903
1904        if !self.window.freeze_key_dispatch_stack {
1905            self.window.key_dispatch_stack.truncate(old_stack_len);
1906        }
1907
1908        result
1909    }
1910
1911    pub fn with_key_dispatch_context<R>(
1912        &mut self,
1913        context: DispatchContext,
1914        f: impl FnOnce(&mut Self) -> R,
1915    ) -> R {
1916        if context.is_empty() {
1917            return f(self);
1918        }
1919
1920        if !self.window.freeze_key_dispatch_stack {
1921            self.window
1922                .key_dispatch_stack
1923                .push(KeyDispatchStackFrame::Context(context));
1924        }
1925
1926        let result = f(self);
1927
1928        if !self.window.freeze_key_dispatch_stack {
1929            self.window.key_dispatch_stack.pop();
1930        }
1931
1932        result
1933    }
1934
1935    pub fn with_focus<R>(
1936        &mut self,
1937        focus_handle: FocusHandle,
1938        f: impl FnOnce(&mut Self) -> R,
1939    ) -> R {
1940        if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1941            self.window
1942                .focus_parents_by_child
1943                .insert(focus_handle.id, parent_focus_id);
1944        }
1945        self.window.focus_stack.push(focus_handle.id);
1946
1947        if Some(focus_handle.id) == self.window.focus {
1948            self.window.freeze_key_dispatch_stack = true;
1949        }
1950
1951        let result = f(self);
1952
1953        self.window.focus_stack.pop();
1954        result
1955    }
1956
1957    pub fn spawn<Fut, R>(
1958        &mut self,
1959        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1960    ) -> Task<R>
1961    where
1962        R: 'static,
1963        Fut: Future<Output = R> + 'static,
1964    {
1965        let view = self.view().downgrade();
1966        self.window_cx.spawn(|cx| f(view, cx))
1967    }
1968
1969    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1970    where
1971        G: 'static,
1972    {
1973        let mut global = self.app.lease_global::<G>();
1974        let result = f(&mut global, self);
1975        self.app.end_global_lease(global);
1976        result
1977    }
1978
1979    pub fn observe_global<G: 'static>(
1980        &mut self,
1981        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
1982    ) -> Subscription {
1983        let window_handle = self.window.handle;
1984        let view = self.view().downgrade();
1985        self.global_observers.insert(
1986            TypeId::of::<G>(),
1987            Box::new(move |cx| {
1988                window_handle
1989                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
1990                    .unwrap_or(false)
1991            }),
1992        )
1993    }
1994
1995    pub fn on_mouse_event<Event: 'static>(
1996        &mut self,
1997        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
1998    ) {
1999        let handle = self.view();
2000        self.window_cx.on_mouse_event(move |event, phase, cx| {
2001            handle.update(cx, |view, cx| {
2002                handler(view, event, phase, cx);
2003            })
2004        });
2005    }
2006}
2007
2008impl<V> ViewContext<'_, V>
2009where
2010    V: InputHandler + 'static,
2011{
2012    pub fn handle_text_input(&mut self) {
2013        self.window.requested_input_handler = Some(Box::new(WindowInputHandler {
2014            cx: self.app.this.clone(),
2015            window: self.window_handle(),
2016            handler: self.view().downgrade(),
2017        }));
2018    }
2019}
2020
2021impl<V> ViewContext<'_, V>
2022where
2023    V: EventEmitter,
2024    V::Event: 'static,
2025{
2026    pub fn emit(&mut self, event: V::Event) {
2027        let emitter = self.view.model.entity_id;
2028        self.app.push_effect(Effect::Emit {
2029            emitter,
2030            event: Box::new(event),
2031        });
2032    }
2033}
2034
2035impl<V> Context for ViewContext<'_, V> {
2036    type Result<U> = U;
2037
2038    fn build_model<T: 'static>(
2039        &mut self,
2040        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2041    ) -> Model<T> {
2042        self.window_cx.build_model(build_model)
2043    }
2044
2045    fn update_model<T: 'static, R>(
2046        &mut self,
2047        model: &Model<T>,
2048        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2049    ) -> R {
2050        self.window_cx.update_model(model, update)
2051    }
2052
2053    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2054    where
2055        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2056    {
2057        self.window_cx.update_window(window, update)
2058    }
2059}
2060
2061impl<V: 'static> VisualContext for ViewContext<'_, V> {
2062    fn build_view<W: 'static>(
2063        &mut self,
2064        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2065    ) -> Self::Result<View<W>> {
2066        self.window_cx.build_view(build_view_state)
2067    }
2068
2069    fn update_view<V2: 'static, R>(
2070        &mut self,
2071        view: &View<V2>,
2072        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2073    ) -> Self::Result<R> {
2074        self.window_cx.update_view(view, update)
2075    }
2076
2077    fn replace_root_view<W>(
2078        &mut self,
2079        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2080    ) -> Self::Result<View<W>>
2081    where
2082        W: Render,
2083    {
2084        self.window_cx.replace_root_view(build_view)
2085    }
2086}
2087
2088impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2089    type Target = WindowContext<'a>;
2090
2091    fn deref(&self) -> &Self::Target {
2092        &self.window_cx
2093    }
2094}
2095
2096impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2097    fn deref_mut(&mut self) -> &mut Self::Target {
2098        &mut self.window_cx
2099    }
2100}
2101
2102// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2103slotmap::new_key_type! { pub struct WindowId; }
2104
2105impl WindowId {
2106    pub fn as_u64(&self) -> u64 {
2107        self.0.as_ffi()
2108    }
2109}
2110
2111#[derive(Deref, DerefMut)]
2112pub struct WindowHandle<V> {
2113    #[deref]
2114    #[deref_mut]
2115    pub(crate) any_handle: AnyWindowHandle,
2116    state_type: PhantomData<V>,
2117}
2118
2119impl<V: 'static + Render> WindowHandle<V> {
2120    pub fn new(id: WindowId) -> Self {
2121        WindowHandle {
2122            any_handle: AnyWindowHandle {
2123                id,
2124                state_type: TypeId::of::<V>(),
2125            },
2126            state_type: PhantomData,
2127        }
2128    }
2129
2130    pub fn update<C, R>(
2131        self,
2132        cx: &mut C,
2133        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2134    ) -> Result<R>
2135    where
2136        C: Context,
2137    {
2138        cx.update_window(self.any_handle, |root_view, cx| {
2139            let view = root_view
2140                .downcast::<V>()
2141                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2142            Ok(cx.update_view(&view, update))
2143        })?
2144    }
2145}
2146
2147impl<V> Copy for WindowHandle<V> {}
2148
2149impl<V> Clone for WindowHandle<V> {
2150    fn clone(&self) -> Self {
2151        WindowHandle {
2152            any_handle: self.any_handle,
2153            state_type: PhantomData,
2154        }
2155    }
2156}
2157
2158impl<V> PartialEq for WindowHandle<V> {
2159    fn eq(&self, other: &Self) -> bool {
2160        self.any_handle == other.any_handle
2161    }
2162}
2163
2164impl<V> Eq for WindowHandle<V> {}
2165
2166impl<V> Hash for WindowHandle<V> {
2167    fn hash<H: Hasher>(&self, state: &mut H) {
2168        self.any_handle.hash(state);
2169    }
2170}
2171
2172impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2173    fn into(self) -> AnyWindowHandle {
2174        self.any_handle
2175    }
2176}
2177
2178#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2179pub struct AnyWindowHandle {
2180    pub(crate) id: WindowId,
2181    state_type: TypeId,
2182}
2183
2184impl AnyWindowHandle {
2185    pub fn window_id(&self) -> WindowId {
2186        self.id
2187    }
2188
2189    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2190        if TypeId::of::<T>() == self.state_type {
2191            Some(WindowHandle {
2192                any_handle: *self,
2193                state_type: PhantomData,
2194            })
2195        } else {
2196            None
2197        }
2198    }
2199
2200    pub fn update<C, R>(
2201        self,
2202        cx: &mut C,
2203        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2204    ) -> Result<R>
2205    where
2206        C: Context,
2207    {
2208        cx.update_window(self, update)
2209    }
2210}
2211
2212#[cfg(any(test, feature = "test-support"))]
2213impl From<SmallVec<[u32; 16]>> for StackingOrder {
2214    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2215        StackingOrder(small_vec)
2216    }
2217}
2218
2219#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2220pub enum ElementId {
2221    View(EntityId),
2222    Number(usize),
2223    Name(SharedString),
2224    FocusHandle(FocusId),
2225}
2226
2227impl From<EntityId> for ElementId {
2228    fn from(id: EntityId) -> Self {
2229        ElementId::View(id)
2230    }
2231}
2232
2233impl From<usize> for ElementId {
2234    fn from(id: usize) -> Self {
2235        ElementId::Number(id)
2236    }
2237}
2238
2239impl From<i32> for ElementId {
2240    fn from(id: i32) -> Self {
2241        Self::Number(id as usize)
2242    }
2243}
2244
2245impl From<SharedString> for ElementId {
2246    fn from(name: SharedString) -> Self {
2247        ElementId::Name(name)
2248    }
2249}
2250
2251impl From<&'static str> for ElementId {
2252    fn from(name: &'static str) -> Self {
2253        ElementId::Name(name.into())
2254    }
2255}
2256
2257impl<'a> From<&'a FocusHandle> for ElementId {
2258    fn from(handle: &'a FocusHandle) -> Self {
2259        ElementId::FocusHandle(handle.id)
2260    }
2261}