window.rs

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