window.rs

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