window.rs

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