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