window.rs

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