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