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