window.rs

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