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