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