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 + Render,
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        cx.entities.insert(slot, entity);
1449
1450        cx.new_view_observers
1451            .clone()
1452            .retain(&TypeId::of::<V>(), |observer| {
1453                let any_view = AnyView::from(view.clone());
1454                (observer)(any_view, self);
1455                true
1456            });
1457
1458        view
1459    }
1460
1461    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1462    fn update_view<T: 'static, R>(
1463        &mut self,
1464        view: &View<T>,
1465        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1466    ) -> Self::Result<R> {
1467        let mut lease = self.app.entities.lease(&view.model);
1468        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1469        let result = update(&mut *lease, &mut cx);
1470        cx.app.entities.end_lease(lease);
1471        result
1472    }
1473
1474    fn replace_root_view<V>(
1475        &mut self,
1476        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1477    ) -> Self::Result<View<V>>
1478    where
1479        V: Render,
1480    {
1481        let slot = self.app.entities.reserve();
1482        let view = View {
1483            model: slot.clone(),
1484        };
1485        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1486        let entity = build_view(&mut cx);
1487        self.entities.insert(slot, entity);
1488        self.window.root_view = Some(view.clone().into());
1489        view
1490    }
1491}
1492
1493impl<'a> std::ops::Deref for WindowContext<'a> {
1494    type Target = AppContext;
1495
1496    fn deref(&self) -> &Self::Target {
1497        &self.app
1498    }
1499}
1500
1501impl<'a> std::ops::DerefMut for WindowContext<'a> {
1502    fn deref_mut(&mut self) -> &mut Self::Target {
1503        &mut self.app
1504    }
1505}
1506
1507impl<'a> Borrow<AppContext> for WindowContext<'a> {
1508    fn borrow(&self) -> &AppContext {
1509        &self.app
1510    }
1511}
1512
1513impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1514    fn borrow_mut(&mut self) -> &mut AppContext {
1515        &mut self.app
1516    }
1517}
1518
1519pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1520    fn app_mut(&mut self) -> &mut AppContext {
1521        self.borrow_mut()
1522    }
1523
1524    fn window(&self) -> &Window {
1525        self.borrow()
1526    }
1527
1528    fn window_mut(&mut self) -> &mut Window {
1529        self.borrow_mut()
1530    }
1531
1532    /// Pushes the given element id onto the global stack and invokes the given closure
1533    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1534    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1535    /// used to associate state with identified elements across separate frames.
1536    fn with_element_id<R>(
1537        &mut self,
1538        id: impl Into<ElementId>,
1539        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1540    ) -> R {
1541        let keymap = self.app_mut().keymap.clone();
1542        let window = self.window_mut();
1543        window.element_id_stack.push(id.into());
1544        let global_id = window.element_id_stack.clone();
1545
1546        if window.current_frame.key_matchers.get(&global_id).is_none() {
1547            window.current_frame.key_matchers.insert(
1548                global_id.clone(),
1549                window
1550                    .previous_frame
1551                    .key_matchers
1552                    .remove(&global_id)
1553                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1554            );
1555        }
1556
1557        let result = f(global_id, self);
1558        let window: &mut Window = self.borrow_mut();
1559        window.element_id_stack.pop();
1560        result
1561    }
1562
1563    /// Invoke the given function with the given content mask after intersecting it
1564    /// with the current mask.
1565    fn with_content_mask<R>(
1566        &mut self,
1567        mask: ContentMask<Pixels>,
1568        f: impl FnOnce(&mut Self) -> R,
1569    ) -> R {
1570        let mask = mask.intersect(&self.content_mask());
1571        self.window_mut()
1572            .current_frame
1573            .content_mask_stack
1574            .push(mask);
1575        let result = f(self);
1576        self.window_mut().current_frame.content_mask_stack.pop();
1577        result
1578    }
1579
1580    /// Update the global element offset based on the given offset. This is used to implement
1581    /// scrolling and position drag handles.
1582    fn with_element_offset<R>(
1583        &mut self,
1584        offset: Option<Point<Pixels>>,
1585        f: impl FnOnce(&mut Self) -> R,
1586    ) -> R {
1587        let Some(offset) = offset else {
1588            return f(self);
1589        };
1590
1591        let offset = self.element_offset() + offset;
1592        self.window_mut()
1593            .current_frame
1594            .element_offset_stack
1595            .push(offset);
1596        let result = f(self);
1597        self.window_mut().current_frame.element_offset_stack.pop();
1598        result
1599    }
1600
1601    /// Obtain the current element offset.
1602    fn element_offset(&self) -> Point<Pixels> {
1603        self.window()
1604            .current_frame
1605            .element_offset_stack
1606            .last()
1607            .copied()
1608            .unwrap_or_default()
1609    }
1610
1611    /// Update or intialize state for an element with the given id that lives across multiple
1612    /// frames. If an element with this id existed in the previous frame, its state will be passed
1613    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1614    /// when drawing the next frame.
1615    fn with_element_state<S, R>(
1616        &mut self,
1617        id: ElementId,
1618        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1619    ) -> R
1620    where
1621        S: 'static,
1622    {
1623        self.with_element_id(id, |global_id, cx| {
1624            if let Some(any) = cx
1625                .window_mut()
1626                .current_frame
1627                .element_states
1628                .remove(&global_id)
1629                .or_else(|| {
1630                    cx.window_mut()
1631                        .previous_frame
1632                        .element_states
1633                        .remove(&global_id)
1634                })
1635            {
1636                // Using the extra inner option to avoid needing to reallocate a new box.
1637                let mut state_box = any
1638                    .downcast::<Option<S>>()
1639                    .expect("invalid element state type for id");
1640                let state = state_box
1641                    .take()
1642                    .expect("element state is already on the stack");
1643                let (result, state) = f(Some(state), cx);
1644                state_box.replace(state);
1645                cx.window_mut()
1646                    .current_frame
1647                    .element_states
1648                    .insert(global_id, state_box);
1649                result
1650            } else {
1651                let (result, state) = f(None, cx);
1652                cx.window_mut()
1653                    .current_frame
1654                    .element_states
1655                    .insert(global_id, Box::new(Some(state)));
1656                result
1657            }
1658        })
1659    }
1660
1661    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1662    /// id is `None`, no state will be retrieved or stored.
1663    fn with_optional_element_state<S, R>(
1664        &mut self,
1665        element_id: Option<ElementId>,
1666        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1667    ) -> R
1668    where
1669        S: 'static,
1670    {
1671        if let Some(element_id) = element_id {
1672            self.with_element_state(element_id, f)
1673        } else {
1674            f(None, self).0
1675        }
1676    }
1677
1678    /// Obtain the current content mask.
1679    fn content_mask(&self) -> ContentMask<Pixels> {
1680        self.window()
1681            .current_frame
1682            .content_mask_stack
1683            .last()
1684            .cloned()
1685            .unwrap_or_else(|| ContentMask {
1686                bounds: Bounds {
1687                    origin: Point::default(),
1688                    size: self.window().content_size,
1689                },
1690            })
1691    }
1692
1693    /// The size of an em for the base font of the application. Adjusting this value allows the
1694    /// UI to scale, just like zooming a web page.
1695    fn rem_size(&self) -> Pixels {
1696        self.window().rem_size
1697    }
1698}
1699
1700impl Borrow<Window> for WindowContext<'_> {
1701    fn borrow(&self) -> &Window {
1702        &self.window
1703    }
1704}
1705
1706impl BorrowMut<Window> for WindowContext<'_> {
1707    fn borrow_mut(&mut self) -> &mut Window {
1708        &mut self.window
1709    }
1710}
1711
1712impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1713
1714pub struct ViewContext<'a, V> {
1715    window_cx: WindowContext<'a>,
1716    view: &'a View<V>,
1717}
1718
1719impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1720    fn borrow(&self) -> &AppContext {
1721        &*self.window_cx.app
1722    }
1723}
1724
1725impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1726    fn borrow_mut(&mut self) -> &mut AppContext {
1727        &mut *self.window_cx.app
1728    }
1729}
1730
1731impl<V> Borrow<Window> for ViewContext<'_, V> {
1732    fn borrow(&self) -> &Window {
1733        &*self.window_cx.window
1734    }
1735}
1736
1737impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1738    fn borrow_mut(&mut self) -> &mut Window {
1739        &mut *self.window_cx.window
1740    }
1741}
1742
1743impl<'a, V: 'static> ViewContext<'a, V> {
1744    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1745        Self {
1746            window_cx: WindowContext::new(app, window),
1747            view,
1748        }
1749    }
1750
1751    // todo!("change this to return a reference");
1752    pub fn view(&self) -> View<V> {
1753        self.view.clone()
1754    }
1755
1756    pub fn model(&self) -> Model<V> {
1757        self.view.model.clone()
1758    }
1759
1760    /// Access the underlying window context.
1761    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1762        &mut self.window_cx
1763    }
1764
1765    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1766        self.window.current_frame.z_index_stack.push(z_index);
1767        let result = f(self);
1768        self.window.current_frame.z_index_stack.pop();
1769        result
1770    }
1771
1772    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1773    where
1774        V: 'static,
1775    {
1776        let view = self.view();
1777        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1778    }
1779
1780    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1781    /// that are currently on the stack to be returned to the app.
1782    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1783        let view = self.view().downgrade();
1784        self.window_cx.defer(move |cx| {
1785            view.update(cx, f).ok();
1786        });
1787    }
1788
1789    pub fn observe<V2, E>(
1790        &mut self,
1791        entity: &E,
1792        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1793    ) -> Subscription
1794    where
1795        V2: 'static,
1796        V: 'static,
1797        E: Entity<V2>,
1798    {
1799        let view = self.view().downgrade();
1800        let entity_id = entity.entity_id();
1801        let entity = entity.downgrade();
1802        let window_handle = self.window.handle;
1803        self.app.observers.insert(
1804            entity_id,
1805            Box::new(move |cx| {
1806                window_handle
1807                    .update(cx, |_, cx| {
1808                        if let Some(handle) = E::upgrade_from(&entity) {
1809                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1810                                .is_ok()
1811                        } else {
1812                            false
1813                        }
1814                    })
1815                    .unwrap_or(false)
1816            }),
1817        )
1818    }
1819
1820    pub fn subscribe<V2, E>(
1821        &mut self,
1822        entity: &E,
1823        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + 'static,
1824    ) -> Subscription
1825    where
1826        V2: EventEmitter,
1827        E: Entity<V2>,
1828    {
1829        let view = self.view().downgrade();
1830        let entity_id = entity.entity_id();
1831        let handle = entity.downgrade();
1832        let window_handle = self.window.handle;
1833        self.app.event_listeners.insert(
1834            entity_id,
1835            Box::new(move |event, cx| {
1836                window_handle
1837                    .update(cx, |_, cx| {
1838                        if let Some(handle) = E::upgrade_from(&handle) {
1839                            let event = event.downcast_ref().expect("invalid event type");
1840                            view.update(cx, |this, cx| on_event(this, handle, event, cx))
1841                                .is_ok()
1842                        } else {
1843                            false
1844                        }
1845                    })
1846                    .unwrap_or(false)
1847            }),
1848        )
1849    }
1850
1851    pub fn on_release(
1852        &mut self,
1853        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1854    ) -> Subscription {
1855        let window_handle = self.window.handle;
1856        self.app.release_listeners.insert(
1857            self.view.model.entity_id,
1858            Box::new(move |this, cx| {
1859                let this = this.downcast_mut().expect("invalid entity type");
1860                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1861            }),
1862        )
1863    }
1864
1865    pub fn observe_release<V2, E>(
1866        &mut self,
1867        entity: &E,
1868        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1869    ) -> Subscription
1870    where
1871        V: 'static,
1872        V2: 'static,
1873        E: Entity<V2>,
1874    {
1875        let view = self.view().downgrade();
1876        let entity_id = entity.entity_id();
1877        let window_handle = self.window.handle;
1878        self.app.release_listeners.insert(
1879            entity_id,
1880            Box::new(move |entity, cx| {
1881                let entity = entity.downcast_mut().expect("invalid entity type");
1882                let _ = window_handle.update(cx, |_, cx| {
1883                    view.update(cx, |this, cx| on_release(this, entity, cx))
1884                });
1885            }),
1886        )
1887    }
1888
1889    pub fn notify(&mut self) {
1890        self.window_cx.notify();
1891        self.window_cx.app.push_effect(Effect::Notify {
1892            emitter: self.view.model.entity_id,
1893        });
1894    }
1895
1896    pub fn observe_window_bounds(
1897        &mut self,
1898        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1899    ) -> Subscription {
1900        let view = self.view.downgrade();
1901        self.window.bounds_observers.insert(
1902            (),
1903            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1904        )
1905    }
1906
1907    pub fn observe_window_activation(
1908        &mut self,
1909        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1910    ) -> Subscription {
1911        let view = self.view.downgrade();
1912        self.window.activation_observers.insert(
1913            (),
1914            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1915        )
1916    }
1917
1918    /// Register a listener to be called when the given focus handle receives focus.
1919    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1920    /// is dropped.
1921    pub fn on_focus(
1922        &mut self,
1923        handle: &FocusHandle,
1924        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1925    ) -> Subscription {
1926        let view = self.view.downgrade();
1927        let focus_id = handle.id;
1928        self.window.focus_listeners.insert(
1929            (),
1930            Box::new(move |event, cx| {
1931                view.update(cx, |view, cx| {
1932                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
1933                        listener(view, cx)
1934                    }
1935                })
1936                .is_ok()
1937            }),
1938        )
1939    }
1940
1941    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
1942    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1943    /// is dropped.
1944    pub fn on_focus_in(
1945        &mut self,
1946        handle: &FocusHandle,
1947        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1948    ) -> Subscription {
1949        let view = self.view.downgrade();
1950        let focus_id = handle.id;
1951        self.window.focus_listeners.insert(
1952            (),
1953            Box::new(move |event, cx| {
1954                view.update(cx, |view, cx| {
1955                    if event
1956                        .focused
1957                        .as_ref()
1958                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
1959                    {
1960                        listener(view, cx)
1961                    }
1962                })
1963                .is_ok()
1964            }),
1965        )
1966    }
1967
1968    /// Register a listener to be called when the given focus handle loses focus.
1969    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1970    /// is dropped.
1971    pub fn on_blur(
1972        &mut self,
1973        handle: &FocusHandle,
1974        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1975    ) -> Subscription {
1976        let view = self.view.downgrade();
1977        let focus_id = handle.id;
1978        self.window.focus_listeners.insert(
1979            (),
1980            Box::new(move |event, cx| {
1981                view.update(cx, |view, cx| {
1982                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
1983                        listener(view, cx)
1984                    }
1985                })
1986                .is_ok()
1987            }),
1988        )
1989    }
1990
1991    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
1992    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1993    /// is dropped.
1994    pub fn on_focus_out(
1995        &mut self,
1996        handle: &FocusHandle,
1997        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1998    ) -> Subscription {
1999        let view = self.view.downgrade();
2000        let focus_id = handle.id;
2001        self.window.focus_listeners.insert(
2002            (),
2003            Box::new(move |event, cx| {
2004                view.update(cx, |view, cx| {
2005                    if event
2006                        .blurred
2007                        .as_ref()
2008                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2009                    {
2010                        listener(view, cx)
2011                    }
2012                })
2013                .is_ok()
2014            }),
2015        )
2016    }
2017
2018    /// Register a focus listener for the current frame only. It will be cleared
2019    /// on the next frame render. You should use this method only from within elements,
2020    /// and we may want to enforce that better via a different context type.
2021    // todo!() Move this to `FrameContext` to emphasize its individuality?
2022    pub fn on_focus_changed(
2023        &mut self,
2024        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
2025    ) {
2026        let handle = self.view().downgrade();
2027        self.window
2028            .current_frame
2029            .focus_listeners
2030            .push(Box::new(move |event, cx| {
2031                handle
2032                    .update(cx, |view, cx| listener(view, event, cx))
2033                    .log_err();
2034            }));
2035    }
2036
2037    pub fn with_key_listeners<R>(
2038        &mut self,
2039        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
2040        f: impl FnOnce(&mut Self) -> R,
2041    ) -> R {
2042        let old_stack_len = self.window.current_frame.key_dispatch_stack.len();
2043        if !self.window.current_frame.freeze_key_dispatch_stack {
2044            for (event_type, listener) in key_listeners {
2045                let handle = self.view().downgrade();
2046                let listener = Box::new(
2047                    move |event: &dyn Any,
2048                          context_stack: &[&DispatchContext],
2049                          phase: DispatchPhase,
2050                          cx: &mut WindowContext<'_>| {
2051                        handle
2052                            .update(cx, |view, cx| {
2053                                listener(view, event, context_stack, phase, cx)
2054                            })
2055                            .log_err()
2056                            .flatten()
2057                    },
2058                );
2059                self.window.current_frame.key_dispatch_stack.push(
2060                    KeyDispatchStackFrame::Listener {
2061                        event_type,
2062                        listener,
2063                    },
2064                );
2065            }
2066        }
2067
2068        let result = f(self);
2069
2070        if !self.window.current_frame.freeze_key_dispatch_stack {
2071            self.window
2072                .current_frame
2073                .key_dispatch_stack
2074                .truncate(old_stack_len);
2075        }
2076
2077        result
2078    }
2079
2080    pub fn with_key_dispatch_context<R>(
2081        &mut self,
2082        context: DispatchContext,
2083        f: impl FnOnce(&mut Self) -> R,
2084    ) -> R {
2085        if context.is_empty() {
2086            return f(self);
2087        }
2088
2089        if !self.window.current_frame.freeze_key_dispatch_stack {
2090            self.window
2091                .current_frame
2092                .key_dispatch_stack
2093                .push(KeyDispatchStackFrame::Context(context));
2094        }
2095
2096        let result = f(self);
2097
2098        if !self.window.previous_frame.freeze_key_dispatch_stack {
2099            self.window.previous_frame.key_dispatch_stack.pop();
2100        }
2101
2102        result
2103    }
2104
2105    pub fn with_focus<R>(
2106        &mut self,
2107        focus_handle: FocusHandle,
2108        f: impl FnOnce(&mut Self) -> R,
2109    ) -> R {
2110        if let Some(parent_focus_id) = self.window.current_frame.focus_stack.last().copied() {
2111            self.window
2112                .current_frame
2113                .focus_parents_by_child
2114                .insert(focus_handle.id, parent_focus_id);
2115        }
2116        self.window.current_frame.focus_stack.push(focus_handle.id);
2117
2118        if Some(focus_handle.id) == self.window.focus {
2119            self.window.current_frame.freeze_key_dispatch_stack = true;
2120        }
2121
2122        let result = f(self);
2123
2124        self.window.current_frame.focus_stack.pop();
2125        result
2126    }
2127
2128    pub fn spawn<Fut, R>(
2129        &mut self,
2130        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2131    ) -> Task<R>
2132    where
2133        R: 'static,
2134        Fut: Future<Output = R> + 'static,
2135    {
2136        let view = self.view().downgrade();
2137        self.window_cx.spawn(|cx| f(view, cx))
2138    }
2139
2140    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2141    where
2142        G: 'static,
2143    {
2144        let mut global = self.app.lease_global::<G>();
2145        let result = f(&mut global, self);
2146        self.app.end_global_lease(global);
2147        result
2148    }
2149
2150    pub fn observe_global<G: 'static>(
2151        &mut self,
2152        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
2153    ) -> Subscription {
2154        let window_handle = self.window.handle;
2155        let view = self.view().downgrade();
2156        self.global_observers.insert(
2157            TypeId::of::<G>(),
2158            Box::new(move |cx| {
2159                window_handle
2160                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2161                    .unwrap_or(false)
2162            }),
2163        )
2164    }
2165
2166    pub fn on_mouse_event<Event: 'static>(
2167        &mut self,
2168        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2169    ) {
2170        let handle = self.view();
2171        self.window_cx.on_mouse_event(move |event, phase, cx| {
2172            handle.update(cx, |view, cx| {
2173                handler(view, event, phase, cx);
2174            })
2175        });
2176    }
2177}
2178
2179impl<V> ViewContext<'_, V>
2180where
2181    V: EventEmitter,
2182    V::Event: 'static,
2183{
2184    pub fn emit(&mut self, event: V::Event) {
2185        let emitter = self.view.model.entity_id;
2186        self.app.push_effect(Effect::Emit {
2187            emitter,
2188            event: Box::new(event),
2189        });
2190    }
2191}
2192
2193impl<V> Context for ViewContext<'_, V> {
2194    type Result<U> = U;
2195
2196    fn build_model<T: 'static>(
2197        &mut self,
2198        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2199    ) -> Model<T> {
2200        self.window_cx.build_model(build_model)
2201    }
2202
2203    fn update_model<T: 'static, R>(
2204        &mut self,
2205        model: &Model<T>,
2206        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2207    ) -> R {
2208        self.window_cx.update_model(model, update)
2209    }
2210
2211    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2212    where
2213        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2214    {
2215        self.window_cx.update_window(window, update)
2216    }
2217
2218    fn read_model<T, R>(
2219        &self,
2220        handle: &Model<T>,
2221        read: impl FnOnce(&T, &AppContext) -> R,
2222    ) -> Self::Result<R>
2223    where
2224        T: 'static,
2225    {
2226        self.window_cx.read_model(handle, read)
2227    }
2228}
2229
2230impl<V: 'static> VisualContext for ViewContext<'_, V> {
2231    fn build_view<W: Render + 'static>(
2232        &mut self,
2233        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2234    ) -> Self::Result<View<W>> {
2235        self.window_cx.build_view(build_view_state)
2236    }
2237
2238    fn update_view<V2: 'static, R>(
2239        &mut self,
2240        view: &View<V2>,
2241        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2242    ) -> Self::Result<R> {
2243        self.window_cx.update_view(view, update)
2244    }
2245
2246    fn replace_root_view<W>(
2247        &mut self,
2248        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2249    ) -> Self::Result<View<W>>
2250    where
2251        W: Render,
2252    {
2253        self.window_cx.replace_root_view(build_view)
2254    }
2255}
2256
2257impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2258    type Target = WindowContext<'a>;
2259
2260    fn deref(&self) -> &Self::Target {
2261        &self.window_cx
2262    }
2263}
2264
2265impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2266    fn deref_mut(&mut self) -> &mut Self::Target {
2267        &mut self.window_cx
2268    }
2269}
2270
2271// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2272slotmap::new_key_type! { pub struct WindowId; }
2273
2274impl WindowId {
2275    pub fn as_u64(&self) -> u64 {
2276        self.0.as_ffi()
2277    }
2278}
2279
2280#[derive(Deref, DerefMut)]
2281pub struct WindowHandle<V> {
2282    #[deref]
2283    #[deref_mut]
2284    pub(crate) any_handle: AnyWindowHandle,
2285    state_type: PhantomData<V>,
2286}
2287
2288impl<V: 'static + Render> WindowHandle<V> {
2289    pub fn new(id: WindowId) -> Self {
2290        WindowHandle {
2291            any_handle: AnyWindowHandle {
2292                id,
2293                state_type: TypeId::of::<V>(),
2294            },
2295            state_type: PhantomData,
2296        }
2297    }
2298
2299    pub fn update<C, R>(
2300        self,
2301        cx: &mut C,
2302        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2303    ) -> Result<R>
2304    where
2305        C: Context,
2306    {
2307        cx.update_window(self.any_handle, |root_view, cx| {
2308            let view = root_view
2309                .downcast::<V>()
2310                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2311            Ok(cx.update_view(&view, update))
2312        })?
2313    }
2314}
2315
2316impl<V> Copy for WindowHandle<V> {}
2317
2318impl<V> Clone for WindowHandle<V> {
2319    fn clone(&self) -> Self {
2320        WindowHandle {
2321            any_handle: self.any_handle,
2322            state_type: PhantomData,
2323        }
2324    }
2325}
2326
2327impl<V> PartialEq for WindowHandle<V> {
2328    fn eq(&self, other: &Self) -> bool {
2329        self.any_handle == other.any_handle
2330    }
2331}
2332
2333impl<V> Eq for WindowHandle<V> {}
2334
2335impl<V> Hash for WindowHandle<V> {
2336    fn hash<H: Hasher>(&self, state: &mut H) {
2337        self.any_handle.hash(state);
2338    }
2339}
2340
2341impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2342    fn into(self) -> AnyWindowHandle {
2343        self.any_handle
2344    }
2345}
2346
2347#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2348pub struct AnyWindowHandle {
2349    pub(crate) id: WindowId,
2350    state_type: TypeId,
2351}
2352
2353impl AnyWindowHandle {
2354    pub fn window_id(&self) -> WindowId {
2355        self.id
2356    }
2357
2358    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2359        if TypeId::of::<T>() == self.state_type {
2360            Some(WindowHandle {
2361                any_handle: *self,
2362                state_type: PhantomData,
2363            })
2364        } else {
2365            None
2366        }
2367    }
2368
2369    pub fn update<C, R>(
2370        self,
2371        cx: &mut C,
2372        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2373    ) -> Result<R>
2374    where
2375        C: Context,
2376    {
2377        cx.update_window(self, update)
2378    }
2379}
2380
2381#[cfg(any(test, feature = "test-support"))]
2382impl From<SmallVec<[u32; 16]>> for StackingOrder {
2383    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2384        StackingOrder(small_vec)
2385    }
2386}
2387
2388#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2389pub enum ElementId {
2390    View(EntityId),
2391    Number(usize),
2392    Name(SharedString),
2393    FocusHandle(FocusId),
2394}
2395
2396impl From<EntityId> for ElementId {
2397    fn from(id: EntityId) -> Self {
2398        ElementId::View(id)
2399    }
2400}
2401
2402impl From<usize> for ElementId {
2403    fn from(id: usize) -> Self {
2404        ElementId::Number(id)
2405    }
2406}
2407
2408impl From<i32> for ElementId {
2409    fn from(id: i32) -> Self {
2410        Self::Number(id as usize)
2411    }
2412}
2413
2414impl From<SharedString> for ElementId {
2415    fn from(name: SharedString) -> Self {
2416        ElementId::Name(name)
2417    }
2418}
2419
2420impl From<&'static str> for ElementId {
2421    fn from(name: &'static str) -> Self {
2422        ElementId::Name(name.into())
2423    }
2424}
2425
2426impl<'a> From<&'a FocusHandle> for ElementId {
2427    fn from(handle: &'a FocusHandle) -> Self {
2428        ElementId::FocusHandle(handle.id)
2429    }
2430}