window.rs

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