window.rs

   1use crate::{
   2    px, size, transparent_black, Action, AnyDrag, AnyView, AppContext, Arena, AsyncWindowContext,
   3    AvailableSpace, Bounds, Context, Corners, CursorStyle, DispatchActionListener, DispatchNodeId,
   4    DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten,
   5    GlobalElementId, Hsla, KeyBinding, KeyContext, KeyDownEvent, KeystrokeEvent, Model,
   6    ModelContext, Modifiers, MouseButton, MouseMoveEvent, MouseUpEvent, Pixels, PlatformAtlas,
   7    PlatformDisplay, PlatformInput, PlatformWindow, Point, PromptLevel, Render, ScaledPixels,
   8    SharedString, Size, SubscriberSet, Subscription, TaffyLayoutEngine, Task, View, VisualContext,
   9    WeakView, WindowBounds, WindowOptions,
  10};
  11use anyhow::{anyhow, Context as _, Result};
  12use collections::FxHashSet;
  13use derive_more::{Deref, DerefMut};
  14use futures::{
  15    channel::{mpsc, oneshot},
  16    StreamExt,
  17};
  18use parking_lot::RwLock;
  19use slotmap::SlotMap;
  20use smallvec::SmallVec;
  21use std::{
  22    any::{Any, TypeId},
  23    borrow::{Borrow, BorrowMut},
  24    cell::RefCell,
  25    collections::hash_map::Entry,
  26    fmt::{Debug, Display},
  27    future::Future,
  28    hash::{Hash, Hasher},
  29    marker::PhantomData,
  30    mem,
  31    rc::Rc,
  32    sync::{
  33        atomic::{AtomicUsize, Ordering::SeqCst},
  34        Arc,
  35    },
  36};
  37use util::ResultExt;
  38
  39mod element_cx;
  40pub use element_cx::*;
  41
  42const ACTIVE_DRAG_Z_INDEX: u8 = 1;
  43
  44/// A global stacking order, which is created by stacking successive z-index values.
  45/// Each z-index will always be interpreted in the context of its parent z-index.
  46#[derive(Deref, DerefMut, Clone, Ord, PartialOrd, PartialEq, Eq, Default)]
  47pub struct StackingOrder {
  48    #[deref]
  49    #[deref_mut]
  50    context_stack: SmallVec<[u8; 64]>,
  51    pub(crate) id: u32,
  52}
  53
  54impl std::fmt::Debug for StackingOrder {
  55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  56        let mut stacks = self.context_stack.iter().peekable();
  57        write!(f, "[({}): ", self.id)?;
  58        while let Some(z_index) = stacks.next() {
  59            write!(f, "{z_index}")?;
  60            if stacks.peek().is_some() {
  61                write!(f, "->")?;
  62            }
  63        }
  64        write!(f, "]")?;
  65        Ok(())
  66    }
  67}
  68
  69/// Represents the two different phases when dispatching events.
  70#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  71pub enum DispatchPhase {
  72    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  73    /// invoked front to back and keyboard event listeners are invoked from the focused element
  74    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  75    /// registering event listeners.
  76    #[default]
  77    Bubble,
  78    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  79    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  80    /// is used for special purposes such as clearing the "pressed" state for click events. If
  81    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  82    /// outside of the immediate region may rely on detecting non-local events during this phase.
  83    Capture,
  84}
  85
  86impl DispatchPhase {
  87    /// Returns true if this represents the "bubble" phase.
  88    pub fn bubble(self) -> bool {
  89        self == DispatchPhase::Bubble
  90    }
  91
  92    /// Returns true if this represents the "capture" phase.
  93    pub fn capture(self) -> bool {
  94        self == DispatchPhase::Capture
  95    }
  96}
  97
  98type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  99
 100type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
 101
 102struct FocusEvent {
 103    previous_focus_path: SmallVec<[FocusId; 8]>,
 104    current_focus_path: SmallVec<[FocusId; 8]>,
 105}
 106
 107slotmap::new_key_type! {
 108    /// A globally unique identifier for a focusable element.
 109    pub struct FocusId;
 110}
 111
 112thread_local! {
 113    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(4 * 1024 * 1024));
 114}
 115
 116impl FocusId {
 117    /// Obtains whether the element associated with this handle is currently focused.
 118    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 119        cx.window.focus == Some(*self)
 120    }
 121
 122    /// Obtains whether the element associated with this handle contains the focused
 123    /// element or is itself focused.
 124    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 125        cx.focused()
 126            .map_or(false, |focused| self.contains(focused.id, cx))
 127    }
 128
 129    /// Obtains whether the element associated with this handle is contained within the
 130    /// focused element or is itself focused.
 131    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 132        let focused = cx.focused();
 133        focused.map_or(false, |focused| focused.id.contains(*self, cx))
 134    }
 135
 136    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 137    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 138        cx.window
 139            .rendered_frame
 140            .dispatch_tree
 141            .focus_contains(*self, other)
 142    }
 143}
 144
 145/// A handle which can be used to track and manipulate the focused element in a window.
 146pub struct FocusHandle {
 147    pub(crate) id: FocusId,
 148    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 149}
 150
 151impl std::fmt::Debug for FocusHandle {
 152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 153        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 154    }
 155}
 156
 157impl FocusHandle {
 158    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 159        let id = handles.write().insert(AtomicUsize::new(1));
 160        Self {
 161            id,
 162            handles: handles.clone(),
 163        }
 164    }
 165
 166    pub(crate) fn for_id(
 167        id: FocusId,
 168        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 169    ) -> Option<Self> {
 170        let lock = handles.read();
 171        let ref_count = lock.get(id)?;
 172        if ref_count.load(SeqCst) == 0 {
 173            None
 174        } else {
 175            ref_count.fetch_add(1, SeqCst);
 176            Some(Self {
 177                id,
 178                handles: handles.clone(),
 179            })
 180        }
 181    }
 182
 183    /// Moves the focus to the element associated with this handle.
 184    pub fn focus(&self, cx: &mut WindowContext) {
 185        cx.focus(self)
 186    }
 187
 188    /// Obtains whether the element associated with this handle is currently focused.
 189    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 190        self.id.is_focused(cx)
 191    }
 192
 193    /// Obtains whether the element associated with this handle contains the focused
 194    /// element or is itself focused.
 195    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 196        self.id.contains_focused(cx)
 197    }
 198
 199    /// Obtains whether the element associated with this handle is contained within the
 200    /// focused element or is itself focused.
 201    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 202        self.id.within_focused(cx)
 203    }
 204
 205    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 206    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 207        self.id.contains(other.id, cx)
 208    }
 209}
 210
 211impl Clone for FocusHandle {
 212    fn clone(&self) -> Self {
 213        Self::for_id(self.id, &self.handles).unwrap()
 214    }
 215}
 216
 217impl PartialEq for FocusHandle {
 218    fn eq(&self, other: &Self) -> bool {
 219        self.id == other.id
 220    }
 221}
 222
 223impl Eq for FocusHandle {}
 224
 225impl Drop for FocusHandle {
 226    fn drop(&mut self) {
 227        self.handles
 228            .read()
 229            .get(self.id)
 230            .unwrap()
 231            .fetch_sub(1, SeqCst);
 232    }
 233}
 234
 235/// FocusableView allows users of your view to easily
 236/// focus it (using cx.focus_view(view))
 237pub trait FocusableView: 'static + Render {
 238    /// Returns the focus handle associated with this view.
 239    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 240}
 241
 242/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 243/// where the lifecycle of the view is handled by another view.
 244pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 245
 246impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 247
 248/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 249pub struct DismissEvent;
 250
 251// Holds the state for a specific window.
 252#[doc(hidden)]
 253pub struct Window {
 254    pub(crate) handle: AnyWindowHandle,
 255    pub(crate) removed: bool,
 256    pub(crate) platform_window: Box<dyn PlatformWindow>,
 257    display_id: DisplayId,
 258    sprite_atlas: Arc<dyn PlatformAtlas>,
 259    pub(crate) rem_size: Pixels,
 260    pub(crate) viewport_size: Size<Pixels>,
 261    layout_engine: Option<TaffyLayoutEngine>,
 262    pub(crate) root_view: Option<AnyView>,
 263    pub(crate) element_id_stack: GlobalElementId,
 264    pub(crate) rendered_frame: Frame,
 265    pub(crate) next_frame: Frame,
 266    pub(crate) dirty_views: FxHashSet<EntityId>,
 267    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 268    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 269    focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 270    default_prevented: bool,
 271    mouse_position: Point<Pixels>,
 272    modifiers: Modifiers,
 273    scale_factor: f32,
 274    bounds: WindowBounds,
 275    bounds_observers: SubscriberSet<(), AnyObserver>,
 276    active: bool,
 277    pub(crate) dirty: bool,
 278    pub(crate) refreshing: bool,
 279    pub(crate) drawing: bool,
 280    activation_observers: SubscriberSet<(), AnyObserver>,
 281    pub(crate) focus: Option<FocusId>,
 282    focus_enabled: bool,
 283
 284    #[cfg(any(test, feature = "test-support"))]
 285    pub(crate) focus_invalidated: bool,
 286}
 287
 288pub(crate) struct ElementStateBox {
 289    pub(crate) inner: Box<dyn Any>,
 290    pub(crate) parent_view_id: EntityId,
 291    #[cfg(debug_assertions)]
 292    pub(crate) type_name: &'static str,
 293}
 294
 295impl Window {
 296    pub(crate) fn new(
 297        handle: AnyWindowHandle,
 298        options: WindowOptions,
 299        cx: &mut AppContext,
 300    ) -> Self {
 301        let platform_window = cx.platform.open_window(handle, options);
 302        let display_id = platform_window.display().id();
 303        let sprite_atlas = platform_window.sprite_atlas();
 304        let mouse_position = platform_window.mouse_position();
 305        let modifiers = platform_window.modifiers();
 306        let content_size = platform_window.content_size();
 307        let scale_factor = platform_window.scale_factor();
 308        let bounds = platform_window.bounds();
 309
 310        platform_window.on_request_frame(Box::new({
 311            let mut cx = cx.to_async();
 312            move || {
 313                handle.update(&mut cx, |_, cx| cx.draw()).log_err();
 314            }
 315        }));
 316        platform_window.on_resize(Box::new({
 317            let mut cx = cx.to_async();
 318            move |_, _| {
 319                handle
 320                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 321                    .log_err();
 322            }
 323        }));
 324        platform_window.on_moved(Box::new({
 325            let mut cx = cx.to_async();
 326            move || {
 327                handle
 328                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 329                    .log_err();
 330            }
 331        }));
 332        platform_window.on_active_status_change(Box::new({
 333            let mut cx = cx.to_async();
 334            move |active| {
 335                handle
 336                    .update(&mut cx, |_, cx| {
 337                        cx.window.active = active;
 338                        cx.window
 339                            .activation_observers
 340                            .clone()
 341                            .retain(&(), |callback| callback(cx));
 342                    })
 343                    .log_err();
 344            }
 345        }));
 346
 347        platform_window.on_input({
 348            let mut cx = cx.to_async();
 349            Box::new(move |event| {
 350                handle
 351                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 352                    .log_err()
 353                    .unwrap_or(false)
 354            })
 355        });
 356
 357        Window {
 358            handle,
 359            removed: false,
 360            platform_window,
 361            display_id,
 362            sprite_atlas,
 363            rem_size: px(16.),
 364            viewport_size: content_size,
 365            layout_engine: Some(TaffyLayoutEngine::new()),
 366            root_view: None,
 367            element_id_stack: GlobalElementId::default(),
 368            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 369            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 370            dirty_views: FxHashSet::default(),
 371            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 372            focus_listeners: SubscriberSet::new(),
 373            focus_lost_listeners: SubscriberSet::new(),
 374            default_prevented: true,
 375            mouse_position,
 376            modifiers,
 377            scale_factor,
 378            bounds,
 379            bounds_observers: SubscriberSet::new(),
 380            active: false,
 381            dirty: false,
 382            refreshing: false,
 383            drawing: false,
 384            activation_observers: SubscriberSet::new(),
 385            focus: None,
 386            focus_enabled: true,
 387
 388            #[cfg(any(test, feature = "test-support"))]
 389            focus_invalidated: false,
 390        }
 391    }
 392}
 393
 394/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 395/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 396/// to leave room to support more complex shapes in the future.
 397#[derive(Clone, Debug, Default, PartialEq, Eq)]
 398#[repr(C)]
 399pub struct ContentMask<P: Clone + Default + Debug> {
 400    /// The bounds
 401    pub bounds: Bounds<P>,
 402}
 403
 404impl ContentMask<Pixels> {
 405    /// Scale the content mask's pixel units by the given scaling factor.
 406    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 407        ContentMask {
 408            bounds: self.bounds.scale(factor),
 409        }
 410    }
 411
 412    /// Intersect the content mask with the given content mask.
 413    pub fn intersect(&self, other: &Self) -> Self {
 414        let bounds = self.bounds.intersect(&other.bounds);
 415        ContentMask { bounds }
 416    }
 417}
 418
 419/// Provides access to application state in the context of a single window. Derefs
 420/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
 421/// an [`AppContext`] and call any [`AppContext`] methods.
 422pub struct WindowContext<'a> {
 423    pub(crate) app: &'a mut AppContext,
 424    pub(crate) window: &'a mut Window,
 425}
 426
 427impl<'a> WindowContext<'a> {
 428    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 429        Self { app, window }
 430    }
 431
 432    /// Obtain a handle to the window that belongs to this context.
 433    pub fn window_handle(&self) -> AnyWindowHandle {
 434        self.window.handle
 435    }
 436
 437    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 438    pub fn refresh(&mut self) {
 439        if !self.window.drawing {
 440            self.window.refreshing = true;
 441            self.window.dirty = true;
 442        }
 443    }
 444
 445    /// Close this window.
 446    pub fn remove_window(&mut self) {
 447        self.window.removed = true;
 448    }
 449
 450    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
 451    /// for elements rendered within this window.
 452    pub fn focus_handle(&mut self) -> FocusHandle {
 453        FocusHandle::new(&self.window.focus_handles)
 454    }
 455
 456    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
 457    pub fn focused(&self) -> Option<FocusHandle> {
 458        self.window
 459            .focus
 460            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 461    }
 462
 463    /// Move focus to the element associated with the given [`FocusHandle`].
 464    pub fn focus(&mut self, handle: &FocusHandle) {
 465        if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
 466            return;
 467        }
 468
 469        self.window.focus = Some(handle.id);
 470        self.window
 471            .rendered_frame
 472            .dispatch_tree
 473            .clear_pending_keystrokes();
 474
 475        #[cfg(any(test, feature = "test-support"))]
 476        {
 477            self.window.focus_invalidated = true;
 478        }
 479
 480        self.refresh();
 481    }
 482
 483    /// Remove focus from all elements within this context's window.
 484    pub fn blur(&mut self) {
 485        if !self.window.focus_enabled {
 486            return;
 487        }
 488
 489        self.window.focus = None;
 490        self.refresh();
 491    }
 492
 493    /// Blur the window and don't allow anything in it to be focused again.
 494    pub fn disable_focus(&mut self) {
 495        self.blur();
 496        self.window.focus_enabled = false;
 497    }
 498
 499    /// Dispatch the given action on the currently focused element.
 500    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 501        let focus_handle = self.focused();
 502
 503        self.defer(move |cx| {
 504            let node_id = focus_handle
 505                .and_then(|handle| {
 506                    cx.window
 507                        .rendered_frame
 508                        .dispatch_tree
 509                        .focusable_node_id(handle.id)
 510                })
 511                .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
 512
 513            cx.propagate_event = true;
 514            cx.dispatch_action_on_node(node_id, action);
 515        })
 516    }
 517
 518    pub(crate) fn dispatch_keystroke_observers(
 519        &mut self,
 520        event: &dyn Any,
 521        action: Option<Box<dyn Action>>,
 522    ) {
 523        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
 524            return;
 525        };
 526
 527        self.keystroke_observers
 528            .clone()
 529            .retain(&(), move |callback| {
 530                (callback)(
 531                    &KeystrokeEvent {
 532                        keystroke: key_down_event.keystroke.clone(),
 533                        action: action.as_ref().map(|action| action.boxed_clone()),
 534                    },
 535                    self,
 536                );
 537                true
 538            });
 539    }
 540
 541    pub(crate) fn clear_pending_keystrokes(&mut self) {
 542        self.window
 543            .rendered_frame
 544            .dispatch_tree
 545            .clear_pending_keystrokes();
 546        self.window
 547            .next_frame
 548            .dispatch_tree
 549            .clear_pending_keystrokes();
 550    }
 551
 552    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 553    /// that are currently on the stack to be returned to the app.
 554    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 555        let handle = self.window.handle;
 556        self.app.defer(move |cx| {
 557            handle.update(cx, |_, cx| f(cx)).ok();
 558        });
 559    }
 560
 561    /// Subscribe to events emitted by a model or view.
 562    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
 563    /// 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.
 564    pub fn subscribe<Emitter, E, Evt>(
 565        &mut self,
 566        entity: &E,
 567        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
 568    ) -> Subscription
 569    where
 570        Emitter: EventEmitter<Evt>,
 571        E: Entity<Emitter>,
 572        Evt: 'static,
 573    {
 574        let entity_id = entity.entity_id();
 575        let entity = entity.downgrade();
 576        let window_handle = self.window.handle;
 577        let (subscription, activate) = self.app.event_listeners.insert(
 578            entity_id,
 579            (
 580                TypeId::of::<Evt>(),
 581                Box::new(move |event, cx| {
 582                    window_handle
 583                        .update(cx, |_, cx| {
 584                            if let Some(handle) = E::upgrade_from(&entity) {
 585                                let event = event.downcast_ref().expect("invalid event type");
 586                                on_event(handle, event, cx);
 587                                true
 588                            } else {
 589                                false
 590                            }
 591                        })
 592                        .unwrap_or(false)
 593                }),
 594            ),
 595        );
 596        self.app.defer(move |_| activate());
 597        subscription
 598    }
 599
 600    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
 601    /// await points in async code.
 602    pub fn to_async(&self) -> AsyncWindowContext {
 603        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 604    }
 605
 606    /// Schedule the given closure to be run directly after the current frame is rendered.
 607    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
 608        let handle = self.window.handle;
 609        let display_id = self.window.display_id;
 610
 611        let mut frame_consumers = std::mem::take(&mut self.app.frame_consumers);
 612        if let Entry::Vacant(e) = frame_consumers.entry(display_id) {
 613            let (tx, mut rx) = mpsc::unbounded::<()>();
 614            self.platform.set_display_link_output_callback(
 615                display_id,
 616                Box::new(move || _ = tx.unbounded_send(())),
 617            );
 618
 619            let consumer_task = self.app.spawn(|cx| async move {
 620                while rx.next().await.is_some() {
 621                    cx.update(|cx| {
 622                        for callback in cx
 623                            .next_frame_callbacks
 624                            .get_mut(&display_id)
 625                            .unwrap()
 626                            .drain(..)
 627                            .collect::<SmallVec<[_; 32]>>()
 628                        {
 629                            callback(cx);
 630                        }
 631                    })
 632                    .ok();
 633
 634                    // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
 635
 636                    cx.update(|cx| {
 637                        if cx.next_frame_callbacks.is_empty() {
 638                            cx.platform.stop_display_link(display_id);
 639                        }
 640                    })
 641                    .ok();
 642                }
 643            });
 644            e.insert(consumer_task);
 645        }
 646        debug_assert!(self.app.frame_consumers.is_empty());
 647        self.app.frame_consumers = frame_consumers;
 648
 649        if self.next_frame_callbacks.is_empty() {
 650            self.platform.start_display_link(display_id);
 651        }
 652
 653        self.next_frame_callbacks
 654            .entry(display_id)
 655            .or_default()
 656            .push(Box::new(move |cx: &mut AppContext| {
 657                cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
 658            }));
 659    }
 660
 661    /// Spawn the future returned by the given closure on the application thread pool.
 662    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 663    /// use within your future.
 664    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 665    where
 666        R: 'static,
 667        Fut: Future<Output = R> + 'static,
 668    {
 669        self.app
 670            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 671    }
 672
 673    /// Updates the global of the given type. The given closure is given simultaneous mutable
 674    /// access both to the global and the context.
 675    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 676    where
 677        G: 'static,
 678    {
 679        let mut global = self.app.lease_global::<G>();
 680        let result = f(&mut global, self);
 681        self.app.end_global_lease(global);
 682        result
 683    }
 684
 685    fn window_bounds_changed(&mut self) {
 686        self.window.scale_factor = self.window.platform_window.scale_factor();
 687        self.window.viewport_size = self.window.platform_window.content_size();
 688        self.window.bounds = self.window.platform_window.bounds();
 689        self.window.display_id = self.window.platform_window.display().id();
 690        self.refresh();
 691
 692        self.window
 693            .bounds_observers
 694            .clone()
 695            .retain(&(), |callback| callback(self));
 696    }
 697
 698    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
 699    pub fn window_bounds(&self) -> WindowBounds {
 700        self.window.bounds
 701    }
 702
 703    /// Returns the size of the drawable area within the window.
 704    pub fn viewport_size(&self) -> Size<Pixels> {
 705        self.window.viewport_size
 706    }
 707
 708    /// Returns whether this window is focused by the operating system (receiving key events).
 709    pub fn is_window_active(&self) -> bool {
 710        self.window.active
 711    }
 712
 713    /// Toggle zoom on the window.
 714    pub fn zoom_window(&self) {
 715        self.window.platform_window.zoom();
 716    }
 717
 718    /// Updates the window's title at the platform level.
 719    pub fn set_window_title(&mut self, title: &str) {
 720        self.window.platform_window.set_title(title);
 721    }
 722
 723    /// Mark the window as dirty at the platform level.
 724    pub fn set_window_edited(&mut self, edited: bool) {
 725        self.window.platform_window.set_edited(edited);
 726    }
 727
 728    /// Determine the display on which the window is visible.
 729    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 730        self.platform
 731            .displays()
 732            .into_iter()
 733            .find(|display| display.id() == self.window.display_id)
 734    }
 735
 736    /// Show the platform character palette.
 737    pub fn show_character_palette(&self) {
 738        self.window.platform_window.show_character_palette();
 739    }
 740
 741    /// The scale factor of the display associated with the window. For example, it could
 742    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 743    /// be rendered as two pixels on screen.
 744    pub fn scale_factor(&self) -> f32 {
 745        self.window.scale_factor
 746    }
 747
 748    /// The size of an em for the base font of the application. Adjusting this value allows the
 749    /// UI to scale, just like zooming a web page.
 750    pub fn rem_size(&self) -> Pixels {
 751        self.window.rem_size
 752    }
 753
 754    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 755    /// UI to scale, just like zooming a web page.
 756    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 757        self.window.rem_size = rem_size.into();
 758    }
 759
 760    /// The line height associated with the current text style.
 761    pub fn line_height(&self) -> Pixels {
 762        let rem_size = self.rem_size();
 763        let text_style = self.text_style();
 764        text_style
 765            .line_height
 766            .to_pixels(text_style.font_size, rem_size)
 767    }
 768
 769    /// Call to prevent the default action of an event. Currently only used to prevent
 770    /// parent elements from becoming focused on mouse down.
 771    pub fn prevent_default(&mut self) {
 772        self.window.default_prevented = true;
 773    }
 774
 775    /// Obtain whether default has been prevented for the event currently being dispatched.
 776    pub fn default_prevented(&self) -> bool {
 777        self.window.default_prevented
 778    }
 779
 780    /// Determine whether the given action is available along the dispatch path to the currently focused element.
 781    pub fn is_action_available(&self, action: &dyn Action) -> bool {
 782        let target = self
 783            .focused()
 784            .and_then(|focused_handle| {
 785                self.window
 786                    .rendered_frame
 787                    .dispatch_tree
 788                    .focusable_node_id(focused_handle.id)
 789            })
 790            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
 791        self.window
 792            .rendered_frame
 793            .dispatch_tree
 794            .is_action_available(action, target)
 795    }
 796
 797    /// The position of the mouse relative to the window.
 798    pub fn mouse_position(&self) -> Point<Pixels> {
 799        self.window.mouse_position
 800    }
 801
 802    /// The current state of the keyboard's modifiers
 803    pub fn modifiers(&self) -> Modifiers {
 804        self.window.modifiers
 805    }
 806
 807    /// Returns true if there is no opaque layer containing the given point
 808    /// on top of the given level. Layers whose level is an extension of the
 809    /// level are not considered to be on top of the level.
 810    pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
 811        for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
 812            if level >= opaque_level {
 813                break;
 814            }
 815
 816            if bounds.contains(point) && !opaque_level.starts_with(level) {
 817                return false;
 818            }
 819        }
 820        true
 821    }
 822
 823    pub(crate) fn was_top_layer_under_active_drag(
 824        &self,
 825        point: &Point<Pixels>,
 826        level: &StackingOrder,
 827    ) -> bool {
 828        for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
 829            if level >= opaque_level {
 830                break;
 831            }
 832            if opaque_level.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
 833                continue;
 834            }
 835
 836            if bounds.contains(point) && !opaque_level.starts_with(level) {
 837                return false;
 838            }
 839        }
 840        true
 841    }
 842
 843    /// Called during painting to get the current stacking order.
 844    pub fn stacking_order(&self) -> &StackingOrder {
 845        &self.window.next_frame.z_index_stack
 846    }
 847
 848    /// Draw pixels to the display for this window based on the contents of its scene.
 849    pub(crate) fn draw(&mut self) {
 850        self.window.dirty = false;
 851        self.window.drawing = true;
 852
 853        #[cfg(any(test, feature = "test-support"))]
 854        {
 855            self.window.focus_invalidated = false;
 856        }
 857
 858        if let Some(requested_handler) = self.window.rendered_frame.requested_input_handler.as_mut()
 859        {
 860            let input_handler = self.window.platform_window.take_input_handler();
 861            requested_handler.handler = input_handler;
 862        }
 863
 864        let root_view = self.window.root_view.take().unwrap();
 865        self.with_element_context(|cx| {
 866            cx.with_z_index(0, |cx| {
 867                cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
 868                    // We need to use cx.cx here so we can utilize borrow splitting
 869                    for (action_type, action_listeners) in &cx.cx.app.global_action_listeners {
 870                        for action_listener in action_listeners.iter().cloned() {
 871                            cx.cx.window.next_frame.dispatch_tree.on_action(
 872                                *action_type,
 873                                Rc::new(
 874                                    move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
 875                                        action_listener(action, phase, cx)
 876                                    },
 877                                ),
 878                            )
 879                        }
 880                    }
 881
 882                    let available_space = cx.window.viewport_size.map(Into::into);
 883                    root_view.draw(Point::default(), available_space, cx);
 884                })
 885            })
 886        });
 887
 888        if let Some(active_drag) = self.app.active_drag.take() {
 889            self.with_element_context(|cx| {
 890                cx.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
 891                    let offset = cx.mouse_position() - active_drag.cursor_offset;
 892                    let available_space =
 893                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 894                    active_drag.view.draw(offset, available_space, cx);
 895                })
 896            });
 897            self.active_drag = Some(active_drag);
 898        } else if let Some(tooltip_request) = self.window.next_frame.tooltip_request.take() {
 899            self.with_element_context(|cx| {
 900                cx.with_z_index(1, |cx| {
 901                    let available_space =
 902                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 903                    tooltip_request.tooltip.view.draw(
 904                        tooltip_request.tooltip.cursor_offset,
 905                        available_space,
 906                        cx,
 907                    );
 908                })
 909            });
 910            self.window.next_frame.tooltip_request = Some(tooltip_request);
 911        }
 912        self.window.dirty_views.clear();
 913
 914        self.window
 915            .next_frame
 916            .dispatch_tree
 917            .preserve_pending_keystrokes(
 918                &mut self.window.rendered_frame.dispatch_tree,
 919                self.window.focus,
 920            );
 921        self.window.next_frame.focus = self.window.focus;
 922        self.window.next_frame.window_active = self.window.active;
 923        self.window.root_view = Some(root_view);
 924
 925        // Set the cursor only if we're the active window.
 926        let cursor_style = self
 927            .window
 928            .next_frame
 929            .requested_cursor_style
 930            .take()
 931            .unwrap_or(CursorStyle::Arrow);
 932        if self.is_window_active() {
 933            self.platform.set_cursor_style(cursor_style);
 934        }
 935
 936        // Register requested input handler with the platform window.
 937        if let Some(requested_input) = self.window.next_frame.requested_input_handler.as_mut() {
 938            if let Some(handler) = requested_input.handler.take() {
 939                self.window.platform_window.set_input_handler(handler);
 940            }
 941        }
 942
 943        self.window.layout_engine.as_mut().unwrap().clear();
 944        self.text_system()
 945            .finish_frame(&self.window.next_frame.reused_views);
 946        self.window
 947            .next_frame
 948            .finish(&mut self.window.rendered_frame);
 949        ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
 950
 951        let previous_focus_path = self.window.rendered_frame.focus_path();
 952        let previous_window_active = self.window.rendered_frame.window_active;
 953        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
 954        self.window.next_frame.clear();
 955        let current_focus_path = self.window.rendered_frame.focus_path();
 956        let current_window_active = self.window.rendered_frame.window_active;
 957
 958        if previous_focus_path != current_focus_path
 959            || previous_window_active != current_window_active
 960        {
 961            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
 962                self.window
 963                    .focus_lost_listeners
 964                    .clone()
 965                    .retain(&(), |listener| listener(self));
 966            }
 967
 968            let event = FocusEvent {
 969                previous_focus_path: if previous_window_active {
 970                    previous_focus_path
 971                } else {
 972                    Default::default()
 973                },
 974                current_focus_path: if current_window_active {
 975                    current_focus_path
 976                } else {
 977                    Default::default()
 978                },
 979            };
 980            self.window
 981                .focus_listeners
 982                .clone()
 983                .retain(&(), |listener| listener(&event, self));
 984        }
 985
 986        self.window
 987            .platform_window
 988            .draw(&self.window.rendered_frame.scene);
 989        self.window.refreshing = false;
 990        self.window.drawing = false;
 991    }
 992
 993    /// Dispatch a mouse or keyboard event on the window.
 994    pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
 995        // Handlers may set this to false by calling `stop_propagation`.
 996        self.app.propagate_event = true;
 997        // Handlers may set this to true by calling `prevent_default`.
 998        self.window.default_prevented = false;
 999
