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            let mut actions = self
1490                .window
1491                .current_frame
1492                .dispatch_tree
1493                .available_actions(focus_id);
1494            actions.extend(
1495                self.app
1496                    .global_action_listeners
1497                    .keys()
1498                    .filter_map(|type_id| self.app.actions.build_action_type(type_id).ok()),
1499            );
1500            actions
1501        } else {
1502            Vec::new()
1503        }
1504    }
1505
1506    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1507        self.window
1508            .current_frame
1509            .dispatch_tree
1510            .bindings_for_action(action)
1511    }
1512
1513    pub fn listener_for<V: Render, E>(
1514        &self,
1515        view: &View<V>,
1516        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1517    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1518        let view = view.downgrade();
1519        move |e: &E, cx: &mut WindowContext| {
1520            view.update(cx, |view, cx| f(view, e, cx)).ok();
1521        }
1522    }
1523
1524    pub fn handler_for<V: Render>(
1525        &self,
1526        view: &View<V>,
1527        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1528    ) -> impl Fn(&mut WindowContext) {
1529        let view = view.downgrade();
1530        move |cx: &mut WindowContext| {
1531            view.update(cx, |view, cx| f(view, cx)).ok();
1532        }
1533    }
1534
1535    //========== ELEMENT RELATED FUNCTIONS ===========
1536    pub fn with_key_dispatch<R>(
1537        &mut self,
1538        context: KeyContext,
1539        focus_handle: Option<FocusHandle>,
1540        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1541    ) -> R {
1542        let window = &mut self.window;
1543        window
1544            .current_frame
1545            .dispatch_tree
1546            .push_node(context.clone());
1547        if let Some(focus_handle) = focus_handle.as_ref() {
1548            window
1549                .current_frame
1550                .dispatch_tree
1551                .make_focusable(focus_handle.id);
1552        }
1553        let result = f(focus_handle, self);
1554
1555        self.window.current_frame.dispatch_tree.pop_node();
1556
1557        result
1558    }
1559
1560    /// Register a focus listener for the current frame only. It will be cleared
1561    /// on the next frame render. You should use this method only from within elements,
1562    /// and we may want to enforce that better via a different context type.
1563    // todo!() Move this to `FrameContext` to emphasize its individuality?
1564    pub fn on_focus_changed(
1565        &mut self,
1566        listener: impl Fn(&FocusEvent, &mut WindowContext) + 'static,
1567    ) {
1568        self.window
1569            .current_frame
1570            .focus_listeners
1571            .push(Box::new(move |event, cx| {
1572                listener(event, cx);
1573            }));
1574    }
1575
1576    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1577    /// platform to receive textual input with proper integration with concerns such
1578    /// as IME interactions.
1579    pub fn handle_input(
1580        &mut self,
1581        focus_handle: &FocusHandle,
1582        input_handler: impl PlatformInputHandler,
1583    ) {
1584        if focus_handle.is_focused(self) {
1585            self.window
1586                .platform_window
1587                .set_input_handler(Box::new(input_handler));
1588        }
1589    }
1590
1591    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1592        let mut this = self.to_async();
1593        self.window
1594            .platform_window
1595            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1596    }
1597}
1598
1599impl Context for WindowContext<'_> {
1600    type Result<T> = T;
1601
1602    fn build_model<T>(
1603        &mut self,
1604        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1605    ) -> Model<T>
1606    where
1607        T: 'static,
1608    {
1609        let slot = self.app.entities.reserve();
1610        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1611        self.entities.insert(slot, model)
1612    }
1613
1614    fn update_model<T: 'static, R>(
1615        &mut self,
1616        model: &Model<T>,
1617        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1618    ) -> R {
1619        let mut entity = self.entities.lease(model);
1620        let result = update(
1621            &mut *entity,
1622            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1623        );
1624        self.entities.end_lease(entity);
1625        result
1626    }
1627
1628    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1629    where
1630        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1631    {
1632        if window == self.window.handle {
1633            let root_view = self.window.root_view.clone().unwrap();
1634            Ok(update(root_view, self))
1635        } else {
1636            window.update(self.app, update)
1637        }
1638    }
1639
1640    fn read_model<T, R>(
1641        &self,
1642        handle: &Model<T>,
1643        read: impl FnOnce(&T, &AppContext) -> R,
1644    ) -> Self::Result<R>
1645    where
1646        T: 'static,
1647    {
1648        let entity = self.entities.read(handle);
1649        read(&*entity, &*self.app)
1650    }
1651
1652    fn read_window<T, R>(
1653        &self,
1654        window: &WindowHandle<T>,
1655        read: impl FnOnce(View<T>, &AppContext) -> R,
1656    ) -> Result<R>
1657    where
1658        T: 'static,
1659    {
1660        if window.any_handle == self.window.handle {
1661            let root_view = self
1662                .window
1663                .root_view
1664                .clone()
1665                .unwrap()
1666                .downcast::<T>()
1667                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1668            Ok(read(root_view, self))
1669        } else {
1670            self.app.read_window(window, read)
1671        }
1672    }
1673}
1674
1675impl VisualContext for WindowContext<'_> {
1676    fn build_view<V>(
1677        &mut self,
1678        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1679    ) -> Self::Result<View<V>>
1680    where
1681        V: 'static + Render,
1682    {
1683        let slot = self.app.entities.reserve();
1684        let view = View {
1685            model: slot.clone(),
1686        };
1687        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1688        let entity = build_view_state(&mut cx);
1689        cx.entities.insert(slot, entity);
1690
1691        cx.new_view_observers
1692            .clone()
1693            .retain(&TypeId::of::<V>(), |observer| {
1694                let any_view = AnyView::from(view.clone());
1695                (observer)(any_view, self);
1696                true
1697            });
1698
1699        view
1700    }
1701
1702    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1703    fn update_view<T: 'static, R>(
1704        &mut self,
1705        view: &View<T>,
1706        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1707    ) -> Self::Result<R> {
1708        let mut lease = self.app.entities.lease(&view.model);
1709        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1710        let result = update(&mut *lease, &mut cx);
1711        cx.app.entities.end_lease(lease);
1712        result
1713    }
1714
1715    fn replace_root_view<V>(
1716        &mut self,
1717        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1718    ) -> Self::Result<View<V>>
1719    where
1720        V: 'static + Render,
1721    {
1722        let slot = self.app.entities.reserve();
1723        let view = View {
1724            model: slot.clone(),
1725        };
1726        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1727        let entity = build_view(&mut cx);
1728        self.entities.insert(slot, entity);
1729        self.window.root_view = Some(view.clone().into());
1730        view
1731    }
1732
1733    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1734        self.update_view(view, |view, cx| {
1735            view.focus_handle(cx).clone().focus(cx);
1736        })
1737    }
1738
1739    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1740    where
1741        V: ManagedView,
1742    {
1743        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1744    }
1745}
1746
1747impl<'a> std::ops::Deref for WindowContext<'a> {
1748    type Target = AppContext;
1749
1750    fn deref(&self) -> &Self::Target {
1751        &self.app
1752    }
1753}
1754
1755impl<'a> std::ops::DerefMut for WindowContext<'a> {
1756    fn deref_mut(&mut self) -> &mut Self::Target {
1757        &mut self.app
1758    }
1759}
1760
1761impl<'a> Borrow<AppContext> for WindowContext<'a> {
1762    fn borrow(&self) -> &AppContext {
1763        &self.app
1764    }
1765}
1766
1767impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1768    fn borrow_mut(&mut self) -> &mut AppContext {
1769        &mut self.app
1770    }
1771}
1772
1773pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1774    fn app_mut(&mut self) -> &mut AppContext {
1775        self.borrow_mut()
1776    }
1777
1778    fn app(&self) -> &AppContext {
1779        self.borrow()
1780    }
1781
1782    fn window(&self) -> &Window {
1783        self.borrow()
1784    }
1785
1786    fn window_mut(&mut self) -> &mut Window {
1787        self.borrow_mut()
1788    }
1789
1790    /// Pushes the given element id onto the global stack and invokes the given closure
1791    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1792    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1793    /// used to associate state with identified elements across separate frames.
1794    fn with_element_id<R>(
1795        &mut self,
1796        id: Option<impl Into<ElementId>>,
1797        f: impl FnOnce(&mut Self) -> R,
1798    ) -> R {
1799        if let Some(id) = id.map(Into::into) {
1800            let window = self.window_mut();
1801            window.element_id_stack.push(id.into());
1802            let result = f(self);
1803            let window: &mut Window = self.borrow_mut();
1804            window.element_id_stack.pop();
1805            result
1806        } else {
1807            f(self)
1808        }
1809    }
1810
1811    /// Invoke the given function with the given content mask after intersecting it
1812    /// with the current mask.
1813    fn with_content_mask<R>(
1814        &mut self,
1815        mask: Option<ContentMask<Pixels>>,
1816        f: impl FnOnce(&mut Self) -> R,
1817    ) -> R {
1818        if let Some(mask) = mask {
1819            let mask = mask.intersect(&self.content_mask());
1820            self.window_mut()
1821                .current_frame
1822                .content_mask_stack
1823                .push(mask);
1824            let result = f(self);
1825            self.window_mut().current_frame.content_mask_stack.pop();
1826            result
1827        } else {
1828            f(self)
1829        }
1830    }
1831
1832    /// Invoke the given function with the content mask reset to that
1833    /// of the window.
1834    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1835        let mask = ContentMask {
1836            bounds: Bounds {
1837                origin: Point::default(),
1838                size: self.window().viewport_size,
1839            },
1840        };
1841        self.window_mut()
1842            .current_frame
1843            .content_mask_stack
1844            .push(mask);
1845        let result = f(self);
1846        self.window_mut().current_frame.content_mask_stack.pop();
1847        result
1848    }
1849
1850    /// Update the global element offset relative to the current offset. This is used to implement
1851    /// scrolling.
1852    fn with_element_offset<R>(
1853        &mut self,
1854        offset: Point<Pixels>,
1855        f: impl FnOnce(&mut Self) -> R,
1856    ) -> R {
1857        if offset.is_zero() {
1858            return f(self);
1859        };
1860
1861        let abs_offset = self.element_offset() + offset;
1862        self.with_absolute_element_offset(abs_offset, f)
1863    }
1864
1865    /// Update the global element offset based on the given offset. This is used to implement
1866    /// drag handles and other manual painting of elements.
1867    fn with_absolute_element_offset<R>(
1868        &mut self,
1869        offset: Point<Pixels>,
1870        f: impl FnOnce(&mut Self) -> R,
1871    ) -> R {
1872        self.window_mut()
1873            .current_frame
1874            .element_offset_stack
1875            .push(offset);
1876        let result = f(self);
1877        self.window_mut().current_frame.element_offset_stack.pop();
1878        result
1879    }
1880
1881    /// Obtain the current element offset.
1882    fn element_offset(&self) -> Point<Pixels> {
1883        self.window()
1884            .current_frame
1885            .element_offset_stack
1886            .last()
1887            .copied()
1888            .unwrap_or_default()
1889    }
1890
1891    /// Update or intialize state for an element with the given id that lives across multiple
1892    /// frames. If an element with this id existed in the previous frame, its state will be passed
1893    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1894    /// when drawing the next frame.
1895    fn with_element_state<S, R>(
1896        &mut self,
1897        id: ElementId,
1898        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1899    ) -> R
1900    where
1901        S: 'static,
1902    {
1903        self.with_element_id(Some(id), |cx| {
1904            let global_id = cx.window().element_id_stack.clone();
1905
1906            if let Some(any) = cx
1907                .window_mut()
1908                .current_frame
1909                .element_states
1910                .remove(&global_id)
1911                .or_else(|| {
1912                    cx.window_mut()
1913                        .previous_frame
1914                        .element_states
1915                        .remove(&global_id)
1916                })
1917            {
1918                let ElementStateBox {
1919                    inner,
1920
1921                    #[cfg(debug_assertions)]
1922                    type_name
1923                } = any;
1924                // Using the extra inner option to avoid needing to reallocate a new box.
1925                let mut state_box = inner
1926                    .downcast::<Option<S>>()
1927                    .map_err(|_| {
1928                        #[cfg(debug_assertions)]
1929                        {
1930                            anyhow!(
1931                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
1932                                std::any::type_name::<S>(),
1933                                type_name
1934                            )
1935                        }
1936
1937                        #[cfg(not(debug_assertions))]
1938                        {
1939                            anyhow!(
1940                                "invalid element state type for id, requested_type {:?}",
1941                                std::any::type_name::<S>(),
1942                            )
1943                        }
1944                    })
1945                    .unwrap();
1946
1947                // Actual: Option<AnyElement> <- View
1948                // Requested: () <- AnyElemet
1949                let state = state_box
1950                    .take()
1951                    .expect("element state is already on the stack");
1952                let (result, state) = f(Some(state), cx);
1953                state_box.replace(state);
1954                cx.window_mut()
1955                    .current_frame
1956                    .element_states
1957                    .insert(global_id, ElementStateBox {
1958                        inner: state_box,
1959
1960                        #[cfg(debug_assertions)]
1961                        type_name
1962                    });
1963                result
1964            } else {
1965                let (result, state) = f(None, cx);
1966                cx.window_mut()
1967                    .current_frame
1968                    .element_states
1969                    .insert(global_id,
1970                        ElementStateBox {
1971                            inner: Box::new(Some(state)),
1972
1973                            #[cfg(debug_assertions)]
1974                            type_name: std::any::type_name::<S>()
1975                        }
1976
1977                    );
1978                result
1979            }
1980        })
1981    }
1982
1983    /// Obtain the current content mask.
1984    fn content_mask(&self) -> ContentMask<Pixels> {
1985        self.window()
1986            .current_frame
1987            .content_mask_stack
1988            .last()
1989            .cloned()
1990            .unwrap_or_else(|| ContentMask {
1991                bounds: Bounds {
1992                    origin: Point::default(),
1993                    size: self.window().viewport_size,
1994                },
1995            })
1996    }
1997
1998    /// The size of an em for the base font of the application. Adjusting this value allows the
1999    /// UI to scale, just like zooming a web page.
2000    fn rem_size(&self) -> Pixels {
2001        self.window().rem_size
2002    }
2003}
2004
2005impl Borrow<Window> for WindowContext<'_> {
2006    fn borrow(&self) -> &Window {
2007        &self.window
2008    }
2009}
2010
2011impl BorrowMut<Window> for WindowContext<'_> {
2012    fn borrow_mut(&mut self) -> &mut Window {
2013        &mut self.window
2014    }
2015}
2016
2017impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2018
2019pub struct ViewContext<'a, V> {
2020    window_cx: WindowContext<'a>,
2021    view: &'a View<V>,
2022}
2023
2024impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2025    fn borrow(&self) -> &AppContext {
2026        &*self.window_cx.app
2027    }
2028}
2029
2030impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2031    fn borrow_mut(&mut self) -> &mut AppContext {
2032        &mut *self.window_cx.app
2033    }
2034}
2035
2036impl<V> Borrow<Window> for ViewContext<'_, V> {
2037    fn borrow(&self) -> &Window {
2038        &*self.window_cx.window
2039    }
2040}
2041
2042impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2043    fn borrow_mut(&mut self) -> &mut Window {
2044        &mut *self.window_cx.window
2045    }
2046}
2047
2048impl<'a, V: 'static> ViewContext<'a, V> {
2049    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2050        Self {
2051            window_cx: WindowContext::new(app, window),
2052            view,
2053        }
2054    }
2055
2056    pub fn entity_id(&self) -> EntityId {
2057        self.view.entity_id()
2058    }
2059
2060    pub fn view(&self) -> &View<V> {
2061        self.view
2062    }
2063
2064    pub fn model(&self) -> &Model<V> {
2065        &self.view.model
2066    }
2067
2068    /// Access the underlying window context.
2069    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2070        &mut self.window_cx
2071    }
2072
2073    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
2074        self.window.current_frame.z_index_stack.push(z_index);
2075        let result = f(self);
2076        self.window.current_frame.z_index_stack.pop();
2077        result
2078    }
2079
2080    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2081    where
2082        V: 'static,
2083    {
2084        let view = self.view().clone();
2085        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2086    }
2087
2088    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2089    /// that are currently on the stack to be returned to the app.
2090    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2091        let view = self.view().downgrade();
2092        self.window_cx.defer(move |cx| {
2093            view.update(cx, f).ok();
2094        });
2095    }
2096
2097    pub fn observe<V2, E>(
2098        &mut self,
2099        entity: &E,
2100        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2101    ) -> Subscription
2102    where
2103        V2: 'static,
2104        V: 'static,
2105        E: Entity<V2>,
2106    {
2107        let view = self.view().downgrade();
2108        let entity_id = entity.entity_id();
2109        let entity = entity.downgrade();
2110        let window_handle = self.window.handle;
2111        let (subscription, activate) = self.app.observers.insert(
2112            entity_id,
2113            Box::new(move |cx| {
2114                window_handle
2115                    .update(cx, |_, cx| {
2116                        if let Some(handle) = E::upgrade_from(&entity) {
2117                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2118                                .is_ok()
2119                        } else {
2120                            false
2121                        }
2122                    })
2123                    .unwrap_or(false)
2124            }),
2125        );
2126        self.app.defer(move |_| activate());
2127        subscription
2128    }
2129
2130    pub fn subscribe<V2, E, Evt>(
2131        &mut self,
2132        entity: &E,
2133        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2134    ) -> Subscription
2135    where
2136        V2: EventEmitter<Evt>,
2137        E: Entity<V2>,
2138        Evt: 'static,
2139    {
2140        let view = self.view().downgrade();
2141        let entity_id = entity.entity_id();
2142        let handle = entity.downgrade();
2143        let window_handle = self.window.handle;
2144        let (subscription, activate) = self.app.event_listeners.insert(
2145            entity_id,
2146            (
2147                TypeId::of::<Evt>(),
2148                Box::new(move |event, cx| {
2149                    window_handle
2150                        .update(cx, |_, cx| {
2151                            if let Some(handle) = E::upgrade_from(&handle) {
2152                                let event = event.downcast_ref().expect("invalid event type");
2153                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2154                                    .is_ok()
2155                            } else {
2156                                false
2157                            }
2158                        })
2159                        .unwrap_or(false)
2160                }),
2161            ),
2162        );
2163        self.app.defer(move |_| activate());
2164        subscription
2165    }
2166
2167    pub fn on_release(
2168        &mut self,
2169        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2170    ) -> Subscription {
2171        let window_handle = self.window.handle;
2172        let (subscription, activate) = self.app.release_listeners.insert(
2173            self.view.model.entity_id,
2174            Box::new(move |this, cx| {
2175                let this = this.downcast_mut().expect("invalid entity type");
2176                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2177            }),
2178        );
2179        activate();
2180        subscription
2181    }
2182
2183    pub fn observe_release<V2, E>(
2184        &mut self,
2185        entity: &E,
2186        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2187    ) -> Subscription
2188    where
2189        V: 'static,
2190        V2: 'static,
2191        E: Entity<V2>,
2192    {
2193        let view = self.view().downgrade();
2194        let entity_id = entity.entity_id();
2195        let window_handle = self.window.handle;
2196        let (subscription, activate) = self.app.release_listeners.insert(
2197            entity_id,
2198            Box::new(move |entity, cx| {
2199                let entity = entity.downcast_mut().expect("invalid entity type");
2200                let _ = window_handle.update(cx, |_, cx| {
2201                    view.update(cx, |this, cx| on_release(this, entity, cx))
2202                });
2203            }),
2204        );
2205        activate();
2206        subscription
2207    }
2208
2209    pub fn notify(&mut self) {
2210        self.window_cx.notify();
2211        self.window_cx.app.push_effect(Effect::Notify {
2212            emitter: self.view.model.entity_id,
2213        });
2214    }
2215
2216    pub fn observe_window_bounds(
2217        &mut self,
2218        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2219    ) -> Subscription {
2220        let view = self.view.downgrade();
2221        let (subscription, activate) = self.window.bounds_observers.insert(
2222            (),
2223            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2224        );
2225        activate();
2226        subscription
2227    }
2228
2229    pub fn observe_window_activation(
2230        &mut self,
2231        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2232    ) -> Subscription {
2233        let view = self.view.downgrade();
2234        let (subscription, activate) = self.window.activation_observers.insert(
2235            (),
2236            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2237        );
2238        activate();
2239        subscription
2240    }
2241
2242    /// Register a listener to be called when the given focus handle receives focus.
2243    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2244    /// is dropped.
2245    pub fn on_focus(
2246        &mut self,
2247        handle: &FocusHandle,
2248        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2249    ) -> Subscription {
2250        let view = self.view.downgrade();
2251        let focus_id = handle.id;
2252        let (subscription, activate) = self.window.focus_listeners.insert(
2253            (),
2254            Box::new(move |event, cx| {
2255                view.update(cx, |view, cx| {
2256                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2257                        listener(view, cx)
2258                    }
2259                })
2260                .is_ok()
2261            }),
2262        );
2263        self.app.defer(move |_| activate());
2264        subscription
2265    }
2266
2267    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2268    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2269    /// is dropped.
2270    pub fn on_focus_in(
2271        &mut self,
2272        handle: &FocusHandle,
2273        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2274    ) -> Subscription {
2275        let view = self.view.downgrade();
2276        let focus_id = handle.id;
2277        let (subscription, activate) = self.window.focus_listeners.insert(
2278            (),
2279            Box::new(move |event, cx| {
2280                view.update(cx, |view, cx| {
2281                    if event
2282                        .focused
2283                        .as_ref()
2284                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
2285                    {
2286                        listener(view, cx)
2287                    }
2288                })
2289                .is_ok()
2290            }),
2291        );
2292        self.app.defer(move |_| activate());
2293        subscription
2294    }
2295
2296    /// Register a listener to be called when the given focus handle loses focus.
2297    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2298    /// is dropped.
2299    pub fn on_blur(
2300        &mut self,
2301        handle: &FocusHandle,
2302        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2303    ) -> Subscription {
2304        let view = self.view.downgrade();
2305        let focus_id = handle.id;
2306        let (subscription, activate) = self.window.focus_listeners.insert(
2307            (),
2308            Box::new(move |event, cx| {
2309                view.update(cx, |view, cx| {
2310                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2311                        listener(view, cx)
2312                    }
2313                })
2314                .is_ok()
2315            }),
2316        );
2317        self.app.defer(move |_| activate());
2318        subscription
2319    }
2320
2321    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2322    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2323    /// is dropped.
2324    pub fn on_focus_out(
2325        &mut self,
2326        handle: &FocusHandle,
2327        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2328    ) -> Subscription {
2329        let view = self.view.downgrade();
2330        let focus_id = handle.id;
2331        let (subscription, activate) = self.window.focus_listeners.insert(
2332            (),
2333            Box::new(move |event, cx| {
2334                view.update(cx, |view, cx| {
2335                    if event
2336                        .blurred
2337                        .as_ref()
2338                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2339                    {
2340                        listener(view, cx)
2341                    }
2342                })
2343                .is_ok()
2344            }),
2345        );
2346        self.app.defer(move |_| activate());
2347        subscription
2348    }
2349
2350    pub fn spawn<Fut, R>(
2351        &mut self,
2352        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2353    ) -> Task<R>
2354    where
2355        R: 'static,
2356        Fut: Future<Output = R> + 'static,
2357    {
2358        let view = self.view().downgrade();
2359        self.window_cx.spawn(|cx| f(view, cx))
2360    }
2361
2362    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2363    where
2364        G: 'static,
2365    {
2366        let mut global = self.app.lease_global::<G>();
2367        let result = f(&mut global, self);
2368        self.app.end_global_lease(global);
2369        result
2370    }
2371
2372    pub fn observe_global<G: 'static>(
2373        &mut self,
2374        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2375    ) -> Subscription {
2376        let window_handle = self.window.handle;
2377        let view = self.view().downgrade();
2378        let (subscription, activate) = self.global_observers.insert(
2379            TypeId::of::<G>(),
2380            Box::new(move |cx| {
2381                window_handle
2382                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2383                    .unwrap_or(false)
2384            }),
2385        );
2386        self.app.defer(move |_| activate());
2387        subscription
2388    }
2389
2390    pub fn on_mouse_event<Event: 'static>(
2391        &mut self,
2392        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2393    ) {
2394        let handle = self.view().clone();
2395        self.window_cx.on_mouse_event(move |event, phase, cx| {
2396            handle.update(cx, |view, cx| {
2397                handler(view, event, phase, cx);
2398            })
2399        });
2400    }
2401
2402    pub fn on_key_event<Event: 'static>(
2403        &mut self,
2404        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2405    ) {
2406        let handle = self.view().clone();
2407        self.window_cx.on_key_event(move |event, phase, cx| {
2408            handle.update(cx, |view, cx| {
2409                handler(view, event, phase, cx);
2410            })
2411        });
2412    }
2413
2414    pub fn on_action(
2415        &mut self,
2416        action_type: TypeId,
2417        handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2418    ) {
2419        let handle = self.view().clone();
2420        self.window_cx
2421            .on_action(action_type, move |action, phase, cx| {
2422                handle.update(cx, |view, cx| {
2423                    handler(view, action, phase, cx);
2424                })
2425            });
2426    }
2427
2428    pub fn emit<Evt>(&mut self, event: Evt)
2429    where
2430        Evt: 'static,
2431        V: EventEmitter<Evt>,
2432    {
2433        let emitter = self.view.model.entity_id;
2434        self.app.push_effect(Effect::Emit {
2435            emitter,
2436            event_type: TypeId::of::<Evt>(),
2437            event: Box::new(event),
2438        });
2439    }
2440
2441    pub fn focus_self(&mut self)
2442    where
2443        V: FocusableView,
2444    {
2445        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2446    }
2447
2448    pub fn dismiss_self(&mut self)
2449    where
2450        V: ManagedView,
2451    {
2452        self.defer(|_, cx| cx.emit(DismissEvent))
2453    }
2454
2455    pub fn listener<E>(
2456        &self,
2457        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2458    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2459        let view = self.view().downgrade();
2460        move |e: &E, cx: &mut WindowContext| {
2461            view.update(cx, |view, cx| f(view, e, cx)).ok();
2462        }
2463    }
2464}
2465
2466impl<V> Context for ViewContext<'_, V> {
2467    type Result<U> = U;
2468
2469    fn build_model<T: 'static>(
2470        &mut self,
2471        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2472    ) -> Model<T> {
2473        self.window_cx.build_model(build_model)
2474    }
2475
2476    fn update_model<T: 'static, R>(
2477        &mut self,
2478        model: &Model<T>,
2479        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2480    ) -> R {
2481        self.window_cx.update_model(model, update)
2482    }
2483
2484    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2485    where
2486        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2487    {
2488        self.window_cx.update_window(window, update)
2489    }
2490
2491    fn read_model<T, R>(
2492        &self,
2493        handle: &Model<T>,
2494        read: impl FnOnce(&T, &AppContext) -> R,
2495    ) -> Self::Result<R>
2496    where
2497        T: 'static,
2498    {
2499        self.window_cx.read_model(handle, read)
2500    }
2501
2502    fn read_window<T, R>(
2503        &self,
2504        window: &WindowHandle<T>,
2505        read: impl FnOnce(View<T>, &AppContext) -> R,
2506    ) -> Result<R>
2507    where
2508        T: 'static,
2509    {
2510        self.window_cx.read_window(window, read)
2511    }
2512}
2513
2514impl<V: 'static> VisualContext for ViewContext<'_, V> {
2515    fn build_view<W: Render + 'static>(
2516        &mut self,
2517        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2518    ) -> Self::Result<View<W>> {
2519        self.window_cx.build_view(build_view_state)
2520    }
2521
2522    fn update_view<V2: 'static, R>(
2523        &mut self,
2524        view: &View<V2>,
2525        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2526    ) -> Self::Result<R> {
2527        self.window_cx.update_view(view, update)
2528    }
2529
2530    fn replace_root_view<W>(
2531        &mut self,
2532        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2533    ) -> Self::Result<View<W>>
2534    where
2535        W: 'static + Render,
2536    {
2537        self.window_cx.replace_root_view(build_view)
2538    }
2539
2540    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2541        self.window_cx.focus_view(view)
2542    }
2543
2544    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2545        self.window_cx.dismiss_view(view)
2546    }
2547}
2548
2549impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2550    type Target = WindowContext<'a>;
2551
2552    fn deref(&self) -> &Self::Target {
2553        &self.window_cx
2554    }
2555}
2556
2557impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2558    fn deref_mut(&mut self) -> &mut Self::Target {
2559        &mut self.window_cx
2560    }
2561}
2562
2563// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2564slotmap::new_key_type! { pub struct WindowId; }
2565
2566impl WindowId {
2567    pub fn as_u64(&self) -> u64 {
2568        self.0.as_ffi()
2569    }
2570}
2571
2572#[derive(Deref, DerefMut)]
2573pub struct WindowHandle<V> {
2574    #[deref]
2575    #[deref_mut]
2576    pub(crate) any_handle: AnyWindowHandle,
2577    state_type: PhantomData<V>,
2578}
2579
2580impl<V: 'static + Render> WindowHandle<V> {
2581    pub fn new(id: WindowId) -> Self {
2582        WindowHandle {
2583            any_handle: AnyWindowHandle {
2584                id,
2585                state_type: TypeId::of::<V>(),
2586            },
2587            state_type: PhantomData,
2588        }
2589    }
2590
2591    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2592    where
2593        C: Context,
2594    {
2595        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2596            root_view
2597                .downcast::<V>()
2598                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2599        }))
2600    }
2601
2602    pub fn update<C, R>(
2603        &self,
2604        cx: &mut C,
2605        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2606    ) -> Result<R>
2607    where
2608        C: Context,
2609    {
2610        cx.update_window(self.any_handle, |root_view, cx| {
2611            let view = root_view
2612                .downcast::<V>()
2613                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2614            Ok(cx.update_view(&view, update))
2615        })?
2616    }
2617
2618    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2619        let x = cx
2620            .windows
2621            .get(self.id)
2622            .and_then(|window| {
2623                window
2624                    .as_ref()
2625                    .and_then(|window| window.root_view.clone())
2626                    .map(|root_view| root_view.downcast::<V>())
2627            })
2628            .ok_or_else(|| anyhow!("window not found"))?
2629            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2630
2631        Ok(x.read(cx))
2632    }
2633
2634    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2635    where
2636        C: Context,
2637    {
2638        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2639    }
2640
2641    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2642    where
2643        C: Context,
2644    {
2645        cx.read_window(self, |root_view, _cx| root_view.clone())
2646    }
2647
2648    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2649        cx.windows
2650            .get(self.id)
2651            .and_then(|window| window.as_ref().map(|window| window.active))
2652    }
2653}
2654
2655impl<V> Copy for WindowHandle<V> {}
2656
2657impl<V> Clone for WindowHandle<V> {
2658    fn clone(&self) -> Self {
2659        WindowHandle {
2660            any_handle: self.any_handle,
2661            state_type: PhantomData,
2662        }
2663    }
2664}
2665
2666impl<V> PartialEq for WindowHandle<V> {
2667    fn eq(&self, other: &Self) -> bool {
2668        self.any_handle == other.any_handle
2669    }
2670}
2671
2672impl<V> Eq for WindowHandle<V> {}
2673
2674impl<V> Hash for WindowHandle<V> {
2675    fn hash<H: Hasher>(&self, state: &mut H) {
2676        self.any_handle.hash(state);
2677    }
2678}
2679
2680impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2681    fn into(self) -> AnyWindowHandle {
2682        self.any_handle
2683    }
2684}
2685
2686#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2687pub struct AnyWindowHandle {
2688    pub(crate) id: WindowId,
2689    state_type: TypeId,
2690}
2691
2692impl AnyWindowHandle {
2693    pub fn window_id(&self) -> WindowId {
2694        self.id
2695    }
2696
2697    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2698        if TypeId::of::<T>() == self.state_type {
2699            Some(WindowHandle {
2700                any_handle: *self,
2701                state_type: PhantomData,
2702            })
2703        } else {
2704            None
2705        }
2706    }
2707
2708    pub fn update<C, R>(
2709        self,
2710        cx: &mut C,
2711        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2712    ) -> Result<R>
2713    where
2714        C: Context,
2715    {
2716        cx.update_window(self, update)
2717    }
2718
2719    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2720    where
2721        C: Context,
2722        T: 'static,
2723    {
2724        let view = self
2725            .downcast::<T>()
2726            .context("the type of the window's root view has changed")?;
2727
2728        cx.read_window(&view, read)
2729    }
2730}
2731
2732#[cfg(any(test, feature = "test-support"))]
2733impl From<SmallVec<[u32; 16]>> for StackingOrder {
2734    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2735        StackingOrder(small_vec)
2736    }
2737}
2738
2739#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2740pub enum ElementId {
2741    View(EntityId),
2742    Integer(usize),
2743    Name(SharedString),
2744    FocusHandle(FocusId),
2745}
2746
2747impl ElementId {
2748    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2749        ElementId::View(entity_id)
2750    }
2751}
2752
2753impl TryInto<SharedString> for ElementId {
2754    type Error = anyhow::Error;
2755
2756    fn try_into(self) -> anyhow::Result<SharedString> {
2757        if let ElementId::Name(name) = self {
2758            Ok(name)
2759        } else {
2760            Err(anyhow!("element id is not string"))
2761        }
2762    }
2763}
2764
2765impl From<usize> for ElementId {
2766    fn from(id: usize) -> Self {
2767        ElementId::Integer(id)
2768    }
2769}
2770
2771impl From<i32> for ElementId {
2772    fn from(id: i32) -> Self {
2773        Self::Integer(id as usize)
2774    }
2775}
2776
2777impl From<SharedString> for ElementId {
2778    fn from(name: SharedString) -> Self {
2779        ElementId::Name(name)
2780    }
2781}
2782
2783impl From<&'static str> for ElementId {
2784    fn from(name: &'static str) -> Self {
2785        ElementId::Name(name.into())
2786    }
2787}
2788
2789impl<'a> From<&'a FocusHandle> for ElementId {
2790    fn from(handle: &'a FocusHandle) -> Self {
2791        ElementId::FocusHandle(handle.id)
2792    }
2793}