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