1000        let event = match event {
1001            // Track the mouse position with our own state, since accessing the platform
1002            // API for the mouse position can only occur on the main thread.
1003            PlatformInput::MouseMove(mouse_move) => {
1004                self.window.mouse_position = mouse_move.position;
1005                self.window.modifiers = mouse_move.modifiers;
1006                PlatformInput::MouseMove(mouse_move)
1007            }
1008            PlatformInput::MouseDown(mouse_down) => {
1009                self.window.mouse_position = mouse_down.position;
1010                self.window.modifiers = mouse_down.modifiers;
1011                PlatformInput::MouseDown(mouse_down)
1012            }
1013            PlatformInput::MouseUp(mouse_up) => {
1014                self.window.mouse_position = mouse_up.position;
1015                self.window.modifiers = mouse_up.modifiers;
1016                PlatformInput::MouseUp(mouse_up)
1017            }
1018            PlatformInput::MouseExited(mouse_exited) => {
1019                self.window.modifiers = mouse_exited.modifiers;
1020                PlatformInput::MouseExited(mouse_exited)
1021            }
1022            PlatformInput::ModifiersChanged(modifiers_changed) => {
1023                self.window.modifiers = modifiers_changed.modifiers;
1024                PlatformInput::ModifiersChanged(modifiers_changed)
1025            }
1026            PlatformInput::ScrollWheel(scroll_wheel) => {
1027                self.window.mouse_position = scroll_wheel.position;
1028                self.window.modifiers = scroll_wheel.modifiers;
1029                PlatformInput::ScrollWheel(scroll_wheel)
1030            }
1031            // Translate dragging and dropping of external files from the operating system
1032            // to internal drag and drop events.
1033            PlatformInput::FileDrop(file_drop) => match file_drop {
1034                FileDropEvent::Entered { position, paths } => {
1035                    self.window.mouse_position = position;
1036                    if self.active_drag.is_none() {
1037                        self.active_drag = Some(AnyDrag {
1038                            value: Box::new(paths.clone()),
1039                            view: self.new_view(|_| paths).into(),
1040                            cursor_offset: position,
1041                        });
1042                    }
1043                    PlatformInput::MouseMove(MouseMoveEvent {
1044                        position,
1045                        pressed_button: Some(MouseButton::Left),
1046                        modifiers: Modifiers::default(),
1047                    })
1048                }
1049                FileDropEvent::Pending { position } => {
1050                    self.window.mouse_position = position;
1051                    PlatformInput::MouseMove(MouseMoveEvent {
1052                        position,
1053                        pressed_button: Some(MouseButton::Left),
1054                        modifiers: Modifiers::default(),
1055                    })
1056                }
1057                FileDropEvent::Submit { position } => {
1058                    self.activate(true);
1059                    self.window.mouse_position = position;
1060                    PlatformInput::MouseUp(MouseUpEvent {
1061                        button: MouseButton::Left,
1062                        position,
1063                        modifiers: Modifiers::default(),
1064                        click_count: 1,
1065                    })
1066                }
1067                FileDropEvent::Exited => PlatformInput::MouseUp(MouseUpEvent {
1068                    button: MouseButton::Left,
1069                    position: Point::default(),
1070                    modifiers: Modifiers::default(),
1071                    click_count: 1,
1072                }),
1073            },
1074            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1075        };
1076
1077        if let Some(any_mouse_event) = event.mouse_event() {
1078            self.dispatch_mouse_event(any_mouse_event);
1079        } else if let Some(any_key_event) = event.keyboard_event() {
1080            self.dispatch_key_event(any_key_event);
1081        }
1082
1083        !self.app.propagate_event
1084    }
1085
1086    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1087        if let Some(mut handlers) = self
1088            .window
1089            .rendered_frame
1090            .mouse_listeners
1091            .remove(&event.type_id())
1092        {
1093            // Because handlers may add other handlers, we sort every time.
1094            handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
1095
1096            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1097            // special purposes, such as detecting events outside of a given Bounds.
1098            for (_, _, handler) in &mut handlers {
1099                self.with_element_context(|cx| {
1100                    handler(event, DispatchPhase::Capture, cx);
1101                });
1102                if !self.app.propagate_event {
1103                    break;
1104                }
1105            }
1106
1107            // Bubble phase, where most normal handlers do their work.
1108            if self.app.propagate_event {
1109                for (_, _, handler) in handlers.iter_mut().rev() {
1110                    self.with_element_context(|cx| {
1111                        handler(event, DispatchPhase::Bubble, cx);
1112                    });
1113                    if !self.app.propagate_event {
1114                        break;
1115                    }
1116                }
1117            }
1118
1119            self.window
1120                .rendered_frame
1121                .mouse_listeners
1122                .insert(event.type_id(), handlers);
1123        }
1124
1125        if self.app.propagate_event && self.has_active_drag() {
1126            if event.is::<MouseMoveEvent>() {
1127                // If this was a mouse move event, redraw the window so that the
1128                // active drag can follow the mouse cursor.
1129                self.refresh();
1130            } else if event.is::<MouseUpEvent>() {
1131                // If this was a mouse up event, cancel the active drag and redraw
1132                // the window.
1133                self.active_drag = None;
1134                self.refresh();
1135            }
1136        }
1137    }
1138
1139    fn dispatch_key_event(&mut self, event: &dyn Any) {
1140        let node_id = self
1141            .window
1142            .focus
1143            .and_then(|focus_id| {
1144                self.window
1145                    .rendered_frame
1146                    .dispatch_tree
1147                    .focusable_node_id(focus_id)
1148            })
1149            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1150
1151        let dispatch_path = self
1152            .window
1153            .rendered_frame
1154            .dispatch_tree
1155            .dispatch_path(node_id);
1156
1157        let mut actions: Vec<Box<dyn Action>> = Vec::new();
1158
1159        let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1160        for node_id in &dispatch_path {
1161            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1162
1163            if let Some(context) = node.context.clone() {
1164                context_stack.push(context);
1165            }
1166        }
1167
1168        for node_id in dispatch_path.iter().rev() {
1169            // Match keystrokes
1170            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1171            if node.context.is_some() {
1172                if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1173                    let mut new_actions = self
1174                        .window
1175                        .rendered_frame
1176                        .dispatch_tree
1177                        .dispatch_key(&key_down_event.keystroke, &context_stack);
1178                    actions.append(&mut new_actions);
1179                }
1180
1181                context_stack.pop();
1182            }
1183        }
1184
1185        if !actions.is_empty() {
1186            self.clear_pending_keystrokes();
1187        }
1188
1189        self.propagate_event = true;
1190        for action in actions {
1191            self.dispatch_action_on_node(node_id, action.boxed_clone());
1192            if !self.propagate_event {
1193                self.dispatch_keystroke_observers(event, Some(action));
1194                return;
1195            }
1196        }
1197
1198        // Capture phase
1199        for node_id in &dispatch_path {
1200            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1201
1202            for key_listener in node.key_listeners.clone() {
1203                self.with_element_context(|cx| {
1204                    key_listener(event, DispatchPhase::Capture, cx);
1205                });
1206                if !self.propagate_event {
1207                    return;
1208                }
1209            }
1210        }
1211
1212        // Bubble phase
1213        for node_id in dispatch_path.iter().rev() {
1214            // Handle low level key events
1215            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1216            for key_listener in node.key_listeners.clone() {
1217                self.with_element_context(|cx| {
1218                    key_listener(event, DispatchPhase::Bubble, cx);
1219                });
1220                if !self.propagate_event {
1221                    return;
1222                }
1223            }
1224        }
1225
1226        self.dispatch_keystroke_observers(event, None);
1227    }
1228
1229    /// Determine whether a potential multi-stroke key binding is in progress on this window.
1230    pub fn has_pending_keystrokes(&self) -> bool {
1231        self.window
1232            .rendered_frame
1233            .dispatch_tree
1234            .has_pending_keystrokes()
1235    }
1236
1237    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1238        let dispatch_path = self
1239            .window
1240            .rendered_frame
1241            .dispatch_tree
1242            .dispatch_path(node_id);
1243
1244        // Capture phase
1245        for node_id in &dispatch_path {
1246            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1247            for DispatchActionListener {
1248                action_type,
1249                listener,
1250            } in node.action_listeners.clone()
1251            {
1252                let any_action = action.as_any();
1253                if action_type == any_action.type_id() {
1254                    self.with_element_context(|cx| {
1255                        listener(any_action, DispatchPhase::Capture, cx);
1256                    });
1257
1258                    if !self.propagate_event {
1259                        return;
1260                    }
1261                }
1262            }
1263        }
1264        // Bubble phase
1265        for node_id in dispatch_path.iter().rev() {
1266            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1267            for DispatchActionListener {
1268                action_type,
1269                listener,
1270            } in node.action_listeners.clone()
1271            {
1272                let any_action = action.as_any();
1273                if action_type == any_action.type_id() {
1274                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1275
1276                    self.with_element_context(|cx| {
1277                        listener(any_action, DispatchPhase::Bubble, cx);
1278                    });
1279
1280                    if !self.propagate_event {
1281                        return;
1282                    }
1283                }
1284            }
1285        }
1286    }
1287
1288    /// Register the given handler to be invoked whenever the global of the given type
1289    /// is updated.
1290    pub fn observe_global<G: 'static>(
1291        &mut self,
1292        f: impl Fn(&mut WindowContext<'_>) + 'static,
1293    ) -> Subscription {
1294        let window_handle = self.window.handle;
1295        let (subscription, activate) = self.global_observers.insert(
1296            TypeId::of::<G>(),
1297            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1298        );
1299        self.app.defer(move |_| activate());
1300        subscription
1301    }
1302
1303    /// Focus the current window and bring it to the foreground at the platform level.
1304    pub fn activate_window(&self) {
1305        self.window.platform_window.activate();
1306    }
1307
1308    /// Minimize the current window at the platform level.
1309    pub fn minimize_window(&self) {
1310        self.window.platform_window.minimize();
1311    }
1312
1313    /// Toggle full screen status on the current window at the platform level.
1314    pub fn toggle_full_screen(&self) {
1315        self.window.platform_window.toggle_full_screen();
1316    }
1317
1318    /// Present a platform dialog.
1319    /// The provided message will be presented, along with buttons for each answer.
1320    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1321    pub fn prompt(
1322        &self,
1323        level: PromptLevel,
1324        message: &str,
1325        answers: &[&str],
1326    ) -> oneshot::Receiver<usize> {
1327        self.window.platform_window.prompt(level, message, answers)
1328    }
1329
1330    /// Returns all available actions for the focused element.
1331    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1332        let node_id = self
1333            .window
1334            .focus
1335            .and_then(|focus_id| {
1336                self.window
1337                    .rendered_frame
1338                    .dispatch_tree
1339                    .focusable_node_id(focus_id)
1340            })
1341            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1342
1343        self.window
1344            .rendered_frame
1345            .dispatch_tree
1346            .available_actions(node_id)
1347    }
1348
1349    /// Returns key bindings that invoke the given action on the currently focused element.
1350    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1351        self.window
1352            .rendered_frame
1353            .dispatch_tree
1354            .bindings_for_action(
1355                action,
1356                &self.window.rendered_frame.dispatch_tree.context_stack,
1357            )
1358    }
1359
1360    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1361    pub fn bindings_for_action_in(
1362        &self,
1363        action: &dyn Action,
1364        focus_handle: &FocusHandle,
1365    ) -> Vec<KeyBinding> {
1366        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1367
1368        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1369            return vec![];
1370        };
1371        let context_stack = dispatch_tree
1372            .dispatch_path(node_id)
1373            .into_iter()
1374            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1375            .collect();
1376        dispatch_tree.bindings_for_action(action, &context_stack)
1377    }
1378
1379    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1380    pub fn listener_for<V: Render, E>(
1381        &self,
1382        view: &View<V>,
1383        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1384    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1385        let view = view.downgrade();
1386        move |e: &E, cx: &mut WindowContext| {
1387            view.update(cx, |view, cx| f(view, e, cx)).ok();
1388        }
1389    }
1390
1391    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1392    pub fn handler_for<V: Render>(
1393        &self,
1394        view: &View<V>,
1395        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1396    ) -> impl Fn(&mut WindowContext) {
1397        let view = view.downgrade();
1398        move |cx: &mut WindowContext| {
1399            view.update(cx, |view, cx| f(view, cx)).ok();
1400        }
1401    }
1402
1403    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1404    /// If the callback returns false, the window won't be closed.
1405    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1406        let mut this = self.to_async();
1407        self.window
1408            .platform_window
1409            .on_should_close(Box::new(move || {
1410                this.update(|cx| {
1411                    // Ensure that the window is removed from the app if it's been closed
1412                    // by always pre-empting the system close event.
1413                    if f(cx) {
1414                        cx.remove_window();
1415                    }
1416                    false
1417                })
1418                .unwrap_or(true)
1419            }))
1420    }
1421
1422    pub(crate) fn parent_view_id(&self) -> EntityId {
1423        *self
1424            .window
1425            .next_frame
1426            .view_stack
1427            .last()
1428            .expect("a view should always be on the stack while drawing")
1429    }
1430
1431    /// Register an action listener on the window for the next frame. The type of action
1432    /// is determined by the first parameter of the given listener. When the next frame is rendered
1433    /// the listener will be cleared.
1434    ///
1435    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1436    /// a specific need to register a global listener.
1437    pub fn on_action(
1438        &mut self,
1439        action_type: TypeId,
1440        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1441    ) {
1442        self.window
1443            .next_frame
1444            .dispatch_tree
1445            .on_action(action_type, Rc::new(listener));
1446    }
1447}
1448
1449impl Context for WindowContext<'_> {
1450    type Result<T> = T;
1451
1452    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1453    where
1454        T: 'static,
1455    {
1456        let slot = self.app.entities.reserve();
1457        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1458        self.entities.insert(slot, model)
1459    }
1460
1461    fn update_model<T: 'static, R>(
1462        &mut self,
1463        model: &Model<T>,
1464        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1465    ) -> R {
1466        let mut entity = self.entities.lease(model);
1467        let result = update(
1468            &mut *entity,
1469            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1470        );
1471        self.entities.end_lease(entity);
1472        result
1473    }
1474
1475    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1476    where
1477        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1478    {
1479        if window == self.window.handle {
1480            let root_view = self.window.root_view.clone().unwrap();
1481            Ok(update(root_view, self))
1482        } else {
1483            window.update(self.app, update)
1484        }
1485    }
1486
1487    fn read_model<T, R>(
1488        &self,
1489        handle: &Model<T>,
1490        read: impl FnOnce(&T, &AppContext) -> R,
1491    ) -> Self::Result<R>
1492    where
1493        T: 'static,
1494    {
1495        let entity = self.entities.read(handle);
1496        read(entity, &*self.app)
1497    }
1498
1499    fn read_window<T, R>(
1500        &self,
1501        window: &WindowHandle<T>,
1502        read: impl FnOnce(View<T>, &AppContext) -> R,
1503    ) -> Result<R>
1504    where
1505        T: 'static,
1506    {
1507        if window.any_handle == self.window.handle {
1508            let root_view = self
1509                .window
1510                .root_view
1511                .clone()
1512                .unwrap()
1513                .downcast::<T>()
1514                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1515            Ok(read(root_view, self))
1516        } else {
1517            self.app.read_window(window, read)
1518        }
1519    }
1520}
1521
1522impl VisualContext for WindowContext<'_> {
1523    fn new_view<V>(
1524        &mut self,
1525        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1526    ) -> Self::Result<View<V>>
1527    where
1528        V: 'static + Render,
1529    {
1530        let slot = self.app.entities.reserve();
1531        let view = View {
1532            model: slot.clone(),
1533        };
1534        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1535        let entity = build_view_state(&mut cx);
1536        cx.entities.insert(slot, entity);
1537
1538        cx.new_view_observers
1539            .clone()
1540            .retain(&TypeId::of::<V>(), |observer| {
1541                let any_view = AnyView::from(view.clone());
1542                (observer)(any_view, self);
1543                true
1544            });
1545
1546        view
1547    }
1548
1549    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1550    fn update_view<T: 'static, R>(
1551        &mut self,
1552        view: &View<T>,
1553        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1554    ) -> Self::Result<R> {
1555        let mut lease = self.app.entities.lease(&view.model);
1556        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1557        let result = update(&mut *lease, &mut cx);
1558        cx.app.entities.end_lease(lease);
1559        result
1560    }
1561
1562    fn replace_root_view<V>(
1563        &mut self,
1564        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1565    ) -> Self::Result<View<V>>
1566    where
1567        V: 'static + Render,
1568    {
1569        let view = self.new_view(build_view);
1570        self.window.root_view = Some(view.clone().into());
1571        self.refresh();
1572        view
1573    }
1574
1575    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1576        self.update_view(view, |view, cx| {
1577            view.focus_handle(cx).clone().focus(cx);
1578        })
1579    }
1580
1581    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1582    where
1583        V: ManagedView,
1584    {
1585        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1586    }
1587}
1588
1589impl<'a> std::ops::Deref for WindowContext<'a> {
1590    type Target = AppContext;
1591
1592    fn deref(&self) -> &Self::Target {
1593        self.app
1594    }
1595}
1596
1597impl<'a> std::ops::DerefMut for WindowContext<'a> {
1598    fn deref_mut(&mut self) -> &mut Self::Target {
1599        self.app
1600    }
1601}
1602
1603impl<'a> Borrow<AppContext> for WindowContext<'a> {
1604    fn borrow(&self) -> &AppContext {
1605        self.app
1606    }
1607}
1608
1609impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1610    fn borrow_mut(&mut self) -> &mut AppContext {
1611        self.app
1612    }
1613}
1614
1615/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1616pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1617    #[doc(hidden)]
1618    fn app_mut(&mut self) -> &mut AppContext {
1619        self.borrow_mut()
1620    }
1621
1622    #[doc(hidden)]
1623    fn app(&self) -> &AppContext {
1624        self.borrow()
1625    }
1626
1627    #[doc(hidden)]
1628    fn window(&self) -> &Window {
1629        self.borrow()
1630    }
1631
1632    #[doc(hidden)]
1633    fn window_mut(&mut self) -> &mut Window {
1634        self.borrow_mut()
1635    }
1636}
1637
1638impl Borrow<Window> for WindowContext<'_> {
1639    fn borrow(&self) -> &Window {
1640        self.window
1641    }
1642}
1643
1644impl BorrowMut<Window> for WindowContext<'_> {
1645    fn borrow_mut(&mut self) -> &mut Window {
1646        self.window
1647    }
1648}
1649
1650impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1651
1652/// Provides access to application state that is specialized for a particular [`View`].
1653/// Allows you to interact with focus, emit events, etc.
1654/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1655/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1656pub struct ViewContext<'a, V> {
1657    window_cx: WindowContext<'a>,
1658    view: &'a View<V>,
1659}
1660
1661impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1662    fn borrow(&self) -> &AppContext {
1663        &*self.window_cx.app
1664    }
1665}
1666
1667impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1668    fn borrow_mut(&mut self) -> &mut AppContext {
1669        &mut *self.window_cx.app
1670    }
1671}
1672
1673impl<V> Borrow<Window> for ViewContext<'_, V> {
1674    fn borrow(&self) -> &Window {
1675        &*self.window_cx.window
1676    }
1677}
1678
1679impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1680    fn borrow_mut(&mut self) -> &mut Window {
1681        &mut *self.window_cx.window
1682    }
1683}
1684
1685impl<'a, V: 'static> ViewContext<'a, V> {
1686    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1687        Self {
1688            window_cx: WindowContext::new(app, window),
1689            view,
1690        }
1691    }
1692
1693    /// Get the entity_id of this view.
1694    pub fn entity_id(&self) -> EntityId {
1695        self.view.entity_id()
1696    }
1697
1698    /// Get the view pointer underlying this context.
1699    pub fn view(&self) -> &View<V> {
1700        self.view
1701    }
1702
1703    /// Get the model underlying this view.
1704    pub fn model(&self) -> &Model<V> {
1705        &self.view.model
1706    }
1707
1708    /// Access the underlying window context.
1709    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1710        &mut self.window_cx
1711    }
1712
1713    /// Sets a given callback to be run on the next frame.
1714    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1715    where
1716        V: 'static,
1717    {
1718        let view = self.view().clone();
1719        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1720    }
1721
1722    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1723    /// that are currently on the stack to be returned to the app.
1724    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1725        let view = self.view().downgrade();
1726        self.window_cx.defer(move |cx| {
1727            view.update(cx, f).ok();
1728        });
1729    }
1730
1731    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
1732    pub fn observe<V2, E>(
1733        &mut self,
1734        entity: &E,
1735        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1736    ) -> Subscription
1737    where
1738        V2: 'static,
1739        V: 'static,
1740        E: Entity<V2>,
1741    {
1742        let view = self.view().downgrade();
1743        let entity_id = entity.entity_id();
1744        let entity = entity.downgrade();
1745        let window_handle = self.window.handle;
1746        let (subscription, activate) = self.app.observers.insert(
1747            entity_id,
1748            Box::new(move |cx| {
1749                window_handle
1750                    .update(cx, |_, cx| {
1751                        if let Some(handle) = E::upgrade_from(&entity) {
1752                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1753                                .is_ok()
1754                        } else {
1755                            false
1756                        }
1757                    })
1758                    .unwrap_or(false)
1759            }),
1760        );
1761        self.app.defer(move |_| activate());
1762        subscription
1763    }
1764
1765    /// Subscribe to events emitted by another model or view.
1766    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1767    /// 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.
1768    pub fn subscribe<V2, E, Evt>(
1769        &mut self,
1770        entity: &E,
1771        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1772    ) -> Subscription
1773    where
1774        V2: EventEmitter<Evt>,
1775        E: Entity<V2>,
1776        Evt: 'static,
1777    {
1778        let view = self.view().downgrade();
1779        let entity_id = entity.entity_id();
1780        let handle = entity.downgrade();
1781        let window_handle = self.window.handle;
1782        let (subscription, activate) = self.app.event_listeners.insert(
1783            entity_id,
1784            (
1785                TypeId::of::<Evt>(),
1786                Box::new(move |event, cx| {
1787                    window_handle
1788                        .update(cx, |_, cx| {
1789                            if let Some(handle) = E::upgrade_from(&handle) {
1790                                let event = event.downcast_ref().expect("invalid event type");
1791                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1792                                    .is_ok()
1793                            } else {
1794                                false
1795                            }
1796                        })
1797                        .unwrap_or(false)
1798                }),
1799            ),
1800        );
1801        self.app.defer(move |_| activate());
1802        subscription
1803    }
1804
1805    /// Register a callback to be invoked when the view is released.
1806    ///
1807    /// The callback receives a handle to the view's window. This handle may be
1808    /// invalid, if the window was closed before the view was released.
1809    pub fn on_release(
1810        &mut self,
1811        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
1812    ) -> Subscription {
1813        let window_handle = self.window.handle;
1814        let (subscription, activate) = self.app.release_listeners.insert(
1815            self.view.model.entity_id,
1816            Box::new(move |this, cx| {
1817                let this = this.downcast_mut().expect("invalid entity type");
1818                on_release(this, window_handle, cx)
1819            }),
1820        );
1821        activate();
1822        subscription
1823    }
1824
1825    /// Register a callback to be invoked when the given Model or View is released.
1826    pub fn observe_release<V2, E>(
1827        &mut self,
1828        entity: &E,
1829        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1830    ) -> Subscription
1831    where
1832        V: 'static,
1833        V2: 'static,
1834        E: Entity<V2>,
1835    {
1836        let view = self.view().downgrade();
1837        let entity_id = entity.entity_id();
1838        let window_handle = self.window.handle;
1839        let (subscription, activate) = self.app.release_listeners.insert(
1840            entity_id,
1841            Box::new(move |entity, cx| {
1842                let entity = entity.downcast_mut().expect("invalid entity type");
1843                let _ = window_handle.update(cx, |_, cx| {
1844                    view.update(cx, |this, cx| on_release(this, entity, cx))
1845                });
1846            }),
1847        );
1848        activate();
1849        subscription
1850    }
1851
1852    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
1853    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
1854    pub fn notify(&mut self) {
1855        for view_id in self
1856            .window
1857            .rendered_frame
1858            .dispatch_tree
1859            .view_path(self.view.entity_id())
1860            .into_iter()
1861            .rev()
1862        {
1863            if !self.window.dirty_views.insert(view_id) {
1864                break;
1865            }
1866        }
1867
1868        if !self.window.drawing {
1869            self.window_cx.window.dirty = true;
1870            self.window_cx.app.push_effect(Effect::Notify {
1871                emitter: self.view.model.entity_id,
1872            });
1873        }
1874    }
1875
1876    /// Register a callback to be invoked when the window is resized.
1877    pub fn observe_window_bounds(
1878        &mut self,
1879        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1880    ) -> Subscription {
1881        let view = self.view.downgrade();
1882        let (subscription, activate) = self.window.bounds_observers.insert(
1883            (),
1884            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1885        );
1886        activate();
1887        subscription
1888    }
1889
1890    /// Register a callback to be invoked when the window is activated or deactivated.
1891    pub fn observe_window_activation(
1892        &mut self,
1893        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1894    ) -> Subscription {
1895        let view = self.view.downgrade();
1896        let (subscription, activate) = self.window.activation_observers.insert(
1897            (),
1898            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1899        );
1900        activate();
1901        subscription
1902    }
1903
1904    /// Register a listener to be called when the given focus handle receives focus.
1905    /// Returns a subscription and persists until the subscription is dropped.
1906    pub fn on_focus(
1907        &mut self,
1908        handle: &FocusHandle,
1909        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1910    ) -> Subscription {
1911        let view = self.view.downgrade();
1912        let focus_id = handle.id;
1913        let (subscription, activate) = self.window.focus_listeners.insert(
1914            (),
1915            Box::new(move |event, cx| {
1916                view.update(cx, |view, cx| {
1917                    if event.previous_focus_path.last() != Some(&focus_id)
1918                        && event.current_focus_path.last() == Some(&focus_id)
1919                    {
1920                        listener(view, cx)
1921                    }
1922                })
1923                .is_ok()
1924            }),
1925        );
1926        self.app.defer(move |_| activate());
1927        subscription
1928    }
1929
1930    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
1931    /// Returns a subscription and persists until the subscription is dropped.
1932    pub fn on_focus_in(
1933        &mut self,
1934        handle: &FocusHandle,
1935        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1936    ) -> Subscription {
1937        let view = self.view.downgrade();
1938        let focus_id = handle.id;
1939        let (subscription, activate) = self.window.focus_listeners.insert(
1940            (),
1941            Box::new(move |event, cx| {
1942                view.update(cx, |view, cx| {
1943                    if !event.previous_focus_path.contains(&focus_id)
1944                        && event.current_focus_path.contains(&focus_id)
1945                    {
1946                        listener(view, cx)
1947                    }
1948                })
1949                .is_ok()
1950            }),
1951        );
1952        self.app.defer(move |_| activate());
1953        subscription
1954    }
1955
1956    /// Register a listener to be called when the given focus handle loses focus.
1957    /// Returns a subscription and persists until the subscription is dropped.
1958    pub fn on_blur(
1959        &mut self,
1960        handle: &FocusHandle,
1961        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1962    ) -> Subscription {
1963        let view = self.view.downgrade();
1964        let focus_id = handle.id;
1965        let (subscription, activate) = self.window.focus_listeners.insert(
1966            (),
1967            Box::new(move |event, cx| {
1968                view.update(cx, |view, cx| {
1969                    if event.previous_focus_path.last() == Some(&focus_id)
1970                        && event.current_focus_path.last() != Some(&focus_id)
1971                    {
1972                        listener(view, cx)
1973                    }
1974                })
1975                .is_ok()
1976            }),
1977        );
1978        self.app.defer(move |_| activate());
1979        subscription
1980    }
1981
1982    /// Register a listener to be called when nothing in the window has focus.
1983    /// This typically happens when the node that was focused is removed from the tree,
1984    /// and this callback lets you chose a default place to restore the users focus.
1985    /// Returns a subscription and persists until the subscription is dropped.
1986    pub fn on_focus_lost(
1987        &mut self,
1988        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1989    ) -> Subscription {
1990        let view = self.view.downgrade();
1991        let (subscription, activate) = self.window.focus_lost_listeners.insert(
1992            (),
1993            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
1994        );
1995        activate();
1996        subscription
1997    }
1998
1999    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2000    /// Returns a subscription and persists until the subscription is dropped.
2001    pub fn on_focus_out(
2002        &mut self,
2003        handle: &FocusHandle,
2004        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2005    ) -> Subscription {
2006        let view = self.view.downgrade();
2007        let focus_id = handle.id;
2008        let (subscription, activate) = self.window.focus_listeners.insert(
2009            (),
2010            Box::new(move |event, cx| {
2011                view.update(cx, |view, cx| {
2012                    if event.previous_focus_path.contains(&focus_id)
2013                        && !event.current_focus_path.contains(&focus_id)
2014                    {
2015                        listener(view, cx)
2016                    }
2017                })
2018                .is_ok()
2019            }),
2020        );
2021        self.app.defer(move |_| activate());
2022        subscription
2023    }
2024
2025    /// Schedule a future to be run asynchronously.
2026    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2027    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2028    /// The returned future will be polled on the main thread.
2029    pub fn spawn<Fut, R>(
2030        &mut self,
2031        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2032    ) -> Task<R>
2033    where
2034        R: 'static,
2035        Fut: Future<Output = R> + 'static,
2036    {
2037        let view = self.view().downgrade();
2038        self.window_cx.spawn(|cx| f(view, cx))
2039    }
2040
2041    /// Updates the global state of the given type.
2042    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2043    where
2044        G: 'static,
2045    {
2046        let mut global = self.app.lease_global::<G>();
2047        let result = f(&mut global, self);
2048        self.app.end_global_lease(global);
2049        result
2050    }
2051
2052    /// Register a callback to be invoked when the given global state changes.
2053    pub fn observe_global<G: 'static>(
2054        &mut self,
2055        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2056    ) -> Subscription {
2057        let window_handle = self.window.handle;
2058        let view = self.view().downgrade();
2059        let (subscription, activate) = self.global_observers.insert(
2060            TypeId::of::<G>(),
2061            Box::new(move |cx| {
2062                window_handle
2063                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2064                    .unwrap_or(false)
2065            }),
2066        );
2067        self.app.defer(move |_| activate());
2068        subscription
2069    }
2070
2071    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2072    pub fn on_action(
2073        &mut self,
2074        action_type: TypeId,
2075        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2076    ) {
2077        let handle = self.view().clone();
2078        self.window_cx
2079            .on_action(action_type, move |action, phase, cx| {
2080                handle.update(cx, |view, cx| {
2081                    listener(view, action, phase, cx);
2082                })
2083            });
2084    }
2085
2086    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2087    pub fn emit<Evt>(&mut self, event: Evt)
2088    where
2089        Evt: 'static,
2090        V: EventEmitter<Evt>,
2091    {
2092        let emitter = self.view.model.entity_id;
2093        self.app.push_effect(Effect::Emit {
2094            emitter,
2095            event_type: TypeId::of::<Evt>(),
2096            event: Box::new(event),
2097        });
2098    }
2099
2100    /// Move focus to the current view, assuming it implements [`FocusableView`].
2101    pub fn focus_self(&mut self)
2102    where
2103        V: FocusableView,
2104    {
2105        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2106    }
2107
2108    /// Convenience method for accessing view state in an event callback.
2109    ///
2110    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2111    /// but it's often useful to be able to access view state in these
2112    /// callbacks. This method provides a convenient way to do so.
2113    pub fn listener<E>(
2114        &self,
2115        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2116    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2117        let view = self.view().downgrade();
2118        move |e: &E, cx: &mut WindowContext| {
2119            view.update(cx, |view, cx| f(view, e, cx)).ok();
2120        }
2121    }
2122}
2123
2124impl<V> Context for ViewContext<'_, V> {
2125    type Result<U> = U;
2126
2127    fn new_model<T: 'static>(
2128        &mut self,
2129        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2130    ) -> Model<T> {
2131        self.window_cx.new_model(build_model)
2132    }
2133
2134    fn update_model<T: 'static, R>(
2135        &mut self,
2136        model: &Model<T>,
2137        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2138    ) -> R {
2139        self.window_cx.update_model(model, update)
2140    }
2141
2142    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2143    where
2144        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2145    {
2146        self.window_cx.update_window(window, update)
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        self.window_cx.read_model(handle, read)
2158    }
2159
2160    fn read_window<T, R>(
2161        &self,
2162        window: &WindowHandle<T>,
2163        read: impl FnOnce(View<T>, &AppContext) -> R,
2164    ) -> Result<R>
2165    where
2166        T: 'static,
2167    {
2168        self.window_cx.read_window(window, read)
2169    }
2170}
2171
2172impl<V: 'static> VisualContext for ViewContext<'_, V> {
2173    fn new_view<W: Render + 'static>(
2174        &mut self,
2175        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2176    ) -> Self::Result<View<W>> {
2177        self.window_cx.new_view(build_view_state)
2178    }
2179
2180    fn update_view<V2: 'static, R>(
2181        &mut self,
2182        view: &View<V2>,
2183        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2184    ) -> Self::Result<R> {
2185        self.window_cx.update_view(view, update)
2186    }
2187
2188    fn replace_root_view<W>(
2189        &mut self,
2190        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2191    ) -> Self::Result<View<W>>
2192    where
2193        W: 'static + Render,
2194    {
2195        self.window_cx.replace_root_view(build_view)
2196    }
2197
2198    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2199        self.window_cx.focus_view(view)
2200    }
2201
2202    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2203        self.window_cx.dismiss_view(view)
2204    }
2205}
2206
2207impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2208    type Target = WindowContext<'a>;
2209
2210    fn deref(&self) -> &Self::Target {
2211        &self.window_cx
2212    }
2213}
2214
2215impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2216    fn deref_mut(&mut self) -> &mut Self::Target {
2217        &mut self.window_cx
2218    }
2219}
2220
2221// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2222slotmap::new_key_type! {
2223    /// A unique identifier for a window.
2224    pub struct WindowId;
2225}
2226
2227impl WindowId {
2228    /// Converts this window ID to a `u64`.
2229    pub fn as_u64(&self) -> u64 {
2230        self.0.as_ffi()
2231    }
2232}
2233
2234/// A handle to a window with a specific root view type.
2235/// Note that this does not keep the window alive on its own.
2236#[derive(Deref, DerefMut)]
2237pub struct WindowHandle<V> {
2238    #[deref]
2239    #[deref_mut]
2240    pub(crate) any_handle: AnyWindowHandle,
2241    state_type: PhantomData<V>,
2242}
2243
2244impl<V: 'static + Render> WindowHandle<V> {
2245    /// Creates a new handle from a window ID.
2246    /// This does not check if the root type of the window is `V`.
2247    pub fn new(id: WindowId) -> Self {
2248        WindowHandle {
2249            any_handle: AnyWindowHandle {
2250                id,
2251                state_type: TypeId::of::<V>(),
2252            },
2253            state_type: PhantomData,
2254        }
2255    }
2256
2257    /// Get the root view out of this window.
2258    ///
2259    /// This will fail if the window is closed or if the root view's type does not match `V`.
2260    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2261    where
2262        C: Context,
2263    {
2264        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2265            root_view
2266                .downcast::<V>()
2267                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2268        }))
2269    }
2270
2271    /// Updates the root view of this window.
2272    ///
2273    /// This will fail if the window has been closed or if the root view's type does not match
2274    pub fn update<C, R>(
2275        &self,
2276        cx: &mut C,
2277        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2278    ) -> Result<R>
2279    where
2280        C: Context,
2281    {
2282        cx.update_window(self.any_handle, |root_view, cx| {
2283            let view = root_view
2284                .downcast::<V>()
2285                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2286            Ok(cx.update_view(&view, update))
2287        })?
2288    }
2289
2290    /// Read the root view out of this window.
2291    ///
2292    /// This will fail if the window is closed or if the root view's type does not match `V`.
2293    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2294        let x = cx
2295            .windows
2296            .get(self.id)
2297            .and_then(|window| {
2298                window
2299                    .as_ref()
2300                    .and_then(|window| window.root_view.clone())
2301                    .map(|root_view| root_view.downcast::<V>())
2302            })
2303            .ok_or_else(|| anyhow!("window not found"))?
2304            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2305
2306        Ok(x.read(cx))
2307    }
2308
2309    /// Read the root view out of this window, with a callback
2310    ///
2311    /// This will fail if the window is closed or if the root view's type does not match `V`.
2312    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2313    where
2314        C: Context,
2315    {
2316        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2317    }
2318
2319    /// Read the root view pointer off of this window.
2320    ///
2321    /// This will fail if the window is closed or if the root view's type does not match `V`.
2322    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2323    where
2324        C: Context,
2325    {
2326        cx.read_window(self, |root_view, _cx| root_view.clone())
2327    }
2328
2329    /// Check if this window is 'active'.
2330    ///
2331    /// Will return `None` if the window is closed.
2332    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2333        cx.windows
2334            .get(self.id)
2335            .and_then(|window| window.as_ref().map(|window| window.active))
2336    }
2337}
2338
2339impl<V> Copy for WindowHandle<V> {}
2340
2341impl<V> Clone for WindowHandle<V> {
2342    fn clone(&self) -> Self {
2343        *self
2344    }
2345}
2346
2347impl<V> PartialEq for WindowHandle<V> {
2348    fn eq(&self, other: &Self) -> bool {
2349        self.any_handle == other.any_handle
2350    }
2351}
2352
2353impl<V> Eq for WindowHandle<V> {}
2354
2355impl<V> Hash for WindowHandle<V> {
2356    fn hash<H: Hasher>(&self, state: &mut H) {
2357        self.any_handle.hash(state);
2358    }
2359}
2360
2361impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2362    fn from(val: WindowHandle<V>) -> Self {
2363        val.any_handle
2364    }
2365}
2366
2367/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2368#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2369pub struct AnyWindowHandle {
2370    pub(crate) id: WindowId,
2371    state_type: TypeId,
2372}
2373
2374impl AnyWindowHandle {
2375    /// Get the ID of this window.
2376    pub fn window_id(&self) -> WindowId {
2377        self.id
2378    }
2379
2380    /// Attempt to convert this handle to a window handle with a specific root view type.
2381    /// If the types do not match, this will return `None`.
2382    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2383        if TypeId::of::<T>() == self.state_type {
2384            Some(WindowHandle {
2385                any_handle: *self,
2386                state_type: PhantomData,
2387            })
2388        } else {
2389            None
2390        }
2391    }
2392
2393    /// Updates the state of the root view of this window.
2394    ///
2395    /// This will fail if the window has been closed.
2396    pub fn update<C, R>(
2397        self,
2398        cx: &mut C,
2399        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2400    ) -> Result<R>
2401    where
2402        C: Context,
2403    {
2404        cx.update_window(self, update)
2405    }
2406
2407    /// Read the state of the root view of this window.
2408    ///
2409    /// This will fail if the window has been closed.
2410    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2411    where
2412        C: Context,
2413        T: 'static,
2414    {
2415        let view = self
2416            .downcast::<T>()
2417            .context("the type of the window's root view has changed")?;
2418
2419        cx.read_window(&view, read)
2420    }
2421}
2422
2423/// An identifier for an [`Element`](crate::Element).
2424///
2425/// Can be constructed with a string, a number, or both, as well
2426/// as other internal representations.
2427#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2428pub enum ElementId {
2429    /// The ID of a View element
2430    View(EntityId),
2431    /// An integer ID.
2432    Integer(usize),
2433    /// A string based ID.
2434    Name(SharedString),
2435    /// An ID that's equated with a focus handle.
2436    FocusHandle(FocusId),
2437    /// A combination of a name and an integer.
2438    NamedInteger(SharedString, usize),
2439}
2440
2441impl Display for ElementId {
2442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2443        match self {
2444            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2445            ElementId::Integer(ix) => write!(f, "{}", ix)?,
2446            ElementId::Name(name) => write!(f, "{}", name)?,
2447            ElementId::FocusHandle(__) => write!(f, "FocusHandle")?,
2448            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2449        }
2450
2451        Ok(())
2452    }
2453}
2454
2455impl ElementId {
2456    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2457        ElementId::View(entity_id)
2458    }
2459}
2460
2461impl TryInto<SharedString> for ElementId {
2462    type Error = anyhow::Error;
2463
2464    fn try_into(self) -> anyhow::Result<SharedString> {
2465        if let ElementId::Name(name) = self {
2466            Ok(name)
2467        } else {
2468            Err(anyhow!("element id is not string"))
2469        }
2470    }
2471}
2472
2473impl From<usize> for ElementId {
2474    fn from(id: usize) -> Self {
2475        ElementId::Integer(id)
2476    }
2477}
2478
2479impl From<i32> for ElementId {
2480    fn from(id: i32) -> Self {
2481        Self::Integer(id as usize)
2482    }
2483}
2484
2485impl From<SharedString> for ElementId {
2486    fn from(name: SharedString) -> Self {
2487        ElementId::Name(name)
2488    }
2489}
2490
2491impl From<&'static str> for ElementId {
2492    fn from(name: &'static str) -> Self {
2493        ElementId::Name(name.into())
2494    }
2495}
2496
2497impl<'a> From<&'a FocusHandle> for ElementId {
2498    fn from(handle: &'a FocusHandle) -> Self {
2499        ElementId::FocusHandle(handle.id)
2500    }
2501}
2502
2503impl From<(&'static str, EntityId)> for ElementId {
2504    fn from((name, id): (&'static str, EntityId)) -> Self {
2505        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2506    }
2507}
2508
2509impl From<(&'static str, usize)> for ElementId {
2510    fn from((name, id): (&'static str, usize)) -> Self {
2511        ElementId::NamedInteger(name.into(), id)
2512    }
2513}
2514
2515impl From<(&'static str, u64)> for ElementId {
2516    fn from((name, id): (&'static str, u64)) -> Self {
2517        ElementId::NamedInteger(name.into(), id as usize)
2518    }
2519}
2520
2521/// A rectangle to be rendered in the window at the given position and size.
2522/// Passed as an argument [`WindowContext::paint_quad`].
2523#[derive(Clone)]
2524pub struct PaintQuad {
2525    bounds: Bounds<Pixels>,
2526    corner_radii: Corners<Pixels>,
2527    background: Hsla,
2528    border_widths: Edges<Pixels>,
2529    border_color: Hsla,
2530}
2531
2532impl PaintQuad {
2533    /// Sets the corner radii of the quad.
2534    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2535        PaintQuad {
2536            corner_radii: corner_radii.into(),
2537            ..self
2538        }
2539    }
2540
2541    /// Sets the border widths of the quad.
2542    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2543        PaintQuad {
2544            border_widths: border_widths.into(),
2545            ..self
2546        }
2547    }
2548
2549    /// Sets the border color of the quad.
2550    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2551        PaintQuad {
2552            border_color: border_color.into(),
2553            ..self
2554        }
2555    }
2556
2557    /// Sets the background color of the quad.
2558    pub fn background(self, background: impl Into<Hsla>) -> Self {
2559        PaintQuad {
2560            background: background.into(),
2561            ..self
2562        }
2563    }
2564}
2565
2566/// Creates a quad with the given parameters.
2567pub fn quad(
2568    bounds: Bounds<Pixels>,
2569    corner_radii: impl Into<Corners<Pixels>>,
2570    background: impl Into<Hsla>,
2571    border_widths: impl Into<Edges<Pixels>>,
2572    border_color: impl Into<Hsla>,
2573) -> PaintQuad {
2574    PaintQuad {
2575        bounds,
2576        corner_radii: corner_radii.into(),
2577        background: background.into(),
2578        border_widths: border_widths.into(),
2579        border_color: border_color.into(),
2580    }
2581}
2582
2583/// Creates a filled quad with the given bounds and background color.
2584pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2585    PaintQuad {
2586        bounds: bounds.into(),
2587        corner_radii: (0.).into(),
2588        background: background.into(),
2589        border_widths: (0.).into(),
2590        border_color: transparent_black(),
2591    }
2592}
2593
2594/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2595pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2596    PaintQuad {
2597        bounds: bounds.into(),
2598        corner_radii: (0.).into(),
2599        background: transparent_black(),
2600        border_widths: (1.).into(),
2601        border_color: border_color.into(),
2602    }
2603}