window.rs

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