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