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