window.rs

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