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