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(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                cx.with_element_offset(offset, |cx| {
1086                    let available_space =
1087                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1088                    active_drag.view.draw(available_space, cx);
1089                    cx.active_drag = Some(active_drag);
1090                });
1091            });
1092        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1093            self.with_z_index(1, |cx| {
1094                cx.with_element_offset(active_tooltip.cursor_offset, |cx| {
1095                    let available_space = Size {
1096                        width: cx.window.viewport_size.width - active_tooltip.cursor_offset.x,
1097                        height: cx.window.viewport_size.height - active_tooltip.cursor_offset.y,
1098                    }
1099                    .map(Into::into);
1100                    active_tooltip.view.draw(available_space, cx);
1101                });
1102            });
1103        }
1104
1105        self.window
1106            .current_frame
1107            .dispatch_tree
1108            .preserve_keystroke_matchers(
1109                &mut self.window.previous_frame.dispatch_tree,
1110                self.window.focus,
1111            );
1112
1113        self.window.root_view = Some(root_view);
1114        let scene = self.window.current_frame.scene_builder.build();
1115
1116        self.window.platform_window.draw(scene);
1117        let cursor_style = self
1118            .window
1119            .requested_cursor_style
1120            .take()
1121            .unwrap_or(CursorStyle::Arrow);
1122        self.platform.set_cursor_style(cursor_style);
1123
1124        self.window.dirty = false;
1125    }
1126
1127    /// Rotate the current frame and the previous frame, then clear the current frame.
1128    /// We repopulate all state in the current frame during each paint.
1129    fn start_frame(&mut self) {
1130        self.text_system().start_frame();
1131
1132        let window = &mut *self.window;
1133        window.layout_engine.clear();
1134
1135        mem::swap(&mut window.previous_frame, &mut window.current_frame);
1136        let frame = &mut window.current_frame;
1137        frame.element_states.clear();
1138        frame.mouse_listeners.values_mut().for_each(Vec::clear);
1139        frame.focus_listeners.clear();
1140        frame.dispatch_tree.clear();
1141    }
1142
1143    /// Dispatch a mouse or keyboard event on the window.
1144    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1145        // Handlers may set this to false by calling `stop_propagation`
1146        self.app.propagate_event = true;
1147        self.window.default_prevented = false;
1148
1149        let event = match event {
1150            // Track the mouse position with our own state, since accessing the platform
1151            // API for the mouse position can only occur on the main thread.
1152            InputEvent::MouseMove(mouse_move) => {
1153                self.window.mouse_position = mouse_move.position;
1154                InputEvent::MouseMove(mouse_move)
1155            }
1156            // Translate dragging and dropping of external files from the operating system
1157            // to internal drag and drop events.
1158            InputEvent::FileDrop(file_drop) => match file_drop {
1159                FileDropEvent::Entered { position, files } => {
1160                    self.window.mouse_position = position;
1161                    if self.active_drag.is_none() {
1162                        self.active_drag = Some(AnyDrag {
1163                            view: self.build_view(|_| files).into(),
1164                            cursor_offset: position,
1165                        });
1166                    }
1167                    InputEvent::MouseDown(MouseDownEvent {
1168                        position,
1169                        button: MouseButton::Left,
1170                        click_count: 1,
1171                        modifiers: Modifiers::default(),
1172                    })
1173                }
1174                FileDropEvent::Pending { position } => {
1175                    self.window.mouse_position = position;
1176                    InputEvent::MouseMove(MouseMoveEvent {
1177                        position,
1178                        pressed_button: Some(MouseButton::Left),
1179                        modifiers: Modifiers::default(),
1180                    })
1181                }
1182                FileDropEvent::Submit { position } => {
1183                    self.window.mouse_position = position;
1184                    InputEvent::MouseUp(MouseUpEvent {
1185                        button: MouseButton::Left,
1186                        position,
1187                        modifiers: Modifiers::default(),
1188                        click_count: 1,
1189                    })
1190                }
1191                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1192                    button: MouseButton::Left,
1193                    position: Point::default(),
1194                    modifiers: Modifiers::default(),
1195                    click_count: 1,
1196                }),
1197            },
1198            _ => event,
1199        };
1200
1201        if let Some(any_mouse_event) = event.mouse_event() {
1202            self.dispatch_mouse_event(any_mouse_event);
1203        } else if let Some(any_key_event) = event.keyboard_event() {
1204            self.dispatch_key_event(any_key_event);
1205        }
1206
1207        !self.app.propagate_event
1208    }
1209
1210    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1211        if let Some(mut handlers) = self
1212            .window
1213            .current_frame
1214            .mouse_listeners
1215            .remove(&event.type_id())
1216        {
1217            // Because handlers may add other handlers, we sort every time.
1218            handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1219
1220            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1221            // special purposes, such as detecting events outside of a given Bounds.
1222            for (_, handler) in &mut handlers {
1223                handler(event, DispatchPhase::Capture, self);
1224                if !self.app.propagate_event {
1225                    break;
1226                }
1227            }
1228
1229            // Bubble phase, where most normal handlers do their work.
1230            if self.app.propagate_event {
1231                for (_, handler) in handlers.iter_mut().rev() {
1232                    handler(event, DispatchPhase::Bubble, self);
1233                    if !self.app.propagate_event {
1234                        break;
1235                    }
1236                }
1237            }
1238
1239            if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1240                self.active_drag = None;
1241            }
1242
1243            // Just in case any handlers added new handlers, which is weird, but possible.
1244            handlers.extend(
1245                self.window
1246                    .current_frame
1247                    .mouse_listeners
1248                    .get_mut(&event.type_id())
1249                    .into_iter()
1250                    .flat_map(|handlers| handlers.drain(..)),
1251            );
1252            self.window
1253                .current_frame
1254                .mouse_listeners
1255                .insert(event.type_id(), handlers);
1256        }
1257    }
1258
1259    fn dispatch_key_event(&mut self, event: &dyn Any) {
1260        if let Some(node_id) = self.window.focus.and_then(|focus_id| {
1261            self.window
1262                .current_frame
1263                .dispatch_tree
1264                .focusable_node_id(focus_id)
1265        }) {
1266            let dispatch_path = self
1267                .window
1268                .current_frame
1269                .dispatch_tree
1270                .dispatch_path(node_id);
1271
1272            // Capture phase
1273            let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1274            self.propagate_event = true;
1275
1276            for node_id in &dispatch_path {
1277                let node = self.window.current_frame.dispatch_tree.node(*node_id);
1278
1279                if !node.context.is_empty() {
1280                    context_stack.push(node.context.clone());
1281                }
1282
1283                for key_listener in node.key_listeners.clone() {
1284                    key_listener(event, DispatchPhase::Capture, self);
1285                    if !self.propagate_event {
1286                        return;
1287                    }
1288                }
1289            }
1290
1291            // Bubble phase
1292            for node_id in dispatch_path.iter().rev() {
1293                // Handle low level key events
1294                let node = self.window.current_frame.dispatch_tree.node(*node_id);
1295                for key_listener in node.key_listeners.clone() {
1296                    key_listener(event, DispatchPhase::Bubble, self);
1297                    if !self.propagate_event {
1298                        return;
1299                    }
1300                }
1301
1302                // Match keystrokes
1303                let node = self.window.current_frame.dispatch_tree.node(*node_id);
1304                if !node.context.is_empty() {
1305                    if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1306                        if let Some(action) = self
1307                            .window
1308                            .current_frame
1309                            .dispatch_tree
1310                            .dispatch_key(&key_down_event.keystroke, &context_stack)
1311                        {
1312                            self.dispatch_action_on_node(*node_id, action);
1313                            if !self.propagate_event {
1314                                return;
1315                            }
1316                        }
1317                    }
1318
1319                    context_stack.pop();
1320                }
1321            }
1322        }
1323    }
1324
1325    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1326        let dispatch_path = self
1327            .window
1328            .current_frame
1329            .dispatch_tree
1330            .dispatch_path(node_id);
1331
1332        // Capture phase
1333        for node_id in &dispatch_path {
1334            let node = self.window.current_frame.dispatch_tree.node(*node_id);
1335            for DispatchActionListener {
1336                action_type,
1337                listener,
1338            } in node.action_listeners.clone()
1339            {
1340                let any_action = action.as_any();
1341                if action_type == any_action.type_id() {
1342                    listener(any_action, DispatchPhase::Capture, self);
1343                    if !self.propagate_event {
1344                        return;
1345                    }
1346                }
1347            }
1348        }
1349
1350        // Bubble phase
1351        for node_id in dispatch_path.iter().rev() {
1352            let node = self.window.current_frame.dispatch_tree.node(*node_id);
1353            for DispatchActionListener {
1354                action_type,
1355                listener,
1356            } in node.action_listeners.clone()
1357            {
1358                let any_action = action.as_any();
1359                if action_type == any_action.type_id() {
1360                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1361                    listener(any_action, DispatchPhase::Bubble, self);
1362                    if !self.propagate_event {
1363                        return;
1364                    }
1365                }
1366            }
1367        }
1368    }
1369
1370    /// Register the given handler to be invoked whenever the global of the given type
1371    /// is updated.
1372    pub fn observe_global<G: 'static>(
1373        &mut self,
1374        f: impl Fn(&mut WindowContext<'_>) + 'static,
1375    ) -> Subscription {
1376        let window_handle = self.window.handle;
1377        self.global_observers.insert(
1378            TypeId::of::<G>(),
1379            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1380        )
1381    }
1382
1383    pub fn activate_window(&self) {
1384        self.window.platform_window.activate();
1385    }
1386
1387    pub fn minimize_window(&self) {
1388        self.window.platform_window.minimize();
1389    }
1390
1391    pub fn toggle_full_screen(&self) {
1392        self.window.platform_window.toggle_full_screen();
1393    }
1394
1395    pub fn prompt(
1396        &self,
1397        level: PromptLevel,
1398        msg: &str,
1399        answers: &[&str],
1400    ) -> oneshot::Receiver<usize> {
1401        self.window.platform_window.prompt(level, msg, answers)
1402    }
1403
1404    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1405        if let Some(focus_id) = self.window.focus {
1406            self.window
1407                .current_frame
1408                .dispatch_tree
1409                .available_actions(focus_id)
1410        } else {
1411            Vec::new()
1412        }
1413    }
1414
1415    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1416        self.window
1417            .current_frame
1418            .dispatch_tree
1419            .bindings_for_action(action)
1420    }
1421}
1422
1423impl Context for WindowContext<'_> {
1424    type Result<T> = T;
1425
1426    fn build_model<T>(
1427        &mut self,
1428        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1429    ) -> Model<T>
1430    where
1431        T: 'static,
1432    {
1433        let slot = self.app.entities.reserve();
1434        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1435        self.entities.insert(slot, model)
1436    }
1437
1438    fn update_model<T: 'static, R>(
1439        &mut self,
1440        model: &Model<T>,
1441        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1442    ) -> R {
1443        let mut entity = self.entities.lease(model);
1444        let result = update(
1445            &mut *entity,
1446            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1447        );
1448        self.entities.end_lease(entity);
1449        result
1450    }
1451
1452    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1453    where
1454        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1455    {
1456        if window == self.window.handle {
1457            let root_view = self.window.root_view.clone().unwrap();
1458            Ok(update(root_view, self))
1459        } else {
1460            window.update(self.app, update)
1461        }
1462    }
1463
1464    fn read_model<T, R>(
1465        &self,
1466        handle: &Model<T>,
1467        read: impl FnOnce(&T, &AppContext) -> R,
1468    ) -> Self::Result<R>
1469    where
1470        T: 'static,
1471    {
1472        let entity = self.entities.read(handle);
1473        read(&*entity, &*self.app)
1474    }
1475
1476    fn read_window<T, R>(
1477        &self,
1478        window: &WindowHandle<T>,
1479        read: impl FnOnce(View<T>, &AppContext) -> R,
1480    ) -> Result<R>
1481    where
1482        T: 'static,
1483    {
1484        if window.any_handle == self.window.handle {
1485            let root_view = self
1486                .window
1487                .root_view
1488                .clone()
1489                .unwrap()
1490                .downcast::<T>()
1491                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1492            Ok(read(root_view, self))
1493        } else {
1494            self.app.read_window(window, read)
1495        }
1496    }
1497}
1498
1499impl VisualContext for WindowContext<'_> {
1500    fn build_view<V>(
1501        &mut self,
1502        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1503    ) -> Self::Result<View<V>>
1504    where
1505        V: 'static + Render,
1506    {
1507        let slot = self.app.entities.reserve();
1508        let view = View {
1509            model: slot.clone(),
1510        };
1511        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1512        let entity = build_view_state(&mut cx);
1513        cx.entities.insert(slot, entity);
1514
1515        cx.new_view_observers
1516            .clone()
1517            .retain(&TypeId::of::<V>(), |observer| {
1518                let any_view = AnyView::from(view.clone());
1519                (observer)(any_view, self);
1520                true
1521            });
1522
1523        view
1524    }
1525
1526    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1527    fn update_view<T: 'static, R>(
1528        &mut self,
1529        view: &View<T>,
1530        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1531    ) -> Self::Result<R> {
1532        let mut lease = self.app.entities.lease(&view.model);
1533        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1534        let result = update(&mut *lease, &mut cx);
1535        cx.app.entities.end_lease(lease);
1536        result
1537    }
1538
1539    fn replace_root_view<V>(
1540        &mut self,
1541        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1542    ) -> Self::Result<View<V>>
1543    where
1544        V: Render,
1545    {
1546        let slot = self.app.entities.reserve();
1547        let view = View {
1548            model: slot.clone(),
1549        };
1550        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1551        let entity = build_view(&mut cx);
1552        self.entities.insert(slot, entity);
1553        self.window.root_view = Some(view.clone().into());
1554        view
1555    }
1556}
1557
1558impl<'a> std::ops::Deref for WindowContext<'a> {
1559    type Target = AppContext;
1560
1561    fn deref(&self) -> &Self::Target {
1562        &self.app
1563    }
1564}
1565
1566impl<'a> std::ops::DerefMut for WindowContext<'a> {
1567    fn deref_mut(&mut self) -> &mut Self::Target {
1568        &mut self.app
1569    }
1570}
1571
1572impl<'a> Borrow<AppContext> for WindowContext<'a> {
1573    fn borrow(&self) -> &AppContext {
1574        &self.app
1575    }
1576}
1577
1578impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1579    fn borrow_mut(&mut self) -> &mut AppContext {
1580        &mut self.app
1581    }
1582}
1583
1584pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1585    fn app_mut(&mut self) -> &mut AppContext {
1586        self.borrow_mut()
1587    }
1588
1589    fn window(&self) -> &Window {
1590        self.borrow()
1591    }
1592
1593    fn window_mut(&mut self) -> &mut Window {
1594        self.borrow_mut()
1595    }
1596
1597    /// Pushes the given element id onto the global stack and invokes the given closure
1598    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1599    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1600    /// used to associate state with identified elements across separate frames.
1601    fn with_element_id<R>(
1602        &mut self,
1603        id: Option<impl Into<ElementId>>,
1604        f: impl FnOnce(&mut Self) -> R,
1605    ) -> R {
1606        if let Some(id) = id.map(Into::into) {
1607            let window = self.window_mut();
1608            window.element_id_stack.push(id.into());
1609            let result = f(self);
1610            let window: &mut Window = self.borrow_mut();
1611            window.element_id_stack.pop();
1612            result
1613        } else {
1614            f(self)
1615        }
1616    }
1617
1618    /// Invoke the given function with the given content mask after intersecting it
1619    /// with the current mask.
1620    fn with_content_mask<R>(
1621        &mut self,
1622        mask: Option<ContentMask<Pixels>>,
1623        f: impl FnOnce(&mut Self) -> R,
1624    ) -> R {
1625        if let Some(mask) = mask {
1626            let mask = mask.intersect(&self.content_mask());
1627            self.window_mut()
1628                .current_frame
1629                .content_mask_stack
1630                .push(mask);
1631            let result = f(self);
1632            self.window_mut().current_frame.content_mask_stack.pop();
1633            result
1634        } else {
1635            f(self)
1636        }
1637    }
1638
1639    /// Update the global element offset based on the given offset. This is used to implement
1640    /// scrolling and position drag handles.
1641    fn with_element_offset<R>(
1642        &mut self,
1643        offset: Point<Pixels>,
1644        f: impl FnOnce(&mut Self) -> R,
1645    ) -> R {
1646        if offset.is_zero() {
1647            return f(self);
1648        };
1649
1650        let offset = self.element_offset() + offset;
1651        self.window_mut()
1652            .current_frame
1653            .element_offset_stack
1654            .push(offset);
1655        let result = f(self);
1656        self.window_mut().current_frame.element_offset_stack.pop();
1657        result
1658    }
1659
1660    /// Obtain the current element offset.
1661    fn element_offset(&self) -> Point<Pixels> {
1662        self.window()
1663            .current_frame
1664            .element_offset_stack
1665            .last()
1666            .copied()
1667            .unwrap_or_default()
1668    }
1669
1670    /// Update or intialize state for an element with the given id that lives across multiple
1671    /// frames. If an element with this id existed in the previous frame, its state will be passed
1672    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1673    /// when drawing the next frame.
1674    fn with_element_state<S, R>(
1675        &mut self,
1676        id: ElementId,
1677        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1678    ) -> R
1679    where
1680        S: 'static,
1681    {
1682        self.with_element_id(Some(id), |cx| {
1683            let global_id = cx.window().element_id_stack.clone();
1684
1685            if let Some(any) = cx
1686                .window_mut()
1687                .current_frame
1688                .element_states
1689                .remove(&global_id)
1690                .or_else(|| {
1691                    cx.window_mut()
1692                        .previous_frame
1693                        .element_states
1694                        .remove(&global_id)
1695                })
1696            {
1697                // Using the extra inner option to avoid needing to reallocate a new box.
1698                let mut state_box = any
1699                    .downcast::<Option<S>>()
1700                    .expect("invalid element state type for id");
1701                let state = state_box
1702                    .take()
1703                    .expect("element state is already on the stack");
1704                let (result, state) = f(Some(state), cx);
1705                state_box.replace(state);
1706                cx.window_mut()
1707                    .current_frame
1708                    .element_states
1709                    .insert(global_id, state_box);
1710                result
1711            } else {
1712                let (result, state) = f(None, cx);
1713                cx.window_mut()
1714                    .current_frame
1715                    .element_states
1716                    .insert(global_id, Box::new(Some(state)));
1717                result
1718            }
1719        })
1720    }
1721
1722    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1723    /// id is `None`, no state will be retrieved or stored.
1724    fn with_optional_element_state<S, R>(
1725        &mut self,
1726        element_id: Option<ElementId>,
1727        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1728    ) -> R
1729    where
1730        S: 'static,
1731    {
1732        if let Some(element_id) = element_id {
1733            self.with_element_state(element_id, f)
1734        } else {
1735            f(None, self).0
1736        }
1737    }
1738
1739    /// Obtain the current content mask.
1740    fn content_mask(&self) -> ContentMask<Pixels> {
1741        self.window()
1742            .current_frame
1743            .content_mask_stack
1744            .last()
1745            .cloned()
1746            .unwrap_or_else(|| ContentMask {
1747                bounds: Bounds {
1748                    origin: Point::default(),
1749                    size: self.window().viewport_size,
1750                },
1751            })
1752    }
1753
1754    /// The size of an em for the base font of the application. Adjusting this value allows the
1755    /// UI to scale, just like zooming a web page.
1756    fn rem_size(&self) -> Pixels {
1757        self.window().rem_size
1758    }
1759}
1760
1761impl Borrow<Window> for WindowContext<'_> {
1762    fn borrow(&self) -> &Window {
1763        &self.window
1764    }
1765}
1766
1767impl BorrowMut<Window> for WindowContext<'_> {
1768    fn borrow_mut(&mut self) -> &mut Window {
1769        &mut self.window
1770    }
1771}
1772
1773impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1774
1775pub struct ViewContext<'a, V> {
1776    window_cx: WindowContext<'a>,
1777    view: &'a View<V>,
1778}
1779
1780impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1781    fn borrow(&self) -> &AppContext {
1782        &*self.window_cx.app
1783    }
1784}
1785
1786impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1787    fn borrow_mut(&mut self) -> &mut AppContext {
1788        &mut *self.window_cx.app
1789    }
1790}
1791
1792impl<V> Borrow<Window> for ViewContext<'_, V> {
1793    fn borrow(&self) -> &Window {
1794        &*self.window_cx.window
1795    }
1796}
1797
1798impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1799    fn borrow_mut(&mut self) -> &mut Window {
1800        &mut *self.window_cx.window
1801    }
1802}
1803
1804impl<'a, V: 'static> ViewContext<'a, V> {
1805    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1806        Self {
1807            window_cx: WindowContext::new(app, window),
1808            view,
1809        }
1810    }
1811
1812    pub fn entity_id(&self) -> EntityId {
1813        self.view.entity_id()
1814    }
1815
1816    pub fn view(&self) -> &View<V> {
1817        self.view
1818    }
1819
1820    pub fn model(&self) -> Model<V> {
1821        self.view.model.clone()
1822    }
1823
1824    /// Access the underlying window context.
1825    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1826        &mut self.window_cx
1827    }
1828
1829    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1830        self.window.current_frame.z_index_stack.push(z_index);
1831        let result = f(self);
1832        self.window.current_frame.z_index_stack.pop();
1833        result
1834    }
1835
1836    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1837    where
1838        V: 'static,
1839    {
1840        let view = self.view().clone();
1841        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1842    }
1843
1844    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1845    /// that are currently on the stack to be returned to the app.
1846    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1847        let view = self.view().downgrade();
1848        self.window_cx.defer(move |cx| {
1849            view.update(cx, f).ok();
1850        });
1851    }
1852
1853    pub fn observe<V2, E>(
1854        &mut self,
1855        entity: &E,
1856        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1857    ) -> Subscription
1858    where
1859        V2: 'static,
1860        V: 'static,
1861        E: Entity<V2>,
1862    {
1863        let view = self.view().downgrade();
1864        let entity_id = entity.entity_id();
1865        let entity = entity.downgrade();
1866        let window_handle = self.window.handle;
1867        self.app.observers.insert(
1868            entity_id,
1869            Box::new(move |cx| {
1870                window_handle
1871                    .update(cx, |_, cx| {
1872                        if let Some(handle) = E::upgrade_from(&entity) {
1873                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1874                                .is_ok()
1875                        } else {
1876                            false
1877                        }
1878                    })
1879                    .unwrap_or(false)
1880            }),
1881        )
1882    }
1883
1884    pub fn subscribe<V2, E, Evt>(
1885        &mut self,
1886        entity: &E,
1887        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1888    ) -> Subscription
1889    where
1890        V2: EventEmitter<Evt>,
1891        E: Entity<V2>,
1892        Evt: 'static,
1893    {
1894        let view = self.view().downgrade();
1895        let entity_id = entity.entity_id();
1896        let handle = entity.downgrade();
1897        let window_handle = self.window.handle;
1898        self.app.event_listeners.insert(
1899            entity_id,
1900            (
1901                TypeId::of::<Evt>(),
1902                Box::new(move |event, cx| {
1903                    window_handle
1904                        .update(cx, |_, cx| {
1905                            if let Some(handle) = E::upgrade_from(&handle) {
1906                                let event = event.downcast_ref().expect("invalid event type");
1907                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1908                                    .is_ok()
1909                            } else {
1910                                false
1911                            }
1912                        })
1913                        .unwrap_or(false)
1914                }),
1915            ),
1916        )
1917    }
1918
1919    pub fn on_release(
1920        &mut self,
1921        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1922    ) -> Subscription {
1923        let window_handle = self.window.handle;
1924        self.app.release_listeners.insert(
1925            self.view.model.entity_id,
1926            Box::new(move |this, cx| {
1927                let this = this.downcast_mut().expect("invalid entity type");
1928                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1929            }),
1930        )
1931    }
1932
1933    pub fn observe_release<V2, E>(
1934        &mut self,
1935        entity: &E,
1936        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1937    ) -> Subscription
1938    where
1939        V: 'static,
1940        V2: 'static,
1941        E: Entity<V2>,
1942    {
1943        let view = self.view().downgrade();
1944        let entity_id = entity.entity_id();
1945        let window_handle = self.window.handle;
1946        self.app.release_listeners.insert(
1947            entity_id,
1948            Box::new(move |entity, cx| {
1949                let entity = entity.downcast_mut().expect("invalid entity type");
1950                let _ = window_handle.update(cx, |_, cx| {
1951                    view.update(cx, |this, cx| on_release(this, entity, cx))
1952                });
1953            }),
1954        )
1955    }
1956
1957    pub fn notify(&mut self) {
1958        self.window_cx.notify();
1959        self.window_cx.app.push_effect(Effect::Notify {
1960            emitter: self.view.model.entity_id,
1961        });
1962    }
1963
1964    pub fn observe_window_bounds(
1965        &mut self,
1966        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1967    ) -> Subscription {
1968        let view = self.view.downgrade();
1969        self.window.bounds_observers.insert(
1970            (),
1971            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1972        )
1973    }
1974
1975    pub fn observe_window_activation(
1976        &mut self,
1977        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1978    ) -> Subscription {
1979        let view = self.view.downgrade();
1980        self.window.activation_observers.insert(
1981            (),
1982            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1983        )
1984    }
1985
1986    /// Register a listener to be called when the given focus handle receives focus.
1987    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1988    /// is dropped.
1989    pub fn on_focus(
1990        &mut self,
1991        handle: &FocusHandle,
1992        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1993    ) -> Subscription {
1994        let view = self.view.downgrade();
1995        let focus_id = handle.id;
1996        self.window.focus_listeners.insert(
1997            (),
1998            Box::new(move |event, cx| {
1999                view.update(cx, |view, cx| {
2000                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2001                        listener(view, cx)
2002                    }
2003                })
2004                .is_ok()
2005            }),
2006        )
2007    }
2008
2009    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2010    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2011    /// is dropped.
2012    pub fn on_focus_in(
2013        &mut self,
2014        handle: &FocusHandle,
2015        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2016    ) -> Subscription {
2017        let view = self.view.downgrade();
2018        let focus_id = handle.id;
2019        self.window.focus_listeners.insert(
2020            (),
2021            Box::new(move |event, cx| {
2022                view.update(cx, |view, cx| {
2023                    if event
2024                        .focused
2025                        .as_ref()
2026                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
2027                    {
2028                        listener(view, cx)
2029                    }
2030                })
2031                .is_ok()
2032            }),
2033        )
2034    }
2035
2036    /// Register a listener to be called when the given focus handle loses focus.
2037    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2038    /// is dropped.
2039    pub fn on_blur(
2040        &mut self,
2041        handle: &FocusHandle,
2042        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2043    ) -> Subscription {
2044        let view = self.view.downgrade();
2045        let focus_id = handle.id;
2046        self.window.focus_listeners.insert(
2047            (),
2048            Box::new(move |event, cx| {
2049                view.update(cx, |view, cx| {
2050                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2051                        listener(view, cx)
2052                    }
2053                })
2054                .is_ok()
2055            }),
2056        )
2057    }
2058
2059    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2060    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2061    /// is dropped.
2062    pub fn on_focus_out(
2063        &mut self,
2064        handle: &FocusHandle,
2065        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2066    ) -> Subscription {
2067        let view = self.view.downgrade();
2068        let focus_id = handle.id;
2069        self.window.focus_listeners.insert(
2070            (),
2071            Box::new(move |event, cx| {
2072                view.update(cx, |view, cx| {
2073                    if event
2074                        .blurred
2075                        .as_ref()
2076                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2077                    {
2078                        listener(view, cx)
2079                    }
2080                })
2081                .is_ok()
2082            }),
2083        )
2084    }
2085
2086    /// Register a focus listener for the current frame only. It will be cleared
2087    /// on the next frame render. You should use this method only from within elements,
2088    /// and we may want to enforce that better via a different context type.
2089    // todo!() Move this to `FrameContext` to emphasize its individuality?
2090    pub fn on_focus_changed(
2091        &mut self,
2092        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
2093    ) {
2094        let handle = self.view().downgrade();
2095        self.window
2096            .current_frame
2097            .focus_listeners
2098            .push(Box::new(move |event, cx| {
2099                handle
2100                    .update(cx, |view, cx| listener(view, event, cx))
2101                    .log_err();
2102            }));
2103    }
2104
2105    pub fn with_key_dispatch<R>(
2106        &mut self,
2107        context: KeyContext,
2108        focus_handle: Option<FocusHandle>,
2109        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
2110    ) -> R {
2111        let window = &mut self.window;
2112        window
2113            .current_frame
2114            .dispatch_tree
2115            .push_node(context.clone());
2116        if let Some(focus_handle) = focus_handle.as_ref() {
2117            window
2118                .current_frame
2119                .dispatch_tree
2120                .make_focusable(focus_handle.id);
2121        }
2122        let result = f(focus_handle, self);
2123
2124        self.window.current_frame.dispatch_tree.pop_node();
2125
2126        result
2127    }
2128
2129    pub fn spawn<Fut, R>(
2130        &mut self,
2131        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2132    ) -> Task<R>
2133    where
2134        R: 'static,
2135        Fut: Future<Output = R> + 'static,
2136    {
2137        let view = self.view().downgrade();
2138        self.window_cx.spawn(|cx| f(view, cx))
2139    }
2140
2141    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2142    where
2143        G: 'static,
2144    {
2145        let mut global = self.app.lease_global::<G>();
2146        let result = f(&mut global, self);
2147        self.app.end_global_lease(global);
2148        result
2149    }
2150
2151    pub fn observe_global<G: 'static>(
2152        &mut self,
2153        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
2154    ) -> Subscription {
2155        let window_handle = self.window.handle;
2156        let view = self.view().downgrade();
2157        self.global_observers.insert(
2158            TypeId::of::<G>(),
2159            Box::new(move |cx| {
2160                window_handle
2161                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2162                    .unwrap_or(false)
2163            }),
2164        )
2165    }
2166
2167    pub fn on_mouse_event<Event: 'static>(
2168        &mut self,
2169        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2170    ) {
2171        let handle = self.view().clone();
2172        self.window_cx.on_mouse_event(move |event, phase, cx| {
2173            handle.update(cx, |view, cx| {
2174                handler(view, event, phase, cx);
2175            })
2176        });
2177    }
2178
2179    pub fn on_key_event<Event: 'static>(
2180        &mut self,
2181        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2182    ) {
2183        let handle = self.view().clone();
2184        self.window_cx.on_key_event(move |event, phase, cx| {
2185            handle.update(cx, |view, cx| {
2186                handler(view, event, phase, cx);
2187            })
2188        });
2189    }
2190
2191    pub fn on_action(
2192        &mut self,
2193        action_type: TypeId,
2194        handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2195    ) {
2196        let handle = self.view().clone();
2197        self.window_cx
2198            .on_action(action_type, move |action, phase, cx| {
2199                handle.update(cx, |view, cx| {
2200                    handler(view, action, phase, cx);
2201                })
2202            });
2203    }
2204
2205    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
2206    /// platform to receive textual input with proper integration with concerns such
2207    /// as IME interactions.
2208    pub fn handle_input(
2209        &mut self,
2210        focus_handle: &FocusHandle,
2211        input_handler: impl PlatformInputHandler,
2212    ) {
2213        if focus_handle.is_focused(self) {
2214            self.window
2215                .platform_window
2216                .set_input_handler(Box::new(input_handler));
2217        }
2218    }
2219}
2220
2221impl<V> ViewContext<'_, V> {
2222    pub fn emit<Evt>(&mut self, event: Evt)
2223    where
2224        Evt: 'static,
2225        V: EventEmitter<Evt>,
2226    {
2227        let emitter = self.view.model.entity_id;
2228        self.app.push_effect(Effect::Emit {
2229            emitter,
2230            event_type: TypeId::of::<Evt>(),
2231            event: Box::new(event),
2232        });
2233    }
2234}
2235
2236impl<V> Context for ViewContext<'_, V> {
2237    type Result<U> = U;
2238
2239    fn build_model<T: 'static>(
2240        &mut self,
2241        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2242    ) -> Model<T> {
2243        self.window_cx.build_model(build_model)
2244    }
2245
2246    fn update_model<T: 'static, R>(
2247        &mut self,
2248        model: &Model<T>,
2249        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2250    ) -> R {
2251        self.window_cx.update_model(model, update)
2252    }
2253
2254    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2255    where
2256        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2257    {
2258        self.window_cx.update_window(window, update)
2259    }
2260
2261    fn read_model<T, R>(
2262        &self,
2263        handle: &Model<T>,
2264        read: impl FnOnce(&T, &AppContext) -> R,
2265    ) -> Self::Result<R>
2266    where
2267        T: 'static,
2268    {
2269        self.window_cx.read_model(handle, read)
2270    }
2271
2272    fn read_window<T, R>(
2273        &self,
2274        window: &WindowHandle<T>,
2275        read: impl FnOnce(View<T>, &AppContext) -> R,
2276    ) -> Result<R>
2277    where
2278        T: 'static,
2279    {
2280        self.window_cx.read_window(window, read)
2281    }
2282}
2283
2284impl<V: 'static> VisualContext for ViewContext<'_, V> {
2285    fn build_view<W: Render + 'static>(
2286        &mut self,
2287        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2288    ) -> Self::Result<View<W>> {
2289        self.window_cx.build_view(build_view_state)
2290    }
2291
2292    fn update_view<V2: 'static, R>(
2293        &mut self,
2294        view: &View<V2>,
2295        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2296    ) -> Self::Result<R> {
2297        self.window_cx.update_view(view, update)
2298    }
2299
2300    fn replace_root_view<W>(
2301        &mut self,
2302        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2303    ) -> Self::Result<View<W>>
2304    where
2305        W: Render,
2306    {
2307        self.window_cx.replace_root_view(build_view)
2308    }
2309}
2310
2311impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2312    type Target = WindowContext<'a>;
2313
2314    fn deref(&self) -> &Self::Target {
2315        &self.window_cx
2316    }
2317}
2318
2319impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2320    fn deref_mut(&mut self) -> &mut Self::Target {
2321        &mut self.window_cx
2322    }
2323}
2324
2325// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2326slotmap::new_key_type! { pub struct WindowId; }
2327
2328impl WindowId {
2329    pub fn as_u64(&self) -> u64 {
2330        self.0.as_ffi()
2331    }
2332}
2333
2334#[derive(Deref, DerefMut)]
2335pub struct WindowHandle<V> {
2336    #[deref]
2337    #[deref_mut]
2338    pub(crate) any_handle: AnyWindowHandle,
2339    state_type: PhantomData<V>,
2340}
2341
2342impl<V: 'static + Render> WindowHandle<V> {
2343    pub fn new(id: WindowId) -> Self {
2344        WindowHandle {
2345            any_handle: AnyWindowHandle {
2346                id,
2347                state_type: TypeId::of::<V>(),
2348            },
2349            state_type: PhantomData,
2350        }
2351    }
2352
2353    pub fn update<C, R>(
2354        &self,
2355        cx: &mut C,
2356        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2357    ) -> Result<R>
2358    where
2359        C: Context,
2360    {
2361        cx.update_window(self.any_handle, |root_view, cx| {
2362            let view = root_view
2363                .downcast::<V>()
2364                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2365            Ok(cx.update_view(&view, update))
2366        })?
2367    }
2368
2369    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2370        let x = cx
2371            .windows
2372            .get(self.id)
2373            .and_then(|window| {
2374                window
2375                    .as_ref()
2376                    .and_then(|window| window.root_view.clone())
2377                    .map(|root_view| root_view.downcast::<V>())
2378            })
2379            .ok_or_else(|| anyhow!("window not found"))?
2380            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2381
2382        Ok(x.read(cx))
2383    }
2384
2385    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2386    where
2387        C: Context,
2388    {
2389        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2390    }
2391
2392    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2393    where
2394        C: Context,
2395    {
2396        cx.read_window(self, |root_view, _cx| root_view.clone())
2397    }
2398
2399    pub fn is_active(&self, cx: &WindowContext) -> Option<bool> {
2400        cx.windows
2401            .get(self.id)
2402            .and_then(|window| window.as_ref().map(|window| window.active))
2403    }
2404}
2405
2406impl<V> Copy for WindowHandle<V> {}
2407
2408impl<V> Clone for WindowHandle<V> {
2409    fn clone(&self) -> Self {
2410        WindowHandle {
2411            any_handle: self.any_handle,
2412            state_type: PhantomData,
2413        }
2414    }
2415}
2416
2417impl<V> PartialEq for WindowHandle<V> {
2418    fn eq(&self, other: &Self) -> bool {
2419        self.any_handle == other.any_handle
2420    }
2421}
2422
2423impl<V> Eq for WindowHandle<V> {}
2424
2425impl<V> Hash for WindowHandle<V> {
2426    fn hash<H: Hasher>(&self, state: &mut H) {
2427        self.any_handle.hash(state);
2428    }
2429}
2430
2431impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2432    fn into(self) -> AnyWindowHandle {
2433        self.any_handle
2434    }
2435}
2436
2437#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2438pub struct AnyWindowHandle {
2439    pub(crate) id: WindowId,
2440    state_type: TypeId,
2441}
2442
2443impl AnyWindowHandle {
2444    pub fn window_id(&self) -> WindowId {
2445        self.id
2446    }
2447
2448    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2449        if TypeId::of::<T>() == self.state_type {
2450            Some(WindowHandle {
2451                any_handle: *self,
2452                state_type: PhantomData,
2453            })
2454        } else {
2455            None
2456        }
2457    }
2458
2459    pub fn update<C, R>(
2460        self,
2461        cx: &mut C,
2462        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2463    ) -> Result<R>
2464    where
2465        C: Context,
2466    {
2467        cx.update_window(self, update)
2468    }
2469
2470    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2471    where
2472        C: Context,
2473        T: 'static,
2474    {
2475        let view = self
2476            .downcast::<T>()
2477            .context("the type of the window's root view has changed")?;
2478
2479        cx.read_window(&view, read)
2480    }
2481}
2482
2483#[cfg(any(test, feature = "test-support"))]
2484impl From<SmallVec<[u32; 16]>> for StackingOrder {
2485    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2486        StackingOrder(small_vec)
2487    }
2488}
2489
2490#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2491pub enum ElementId {
2492    View(EntityId),
2493    Integer(usize),
2494    Name(SharedString),
2495    FocusHandle(FocusId),
2496}
2497
2498impl From<EntityId> for ElementId {
2499    fn from(id: EntityId) -> Self {
2500        ElementId::View(id)
2501    }
2502}
2503
2504impl From<usize> for ElementId {
2505    fn from(id: usize) -> Self {
2506        ElementId::Integer(id)
2507    }
2508}
2509
2510impl From<i32> for ElementId {
2511    fn from(id: i32) -> Self {
2512        Self::Integer(id as usize)
2513    }
2514}
2515
2516impl From<SharedString> for ElementId {
2517    fn from(name: SharedString) -> Self {
2518        ElementId::Name(name)
2519    }
2520}
2521
2522impl From<&'static str> for ElementId {
2523    fn from(name: &'static str) -> Self {
2524        ElementId::Name(name.into())
2525    }
2526}
2527
2528impl<'a> From<&'a FocusHandle> for ElementId {
2529    fn from(handle: &'a FocusHandle) -> Self {
2530        ElementId::FocusHandle(handle.id)
2531    }
2532}