window.rs

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