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