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