window.rs

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