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