window.rs

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