window.rs

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