context.rs

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