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