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, 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.content_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 is_window_active(&self) -> bool {
 631        self.window.active
 632    }
 633
 634    pub fn zoom_window(&self) {
 635        self.window.platform_window.zoom();
 636    }
 637
 638    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 639        self.platform
 640            .displays()
 641            .into_iter()
 642            .find(|display| display.id() == self.window.display_id)
 643    }
 644
 645    pub fn show_character_palette(&self) {
 646        self.window.platform_window.show_character_palette();
 647    }
 648
 649    /// The scale factor of the display associated with the window. For example, it could
 650    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 651    /// be rendered as two pixels on screen.
 652    pub fn scale_factor(&self) -> f32 {
 653        self.window.scale_factor
 654    }
 655
 656    /// The size of an em for the base font of the application. Adjusting this value allows the
 657    /// UI to scale, just like zooming a web page.
 658    pub fn rem_size(&self) -> Pixels {
 659        self.window.rem_size
 660    }
 661
 662    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 663    /// UI to scale, just like zooming a web page.
 664    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 665        self.window.rem_size = rem_size.into();
 666    }
 667
 668    /// The line height associated with the current text style.
 669    pub fn line_height(&self) -> Pixels {
 670        let rem_size = self.rem_size();
 671        let text_style = self.text_style();
 672        text_style
 673            .line_height
 674            .to_pixels(text_style.font_size.into(), rem_size)
 675    }
 676
 677    /// Call to prevent the default action of an event. Currently only used to prevent
 678    /// parent elements from becoming focused on mouse down.
 679    pub fn prevent_default(&mut self) {
 680        self.window.default_prevented = true;
 681    }
 682
 683    /// Obtain whether default has been prevented for the event currently being dispatched.
 684    pub fn default_prevented(&self) -> bool {
 685        self.window.default_prevented
 686    }
 687
 688    /// Register a mouse event listener on the window for the current frame. The type of event
 689    /// is determined by the first parameter of the given listener. When the next frame is rendered
 690    /// the listener will be cleared.
 691    ///
 692    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 693    /// a specific need to register a global listener.
 694    pub fn on_mouse_event<Event: 'static>(
 695        &mut self,
 696        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 697    ) {
 698        let order = self.window.current_frame.z_index_stack.clone();
 699        self.window
 700            .current_frame
 701            .mouse_listeners
 702            .entry(TypeId::of::<Event>())
 703            .or_default()
 704            .push((
 705                order,
 706                Box::new(move |event: &dyn Any, phase, cx| {
 707                    handler(event.downcast_ref().unwrap(), phase, cx)
 708                }),
 709            ))
 710    }
 711
 712    /// The position of the mouse relative to the window.
 713    pub fn mouse_position(&self) -> Point<Pixels> {
 714        self.window.mouse_position
 715    }
 716
 717    pub fn set_cursor_style(&mut self, style: CursorStyle) {
 718        self.window.requested_cursor_style = Some(style)
 719    }
 720
 721    /// Called during painting to invoke the given closure in a new stacking context. The given
 722    /// z-index is interpreted relative to the previous call to `stack`.
 723    pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
 724        self.window.current_frame.z_index_stack.push(z_index);
 725        let result = f(self);
 726        self.window.current_frame.z_index_stack.pop();
 727        result
 728    }
 729
 730    /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
 731    pub fn paint_shadows(
 732        &mut self,
 733        bounds: Bounds<Pixels>,
 734        corner_radii: Corners<Pixels>,
 735        shadows: &[BoxShadow],
 736    ) {
 737        let scale_factor = self.scale_factor();
 738        let content_mask = self.content_mask();
 739        let window = &mut *self.window;
 740        for shadow in shadows {
 741            let mut shadow_bounds = bounds;
 742            shadow_bounds.origin += shadow.offset;
 743            shadow_bounds.dilate(shadow.spread_radius);
 744            window.current_frame.scene_builder.insert(
 745                &window.current_frame.z_index_stack,
 746                Shadow {
 747                    order: 0,
 748                    bounds: shadow_bounds.scale(scale_factor),
 749                    content_mask: content_mask.scale(scale_factor),
 750                    corner_radii: corner_radii.scale(scale_factor),
 751                    color: shadow.color,
 752                    blur_radius: shadow.blur_radius.scale(scale_factor),
 753                },
 754            );
 755        }
 756    }
 757
 758    /// Paint one or more quads into the scene for the current frame at the current stacking context.
 759    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 760    pub fn paint_quad(
 761        &mut self,
 762        bounds: Bounds<Pixels>,
 763        corner_radii: Corners<Pixels>,
 764        background: impl Into<Hsla>,
 765        border_widths: Edges<Pixels>,
 766        border_color: impl Into<Hsla>,
 767    ) {
 768        let scale_factor = self.scale_factor();
 769        let content_mask = self.content_mask();
 770
 771        let window = &mut *self.window;
 772        window.current_frame.scene_builder.insert(
 773            &window.current_frame.z_index_stack,
 774            Quad {
 775                order: 0,
 776                bounds: bounds.scale(scale_factor),
 777                content_mask: content_mask.scale(scale_factor),
 778                background: background.into(),
 779                border_color: border_color.into(),
 780                corner_radii: corner_radii.scale(scale_factor),
 781                border_widths: border_widths.scale(scale_factor),
 782            },
 783        );
 784    }
 785
 786    /// Paint the given `Path` into the scene for the current frame at the current z-index.
 787    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 788        let scale_factor = self.scale_factor();
 789        let content_mask = self.content_mask();
 790        path.content_mask = content_mask;
 791        path.color = color.into();
 792        let window = &mut *self.window;
 793        window.current_frame.scene_builder.insert(
 794            &window.current_frame.z_index_stack,
 795            path.scale(scale_factor),
 796        );
 797    }
 798
 799    /// Paint an underline into the scene for the current frame at the current z-index.
 800    pub fn paint_underline(
 801        &mut self,
 802        origin: Point<Pixels>,
 803        width: Pixels,
 804        style: &UnderlineStyle,
 805    ) -> Result<()> {
 806        let scale_factor = self.scale_factor();
 807        let height = if style.wavy {
 808            style.thickness * 3.
 809        } else {
 810            style.thickness
 811        };
 812        let bounds = Bounds {
 813            origin,
 814            size: size(width, height),
 815        };
 816        let content_mask = self.content_mask();
 817        let window = &mut *self.window;
 818        window.current_frame.scene_builder.insert(
 819            &window.current_frame.z_index_stack,
 820            Underline {
 821                order: 0,
 822                bounds: bounds.scale(scale_factor),
 823                content_mask: content_mask.scale(scale_factor),
 824                thickness: style.thickness.scale(scale_factor),
 825                color: style.color.unwrap_or_default(),
 826                wavy: style.wavy,
 827            },
 828        );
 829        Ok(())
 830    }
 831
 832    /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
 833    /// The y component of the origin is the baseline of the glyph.
 834    pub fn paint_glyph(
 835        &mut self,
 836        origin: Point<Pixels>,
 837        font_id: FontId,
 838        glyph_id: GlyphId,
 839        font_size: Pixels,
 840        color: Hsla,
 841    ) -> Result<()> {
 842        let scale_factor = self.scale_factor();
 843        let glyph_origin = origin.scale(scale_factor);
 844        let subpixel_variant = Point {
 845            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 846            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 847        };
 848        let params = RenderGlyphParams {
 849            font_id,
 850            glyph_id,
 851            font_size,
 852            subpixel_variant,
 853            scale_factor,
 854            is_emoji: false,
 855        };
 856
 857        let raster_bounds = self.text_system().raster_bounds(&params)?;
 858        if !raster_bounds.is_zero() {
 859            let tile =
 860                self.window
 861                    .sprite_atlas
 862                    .get_or_insert_with(&params.clone().into(), &mut || {
 863                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 864                        Ok((size, Cow::Owned(bytes)))
 865                    })?;
 866            let bounds = Bounds {
 867                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 868                size: tile.bounds.size.map(Into::into),
 869            };
 870            let content_mask = self.content_mask().scale(scale_factor);
 871            let window = &mut *self.window;
 872            window.current_frame.scene_builder.insert(
 873                &window.current_frame.z_index_stack,
 874                MonochromeSprite {
 875                    order: 0,
 876                    bounds,
 877                    content_mask,
 878                    color,
 879                    tile,
 880                },
 881            );
 882        }
 883        Ok(())
 884    }
 885
 886    /// Paint an emoji glyph into the scene for the current frame at the current z-index.
 887    /// The y component of the origin is the baseline of the glyph.
 888    pub fn paint_emoji(
 889        &mut self,
 890        origin: Point<Pixels>,
 891        font_id: FontId,
 892        glyph_id: GlyphId,
 893        font_size: Pixels,
 894    ) -> Result<()> {
 895        let scale_factor = self.scale_factor();
 896        let glyph_origin = origin.scale(scale_factor);
 897        let params = RenderGlyphParams {
 898            font_id,
 899            glyph_id,
 900            font_size,
 901            // We don't render emojis with subpixel variants.
 902            subpixel_variant: Default::default(),
 903            scale_factor,
 904            is_emoji: true,
 905        };
 906
 907        let raster_bounds = self.text_system().raster_bounds(&params)?;
 908        if !raster_bounds.is_zero() {
 909            let tile =
 910                self.window
 911                    .sprite_atlas
 912                    .get_or_insert_with(&params.clone().into(), &mut || {
 913                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 914                        Ok((size, Cow::Owned(bytes)))
 915                    })?;
 916            let bounds = Bounds {
 917                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 918                size: tile.bounds.size.map(Into::into),
 919            };
 920            let content_mask = self.content_mask().scale(scale_factor);
 921            let window = &mut *self.window;
 922
 923            window.current_frame.scene_builder.insert(
 924                &window.current_frame.z_index_stack,
 925                PolychromeSprite {
 926                    order: 0,
 927                    bounds,
 928                    corner_radii: Default::default(),
 929                    content_mask,
 930                    tile,
 931                    grayscale: false,
 932                },
 933            );
 934        }
 935        Ok(())
 936    }
 937
 938    /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
 939    pub fn paint_svg(
 940        &mut self,
 941        bounds: Bounds<Pixels>,
 942        path: SharedString,
 943        color: Hsla,
 944    ) -> Result<()> {
 945        let scale_factor = self.scale_factor();
 946        let bounds = bounds.scale(scale_factor);
 947        // Render the SVG at twice the size to get a higher quality result.
 948        let params = RenderSvgParams {
 949            path,
 950            size: bounds
 951                .size
 952                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 953        };
 954
 955        let tile =
 956            self.window
 957                .sprite_atlas
 958                .get_or_insert_with(&params.clone().into(), &mut || {
 959                    let bytes = self.svg_renderer.render(&params)?;
 960                    Ok((params.size, Cow::Owned(bytes)))
 961                })?;
 962        let content_mask = self.content_mask().scale(scale_factor);
 963
 964        let window = &mut *self.window;
 965        window.current_frame.scene_builder.insert(
 966            &window.current_frame.z_index_stack,
 967            MonochromeSprite {
 968                order: 0,
 969                bounds,
 970                content_mask,
 971                color,
 972                tile,
 973            },
 974        );
 975
 976        Ok(())
 977    }
 978
 979    /// Paint an image into the scene for the current frame at the current z-index.
 980    pub fn paint_image(
 981        &mut self,
 982        bounds: Bounds<Pixels>,
 983        corner_radii: Corners<Pixels>,
 984        data: Arc<ImageData>,
 985        grayscale: bool,
 986    ) -> Result<()> {
 987        let scale_factor = self.scale_factor();
 988        let bounds = bounds.scale(scale_factor);
 989        let params = RenderImageParams { image_id: data.id };
 990
 991        let tile = self
 992            .window
 993            .sprite_atlas
 994            .get_or_insert_with(&params.clone().into(), &mut || {
 995                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
 996            })?;
 997        let content_mask = self.content_mask().scale(scale_factor);
 998        let corner_radii = corner_radii.scale(scale_factor);
 999
1000        let window = &mut *self.window;
1001        window.current_frame.scene_builder.insert(
1002            &window.current_frame.z_index_stack,
1003            PolychromeSprite {
1004                order: 0,
1005                bounds,
1006                content_mask,
1007                corner_radii,
1008                tile,
1009                grayscale,
1010            },
1011        );
1012        Ok(())
1013    }
1014
1015    /// Draw pixels to the display for this window based on the contents of its scene.
1016    pub(crate) fn draw(&mut self) {
1017        let root_view = self.window.root_view.take().unwrap();
1018
1019        self.start_frame();
1020
1021        self.stack(0, |cx| {
1022            let available_space = cx.window.content_size.map(Into::into);
1023            root_view.draw(available_space, cx);
1024        });
1025
1026        if let Some(active_drag) = self.app.active_drag.take() {
1027            self.stack(1, |cx| {
1028                let offset = cx.mouse_position() - active_drag.cursor_offset;
1029                cx.with_element_offset(Some(offset), |cx| {
1030                    let available_space =
1031                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1032                    active_drag.view.draw(available_space, cx);
1033                    cx.active_drag = Some(active_drag);
1034                });
1035            });
1036        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1037            self.stack(1, |cx| {
1038                cx.with_element_offset(Some(active_tooltip.cursor_offset), |cx| {
1039                    let available_space =
1040                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1041                    active_tooltip.view.draw(available_space, cx);
1042                });
1043            });
1044        }
1045
1046        self.window.root_view = Some(root_view);
1047        let scene = self.window.current_frame.scene_builder.build();
1048
1049        self.window.platform_window.draw(scene);
1050        let cursor_style = self
1051            .window
1052            .requested_cursor_style
1053            .take()
1054            .unwrap_or(CursorStyle::Arrow);
1055        self.platform.set_cursor_style(cursor_style);
1056        if let Some(handler) = self.window.requested_input_handler.take() {
1057            self.window.platform_window.set_input_handler(handler);
1058        }
1059
1060        self.window.dirty = false;
1061    }
1062
1063    /// Rotate the current frame and the previous frame, then clear the current frame.
1064    /// We repopulate all state in the current frame during each paint.
1065    fn start_frame(&mut self) {
1066        self.text_system().start_frame();
1067
1068        let window = &mut *self.window;
1069        mem::swap(&mut window.previous_frame, &mut window.current_frame);
1070        let frame = &mut window.current_frame;
1071        frame.element_states.clear();
1072        frame.key_matchers.clear();
1073        frame.mouse_listeners.values_mut().for_each(Vec::clear);
1074        frame.focus_listeners.clear();
1075        frame.key_dispatch_stack.clear();
1076        frame.focus_parents_by_child.clear();
1077        frame.freeze_key_dispatch_stack = false;
1078    }
1079
1080    /// Dispatch a mouse or keyboard event on the window.
1081    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1082        // Handlers may set this to false by calling `stop_propagation`
1083        self.app.propagate_event = true;
1084        self.window.default_prevented = false;
1085
1086        let event = match event {
1087            // Track the mouse position with our own state, since accessing the platform
1088            // API for the mouse position can only occur on the main thread.
1089            InputEvent::MouseMove(mouse_move) => {
1090                self.window.mouse_position = mouse_move.position;
1091                InputEvent::MouseMove(mouse_move)
1092            }
1093            // Translate dragging and dropping of external files from the operating system
1094            // to internal drag and drop events.
1095            InputEvent::FileDrop(file_drop) => match file_drop {
1096                FileDropEvent::Entered { position, files } => {
1097                    self.window.mouse_position = position;
1098                    if self.active_drag.is_none() {
1099                        self.active_drag = Some(AnyDrag {
1100                            view: self.build_view(|_| files).into(),
1101                            cursor_offset: position,
1102                        });
1103                    }
1104                    InputEvent::MouseDown(MouseDownEvent {
1105                        position,
1106                        button: MouseButton::Left,
1107                        click_count: 1,
1108                        modifiers: Modifiers::default(),
1109                    })
1110                }
1111                FileDropEvent::Pending { position } => {
1112                    self.window.mouse_position = position;
1113                    InputEvent::MouseMove(MouseMoveEvent {
1114                        position,
1115                        pressed_button: Some(MouseButton::Left),
1116                        modifiers: Modifiers::default(),
1117                    })
1118                }
1119                FileDropEvent::Submit { position } => {
1120                    self.window.mouse_position = position;
1121                    InputEvent::MouseUp(MouseUpEvent {
1122                        button: MouseButton::Left,
1123                        position,
1124                        modifiers: Modifiers::default(),
1125                        click_count: 1,
1126                    })
1127                }
1128                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1129                    button: MouseButton::Left,
1130                    position: Point::default(),
1131                    modifiers: Modifiers::default(),
1132                    click_count: 1,
1133                }),
1134            },
1135            _ => event,
1136        };
1137
1138        if let Some(any_mouse_event) = event.mouse_event() {
1139            if let Some(mut handlers) = self
1140                .window
1141                .current_frame
1142                .mouse_listeners
1143                .remove(&any_mouse_event.type_id())
1144            {
1145                // Because handlers may add other handlers, we sort every time.
1146                handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1147
1148                // Capture phase, events bubble from back to front. Handlers for this phase are used for
1149                // special purposes, such as detecting events outside of a given Bounds.
1150                for (_, handler) in &mut handlers {
1151                    handler(any_mouse_event, DispatchPhase::Capture, self);
1152                    if !self.app.propagate_event {
1153                        break;
1154                    }
1155                }
1156
1157                // Bubble phase, where most normal handlers do their work.
1158                if self.app.propagate_event {
1159                    for (_, handler) in handlers.iter_mut().rev() {
1160                        handler(any_mouse_event, DispatchPhase::Bubble, self);
1161                        if !self.app.propagate_event {
1162                            break;
1163                        }
1164                    }
1165                }
1166
1167                if self.app.propagate_event
1168                    && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1169                {
1170                    self.active_drag = None;
1171                }
1172
1173                // Just in case any handlers added new handlers, which is weird, but possible.
1174                handlers.extend(
1175                    self.window
1176                        .current_frame
1177                        .mouse_listeners
1178                        .get_mut(&any_mouse_event.type_id())
1179                        .into_iter()
1180                        .flat_map(|handlers| handlers.drain(..)),
1181                );
1182                self.window
1183                    .current_frame
1184                    .mouse_listeners
1185                    .insert(any_mouse_event.type_id(), handlers);
1186            }
1187        } else if let Some(any_key_event) = event.keyboard_event() {
1188            let key_dispatch_stack = mem::take(&mut self.window.current_frame.key_dispatch_stack);
1189            let key_event_type = any_key_event.type_id();
1190            let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1191
1192            for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1193                match frame {
1194                    KeyDispatchStackFrame::Listener {
1195                        event_type,
1196                        listener,
1197                    } => {
1198                        if key_event_type == *event_type {
1199                            if let Some(action) = listener(
1200                                any_key_event,
1201                                &context_stack,
1202                                DispatchPhase::Capture,
1203                                self,
1204                            ) {
1205                                self.dispatch_action(action, &key_dispatch_stack[..ix]);
1206                            }
1207                            if !self.app.propagate_event {
1208                                break;
1209                            }
1210                        }
1211                    }
1212                    KeyDispatchStackFrame::Context(context) => {
1213                        context_stack.push(&context);
1214                    }
1215                }
1216            }
1217
1218            if self.app.propagate_event {
1219                for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1220                    match frame {
1221                        KeyDispatchStackFrame::Listener {
1222                            event_type,
1223                            listener,
1224                        } => {
1225                            if key_event_type == *event_type {
1226                                if let Some(action) = listener(
1227                                    any_key_event,
1228                                    &context_stack,
1229                                    DispatchPhase::Bubble,
1230                                    self,
1231                                ) {
1232                                    self.dispatch_action(action, &key_dispatch_stack[..ix]);
1233                                }
1234
1235                                if !self.app.propagate_event {
1236                                    break;
1237                                }
1238                            }
1239                        }
1240                        KeyDispatchStackFrame::Context(_) => {
1241                            context_stack.pop();
1242                        }
1243                    }
1244                }
1245            }
1246
1247            drop(context_stack);
1248            self.window.current_frame.key_dispatch_stack = key_dispatch_stack;
1249        }
1250
1251        !self.app.propagate_event
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    fn read_model<T, R>(
1427        &self,
1428        handle: &Model<T>,
1429        read: impl FnOnce(&T, &AppContext) -> R,
1430    ) -> Self::Result<R>
1431    where
1432        T: 'static,
1433    {
1434        let entity = self.entities.read(handle);
1435        read(&*entity, &*self.app)
1436    }
1437}
1438
1439impl VisualContext for WindowContext<'_> {
1440    fn build_view<V>(
1441        &mut self,
1442        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1443    ) -> Self::Result<View<V>>
1444    where
1445        V: 'static,
1446    {
1447        let slot = self.app.entities.reserve();
1448        let view = View {
1449            model: slot.clone(),
1450        };
1451        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1452        let entity = build_view_state(&mut cx);
1453        self.entities.insert(slot, entity);
1454        view
1455    }
1456
1457    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1458    fn update_view<T: 'static, R>(
1459        &mut self,
1460        view: &View<T>,
1461        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1462    ) -> Self::Result<R> {
1463        let mut lease = self.app.entities.lease(&view.model);
1464        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1465        let result = update(&mut *lease, &mut cx);
1466        cx.app.entities.end_lease(lease);
1467        result
1468    }
1469
1470    fn replace_root_view<V>(
1471        &mut self,
1472        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1473    ) -> Self::Result<View<V>>
1474    where
1475        V: Render,
1476    {
1477        let slot = self.app.entities.reserve();
1478        let view = View {
1479            model: slot.clone(),
1480        };
1481        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1482        let entity = build_view(&mut cx);
1483        self.entities.insert(slot, entity);
1484        self.window.root_view = Some(view.clone().into());
1485        view
1486    }
1487}
1488
1489impl<'a> std::ops::Deref for WindowContext<'a> {
1490    type Target = AppContext;
1491
1492    fn deref(&self) -> &Self::Target {
1493        &self.app
1494    }
1495}
1496
1497impl<'a> std::ops::DerefMut for WindowContext<'a> {
1498    fn deref_mut(&mut self) -> &mut Self::Target {
1499        &mut self.app
1500    }
1501}
1502
1503impl<'a> Borrow<AppContext> for WindowContext<'a> {
1504    fn borrow(&self) -> &AppContext {
1505        &self.app
1506    }
1507}
1508
1509impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1510    fn borrow_mut(&mut self) -> &mut AppContext {
1511        &mut self.app
1512    }
1513}
1514
1515pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1516    fn app_mut(&mut self) -> &mut AppContext {
1517        self.borrow_mut()
1518    }
1519
1520    fn window(&self) -> &Window {
1521        self.borrow()
1522    }
1523
1524    fn window_mut(&mut self) -> &mut Window {
1525        self.borrow_mut()
1526    }
1527
1528    /// Pushes the given element id onto the global stack and invokes the given closure
1529    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1530    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1531    /// used to associate state with identified elements across separate frames.
1532    fn with_element_id<R>(
1533        &mut self,
1534        id: impl Into<ElementId>,
1535        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1536    ) -> R {
1537        let keymap = self.app_mut().keymap.clone();
1538        let window = self.window_mut();
1539        window.element_id_stack.push(id.into());
1540        let global_id = window.element_id_stack.clone();
1541
1542        if window.current_frame.key_matchers.get(&global_id).is_none() {
1543            window.current_frame.key_matchers.insert(
1544                global_id.clone(),
1545                window
1546                    .previous_frame
1547                    .key_matchers
1548                    .remove(&global_id)
1549                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1550            );
1551        }
1552
1553        let result = f(global_id, self);
1554        let window: &mut Window = self.borrow_mut();
1555        window.element_id_stack.pop();
1556        result
1557    }
1558
1559    /// Invoke the given function with the given content mask after intersecting it
1560    /// with the current mask.
1561    fn with_content_mask<R>(
1562        &mut self,
1563        mask: ContentMask<Pixels>,
1564        f: impl FnOnce(&mut Self) -> R,
1565    ) -> R {
1566        let mask = mask.intersect(&self.content_mask());
1567        self.window_mut()
1568            .current_frame
1569            .content_mask_stack
1570            .push(mask);
1571        let result = f(self);
1572        self.window_mut().current_frame.content_mask_stack.pop();
1573        result
1574    }
1575
1576    /// Update the global element offset based on the given offset. This is used to implement
1577    /// scrolling and position drag handles.
1578    fn with_element_offset<R>(
1579        &mut self,
1580        offset: Option<Point<Pixels>>,
1581        f: impl FnOnce(&mut Self) -> R,
1582    ) -> R {
1583        let Some(offset) = offset else {
1584            return f(self);
1585        };
1586
1587        let offset = self.element_offset() + offset;
1588        self.window_mut()
1589            .current_frame
1590            .element_offset_stack
1591            .push(offset);
1592        let result = f(self);
1593        self.window_mut().current_frame.element_offset_stack.pop();
1594        result
1595    }
1596
1597    /// Obtain the current element offset.
1598    fn element_offset(&self) -> Point<Pixels> {
1599        self.window()
1600            .current_frame
1601            .element_offset_stack
1602            .last()
1603            .copied()
1604            .unwrap_or_default()
1605    }
1606
1607    /// Update or intialize state for an element with the given id that lives across multiple
1608    /// frames. If an element with this id existed in the previous frame, its state will be passed
1609    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1610    /// when drawing the next frame.
1611    fn with_element_state<S, R>(
1612        &mut self,
1613        id: ElementId,
1614        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1615    ) -> R
1616    where
1617        S: 'static,
1618    {
1619        self.with_element_id(id, |global_id, cx| {
1620            if let Some(any) = cx
1621                .window_mut()
1622                .current_frame
1623                .element_states
1624                .remove(&global_id)
1625                .or_else(|| {
1626                    cx.window_mut()
1627                        .previous_frame
1628                        .element_states
1629                        .remove(&global_id)
1630                })
1631            {
1632                // Using the extra inner option to avoid needing to reallocate a new box.
1633                let mut state_box = any
1634                    .downcast::<Option<S>>()
1635                    .expect("invalid element state type for id");
1636                let state = state_box
1637                    .take()
1638                    .expect("element state is already on the stack");
1639                let (result, state) = f(Some(state), cx);
1640                state_box.replace(state);
1641                cx.window_mut()
1642                    .current_frame
1643                    .element_states
1644                    .insert(global_id, state_box);
1645                result
1646            } else {
1647                let (result, state) = f(None, cx);
1648                cx.window_mut()
1649                    .current_frame
1650                    .element_states
1651                    .insert(global_id, Box::new(Some(state)));
1652                result
1653            }
1654        })
1655    }
1656
1657    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1658    /// id is `None`, no state will be retrieved or stored.
1659    fn with_optional_element_state<S, R>(
1660        &mut self,
1661        element_id: Option<ElementId>,
1662        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1663    ) -> R
1664    where
1665        S: 'static,
1666    {
1667        if let Some(element_id) = element_id {
1668            self.with_element_state(element_id, f)
1669        } else {
1670            f(None, self).0
1671        }
1672    }
1673
1674    /// Obtain the current content mask.
1675    fn content_mask(&self) -> ContentMask<Pixels> {
1676        self.window()
1677            .current_frame
1678            .content_mask_stack
1679            .last()
1680            .cloned()
1681            .unwrap_or_else(|| ContentMask {
1682                bounds: Bounds {
1683                    origin: Point::default(),
1684                    size: self.window().content_size,
1685                },
1686            })
1687    }
1688
1689    /// The size of an em for the base font of the application. Adjusting this value allows the
1690    /// UI to scale, just like zooming a web page.
1691    fn rem_size(&self) -> Pixels {
1692        self.window().rem_size
1693    }
1694}
1695
1696impl Borrow<Window> for WindowContext<'_> {
1697    fn borrow(&self) -> &Window {
1698        &self.window
1699    }
1700}
1701
1702impl BorrowMut<Window> for WindowContext<'_> {
1703    fn borrow_mut(&mut self) -> &mut Window {
1704        &mut self.window
1705    }
1706}
1707
1708impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1709
1710pub struct ViewContext<'a, V> {
1711    window_cx: WindowContext<'a>,
1712    view: &'a View<V>,
1713}
1714
1715impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1716    fn borrow(&self) -> &AppContext {
1717        &*self.window_cx.app
1718    }
1719}
1720
1721impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1722    fn borrow_mut(&mut self) -> &mut AppContext {
1723        &mut *self.window_cx.app
1724    }
1725}
1726
1727impl<V> Borrow<Window> for ViewContext<'_, V> {
1728    fn borrow(&self) -> &Window {
1729        &*self.window_cx.window
1730    }
1731}
1732
1733impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1734    fn borrow_mut(&mut self) -> &mut Window {
1735        &mut *self.window_cx.window
1736    }
1737}
1738
1739impl<'a, V: 'static> ViewContext<'a, V> {
1740    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1741        Self {
1742            window_cx: WindowContext::new(app, window),
1743            view,
1744        }
1745    }
1746
1747    // todo!("change this to return a reference");
1748    pub fn view(&self) -> View<V> {
1749        self.view.clone()
1750    }
1751
1752    pub fn model(&self) -> Model<V> {
1753        self.view.model.clone()
1754    }
1755
1756    /// Access the underlying window context.
1757    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1758        &mut self.window_cx
1759    }
1760
1761    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1762        self.window.current_frame.z_index_stack.push(z_index);
1763        let result = f(self);
1764        self.window.current_frame.z_index_stack.pop();
1765        result
1766    }
1767
1768    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1769    where
1770        V: 'static,
1771    {
1772        let view = self.view();
1773        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1774    }
1775
1776    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1777    /// that are currently on the stack to be returned to the app.
1778    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1779        let view = self.view().downgrade();
1780        self.window_cx.defer(move |cx| {
1781            view.update(cx, f).ok();
1782        });
1783    }
1784
1785    pub fn observe<V2, E>(
1786        &mut self,
1787        entity: &E,
1788        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1789    ) -> Subscription
1790    where
1791        V2: 'static,
1792        V: 'static,
1793        E: Entity<V2>,
1794    {
1795        let view = self.view().downgrade();
1796        let entity_id = entity.entity_id();
1797        let entity = entity.downgrade();
1798        let window_handle = self.window.handle;
1799        self.app.observers.insert(
1800            entity_id,
1801            Box::new(move |cx| {
1802                window_handle
1803                    .update(cx, |_, cx| {
1804                        if let Some(handle) = E::upgrade_from(&entity) {
1805                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1806                                .is_ok()
1807                        } else {
1808                            false
1809                        }
1810                    })
1811                    .unwrap_or(false)
1812            }),
1813        )
1814    }
1815
1816    // Options for simplifying this new event API:
1817    //
1818    // - Make a new stlye of API which does partial application of the arguments to capture
1819    //   the types involved e.g.
1820    //      `cx.for_entity(handle).subscribe::<ItemEvents>(..)`
1821    //
1822    // - Make it so there are less types:
1823    //   - Bail on this idea all together, go back to associated types.
1824    //      causes our event enums to be a blob of anything that could happen ever, and
1825    //      makes applications have some translation boilerplate
1826    //
1827    //   - Move some of the types into the method names,
1828    //      `cx.subscribe_model::<_, ItemEvents>(handle)`
1829    //
1830    //   - Do something drastic like removing views and models, or removing the multiple
1831    //      kind of contexts. (Not going to happen, we already tried this before.)
1832    //
1833    // - Accept it, and use `cx.subscribe::<_, _, ItemEvents>(handle, ...)`
1834    pub fn subscribe<V2, E, Evt>(
1835        &mut self,
1836        entity: &E,
1837        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1838    ) -> Subscription
1839    where
1840        V2: EventEmitter<Evt>,
1841        E: Entity<V2>,
1842        Evt: 'static,
1843    {
1844        let view = self.view().downgrade();
1845        let entity_id = entity.entity_id();
1846        let handle = entity.downgrade();
1847        let window_handle = self.window.handle;
1848        self.app.event_listeners.insert(
1849            entity_id,
1850            (
1851                TypeId::of::<Evt>(),
1852                Box::new(move |event, cx| {
1853                    window_handle
1854                        .update(cx, |_, cx| {
1855                            if let Some(handle) = E::upgrade_from(&handle) {
1856                                let event = event.downcast_ref().expect("invalid event type");
1857                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1858                                    .is_ok()
1859                            } else {
1860                                false
1861                            }
1862                        })
1863                        .unwrap_or(false)
1864                }),
1865            ),
1866        )
1867    }
1868
1869    pub fn on_release(
1870        &mut self,
1871        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1872    ) -> Subscription {
1873        let window_handle = self.window.handle;
1874        self.app.release_listeners.insert(
1875            self.view.model.entity_id,
1876            Box::new(move |this, cx| {
1877                let this = this.downcast_mut().expect("invalid entity type");
1878                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1879            }),
1880        )
1881    }
1882
1883    pub fn observe_release<V2, E>(
1884        &mut self,
1885        entity: &E,
1886        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1887    ) -> Subscription
1888    where
1889        V: 'static,
1890        V2: 'static,
1891        E: Entity<V2>,
1892    {
1893        let view = self.view().downgrade();
1894        let entity_id = entity.entity_id();
1895        let window_handle = self.window.handle;
1896        self.app.release_listeners.insert(
1897            entity_id,
1898            Box::new(move |entity, cx| {
1899                let entity = entity.downcast_mut().expect("invalid entity type");
1900                let _ = window_handle.update(cx, |_, cx| {
1901                    view.update(cx, |this, cx| on_release(this, entity, cx))
1902                });
1903            }),
1904        )
1905    }
1906
1907    pub fn notify(&mut self) {
1908        self.window_cx.notify();
1909        self.window_cx.app.push_effect(Effect::Notify {
1910            emitter: self.view.model.entity_id,
1911        });
1912    }
1913
1914    pub fn observe_window_bounds(
1915        &mut self,
1916        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1917    ) -> Subscription {
1918        let view = self.view.downgrade();
1919        self.window.bounds_observers.insert(
1920            (),
1921            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1922        )
1923    }
1924
1925    pub fn observe_window_activation(
1926        &mut self,
1927        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1928    ) -> Subscription {
1929        let view = self.view.downgrade();
1930        self.window.activation_observers.insert(
1931            (),
1932            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1933        )
1934    }
1935
1936    /// Register a listener to be called when the given focus handle receives focus.
1937    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1938    /// is dropped.
1939    pub fn on_focus(
1940        &mut self,
1941        handle: &FocusHandle,
1942        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1943    ) -> Subscription {
1944        let view = self.view.downgrade();
1945        let focus_id = handle.id;
1946        self.window.focus_listeners.insert(
1947            (),
1948            Box::new(move |event, cx| {
1949                view.update(cx, |view, cx| {
1950                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
1951                        listener(view, cx)
1952                    }
1953                })
1954                .is_ok()
1955            }),
1956        )
1957    }
1958
1959    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
1960    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1961    /// is dropped.
1962    pub fn on_focus_in(
1963        &mut self,
1964        handle: &FocusHandle,
1965        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1966    ) -> Subscription {
1967        let view = self.view.downgrade();
1968        let focus_id = handle.id;
1969        self.window.focus_listeners.insert(
1970            (),
1971            Box::new(move |event, cx| {
1972                view.update(cx, |view, cx| {
1973                    if event
1974                        .focused
1975                        .as_ref()
1976                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
1977                    {
1978                        listener(view, cx)
1979                    }
1980                })
1981                .is_ok()
1982            }),
1983        )
1984    }
1985
1986    /// Register a listener to be called when the given focus handle loses focus.
1987    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1988    /// is dropped.
1989    pub fn on_blur(
1990        &mut self,
1991        handle: &FocusHandle,
1992        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1993    ) -> Subscription {
1994        let view = self.view.downgrade();
1995        let focus_id = handle.id;
1996        self.window.focus_listeners.insert(
1997            (),
1998            Box::new(move |event, cx| {
1999                view.update(cx, |view, cx| {
2000                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2001                        listener(view, cx)
2002                    }
2003                })
2004                .is_ok()
2005            }),
2006        )
2007    }
2008
2009    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2010    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2011    /// is dropped.
2012    pub fn on_focus_out(
2013        &mut self,
2014        handle: &FocusHandle,
2015        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2016    ) -> Subscription {
2017        let view = self.view.downgrade();
2018        let focus_id = handle.id;
2019        self.window.focus_listeners.insert(
2020            (),
2021            Box::new(move |event, cx| {
2022                view.update(cx, |view, cx| {
2023                    if event
2024                        .blurred
2025                        .as_ref()
2026                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2027                    {
2028                        listener(view, cx)
2029                    }
2030                })
2031                .is_ok()
2032            }),
2033        )
2034    }
2035
2036    /// Register a focus listener for the current frame only. It will be cleared
2037    /// on the next frame render. You should use this method only from within elements,
2038    /// and we may want to enforce that better via a different context type.
2039    // todo!() Move this to `FrameContext` to emphasize its individuality?
2040    pub fn on_focus_changed(
2041        &mut self,
2042        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
2043    ) {
2044        let handle = self.view().downgrade();
2045        self.window
2046            .current_frame
2047            .focus_listeners
2048            .push(Box::new(move |event, cx| {
2049                handle
2050                    .update(cx, |view, cx| listener(view, event, cx))
2051                    .log_err();
2052            }));
2053    }
2054
2055    pub fn with_key_listeners<R>(
2056        &mut self,
2057        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
2058        f: impl FnOnce(&mut Self) -> R,
2059    ) -> R {
2060        let old_stack_len = self.window.current_frame.key_dispatch_stack.len();
2061        if !self.window.current_frame.freeze_key_dispatch_stack {
2062            for (event_type, listener) in key_listeners {
2063                let handle = self.view().downgrade();
2064                let listener = Box::new(
2065                    move |event: &dyn Any,
2066                          context_stack: &[&DispatchContext],
2067                          phase: DispatchPhase,
2068                          cx: &mut WindowContext<'_>| {
2069                        handle
2070                            .update(cx, |view, cx| {
2071                                listener(view, event, context_stack, phase, cx)
2072                            })
2073                            .log_err()
2074                            .flatten()
2075                    },
2076                );
2077                self.window.current_frame.key_dispatch_stack.push(
2078                    KeyDispatchStackFrame::Listener {
2079                        event_type,
2080                        listener,
2081                    },
2082                );
2083            }
2084        }
2085
2086        let result = f(self);
2087
2088        if !self.window.current_frame.freeze_key_dispatch_stack {
2089            self.window
2090                .current_frame
2091                .key_dispatch_stack
2092                .truncate(old_stack_len);
2093        }
2094
2095        result
2096    }
2097
2098    pub fn with_key_dispatch_context<R>(
2099        &mut self,
2100        context: DispatchContext,
2101        f: impl FnOnce(&mut Self) -> R,
2102    ) -> R {
2103        if context.is_empty() {
2104            return f(self);
2105        }
2106
2107        if !self.window.current_frame.freeze_key_dispatch_stack {
2108            self.window
2109                .current_frame
2110                .key_dispatch_stack
2111                .push(KeyDispatchStackFrame::Context(context));
2112        }
2113
2114        let result = f(self);
2115
2116        if !self.window.previous_frame.freeze_key_dispatch_stack {
2117            self.window.previous_frame.key_dispatch_stack.pop();
2118        }
2119
2120        result
2121    }
2122
2123    pub fn with_focus<R>(
2124        &mut self,
2125        focus_handle: FocusHandle,
2126        f: impl FnOnce(&mut Self) -> R,
2127    ) -> R {
2128        if let Some(parent_focus_id) = self.window.current_frame.focus_stack.last().copied() {
2129            self.window
2130                .current_frame
2131                .focus_parents_by_child
2132                .insert(focus_handle.id, parent_focus_id);
2133        }
2134        self.window.current_frame.focus_stack.push(focus_handle.id);
2135
2136        if Some(focus_handle.id) == self.window.focus {
2137            self.window.current_frame.freeze_key_dispatch_stack = true;
2138        }
2139
2140        let result = f(self);
2141
2142        self.window.current_frame.focus_stack.pop();
2143        result
2144    }
2145
2146    pub fn spawn<Fut, R>(
2147        &mut self,
2148        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2149    ) -> Task<R>
2150    where
2151        R: 'static,
2152        Fut: Future<Output = R> + 'static,
2153    {
2154        let view = self.view().downgrade();
2155        self.window_cx.spawn(|cx| f(view, cx))
2156    }
2157
2158    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2159    where
2160        G: 'static,
2161    {
2162        let mut global = self.app.lease_global::<G>();
2163        let result = f(&mut global, self);
2164        self.app.end_global_lease(global);
2165        result
2166    }
2167
2168    pub fn observe_global<G: 'static>(
2169        &mut self,
2170        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
2171    ) -> Subscription {
2172        let window_handle = self.window.handle;
2173        let view = self.view().downgrade();
2174        self.global_observers.insert(
2175            TypeId::of::<G>(),
2176            Box::new(move |cx| {
2177                window_handle
2178                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2179                    .unwrap_or(false)
2180            }),
2181        )
2182    }
2183
2184    pub fn on_mouse_event<Event: 'static>(
2185        &mut self,
2186        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2187    ) {
2188        let handle = self.view();
2189        self.window_cx.on_mouse_event(move |event, phase, cx| {
2190            handle.update(cx, |view, cx| {
2191                handler(view, event, phase, cx);
2192            })
2193        });
2194    }
2195}
2196
2197impl<V> ViewContext<'_, V>
2198where
2199    V: InputHandler + 'static,
2200{
2201    pub fn handle_text_input(&mut self) {
2202        self.window.requested_input_handler = Some(Box::new(WindowInputHandler {
2203            cx: self.app.this.clone(),
2204            window: self.window_handle(),
2205            handler: self.view().downgrade(),
2206        }));
2207    }
2208}
2209
2210impl<V> ViewContext<'_, V> {
2211    pub fn emit<Evt>(&mut self, event: Evt)
2212    where
2213        Evt: 'static,
2214        V: EventEmitter<Evt>,
2215    {
2216        let emitter = self.view.model.entity_id;
2217        self.app.push_effect(Effect::Emit {
2218            emitter,
2219            event_type: TypeId::of::<Evt>(),
2220            event: Box::new(event),
2221        });
2222    }
2223}
2224
2225impl<V> Context for ViewContext<'_, V> {
2226    type Result<U> = U;
2227
2228    fn build_model<T: 'static>(
2229        &mut self,
2230        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2231    ) -> Model<T> {
2232        self.window_cx.build_model(build_model)
2233    }
2234
2235    fn update_model<T: 'static, R>(
2236        &mut self,
2237        model: &Model<T>,
2238        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2239    ) -> R {
2240        self.window_cx.update_model(model, update)
2241    }
2242
2243    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2244    where
2245        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2246    {
2247        self.window_cx.update_window(window, update)
2248    }
2249
2250    fn read_model<T, R>(
2251        &self,
2252        handle: &Model<T>,
2253        read: impl FnOnce(&T, &AppContext) -> R,
2254    ) -> Self::Result<R>
2255    where
2256        T: 'static,
2257    {
2258        self.window_cx.read_model(handle, read)
2259    }
2260}
2261
2262impl<V: 'static> VisualContext for ViewContext<'_, V> {
2263    fn build_view<W: 'static>(
2264        &mut self,
2265        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2266    ) -> Self::Result<View<W>> {
2267        self.window_cx.build_view(build_view_state)
2268    }
2269
2270    fn update_view<V2: 'static, R>(
2271        &mut self,
2272        view: &View<V2>,
2273        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2274    ) -> Self::Result<R> {
2275        self.window_cx.update_view(view, update)
2276    }
2277
2278    fn replace_root_view<W>(
2279        &mut self,
2280        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2281    ) -> Self::Result<View<W>>
2282    where
2283        W: Render,
2284    {
2285        self.window_cx.replace_root_view(build_view)
2286    }
2287}
2288
2289impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2290    type Target = WindowContext<'a>;
2291
2292    fn deref(&self) -> &Self::Target {
2293        &self.window_cx
2294    }
2295}
2296
2297impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2298    fn deref_mut(&mut self) -> &mut Self::Target {
2299        &mut self.window_cx
2300    }
2301}
2302
2303// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2304slotmap::new_key_type! { pub struct WindowId; }
2305
2306impl WindowId {
2307    pub fn as_u64(&self) -> u64 {
2308        self.0.as_ffi()
2309    }
2310}
2311
2312#[derive(Deref, DerefMut)]
2313pub struct WindowHandle<V> {
2314    #[deref]
2315    #[deref_mut]
2316    pub(crate) any_handle: AnyWindowHandle,
2317    state_type: PhantomData<V>,
2318}
2319
2320impl<V: 'static + Render> WindowHandle<V> {
2321    pub fn new(id: WindowId) -> Self {
2322        WindowHandle {
2323            any_handle: AnyWindowHandle {
2324                id,
2325                state_type: TypeId::of::<V>(),
2326            },
2327            state_type: PhantomData,
2328        }
2329    }
2330
2331    pub fn update<C, R>(
2332        self,
2333        cx: &mut C,
2334        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2335    ) -> Result<R>
2336    where
2337        C: Context,
2338    {
2339        cx.update_window(self.any_handle, |root_view, cx| {
2340            let view = root_view
2341                .downcast::<V>()
2342                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2343            Ok(cx.update_view(&view, update))
2344        })?
2345    }
2346}
2347
2348impl<V> Copy for WindowHandle<V> {}
2349
2350impl<V> Clone for WindowHandle<V> {
2351    fn clone(&self) -> Self {
2352        WindowHandle {
2353            any_handle: self.any_handle,
2354            state_type: PhantomData,
2355        }
2356    }
2357}
2358
2359impl<V> PartialEq for WindowHandle<V> {
2360    fn eq(&self, other: &Self) -> bool {
2361        self.any_handle == other.any_handle
2362    }
2363}
2364
2365impl<V> Eq for WindowHandle<V> {}
2366
2367impl<V> Hash for WindowHandle<V> {
2368    fn hash<H: Hasher>(&self, state: &mut H) {
2369        self.any_handle.hash(state);
2370    }
2371}
2372
2373impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2374    fn into(self) -> AnyWindowHandle {
2375        self.any_handle
2376    }
2377}
2378
2379#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2380pub struct AnyWindowHandle {
2381    pub(crate) id: WindowId,
2382    state_type: TypeId,
2383}
2384
2385impl AnyWindowHandle {
2386    pub fn window_id(&self) -> WindowId {
2387        self.id
2388    }
2389
2390    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2391        if TypeId::of::<T>() == self.state_type {
2392            Some(WindowHandle {
2393                any_handle: *self,
2394                state_type: PhantomData,
2395            })
2396        } else {
2397            None
2398        }
2399    }
2400
2401    pub fn update<C, R>(
2402        self,
2403        cx: &mut C,
2404        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2405    ) -> Result<R>
2406    where
2407        C: Context,
2408    {
2409        cx.update_window(self, update)
2410    }
2411}
2412
2413#[cfg(any(test, feature = "test-support"))]
2414impl From<SmallVec<[u32; 16]>> for StackingOrder {
2415    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2416        StackingOrder(small_vec)
2417    }
2418}
2419
2420#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2421pub enum ElementId {
2422    View(EntityId),
2423    Number(usize),
2424    Name(SharedString),
2425    FocusHandle(FocusId),
2426}
2427
2428impl From<EntityId> for ElementId {
2429    fn from(id: EntityId) -> Self {
2430        ElementId::View(id)
2431    }
2432}
2433
2434impl From<usize> for ElementId {
2435    fn from(id: usize) -> Self {
2436        ElementId::Number(id)
2437    }
2438}
2439
2440impl From<i32> for ElementId {
2441    fn from(id: i32) -> Self {
2442        Self::Number(id as usize)
2443    }
2444}
2445
2446impl From<SharedString> for ElementId {
2447    fn from(name: SharedString) -> Self {
2448        ElementId::Name(name)
2449    }
2450}
2451
2452impl From<&'static str> for ElementId {
2453    fn from(name: &'static str) -> Self {
2454        ElementId::Name(name.into())
2455    }
2456}
2457
2458impl<'a> From<&'a FocusHandle> for ElementId {
2459    fn from(handle: &'a FocusHandle) -> Self {
2460        ElementId::FocusHandle(handle.id)
2461    }
2462}