window.rs

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