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