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