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