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