window.rs

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