window.rs

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