window.rs

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