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