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, KeyContext, KeyDownEvent, LayoutId, Model, ModelContext, Modifiers,
   7    MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
   8    PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
   9    PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels,
  10    SceneBuilder, Shadow, SharedString, Size, Style, SubscriberSet, Subscription,
  11    TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakView,
  12    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(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(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
1382impl Context for WindowContext<'_> {
1383    type Result<T> = T;
1384
1385    fn build_model<T>(
1386        &mut self,
1387        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1388    ) -> Model<T>
1389    where
1390        T: 'static,
1391    {
1392        let slot = self.app.entities.reserve();
1393        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1394        self.entities.insert(slot, model)
1395    }
1396
1397    fn update_model<T: 'static, R>(
1398        &mut self,
1399        model: &Model<T>,
1400        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1401    ) -> R {
1402        let mut entity = self.entities.lease(model);
1403        let result = update(
1404            &mut *entity,
1405            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1406        );
1407        self.entities.end_lease(entity);
1408        result
1409    }
1410
1411    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1412    where
1413        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1414    {
1415        if window == self.window.handle {
1416            let root_view = self.window.root_view.clone().unwrap();
1417            Ok(update(root_view, self))
1418        } else {
1419            window.update(self.app, update)
1420        }
1421    }
1422
1423    fn read_model<T, R>(
1424        &self,
1425        handle: &Model<T>,
1426        read: impl FnOnce(&T, &AppContext) -> R,
1427    ) -> Self::Result<R>
1428    where
1429        T: 'static,
1430    {
1431        let entity = self.entities.read(handle);
1432        read(&*entity, &*self.app)
1433    }
1434}
1435
1436impl VisualContext for WindowContext<'_> {
1437    fn build_view<V>(
1438        &mut self,
1439        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1440    ) -> Self::Result<View<V>>
1441    where
1442        V: 'static + Render,
1443    {
1444        let slot = self.app.entities.reserve();
1445        let view = View {
1446            model: slot.clone(),
1447        };
1448        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1449        let entity = build_view_state(&mut cx);
1450        cx.entities.insert(slot, entity);
1451
1452        cx.new_view_observers
1453            .clone()
1454            .retain(&TypeId::of::<V>(), |observer| {
1455                let any_view = AnyView::from(view.clone());
1456                (observer)(any_view, self);
1457                true
1458            });
1459
1460        view
1461    }
1462
1463    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1464    fn update_view<T: 'static, R>(
1465        &mut self,
1466        view: &View<T>,
1467        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1468    ) -> Self::Result<R> {
1469        let mut lease = self.app.entities.lease(&view.model);
1470        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1471        let result = update(&mut *lease, &mut cx);
1472        cx.app.entities.end_lease(lease);
1473        result
1474    }
1475
1476    fn replace_root_view<V>(
1477        &mut self,
1478        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1479    ) -> Self::Result<View<V>>
1480    where
1481        V: Render,
1482    {
1483        let slot = self.app.entities.reserve();
1484        let view = View {
1485            model: slot.clone(),
1486        };
1487        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1488        let entity = build_view(&mut cx);
1489        self.entities.insert(slot, entity);
1490        self.window.root_view = Some(view.clone().into());
1491        view
1492    }
1493}
1494
1495impl<'a> std::ops::Deref for WindowContext<'a> {
1496    type Target = AppContext;
1497
1498    fn deref(&self) -> &Self::Target {
1499        &self.app
1500    }
1501}
1502
1503impl<'a> std::ops::DerefMut for WindowContext<'a> {
1504    fn deref_mut(&mut self) -> &mut Self::Target {
1505        &mut self.app
1506    }
1507}
1508
1509impl<'a> Borrow<AppContext> for WindowContext<'a> {
1510    fn borrow(&self) -> &AppContext {
1511        &self.app
1512    }
1513}
1514
1515impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1516    fn borrow_mut(&mut self) -> &mut AppContext {
1517        &mut self.app
1518    }
1519}
1520
1521pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1522    fn app_mut(&mut self) -> &mut AppContext {
1523        self.borrow_mut()
1524    }
1525
1526    fn window(&self) -> &Window {
1527        self.borrow()
1528    }
1529
1530    fn window_mut(&mut self) -> &mut Window {
1531        self.borrow_mut()
1532    }
1533
1534    /// Pushes the given element id onto the global stack and invokes the given closure
1535    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1536    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1537    /// used to associate state with identified elements across separate frames.
1538    fn with_element_id<R>(
1539        &mut self,
1540        id: Option<impl Into<ElementId>>,
1541        f: impl FnOnce(&mut Self) -> R,
1542    ) -> R {
1543        if let Some(id) = id.map(Into::into) {
1544            let window = self.window_mut();
1545            window.element_id_stack.push(id.into());
1546            let result = f(self);
1547            let window: &mut Window = self.borrow_mut();
1548            window.element_id_stack.pop();
1549            result
1550        } else {
1551            f(self)
1552        }
1553    }
1554
1555    /// Invoke the given function with the given content mask after intersecting it
1556    /// with the current mask.
1557    fn with_content_mask<R>(
1558        &mut self,
1559        mask: Option<ContentMask<Pixels>>,
1560        f: impl FnOnce(&mut Self) -> R,
1561    ) -> R {
1562        if let Some(mask) = mask {
1563            let mask = mask.intersect(&self.content_mask());
1564            self.window_mut()
1565                .current_frame
1566                .content_mask_stack
1567                .push(mask);
1568            let result = f(self);
1569            self.window_mut().current_frame.content_mask_stack.pop();
1570            result
1571        } else {
1572            f(self)
1573        }
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: Point<Pixels>,
1581        f: impl FnOnce(&mut Self) -> R,
1582    ) -> R {
1583        if offset.is_zero() {
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(Some(id), |cx| {
1620            let global_id = cx.window().element_id_stack.clone();
1621
1622            if let Some(any) = cx
1623                .window_mut()
1624                .current_frame
1625                .element_states
1626                .remove(&global_id)
1627                .or_else(|| {
1628                    cx.window_mut()
1629                        .previous_frame
1630                        .element_states
1631                        .remove(&global_id)
1632                })
1633            {
1634                // Using the extra inner option to avoid needing to reallocate a new box.
1635                let mut state_box = any
1636                    .downcast::<Option<S>>()
1637                    .expect("invalid element state type for id");
1638                let state = state_box
1639                    .take()
1640                    .expect("element state is already on the stack");
1641                let (result, state) = f(Some(state), cx);
1642                state_box.replace(state);
1643                cx.window_mut()
1644                    .current_frame
1645                    .element_states
1646                    .insert(global_id, state_box);
1647                result
1648            } else {
1649                let (result, state) = f(None, cx);
1650                cx.window_mut()
1651                    .current_frame
1652                    .element_states
1653                    .insert(global_id, Box::new(Some(state)));
1654                result
1655            }
1656        })
1657    }
1658
1659    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1660    /// id is `None`, no state will be retrieved or stored.
1661    fn with_optional_element_state<S, R>(
1662        &mut self,
1663        element_id: Option<ElementId>,
1664        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1665    ) -> R
1666    where
1667        S: 'static,
1668    {
1669        if let Some(element_id) = element_id {
1670            self.with_element_state(element_id, f)
1671        } else {
1672            f(None, self).0
1673        }
1674    }
1675
1676    /// Obtain the current content mask.
1677    fn content_mask(&self) -> ContentMask<Pixels> {
1678        self.window()
1679            .current_frame
1680            .content_mask_stack
1681            .last()
1682            .cloned()
1683            .unwrap_or_else(|| ContentMask {
1684                bounds: Bounds {
1685                    origin: Point::default(),
1686                    size: self.window().viewport_size,
1687                },
1688            })
1689    }
1690
1691    /// The size of an em for the base font of the application. Adjusting this value allows the
1692    /// UI to scale, just like zooming a web page.
1693    fn rem_size(&self) -> Pixels {
1694        self.window().rem_size
1695    }
1696}
1697
1698impl Borrow<Window> for WindowContext<'_> {
1699    fn borrow(&self) -> &Window {
1700        &self.window
1701    }
1702}
1703
1704impl BorrowMut<Window> for WindowContext<'_> {
1705    fn borrow_mut(&mut self) -> &mut Window {
1706        &mut self.window
1707    }
1708}
1709
1710impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1711
1712pub struct ViewContext<'a, V> {
1713    window_cx: WindowContext<'a>,
1714    view: &'a View<V>,
1715}
1716
1717impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1718    fn borrow(&self) -> &AppContext {
1719        &*self.window_cx.app
1720    }
1721}
1722
1723impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1724    fn borrow_mut(&mut self) -> &mut AppContext {
1725        &mut *self.window_cx.app
1726    }
1727}
1728
1729impl<V> Borrow<Window> for ViewContext<'_, V> {
1730    fn borrow(&self) -> &Window {
1731        &*self.window_cx.window
1732    }
1733}
1734
1735impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1736    fn borrow_mut(&mut self) -> &mut Window {
1737        &mut *self.window_cx.window
1738    }
1739}
1740
1741impl<'a, V: 'static> ViewContext<'a, V> {
1742    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1743        Self {
1744            window_cx: WindowContext::new(app, window),
1745            view,
1746        }
1747    }
1748
1749    // todo!("change this to return a reference");
1750    pub fn view(&self) -> View<V> {
1751        self.view.clone()
1752    }
1753
1754    pub fn model(&self) -> Model<V> {
1755        self.view.model.clone()
1756    }
1757
1758    /// Access the underlying window context.
1759    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1760        &mut self.window_cx
1761    }
1762
1763    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1764        self.window.current_frame.z_index_stack.push(z_index);
1765        let result = f(self);
1766        self.window.current_frame.z_index_stack.pop();
1767        result
1768    }
1769
1770    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1771    where
1772        V: 'static,
1773    {
1774        let view = self.view();
1775        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1776    }
1777
1778    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1779    /// that are currently on the stack to be returned to the app.
1780    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1781        let view = self.view().downgrade();
1782        self.window_cx.defer(move |cx| {
1783            view.update(cx, f).ok();
1784        });
1785    }
1786
1787    pub fn observe<V2, E>(
1788        &mut self,
1789        entity: &E,
1790        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1791    ) -> Subscription
1792    where
1793        V2: 'static,
1794        V: 'static,
1795        E: Entity<V2>,
1796    {
1797        let view = self.view().downgrade();
1798        let entity_id = entity.entity_id();
1799        let entity = entity.downgrade();
1800        let window_handle = self.window.handle;
1801        self.app.observers.insert(
1802            entity_id,
1803            Box::new(move |cx| {
1804                window_handle
1805                    .update(cx, |_, cx| {
1806                        if let Some(handle) = E::upgrade_from(&entity) {
1807                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1808                                .is_ok()
1809                        } else {
1810                            false
1811                        }
1812                    })
1813                    .unwrap_or(false)
1814            }),
1815        )
1816    }
1817
1818    pub fn subscribe<V2, E, Evt>(
1819        &mut self,
1820        entity: &E,
1821        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1822    ) -> Subscription
1823    where
1824        V2: EventEmitter<Evt>,
1825        E: Entity<V2>,
1826        Evt: 'static,
1827    {
1828        let view = self.view().downgrade();
1829        let entity_id = entity.entity_id();
1830        let handle = entity.downgrade();
1831        let window_handle = self.window.handle;
1832        self.app.event_listeners.insert(
1833            entity_id,
1834            (
1835                TypeId::of::<Evt>(),
1836                Box::new(move |event, cx| {
1837                    window_handle
1838                        .update(cx, |_, cx| {
1839                            if let Some(handle) = E::upgrade_from(&handle) {
1840                                let event = event.downcast_ref().expect("invalid event type");
1841                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1842                                    .is_ok()
1843                            } else {
1844                                false
1845                            }
1846                        })
1847                        .unwrap_or(false)
1848                }),
1849            ),
1850        )
1851    }
1852
1853    pub fn on_release(
1854        &mut self,
1855        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1856    ) -> Subscription {
1857        let window_handle = self.window.handle;
1858        self.app.release_listeners.insert(
1859            self.view.model.entity_id,
1860            Box::new(move |this, cx| {
1861                let this = this.downcast_mut().expect("invalid entity type");
1862                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1863            }),
1864        )
1865    }
1866
1867    pub fn observe_release<V2, E>(
1868        &mut self,
1869        entity: &E,
1870        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1871    ) -> Subscription
1872    where
1873        V: 'static,
1874        V2: 'static,
1875        E: Entity<V2>,
1876    {
1877        let view = self.view().downgrade();
1878        let entity_id = entity.entity_id();
1879        let window_handle = self.window.handle;
1880        self.app.release_listeners.insert(
1881            entity_id,
1882            Box::new(move |entity, cx| {
1883                let entity = entity.downcast_mut().expect("invalid entity type");
1884                let _ = window_handle.update(cx, |_, cx| {
1885                    view.update(cx, |this, cx| on_release(this, entity, cx))
1886                });
1887            }),
1888        )
1889    }
1890
1891    pub fn notify(&mut self) {
1892        self.window_cx.notify();
1893        self.window_cx.app.push_effect(Effect::Notify {
1894            emitter: self.view.model.entity_id,
1895        });
1896    }
1897
1898    pub fn observe_window_bounds(
1899        &mut self,
1900        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1901    ) -> Subscription {
1902        let view = self.view.downgrade();
1903        self.window.bounds_observers.insert(
1904            (),
1905            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1906        )
1907    }
1908
1909    pub fn observe_window_activation(
1910        &mut self,
1911        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1912    ) -> Subscription {
1913        let view = self.view.downgrade();
1914        self.window.activation_observers.insert(
1915            (),
1916            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1917        )
1918    }
1919
1920    /// Register a listener to be called when the given focus handle receives focus.
1921    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1922    /// is dropped.
1923    pub fn on_focus(
1924        &mut self,
1925        handle: &FocusHandle,
1926        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1927    ) -> Subscription {
1928        let view = self.view.downgrade();
1929        let focus_id = handle.id;
1930        self.window.focus_listeners.insert(
1931            (),
1932            Box::new(move |event, cx| {
1933                view.update(cx, |view, cx| {
1934                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
1935                        listener(view, cx)
1936                    }
1937                })
1938                .is_ok()
1939            }),
1940        )
1941    }
1942
1943    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
1944    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1945    /// is dropped.
1946    pub fn on_focus_in(
1947        &mut self,
1948        handle: &FocusHandle,
1949        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1950    ) -> Subscription {
1951        let view = self.view.downgrade();
1952        let focus_id = handle.id;
1953        self.window.focus_listeners.insert(
1954            (),
1955            Box::new(move |event, cx| {
1956                view.update(cx, |view, cx| {
1957                    if event
1958                        .focused
1959                        .as_ref()
1960                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
1961                    {
1962                        listener(view, cx)
1963                    }
1964                })
1965                .is_ok()
1966            }),
1967        )
1968    }
1969
1970    /// Register a listener to be called when the given focus handle loses focus.
1971    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1972    /// is dropped.
1973    pub fn on_blur(
1974        &mut self,
1975        handle: &FocusHandle,
1976        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1977    ) -> Subscription {
1978        let view = self.view.downgrade();
1979        let focus_id = handle.id;
1980        self.window.focus_listeners.insert(
1981            (),
1982            Box::new(move |event, cx| {
1983                view.update(cx, |view, cx| {
1984                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
1985                        listener(view, cx)
1986                    }
1987                })
1988                .is_ok()
1989            }),
1990        )
1991    }
1992
1993    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
1994    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1995    /// is dropped.
1996    pub fn on_focus_out(
1997        &mut self,
1998        handle: &FocusHandle,
1999        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2000    ) -> Subscription {
2001        let view = self.view.downgrade();
2002        let focus_id = handle.id;
2003        self.window.focus_listeners.insert(
2004            (),
2005            Box::new(move |event, cx| {
2006                view.update(cx, |view, cx| {
2007                    if event
2008                        .blurred
2009                        .as_ref()
2010                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2011                    {
2012                        listener(view, cx)
2013                    }
2014                })
2015                .is_ok()
2016            }),
2017        )
2018    }
2019
2020    /// Register a focus listener for the current frame only. It will be cleared
2021    /// on the next frame render. You should use this method only from within elements,
2022    /// and we may want to enforce that better via a different context type.
2023    // todo!() Move this to `FrameContext` to emphasize its individuality?
2024    pub fn on_focus_changed(
2025        &mut self,
2026        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
2027    ) {
2028        let handle = self.view().downgrade();
2029        self.window
2030            .current_frame
2031            .focus_listeners
2032            .push(Box::new(move |event, cx| {
2033                handle
2034                    .update(cx, |view, cx| listener(view, event, cx))
2035                    .log_err();
2036            }));
2037    }
2038
2039    pub fn with_key_dispatch<R>(
2040        &mut self,
2041        context: KeyContext,
2042        focus_handle: Option<FocusHandle>,
2043        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
2044    ) -> R {
2045        let window = &mut self.window;
2046
2047        window
2048            .current_frame
2049            .dispatch_tree
2050            .push_node(context, &mut window.previous_frame.dispatch_tree);
2051        if let Some(focus_handle) = focus_handle.as_ref() {
2052            window
2053                .current_frame
2054                .dispatch_tree
2055                .make_focusable(focus_handle.id);
2056        }
2057        let result = f(focus_handle, self);
2058
2059        self.window.current_frame.dispatch_tree.pop_node();
2060
2061        result
2062    }
2063
2064    pub fn spawn<Fut, R>(
2065        &mut self,
2066        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2067    ) -> Task<R>
2068    where
2069        R: 'static,
2070        Fut: Future<Output = R> + 'static,
2071    {
2072        let view = self.view().downgrade();
2073        self.window_cx.spawn(|cx| f(view, cx))
2074    }
2075
2076    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2077    where
2078        G: 'static,
2079    {
2080        let mut global = self.app.lease_global::<G>();
2081        let result = f(&mut global, self);
2082        self.app.end_global_lease(global);
2083        result
2084    }
2085
2086    pub fn observe_global<G: 'static>(
2087        &mut self,
2088        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
2089    ) -> Subscription {
2090        let window_handle = self.window.handle;
2091        let view = self.view().downgrade();
2092        self.global_observers.insert(
2093            TypeId::of::<G>(),
2094            Box::new(move |cx| {
2095                window_handle
2096                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2097                    .unwrap_or(false)
2098            }),
2099        )
2100    }
2101
2102    pub fn on_mouse_event<Event: 'static>(
2103        &mut self,
2104        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2105    ) {
2106        let handle = self.view();
2107        self.window_cx.on_mouse_event(move |event, phase, cx| {
2108            handle.update(cx, |view, cx| {
2109                handler(view, event, phase, cx);
2110            })
2111        });
2112    }
2113
2114    pub fn on_key_event<Event: 'static>(
2115        &mut self,
2116        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2117    ) {
2118        let handle = self.view();
2119        self.window_cx.on_key_event(move |event, phase, cx| {
2120            handle.update(cx, |view, cx| {
2121                handler(view, event, phase, cx);
2122            })
2123        });
2124    }
2125
2126    pub fn on_action(
2127        &mut self,
2128        action_type: TypeId,
2129        handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2130    ) {
2131        let handle = self.view();
2132        self.window_cx
2133            .on_action(action_type, move |action, phase, cx| {
2134                handle.update(cx, |view, cx| {
2135                    handler(view, action, phase, cx);
2136                })
2137            });
2138    }
2139
2140    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
2141    /// platform to receive textual input with proper integration with concerns such
2142    /// as IME interactions.
2143    pub fn handle_input(
2144        &mut self,
2145        focus_handle: &FocusHandle,
2146        input_handler: impl PlatformInputHandler,
2147    ) {
2148        if focus_handle.is_focused(self) {
2149            self.window
2150                .platform_window
2151                .set_input_handler(Box::new(input_handler));
2152        }
2153    }
2154}
2155
2156impl<V> ViewContext<'_, V> {
2157    pub fn emit<Evt>(&mut self, event: Evt)
2158    where
2159        Evt: 'static,
2160        V: EventEmitter<Evt>,
2161    {
2162        let emitter = self.view.model.entity_id;
2163        self.app.push_effect(Effect::Emit {
2164            emitter,
2165            event_type: TypeId::of::<Evt>(),
2166            event: Box::new(event),
2167        });
2168    }
2169}
2170
2171impl<V> Context for ViewContext<'_, V> {
2172    type Result<U> = U;
2173
2174    fn build_model<T: 'static>(
2175        &mut self,
2176        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2177    ) -> Model<T> {
2178        self.window_cx.build_model(build_model)
2179    }
2180
2181    fn update_model<T: 'static, R>(
2182        &mut self,
2183        model: &Model<T>,
2184        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2185    ) -> R {
2186        self.window_cx.update_model(model, update)
2187    }
2188
2189    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2190    where
2191        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2192    {
2193        self.window_cx.update_window(window, update)
2194    }
2195
2196    fn read_model<T, R>(
2197        &self,
2198        handle: &Model<T>,
2199        read: impl FnOnce(&T, &AppContext) -> R,
2200    ) -> Self::Result<R>
2201    where
2202        T: 'static,
2203    {
2204        self.window_cx.read_model(handle, read)
2205    }
2206}
2207
2208impl<V: 'static> VisualContext for ViewContext<'_, V> {
2209    fn build_view<W: Render + 'static>(
2210        &mut self,
2211        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2212    ) -> Self::Result<View<W>> {
2213        self.window_cx.build_view(build_view_state)
2214    }
2215
2216    fn update_view<V2: 'static, R>(
2217        &mut self,
2218        view: &View<V2>,
2219        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2220    ) -> Self::Result<R> {
2221        self.window_cx.update_view(view, update)
2222    }
2223
2224    fn replace_root_view<W>(
2225        &mut self,
2226        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2227    ) -> Self::Result<View<W>>
2228    where
2229        W: Render,
2230    {
2231        self.window_cx.replace_root_view(build_view)
2232    }
2233}
2234
2235impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2236    type Target = WindowContext<'a>;
2237
2238    fn deref(&self) -> &Self::Target {
2239        &self.window_cx
2240    }
2241}
2242
2243impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2244    fn deref_mut(&mut self) -> &mut Self::Target {
2245        &mut self.window_cx
2246    }
2247}
2248
2249// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2250slotmap::new_key_type! { pub struct WindowId; }
2251
2252impl WindowId {
2253    pub fn as_u64(&self) -> u64 {
2254        self.0.as_ffi()
2255    }
2256}
2257
2258#[derive(Deref, DerefMut)]
2259pub struct WindowHandle<V> {
2260    #[deref]
2261    #[deref_mut]
2262    pub(crate) any_handle: AnyWindowHandle,
2263    state_type: PhantomData<V>,
2264}
2265
2266impl<V: 'static + Render> WindowHandle<V> {
2267    pub fn new(id: WindowId) -> Self {
2268        WindowHandle {
2269            any_handle: AnyWindowHandle {
2270                id,
2271                state_type: TypeId::of::<V>(),
2272            },
2273            state_type: PhantomData,
2274        }
2275    }
2276
2277    pub fn update<C, R>(
2278        self,
2279        cx: &mut C,
2280        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2281    ) -> Result<R>
2282    where
2283        C: Context,
2284    {
2285        cx.update_window(self.any_handle, |root_view, cx| {
2286            let view = root_view
2287                .downcast::<V>()
2288                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2289            Ok(cx.update_view(&view, update))
2290        })?
2291    }
2292}
2293
2294impl<V> Copy for WindowHandle<V> {}
2295
2296impl<V> Clone for WindowHandle<V> {
2297    fn clone(&self) -> Self {
2298        WindowHandle {
2299            any_handle: self.any_handle,
2300            state_type: PhantomData,
2301        }
2302    }
2303}
2304
2305impl<V> PartialEq for WindowHandle<V> {
2306    fn eq(&self, other: &Self) -> bool {
2307        self.any_handle == other.any_handle
2308    }
2309}
2310
2311impl<V> Eq for WindowHandle<V> {}
2312
2313impl<V> Hash for WindowHandle<V> {
2314    fn hash<H: Hasher>(&self, state: &mut H) {
2315        self.any_handle.hash(state);
2316    }
2317}
2318
2319impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2320    fn into(self) -> AnyWindowHandle {
2321        self.any_handle
2322    }
2323}
2324
2325#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2326pub struct AnyWindowHandle {
2327    pub(crate) id: WindowId,
2328    state_type: TypeId,
2329}
2330
2331impl AnyWindowHandle {
2332    pub fn window_id(&self) -> WindowId {
2333        self.id
2334    }
2335
2336    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2337        if TypeId::of::<T>() == self.state_type {
2338            Some(WindowHandle {
2339                any_handle: *self,
2340                state_type: PhantomData,
2341            })
2342        } else {
2343            None
2344        }
2345    }
2346
2347    pub fn update<C, R>(
2348        self,
2349        cx: &mut C,
2350        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2351    ) -> Result<R>
2352    where
2353        C: Context,
2354    {
2355        cx.update_window(self, update)
2356    }
2357}
2358
2359#[cfg(any(test, feature = "test-support"))]
2360impl From<SmallVec<[u32; 16]>> for StackingOrder {
2361    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2362        StackingOrder(small_vec)
2363    }
2364}
2365
2366#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2367pub enum ElementId {
2368    View(EntityId),
2369    Number(usize),
2370    Name(SharedString),
2371    FocusHandle(FocusId),
2372}
2373
2374impl From<EntityId> for ElementId {
2375    fn from(id: EntityId) -> Self {
2376        ElementId::View(id)
2377    }
2378}
2379
2380impl From<usize> for ElementId {
2381    fn from(id: usize) -> Self {
2382        ElementId::Number(id)
2383    }
2384}
2385
2386impl From<i32> for ElementId {
2387    fn from(id: i32) -> Self {
2388        Self::Number(id as usize)
2389    }
2390}
2391
2392impl From<SharedString> for ElementId {
2393    fn from(name: SharedString) -> Self {
2394        ElementId::Name(name)
2395    }
2396}
2397
2398impl From<&'static str> for ElementId {
2399    fn from(name: &'static str) -> Self {
2400        ElementId::Name(name.into())
2401    }
2402}
2403
2404impl<'a> From<&'a FocusHandle> for ElementId {
2405    fn from(handle: &'a FocusHandle) -> Self {
2406        ElementId::FocusHandle(handle.id)
2407    }
2408}