window.rs

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