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