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