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