window.rs

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