Skip to main content

gpui/app/
context.rs

1use crate::{
2    AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, Effect, EntityId, EventEmitter,
3    FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Priority, Reservation,
4    SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
5    WindowVisibility,
6};
7use anyhow::Result;
8use futures::FutureExt;
9use gpui_util::Deferred;
10use std::{
11    any::{Any, TypeId},
12    borrow::{Borrow, BorrowMut},
13    future::Future,
14    ops,
15    sync::Arc,
16};
17
18use super::{App, AsyncWindowContext, Entity, KeystrokeEvent};
19
20/// The app context, with specialized behavior for the given entity.
21pub struct Context<'a, T> {
22    app: &'a mut App,
23    entity_state: WeakEntity<T>,
24}
25
26impl<'a, T> ops::Deref for Context<'a, T> {
27    type Target = App;
28
29    fn deref(&self) -> &Self::Target {
30        self.app
31    }
32}
33
34impl<'a, T> ops::DerefMut for Context<'a, T> {
35    fn deref_mut(&mut self) -> &mut Self::Target {
36        self.app
37    }
38}
39
40impl<'a, T: 'static> Context<'a, T> {
41    pub(crate) fn new_context(app: &'a mut App, entity_state: WeakEntity<T>) -> Self {
42        Self { app, entity_state }
43    }
44
45    /// The entity id of the entity backing this context.
46    pub fn entity_id(&self) -> EntityId {
47        self.entity_state.entity_id
48    }
49
50    /// Returns a handle to the entity belonging to this context.
51    pub fn entity(&self) -> Entity<T> {
52        self.weak_entity()
53            .upgrade()
54            .expect("The entity must be alive if we have a entity context")
55    }
56
57    /// Returns a weak handle to the entity belonging to this context.
58    pub fn weak_entity(&self) -> WeakEntity<T> {
59        self.entity_state.clone()
60    }
61
62    /// Arranges for the given function to be called whenever [`Context::notify`] is
63    /// called with the given entity.
64    pub fn observe<W>(
65        &mut self,
66        entity: &Entity<W>,
67        mut on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<T>) + 'static,
68    ) -> Subscription
69    where
70        T: 'static,
71        W: 'static,
72    {
73        let observer = self.weak_entity();
74        self.app.observe_internal(entity, move |entity, cx| {
75            invoke_observer(&observer, entity, cx, &mut on_notify)
76        })
77    }
78
79    /// Observe changes to ourselves
80    pub fn observe_self(
81        &mut self,
82        mut on_event: impl FnMut(&mut T, &mut Context<T>) + 'static,
83    ) -> Subscription
84    where
85        T: 'static,
86    {
87        let this = self.entity();
88        self.app.observe(&this, move |this, cx| {
89            this.update(cx, |this, cx| on_event(this, cx))
90        })
91    }
92
93    /// Subscribe to an event type from another entity
94    pub fn subscribe<T2, Evt>(
95        &mut self,
96        entity: &Entity<T2>,
97        mut on_event: impl FnMut(&mut T, Entity<T2>, &Evt, &mut Context<T>) + 'static,
98    ) -> Subscription
99    where
100        T: 'static,
101        T2: 'static + EventEmitter<Evt>,
102        Evt: 'static,
103    {
104        let subscriber = self.weak_entity();
105        self.app
106            .subscribe_internal(entity, move |entity, event, cx| {
107                invoke_subscriber(&subscriber, entity, event, cx, &mut on_event)
108            })
109    }
110
111    /// Subscribe to an event type from ourself
112    pub fn subscribe_self<Evt>(
113        &mut self,
114        mut on_event: impl FnMut(&mut T, &Evt, &mut Context<T>) + 'static,
115    ) -> Subscription
116    where
117        T: 'static + EventEmitter<Evt>,
118        Evt: 'static,
119    {
120        let this = self.entity();
121        self.app.subscribe(&this, move |this, evt, cx| {
122            this.update(cx, |this, cx| on_event(this, evt, cx))
123        })
124    }
125
126    /// Register a callback to be invoked when GPUI releases this entity.
127    pub fn on_release(&self, on_release: impl FnOnce(&mut T, &mut App) + 'static) -> Subscription
128    where
129        T: 'static,
130    {
131        let (subscription, activate) = self.app.release_listeners.insert(
132            self.entity_state.entity_id,
133            Box::new(move |this, cx| {
134                let this = this.downcast_mut().expect("invalid entity type");
135                on_release(this, cx);
136            }),
137        );
138        activate();
139        subscription
140    }
141
142    /// Register a callback to be run on the release of another entity
143    pub fn observe_release<T2>(
144        &self,
145        entity: &Entity<T2>,
146        on_release: impl FnOnce(&mut T, &mut T2, &mut Context<T>) + 'static,
147    ) -> Subscription
148    where
149        T: Any,
150        T2: 'static,
151    {
152        let entity_id = entity.entity_id();
153        let this = self.weak_entity();
154        let (subscription, activate) = self.app.release_listeners.insert(
155            entity_id,
156            Box::new(move |entity, cx| {
157                let entity = entity.downcast_mut().expect("invalid entity type");
158                if let Some(this) = this.upgrade() {
159                    this.update(cx, |this, cx| on_release(this, entity, cx));
160                }
161            }),
162        );
163        activate();
164        subscription
165    }
166
167    /// Register a callback to for updates to the given global
168    pub fn observe_global<G: 'static>(
169        &mut self,
170        mut f: impl FnMut(&mut T, &mut Context<T>) + 'static,
171    ) -> Subscription
172    where
173        T: 'static,
174    {
175        let handle = self.weak_entity();
176        let (subscription, activate) = self.global_observers.insert(
177            TypeId::of::<G>(),
178            Box::new(move |cx| handle.update(cx, |view, cx| f(view, cx)).is_ok()),
179        );
180        self.defer(move |_| activate());
181        subscription
182    }
183
184    /// Register a callback to be invoked when the application is about to restart.
185    pub fn on_app_restart(
186        &self,
187        mut on_restart: impl FnMut(&mut T, &mut App) + 'static,
188    ) -> Subscription
189    where
190        T: 'static,
191    {
192        let handle = self.weak_entity();
193        self.app.on_app_restart(move |cx| {
194            handle.update(cx, |entity, cx| on_restart(entity, cx)).ok();
195        })
196    }
197
198    /// Arrange for the given function to be invoked whenever the application is quit.
199    /// The future returned from this callback will be polled for up to [crate::SHUTDOWN_TIMEOUT] until the app fully quits.
200    pub fn on_app_quit<Fut>(
201        &self,
202        mut on_quit: impl FnMut(&mut T, &mut Context<T>) -> Fut + 'static,
203    ) -> Subscription
204    where
205        Fut: 'static + Future<Output = ()>,
206        T: 'static,
207    {
208        let handle = self.weak_entity();
209        self.app.on_app_quit(move |cx| {
210            let future = handle.update(cx, |entity, cx| on_quit(entity, cx)).ok();
211            async move {
212                if let Some(future) = future {
213                    future.await;
214                }
215            }
216            .boxed_local()
217        })
218    }
219
220    /// Tell GPUI that this entity has changed and observers of it should be notified.
221    pub fn notify(&mut self) {
222        self.app.notify(self.entity_state.entity_id);
223    }
224
225    /// Spawn the future returned by the given function.
226    /// The function is provided a weak handle to the entity owned by this context and a context that can be held across await points.
227    /// The returned task must be held or detached.
228    #[track_caller]
229    #[inline(always)]
230    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
231    where
232        T: 'static,
233        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncApp) -> R + 'static,
234        R: 'static,
235    {
236        let this = self.weak_entity();
237        self.app.spawn(async move |cx| f(this, cx).await)
238    }
239
240    /// Convenience method for accessing view state in an event callback.
241    ///
242    /// Many GPUI callbacks take the form of `Fn(&E, &mut Window, &mut App)`,
243    /// but it's often useful to be able to access view state in these
244    /// callbacks. This method provides a convenient way to do so.
245    #[inline(always)]
246    pub fn listener<E: ?Sized>(
247        &self,
248        listener: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
249    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
250        let view = self.entity().downgrade();
251        move |event: &E, window: &mut Window, cx: &mut App| {
252            invoke_listener(&view, window, cx, &|view, window, cx| {
253                listener(view, event, window, cx);
254            });
255        }
256    }
257
258    /// Convenience method for producing view state in a closure.
259    /// See `listener` for more details.
260    pub fn processor<E, R>(
261        &self,
262        f: impl Fn(&mut T, E, &mut Window, &mut Context<T>) -> R + 'static,
263    ) -> impl Fn(E, &mut Window, &mut App) -> R + 'static {
264        let view = self.entity();
265        move |e: E, window: &mut Window, cx: &mut App| {
266            view.update(cx, |view, cx| f(view, e, window, cx))
267        }
268    }
269
270    /// Run something using this entity and cx, when the returned struct is dropped
271    pub fn on_drop(
272        &self,
273        f: impl FnOnce(&mut T, &mut Context<T>) + 'static,
274    ) -> Deferred<impl FnOnce()> {
275        let this = self.weak_entity();
276        let mut cx = self.to_async();
277        gpui_util::defer(move || {
278            this.update(&mut cx, f).ok();
279        })
280    }
281
282    /// Focus the given view in the given window. View type is required to implement Focusable.
283    pub fn focus_view<W: Focusable>(&mut self, view: &Entity<W>, window: &mut Window) {
284        window.focus(&view.focus_handle(self), self);
285    }
286
287    /// Sets a given callback to be run on the next frame.
288    pub fn on_next_frame(
289        &self,
290        window: &mut Window,
291        f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
292    ) where
293        T: 'static,
294    {
295        let view = self.entity();
296        window.on_next_frame(move |window, cx| view.update(cx, |view, cx| f(view, window, cx)));
297    }
298
299    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
300    /// that are currently on the stack to be returned to the app.
301    pub fn defer_in(
302        &mut self,
303        window: &Window,
304        f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
305    ) {
306        let view = self.weak_entity();
307        let entity_id = self.entity_id();
308        self.ensure_window(entity_id, window.handle.id);
309        self.app.defer(move |cx| {
310            cx.with_window(entity_id, |window, cx| {
311                view.update(cx, |view, cx| f(view, window, cx)).ok();
312            });
313        });
314    }
315
316    /// Observe another entity for changes to its state, as tracked by [`Context::notify`].
317    pub fn observe_in<V2>(
318        &mut self,
319        observed: &Entity<V2>,
320        window: &mut Window,
321        mut on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<T>) + 'static,
322    ) -> Subscription
323    where
324        V2: 'static,
325        T: 'static,
326    {
327        let observed_id = observed.entity_id();
328        let observed = observed.downgrade();
329        let observer = self.weak_entity();
330        let observer_id = self.entity_id();
331        self.ensure_window(observer_id, window.handle.id);
332        self.new_observer(
333            observed_id,
334            Box::new(move |cx| invoke_observer_in(&observer, &observed, cx, &mut on_notify)),
335        )
336    }
337
338    /// Subscribe to events emitted by another entity.
339    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
340    /// The callback will be invoked with a reference to the current view, a handle to the emitting `Entity`, the event, a mutable reference to the `Window`, and the context for the entity.
341    pub fn subscribe_in<Emitter, Evt>(
342        &mut self,
343        emitter: &Entity<Emitter>,
344        window: &Window,
345        mut on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<T>) + 'static,
346    ) -> Subscription
347    where
348        Emitter: EventEmitter<Evt>,
349        Evt: 'static,
350    {
351        let emitter = emitter.downgrade();
352        let subscriber = self.weak_entity();
353        let subscriber_id = self.entity_id();
354        self.ensure_window(subscriber_id, window.handle.id);
355        self.new_subscription(
356            emitter.entity_id(),
357            (
358                TypeId::of::<Evt>(),
359                Box::new(move |event, cx| {
360                    invoke_subscriber_in(&subscriber, &emitter, event, cx, &mut on_event)
361                }),
362            ),
363        )
364    }
365
366    /// Register a callback to be invoked when the view is released.
367    ///
368    /// The callback receives a handle to the view's window. This handle may be
369    /// invalid, if the window was closed before the view was released.
370    pub fn on_release_in(
371        &mut self,
372        window: &Window,
373        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
374    ) -> Subscription {
375        let entity = self.entity();
376        self.app.observe_release_in(&entity, window, on_release)
377    }
378
379    /// Register a callback to be invoked when the given Entity is released.
380    pub fn observe_release_in<T2>(
381        &self,
382        observed: &Entity<T2>,
383        window: &Window,
384        mut on_release: impl FnMut(&mut T, &mut T2, &mut Window, &mut Context<T>) + 'static,
385    ) -> Subscription
386    where
387        T: 'static,
388        T2: 'static,
389    {
390        let observer = self.weak_entity();
391        self.app
392            .observe_release_in(observed, window, move |observed, window, cx| {
393                observer
394                    .update(cx, |observer, cx| {
395                        on_release(observer, observed, window, cx)
396                    })
397                    .ok();
398            })
399    }
400
401    /// Register a callback to be invoked when the window is resized.
402    pub fn observe_window_bounds(
403        &self,
404        window: &mut Window,
405        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
406    ) -> Subscription {
407        let view = self.weak_entity();
408        let (subscription, activate) = window.bounds_observers.insert(
409            (),
410            Box::new(move |window, cx| {
411                view.update(cx, |view, cx| callback(view, window, cx))
412                    .is_ok()
413            }),
414        );
415        activate();
416        subscription
417    }
418
419    /// Register a callback to be invoked when the window is activated or deactivated.
420    pub fn observe_window_activation(
421        &self,
422        window: &mut Window,
423        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
424    ) -> Subscription {
425        let view = self.weak_entity();
426        let (subscription, activate) = window.activation_observers.insert(
427            (),
428            Box::new(move |window, cx| {
429                view.update(cx, |view, cx| callback(view, window, cx))
430                    .is_ok()
431            }),
432        );
433        activate();
434        subscription
435    }
436
437    /// Registers a callback to be invoked when the window's visibility changes
438    /// (see [`WindowVisibility`]).
439    pub fn observe_window_visibility(
440        &self,
441        window: &mut Window,
442        mut callback: impl FnMut(&mut T, WindowVisibility, &mut Window, &mut Context<T>) + 'static,
443    ) -> Subscription {
444        let view = self.weak_entity();
445        let (subscription, activate) = window.visibility_observers.insert(
446            (),
447            Box::new(move |visibility, window, cx| {
448                view.update(cx, |view, cx| callback(view, visibility, window, cx))
449                    .is_ok()
450            }),
451        );
452        activate();
453        subscription
454    }
455
456    /// Registers a callback to be invoked when the window appearance changes.
457    pub fn observe_window_appearance(
458        &self,
459        window: &mut Window,
460        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
461    ) -> Subscription {
462        let view = self.weak_entity();
463        let (subscription, activate) = window.appearance_observers.insert(
464            (),
465            Box::new(move |window, cx| {
466                view.update(cx, |view, cx| callback(view, window, cx))
467                    .is_ok()
468            }),
469        );
470        activate();
471        subscription
472    }
473
474    /// Registers a callback to be invoked when the window button layout changes.
475    pub fn observe_button_layout_changed(
476        &self,
477        window: &mut Window,
478        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
479    ) -> Subscription {
480        let view = self.weak_entity();
481        let (subscription, activate) = window.button_layout_observers.insert(
482            (),
483            Box::new(move |window, cx| {
484                view.update(cx, |view, cx| callback(view, window, cx))
485                    .is_ok()
486            }),
487        );
488        activate();
489        subscription
490    }
491
492    /// Register a callback to be invoked when a keystroke is received by the application
493    /// in any window. Note that this fires after all other action and event mechanisms have resolved
494    /// and that this API will not be invoked if the event's propagation is stopped.
495    pub fn observe_keystrokes(
496        &mut self,
497        mut f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<T>) + 'static,
498    ) -> Subscription {
499        fn inner(
500            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
501            handler: KeystrokeObserver,
502        ) -> Subscription {
503            let (subscription, activate) = keystroke_observers.insert((), handler);
504            activate();
505            subscription
506        }
507
508        let view = self.weak_entity();
509        inner(
510            &self.keystroke_observers,
511            Box::new(move |event, window, cx| {
512                if let Some(view) = view.upgrade() {
513                    view.update(cx, |view, cx| f(view, event, window, cx));
514                    true
515                } else {
516                    false
517                }
518            }),
519        )
520    }
521
522    /// Register a callback to be invoked when the window's pending input changes.
523    pub fn observe_pending_input(
524        &self,
525        window: &mut Window,
526        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
527    ) -> Subscription {
528        let view = self.weak_entity();
529        let (subscription, activate) = window.pending_input_observers.insert(
530            (),
531            Box::new(move |window, cx| {
532                view.update(cx, |view, cx| callback(view, window, cx))
533                    .is_ok()
534            }),
535        );
536        activate();
537        subscription
538    }
539
540    /// Register a listener to be called when the given focus handle receives focus.
541    /// Returns a subscription and persists until the subscription is dropped.
542    pub fn on_focus(
543        &mut self,
544        handle: &FocusHandle,
545        window: &mut Window,
546        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
547    ) -> Subscription {
548        let view = self.weak_entity();
549        let focus_id = handle.id;
550        let (subscription, activate) =
551            window.new_focus_listener(Box::new(move |event, window, cx| {
552                view.update(cx, |view, cx| {
553                    if event.previous_focus_path.last() != Some(&focus_id)
554                        && event.current_focus_path.last() == Some(&focus_id)
555                    {
556                        listener(view, window, cx)
557                    }
558                })
559                .is_ok()
560            }));
561        self.defer(|_| activate());
562        subscription
563    }
564
565    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
566    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
567    /// Returns a subscription and persists until the subscription is dropped.
568    pub fn on_focus_in(
569        &mut self,
570        handle: &FocusHandle,
571        window: &mut Window,
572        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
573    ) -> Subscription {
574        let view = self.weak_entity();
575        let focus_id = handle.id;
576        let (subscription, activate) =
577            window.new_focus_listener(Box::new(move |event, window, cx| {
578                view.update(cx, |view, cx| {
579                    if event.is_focus_in(focus_id) {
580                        listener(view, window, cx)
581                    }
582                })
583                .is_ok()
584            }));
585        self.defer(|_| activate());
586        subscription
587    }
588
589    /// Register a listener to be called when the given focus handle loses focus.
590    /// Returns a subscription and persists until the subscription is dropped.
591    pub fn on_blur(
592        &mut self,
593        handle: &FocusHandle,
594        window: &mut Window,
595        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
596    ) -> Subscription {
597        let view = self.weak_entity();
598        let focus_id = handle.id;
599        let (subscription, activate) =
600            window.new_focus_listener(Box::new(move |event, window, cx| {
601                view.update(cx, |view, cx| {
602                    if event.previous_focus_path.last() == Some(&focus_id)
603                        && event.current_focus_path.last() != Some(&focus_id)
604                    {
605                        listener(view, window, cx)
606                    }
607                })
608                .is_ok()
609            }));
610        self.defer(|_| activate());
611        subscription
612    }
613
614    /// Register a listener to be called when nothing in the window has focus.
615    /// This typically happens when the node that was focused is removed from the tree,
616    /// and this callback lets you chose a default place to restore the users focus.
617    /// Returns a subscription and persists until the subscription is dropped.
618    pub fn on_focus_lost(
619        &mut self,
620        window: &mut Window,
621        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
622    ) -> Subscription {
623        let view = self.weak_entity();
624        let (subscription, activate) = window.focus_lost_listeners.insert(
625            (),
626            Box::new(move |window, cx| {
627                view.update(cx, |view, cx| listener(view, window, cx))
628                    .is_ok()
629            }),
630        );
631        self.defer(|_| activate());
632        subscription
633    }
634
635    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
636    /// Returns a subscription and persists until the subscription is dropped.
637    pub fn on_focus_out(
638        &mut self,
639        handle: &FocusHandle,
640        window: &mut Window,
641        mut listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<T>) + 'static,
642    ) -> Subscription {
643        let view = self.weak_entity();
644        let focus_id = handle.id;
645        let (subscription, activate) =
646            window.new_focus_listener(Box::new(move |event, window, cx| {
647                view.update(cx, |view, cx| {
648                    if let Some(blurred_id) = event.previous_focus_path.last().copied()
649                        && event.is_focus_out(focus_id)
650                    {
651                        let event = FocusOutEvent {
652                            blurred: WeakFocusHandle {
653                                id: blurred_id,
654                                handles: Arc::downgrade(&cx.focus_handles),
655                            },
656                        };
657                        listener(view, event, window, cx)
658                    }
659                })
660                .is_ok()
661            }));
662        self.defer(|_| activate());
663        subscription
664    }
665
666    /// Schedule a future to be run asynchronously.
667    /// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
668    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
669    /// The returned future will be polled on the main thread.
670    #[track_caller]
671    #[inline(always)]
672    pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R>
673    where
674        R: 'static,
675        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
676    {
677        let view = self.weak_entity();
678        window.spawn(self, async move |cx| f(view, cx).await)
679    }
680
681    /// Schedule a future to be run asynchronously with the given priority.
682    /// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
683    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
684    /// The returned future will be polled on the main thread.
685    #[track_caller]
686    #[inline(always)]
687    pub fn spawn_in_with_priority<AsyncFn, R>(
688        &self,
689        priority: Priority,
690        window: &Window,
691        f: AsyncFn,
692    ) -> Task<R>
693    where
694        R: 'static,
695        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
696    {
697        let view = self.weak_entity();
698        window.spawn_with_priority(priority, self, async move |cx| f(view, cx).await)
699    }
700
701    /// Register a callback to be invoked when the given global state changes.
702    pub fn observe_global_in<G: Global>(
703        &mut self,
704        window: &Window,
705        mut f: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
706    ) -> Subscription {
707        let window_handle = window.handle;
708        let view = self.weak_entity();
709        let (subscription, activate) = self.global_observers.insert(
710            TypeId::of::<G>(),
711            Box::new(move |cx| {
712                // If the entity has been dropped, remove this observer.
713                if view.upgrade().is_none() {
714                    return false;
715                }
716                // If the window is unavailable (e.g. temporarily taken during a
717                // nested update, or already closed), skip this notification but
718                // keep the observer alive so it can fire on future changes.
719                let Ok(entity_alive) = window_handle.update(cx, |_, window, cx| {
720                    view.update(cx, |view, cx| f(view, window, cx)).is_ok()
721                }) else {
722                    return true;
723                };
724                entity_alive
725            }),
726        );
727        self.defer(move |_| activate());
728        subscription
729    }
730
731    /// Register a callback to be invoked when the given Action type is dispatched to the window.
732    pub fn on_action(
733        &mut self,
734        action_type: TypeId,
735        window: &mut Window,
736        listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<T>) + 'static,
737    ) {
738        let handle = self.weak_entity();
739        window.on_action(action_type, move |action, phase, window, cx| {
740            handle
741                .update(cx, |view, cx| {
742                    listener(view, action, phase, window, cx);
743                })
744                .ok();
745        });
746    }
747
748    /// Move focus to the current view, assuming it implements [`Focusable`].
749    pub fn focus_self(&mut self, window: &mut Window)
750    where
751        T: Focusable,
752    {
753        let view = self.entity();
754        window.defer(self, move |window, cx| {
755            view.read(cx).focus_handle(cx).focus(window, cx)
756        })
757    }
758}
759
760impl<T> Context<'_, T> {
761    /// Emit an event of the specified type, which can be handled by other entities that have subscribed via `subscribe` methods on their respective contexts.
762    pub fn emit<Evt>(&mut self, event: Evt)
763    where
764        T: EventEmitter<Evt>,
765        Evt: 'static,
766    {
767        let event = self
768            .event_arena
769            .alloc(|| event)
770            .map(|it| it as &mut dyn Any);
771        self.app.pending_effects.push_back(Effect::Emit {
772            emitter: self.entity_state.entity_id,
773            event_type: TypeId::of::<Evt>(),
774            event,
775        });
776    }
777}
778
779impl<T> AppContext for Context<'_, T> {
780    #[inline]
781    fn new<U: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<U>) -> U) -> Entity<U> {
782        self.app.new(build_entity)
783    }
784
785    #[inline]
786    fn reserve_entity<U: 'static>(&mut self) -> Reservation<U> {
787        self.app.reserve_entity()
788    }
789
790    #[inline]
791    fn insert_entity<U: 'static>(
792        &mut self,
793        reservation: Reservation<U>,
794        build_entity: impl FnOnce(&mut Context<U>) -> U,
795    ) -> Entity<U> {
796        self.app.insert_entity(reservation, build_entity)
797    }
798
799    #[inline]
800    fn update_entity<U: 'static, R>(
801        &mut self,
802        handle: &Entity<U>,
803        update: impl FnOnce(&mut U, &mut Context<U>) -> R,
804    ) -> R {
805        self.app.update_entity(handle, update)
806    }
807
808    #[inline]
809    fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> super::GpuiBorrow<'a, E>
810    where
811        E: 'static,
812    {
813        self.app.as_mut(handle)
814    }
815
816    #[inline]
817    fn read_entity<U, R>(&self, handle: &Entity<U>, read: impl FnOnce(&U, &App) -> R) -> R
818    where
819        U: 'static,
820    {
821        self.app.read_entity(handle, read)
822    }
823
824    #[inline]
825    fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
826    where
827        F: FnOnce(AnyView, &mut Window, &mut App) -> R,
828    {
829        self.app.update_window(window, update)
830    }
831
832    #[inline]
833    fn with_window<R>(
834        &mut self,
835        entity_id: EntityId,
836        f: impl FnOnce(&mut Window, &mut App) -> R,
837    ) -> Option<R> {
838        self.app.with_window(entity_id, f)
839    }
840
841    #[inline]
842    fn read_window<U, R>(
843        &self,
844        window: &WindowHandle<U>,
845        read: impl FnOnce(Entity<U>, &App) -> R,
846    ) -> Result<R>
847    where
848        U: 'static,
849    {
850        self.app.read_window(window, read)
851    }
852
853    #[inline]
854    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
855    where
856        R: Send + 'static,
857    {
858        self.app.background_executor.spawn(future)
859    }
860
861    #[inline]
862    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
863    where
864        G: Global,
865    {
866        self.app.read_global(callback)
867    }
868}
869
870impl<T> Borrow<App> for Context<'_, T> {
871    fn borrow(&self) -> &App {
872        self.app
873    }
874}
875
876impl<T> BorrowMut<App> for Context<'_, T> {
877    fn borrow_mut(&mut self) -> &mut App {
878        self.app
879    }
880}
881
882#[inline(never)]
883fn invoke_observer<T: 'static, W: 'static>(
884    observer: &WeakEntity<T>,
885    observed: Entity<W>,
886    cx: &mut App,
887    on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Context<T>),
888) -> bool {
889    if let Some(observer) = observer.upgrade() {
890        observer.update(cx, |observer, cx| on_notify(observer, observed, cx));
891        true
892    } else {
893        false
894    }
895}
896
897#[inline(never)]
898fn invoke_subscriber<T: 'static, Emitter: 'static, Event: 'static>(
899    subscriber: &WeakEntity<T>,
900    emitter: Entity<Emitter>,
901    event: &Event,
902    cx: &mut App,
903    on_event: &mut dyn FnMut(&mut T, Entity<Emitter>, &Event, &mut Context<T>),
904) -> bool {
905    if let Some(subscriber) = subscriber.upgrade() {
906        subscriber.update(cx, |subscriber, cx| {
907            on_event(subscriber, emitter, event, cx)
908        });
909        true
910    } else {
911        false
912    }
913}
914
915#[inline(never)]
916fn invoke_observer_in<T: 'static, W: 'static>(
917    observer: &WeakEntity<T>,
918    observed: &WeakEntity<W>,
919    cx: &mut App,
920    on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Window, &mut Context<T>),
921) -> bool {
922    let Some((observer, observed)) = observer.upgrade().zip(observed.upgrade()) else {
923        return false;
924    };
925    cx.with_window(observer.entity_id(), |window, cx| {
926        observer.update(cx, |observer, cx| {
927            on_notify(observer, observed, window, cx);
928        });
929    });
930    true
931}
932
933#[inline(never)]
934fn invoke_subscriber_in<T: 'static, Emitter: 'static, Event: 'static>(
935    subscriber: &WeakEntity<T>,
936    emitter: &WeakEntity<Emitter>,
937    event: &dyn Any,
938    cx: &mut App,
939    on_event: &mut dyn FnMut(&mut T, &Entity<Emitter>, &Event, &mut Window, &mut Context<T>),
940) -> bool {
941    let Some((subscriber, emitter)) = subscriber.upgrade().zip(emitter.upgrade()) else {
942        return false;
943    };
944    let event = event.downcast_ref().expect("invalid event type");
945    cx.with_window(subscriber.entity_id(), |window, cx| {
946        subscriber.update(cx, |subscriber, cx| {
947            on_event(subscriber, &emitter, event, window, cx);
948        });
949    });
950    true
951}
952
953#[inline(never)]
954fn invoke_listener<T: 'static>(
955    view: &WeakEntity<T>,
956    window: &mut Window,
957    cx: &mut App,
958    listener: &dyn Fn(&mut T, &mut Window, &mut Context<T>),
959) {
960    view.update(cx, |view, cx| listener(view, window, cx)).ok();
961}