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    /// Registers a callback for [`App::observe_keystrokes`] that updates this entity.
493    pub fn observe_keystrokes(
494        &mut self,
495        mut f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<T>) + 'static,
496    ) -> Subscription {
497        fn inner(
498            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
499            handler: KeystrokeObserver,
500        ) -> Subscription {
501            let (subscription, activate) = keystroke_observers.insert((), handler);
502            activate();
503            subscription
504        }
505
506        let view = self.weak_entity();
507        inner(
508            &self.keystroke_observers,
509            Box::new(move |event, window, cx| {
510                if let Some(view) = view.upgrade() {
511                    view.update(cx, |view, cx| f(view, event, window, cx));
512                    true
513                } else {
514                    false
515                }
516            }),
517        )
518    }
519
520    /// Register a callback to be invoked when the window's pending input changes.
521    pub fn observe_pending_input(
522        &self,
523        window: &mut Window,
524        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
525    ) -> Subscription {
526        let view = self.weak_entity();
527        let (subscription, activate) = window.pending_input_observers.insert(
528            (),
529            Box::new(move |window, cx| {
530                view.update(cx, |view, cx| callback(view, window, cx))
531                    .is_ok()
532            }),
533        );
534        activate();
535        subscription
536    }
537
538    /// Register a listener to be called when the given focus handle receives focus.
539    /// Returns a subscription and persists until the subscription is dropped.
540    pub fn on_focus(
541        &mut self,
542        handle: &FocusHandle,
543        window: &mut Window,
544        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
545    ) -> Subscription {
546        let view = self.weak_entity();
547        let focus_id = handle.id;
548        let (subscription, activate) =
549            window.new_focus_listener(Box::new(move |event, window, cx| {
550                view.update(cx, |view, cx| {
551                    if event.previous_focus_path.last() != Some(&focus_id)
552                        && event.current_focus_path.last() == Some(&focus_id)
553                    {
554                        listener(view, window, cx)
555                    }
556                })
557                .is_ok()
558            }));
559        self.defer(|_| activate());
560        subscription
561    }
562
563    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
564    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
565    /// Returns a subscription and persists until the subscription is dropped.
566    pub fn on_focus_in(
567        &mut self,
568        handle: &FocusHandle,
569        window: &mut Window,
570        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
571    ) -> Subscription {
572        let view = self.weak_entity();
573        let focus_id = handle.id;
574        let (subscription, activate) =
575            window.new_focus_listener(Box::new(move |event, window, cx| {
576                view.update(cx, |view, cx| {
577                    if event.is_focus_in(focus_id) {
578                        listener(view, window, cx)
579                    }
580                })
581                .is_ok()
582            }));
583        self.defer(|_| activate());
584        subscription
585    }
586
587    /// Register a listener to be called when the given focus handle loses focus.
588    /// Returns a subscription and persists until the subscription is dropped.
589    pub fn on_blur(
590        &mut self,
591        handle: &FocusHandle,
592        window: &mut Window,
593        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
594    ) -> Subscription {
595        let view = self.weak_entity();
596        let focus_id = handle.id;
597        let (subscription, activate) =
598            window.new_focus_listener(Box::new(move |event, window, cx| {
599                view.update(cx, |view, cx| {
600                    if event.previous_focus_path.last() == Some(&focus_id)
601                        && event.current_focus_path.last() != Some(&focus_id)
602                    {
603                        listener(view, window, cx)
604                    }
605                })
606                .is_ok()
607            }));
608        self.defer(|_| activate());
609        subscription
610    }
611
612    /// Register a listener to be called when nothing in the window has focus.
613    /// This typically happens when the node that was focused is removed from the tree,
614    /// and this callback lets you chose a default place to restore the users focus.
615    /// Returns a subscription and persists until the subscription is dropped.
616    pub fn on_focus_lost(
617        &mut self,
618        window: &mut Window,
619        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
620    ) -> Subscription {
621        let view = self.weak_entity();
622        let (subscription, activate) = window.focus_lost_listeners.insert(
623            (),
624            Box::new(move |window, cx| {
625                view.update(cx, |view, cx| listener(view, window, cx))
626                    .is_ok()
627            }),
628        );
629        self.defer(|_| activate());
630        subscription
631    }
632
633    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
634    /// Returns a subscription and persists until the subscription is dropped.
635    pub fn on_focus_out(
636        &mut self,
637        handle: &FocusHandle,
638        window: &mut Window,
639        mut listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<T>) + 'static,
640    ) -> Subscription {
641        let view = self.weak_entity();
642        let focus_id = handle.id;
643        let (subscription, activate) =
644            window.new_focus_listener(Box::new(move |event, window, cx| {
645                view.update(cx, |view, cx| {
646                    if let Some(blurred_id) = event.previous_focus_path.last().copied()
647                        && event.is_focus_out(focus_id)
648                    {
649                        let event = FocusOutEvent {
650                            blurred: WeakFocusHandle {
651                                id: blurred_id,
652                                handles: Arc::downgrade(&cx.focus_handles),
653                            },
654                        };
655                        listener(view, event, window, cx)
656                    }
657                })
658                .is_ok()
659            }));
660        self.defer(|_| activate());
661        subscription
662    }
663
664    /// Schedule a future to be run asynchronously.
665    /// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
666    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
667    /// The returned future will be polled on the main thread.
668    #[track_caller]
669    #[inline(always)]
670    pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R>
671    where
672        R: 'static,
673        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
674    {
675        let view = self.weak_entity();
676        window.spawn(self, async move |cx| f(view, cx).await)
677    }
678
679    /// Schedule a future to be run asynchronously with the given priority.
680    /// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
681    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
682    /// The returned future will be polled on the main thread.
683    #[track_caller]
684    #[inline(always)]
685    pub fn spawn_in_with_priority<AsyncFn, R>(
686        &self,
687        priority: Priority,
688        window: &Window,
689        f: AsyncFn,
690    ) -> Task<R>
691    where
692        R: 'static,
693        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
694    {
695        let view = self.weak_entity();
696        window.spawn_with_priority(priority, self, async move |cx| f(view, cx).await)
697    }
698
699    /// Register a callback to be invoked when the given global state changes.
700    pub fn observe_global_in<G: Global>(
701        &mut self,
702        window: &Window,
703        mut f: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
704    ) -> Subscription {
705        let window_handle = window.handle;
706        let view = self.weak_entity();
707        let (subscription, activate) = self.global_observers.insert(
708            TypeId::of::<G>(),
709            Box::new(move |cx| {
710                // If the entity has been dropped, remove this observer.
711                if view.upgrade().is_none() {
712                    return false;
713                }
714                // If the window is unavailable (e.g. temporarily taken during a
715                // nested update, or already closed), skip this notification but
716                // keep the observer alive so it can fire on future changes.
717                let Ok(entity_alive) = window_handle.update(cx, |_, window, cx| {
718                    view.update(cx, |view, cx| f(view, window, cx)).is_ok()
719                }) else {
720                    return true;
721                };
722                entity_alive
723            }),
724        );
725        self.defer(move |_| activate());
726        subscription
727    }
728
729    /// Register a callback to be invoked when the given Action type is dispatched to the window.
730    pub fn on_action(
731        &mut self,
732        action_type: TypeId,
733        window: &mut Window,
734        listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<T>) + 'static,
735    ) {
736        let handle = self.weak_entity();
737        window.on_action(action_type, move |action, phase, window, cx| {
738            handle
739                .update(cx, |view, cx| {
740                    listener(view, action, phase, window, cx);
741                })
742                .ok();
743        });
744    }
745
746    /// Move focus to the current view, assuming it implements [`Focusable`].
747    pub fn focus_self(&mut self, window: &mut Window)
748    where
749        T: Focusable,
750    {
751        let view = self.entity();
752        window.defer(self, move |window, cx| {
753            view.read(cx).focus_handle(cx).focus(window, cx)
754        })
755    }
756}
757
758impl<T> Context<'_, T> {
759    /// Emit an event of the specified type, which can be handled by other entities that have subscribed via `subscribe` methods on their respective contexts.
760    pub fn emit<Evt>(&mut self, event: Evt)
761    where
762        T: EventEmitter<Evt>,
763        Evt: 'static,
764    {
765        let event = self
766            .event_arena
767            .alloc(|| event)
768            .map(|it| it as &mut dyn Any);
769        self.app.pending_effects.push_back(Effect::Emit {
770            emitter: self.entity_state.entity_id,
771            event_type: TypeId::of::<Evt>(),
772            event,
773        });
774    }
775}
776
777impl<T> AppContext for Context<'_, T> {
778    #[inline]
779    fn new<U: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<U>) -> U) -> Entity<U> {
780        self.app.new(build_entity)
781    }
782
783    #[inline]
784    fn reserve_entity<U: 'static>(&mut self) -> Reservation<U> {
785        self.app.reserve_entity()
786    }
787
788    #[inline]
789    fn insert_entity<U: 'static>(
790        &mut self,
791        reservation: Reservation<U>,
792        build_entity: impl FnOnce(&mut Context<U>) -> U,
793    ) -> Entity<U> {
794        self.app.insert_entity(reservation, build_entity)
795    }
796
797    #[inline]
798    fn update_entity<U: 'static, R>(
799        &mut self,
800        handle: &Entity<U>,
801        update: impl FnOnce(&mut U, &mut Context<U>) -> R,
802    ) -> R {
803        self.app.update_entity(handle, update)
804    }
805
806    #[inline]
807    fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> super::GpuiBorrow<'a, E>
808    where
809        E: 'static,
810    {
811        self.app.as_mut(handle)
812    }
813
814    #[inline]
815    fn read_entity<U, R>(&self, handle: &Entity<U>, read: impl FnOnce(&U, &App) -> R) -> R
816    where
817        U: 'static,
818    {
819        self.app.read_entity(handle, read)
820    }
821
822    #[inline]
823    fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
824    where
825        F: FnOnce(AnyView, &mut Window, &mut App) -> R,
826    {
827        self.app.update_window(window, update)
828    }
829
830    #[inline]
831    fn with_window<R>(
832        &mut self,
833        entity_id: EntityId,
834        f: impl FnOnce(&mut Window, &mut App) -> R,
835    ) -> Option<R> {
836        self.app.with_window(entity_id, f)
837    }
838
839    #[inline]
840    fn read_window<U, R>(
841        &self,
842        window: &WindowHandle<U>,
843        read: impl FnOnce(Entity<U>, &App) -> R,
844    ) -> Result<R>
845    where
846        U: 'static,
847    {
848        self.app.read_window(window, read)
849    }
850
851    #[inline]
852    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
853    where
854        R: Send + 'static,
855    {
856        self.app.background_executor.spawn(future)
857    }
858
859    #[inline]
860    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
861    where
862        G: Global,
863    {
864        self.app.read_global(callback)
865    }
866}
867
868impl<T> Borrow<App> for Context<'_, T> {
869    fn borrow(&self) -> &App {
870        self.app
871    }
872}
873
874impl<T> BorrowMut<App> for Context<'_, T> {
875    fn borrow_mut(&mut self) -> &mut App {
876        self.app
877    }
878}
879
880#[inline(never)]
881fn invoke_observer<T: 'static, W: 'static>(
882    observer: &WeakEntity<T>,
883    observed: Entity<W>,
884    cx: &mut App,
885    on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Context<T>),
886) -> bool {
887    if let Some(observer) = observer.upgrade() {
888        observer.update(cx, |observer, cx| on_notify(observer, observed, cx));
889        true
890    } else {
891        false
892    }
893}
894
895#[inline(never)]
896fn invoke_subscriber<T: 'static, Emitter: 'static, Event: 'static>(
897    subscriber: &WeakEntity<T>,
898    emitter: Entity<Emitter>,
899    event: &Event,
900    cx: &mut App,
901    on_event: &mut dyn FnMut(&mut T, Entity<Emitter>, &Event, &mut Context<T>),
902) -> bool {
903    if let Some(subscriber) = subscriber.upgrade() {
904        subscriber.update(cx, |subscriber, cx| {
905            on_event(subscriber, emitter, event, cx)
906        });
907        true
908    } else {
909        false
910    }
911}
912
913#[inline(never)]
914fn invoke_observer_in<T: 'static, W: 'static>(
915    observer: &WeakEntity<T>,
916    observed: &WeakEntity<W>,
917    cx: &mut App,
918    on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Window, &mut Context<T>),
919) -> bool {
920    let Some((observer, observed)) = observer.upgrade().zip(observed.upgrade()) else {
921        return false;
922    };
923    cx.with_window(observer.entity_id(), |window, cx| {
924        observer.update(cx, |observer, cx| {
925            on_notify(observer, observed, window, cx);
926        });
927    });
928    true
929}
930
931#[inline(never)]
932fn invoke_subscriber_in<T: 'static, Emitter: 'static, Event: 'static>(
933    subscriber: &WeakEntity<T>,
934    emitter: &WeakEntity<Emitter>,
935    event: &dyn Any,
936    cx: &mut App,
937    on_event: &mut dyn FnMut(&mut T, &Entity<Emitter>, &Event, &mut Window, &mut Context<T>),
938) -> bool {
939    let Some((subscriber, emitter)) = subscriber.upgrade().zip(emitter.upgrade()) else {
940        return false;
941    };
942    let event = event.downcast_ref().expect("invalid event type");
943    cx.with_window(subscriber.entity_id(), |window, cx| {
944        subscriber.update(cx, |subscriber, cx| {
945            on_event(subscriber, &emitter, event, window, cx);
946        });
947    });
948    true
949}
950
951#[inline(never)]
952fn invoke_listener<T: 'static>(
953    view: &WeakEntity<T>,
954    window: &mut Window,
955    cx: &mut App,
956    listener: &dyn Fn(&mut T, &mut Window, &mut Context<T>),
957) {
958    view.update(cx, |view, cx| listener(view, window, cx)).ok();
959}