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