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 App)`,
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    /// Convenience method for producing view state in a closure.
229    /// See `listener` for more details.
230    pub fn processor<E, R>(
231        &self,
232        f: impl Fn(&mut T, E, &mut Window, &mut Context<T>) -> R + 'static,
233    ) -> impl Fn(E, &mut Window, &mut App) -> R + 'static {
234        let view = self.entity();
235        move |e: E, window: &mut Window, cx: &mut App| {
236            view.update(cx, |view, cx| f(view, e, window, cx))
237        }
238    }
239
240    /// Run something using this entity and cx, when the returned struct is dropped
241    pub fn on_drop(
242        &self,
243        f: impl FnOnce(&mut T, &mut Context<T>) + 'static,
244    ) -> Deferred<impl FnOnce()> {
245        let this = self.weak_entity();
246        let mut cx = self.to_async();
247        util::defer(move || {
248            this.update(&mut cx, f).ok();
249        })
250    }
251
252    /// Focus the given view in the given window. View type is required to implement Focusable.
253    pub fn focus_view<W: Focusable>(&mut self, view: &Entity<W>, window: &mut Window) {
254        window.focus(&view.focus_handle(self));
255    }
256
257    /// Sets a given callback to be run on the next frame.
258    pub fn on_next_frame(
259        &self,
260        window: &mut Window,
261        f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
262    ) where
263        T: 'static,
264    {
265        let view = self.entity();
266        window.on_next_frame(move |window, cx| view.update(cx, |view, cx| f(view, window, cx)));
267    }
268
269    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
270    /// that are currently on the stack to be returned to the app.
271    pub fn defer_in(
272        &mut self,
273        window: &Window,
274        f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
275    ) {
276        let view = self.entity();
277        window.defer(self, move |window, cx| {
278            view.update(cx, |view, cx| f(view, window, cx))
279        });
280    }
281
282    /// Observe another entity for changes to its state, as tracked by [`Context::notify`].
283    pub fn observe_in<V2>(
284        &mut self,
285        observed: &Entity<V2>,
286        window: &mut Window,
287        mut on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<T>) + 'static,
288    ) -> Subscription
289    where
290        V2: 'static,
291        T: 'static,
292    {
293        let observed_id = observed.entity_id();
294        let observed = observed.downgrade();
295        let window_handle = window.handle;
296        let observer = self.weak_entity();
297        self.new_observer(
298            observed_id,
299            Box::new(move |cx| {
300                window_handle
301                    .update(cx, |_, window, cx| {
302                        if let Some((observer, observed)) =
303                            observer.upgrade().zip(observed.upgrade())
304                        {
305                            observer.update(cx, |observer, cx| {
306                                on_notify(observer, observed, window, cx);
307                            });
308                            true
309                        } else {
310                            false
311                        }
312                    })
313                    .unwrap_or(false)
314            }),
315        )
316    }
317
318    /// Subscribe to events emitted by another entity.
319    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
320    /// 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.
321    pub fn subscribe_in<Emitter, Evt>(
322        &mut self,
323        emitter: &Entity<Emitter>,
324        window: &Window,
325        mut on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<T>) + 'static,
326    ) -> Subscription
327    where
328        Emitter: EventEmitter<Evt>,
329        Evt: 'static,
330    {
331        let emitter = emitter.downgrade();
332        let window_handle = window.handle;
333        let subscriber = self.weak_entity();
334        self.new_subscription(
335            emitter.entity_id(),
336            (
337                TypeId::of::<Evt>(),
338                Box::new(move |event, cx| {
339                    window_handle
340                        .update(cx, |_, window, cx| {
341                            if let Some((subscriber, emitter)) =
342                                subscriber.upgrade().zip(emitter.upgrade())
343                            {
344                                let event = event.downcast_ref().expect("invalid event type");
345                                subscriber.update(cx, |subscriber, cx| {
346                                    on_event(subscriber, &emitter, event, window, cx);
347                                });
348                                true
349                            } else {
350                                false
351                            }
352                        })
353                        .unwrap_or(false)
354                }),
355            ),
356        )
357    }
358
359    /// Register a callback to be invoked when the view is released.
360    ///
361    /// The callback receives a handle to the view's window. This handle may be
362    /// invalid, if the window was closed before the view was released.
363    pub fn on_release_in(
364        &mut self,
365        window: &Window,
366        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
367    ) -> Subscription {
368        let entity = self.entity();
369        self.app.observe_release_in(&entity, window, on_release)
370    }
371
372    /// Register a callback to be invoked when the given Entity is released.
373    pub fn observe_release_in<T2>(
374        &self,
375        observed: &Entity<T2>,
376        window: &Window,
377        mut on_release: impl FnMut(&mut T, &mut T2, &mut Window, &mut Context<T>) + 'static,
378    ) -> Subscription
379    where
380        T: 'static,
381        T2: 'static,
382    {
383        let observer = self.weak_entity();
384        self.app
385            .observe_release_in(observed, window, move |observed, window, cx| {
386                observer
387                    .update(cx, |observer, cx| {
388                        on_release(observer, observed, window, cx)
389                    })
390                    .ok();
391            })
392    }
393
394    /// Register a callback to be invoked when the window is resized.
395    pub fn observe_window_bounds(
396        &self,
397        window: &mut Window,
398        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
399    ) -> Subscription {
400        let view = self.weak_entity();
401        let (subscription, activate) = window.bounds_observers.insert(
402            (),
403            Box::new(move |window, cx| {
404                view.update(cx, |view, cx| callback(view, window, cx))
405                    .is_ok()
406            }),
407        );
408        activate();
409        subscription
410    }
411
412    /// Register a callback to be invoked when the window is activated or deactivated.
413    pub fn observe_window_activation(
414        &self,
415        window: &mut Window,
416        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
417    ) -> Subscription {
418        let view = self.weak_entity();
419        let (subscription, activate) = window.activation_observers.insert(
420            (),
421            Box::new(move |window, cx| {
422                view.update(cx, |view, cx| callback(view, window, cx))
423                    .is_ok()
424            }),
425        );
426        activate();
427        subscription
428    }
429
430    /// Registers a callback to be invoked when the window appearance changes.
431    pub fn observe_window_appearance(
432        &self,
433        window: &mut Window,
434        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
435    ) -> Subscription {
436        let view = self.weak_entity();
437        let (subscription, activate) = window.appearance_observers.insert(
438            (),
439            Box::new(move |window, cx| {
440                view.update(cx, |view, cx| callback(view, window, cx))
441                    .is_ok()
442            }),
443        );
444        activate();
445        subscription
446    }
447
448    /// Register a callback to be invoked when a keystroke is received by the application
449    /// in any window. Note that this fires after all other action and event mechanisms have resolved
450    /// and that this API will not be invoked if the event's propagation is stopped.
451    pub fn observe_keystrokes(
452        &mut self,
453        mut f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<T>) + 'static,
454    ) -> Subscription {
455        fn inner(
456            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
457            handler: KeystrokeObserver,
458        ) -> Subscription {
459            let (subscription, activate) = keystroke_observers.insert((), handler);
460            activate();
461            subscription
462        }
463
464        let view = self.weak_entity();
465        inner(
466            &mut self.keystroke_observers,
467            Box::new(move |event, window, cx| {
468                if let Some(view) = view.upgrade() {
469                    view.update(cx, |view, cx| f(view, event, window, cx));
470                    true
471                } else {
472                    false
473                }
474            }),
475        )
476    }
477
478    /// Register a callback to be invoked when the window's pending input changes.
479    pub fn observe_pending_input(
480        &self,
481        window: &mut Window,
482        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
483    ) -> Subscription {
484        let view = self.weak_entity();
485        let (subscription, activate) = window.pending_input_observers.insert(
486            (),
487            Box::new(move |window, cx| {
488                view.update(cx, |view, cx| callback(view, window, cx))
489                    .is_ok()
490            }),
491        );
492        activate();
493        subscription
494    }
495
496    /// Register a listener to be called when the given focus handle receives focus.
497    /// Returns a subscription and persists until the subscription is dropped.
498    pub fn on_focus(
499        &mut self,
500        handle: &FocusHandle,
501        window: &mut Window,
502        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
503    ) -> Subscription {
504        let view = self.weak_entity();
505        let focus_id = handle.id;
506        let (subscription, activate) =
507            window.new_focus_listener(Box::new(move |event, window, cx| {
508                view.update(cx, |view, cx| {
509                    if event.previous_focus_path.last() != Some(&focus_id)
510                        && event.current_focus_path.last() == Some(&focus_id)
511                    {
512                        listener(view, window, cx)
513                    }
514                })
515                .is_ok()
516            }));
517        self.defer(|_| activate());
518        subscription
519    }
520
521    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
522    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
523    /// Returns a subscription and persists until the subscription is dropped.
524    pub fn on_focus_in(
525        &mut self,
526        handle: &FocusHandle,
527        window: &mut Window,
528        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
529    ) -> Subscription {
530        let view = self.weak_entity();
531        let focus_id = handle.id;
532        let (subscription, activate) =
533            window.new_focus_listener(Box::new(move |event, window, cx| {
534                view.update(cx, |view, cx| {
535                    if event.is_focus_in(focus_id) {
536                        listener(view, window, cx)
537                    }
538                })
539                .is_ok()
540            }));
541        self.defer(|_| activate());
542        subscription
543    }
544
545    /// Register a listener to be called when the given focus handle loses focus.
546    /// Returns a subscription and persists until the subscription is dropped.
547    pub fn on_blur(
548        &mut self,
549        handle: &FocusHandle,
550        window: &mut Window,
551        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
552    ) -> Subscription {
553        let view = self.weak_entity();
554        let focus_id = handle.id;
555        let (subscription, activate) =
556            window.new_focus_listener(Box::new(move |event, window, cx| {
557                view.update(cx, |view, cx| {
558                    if event.previous_focus_path.last() == Some(&focus_id)
559                        && event.current_focus_path.last() != Some(&focus_id)
560                    {
561                        listener(view, window, cx)
562                    }
563                })
564                .is_ok()
565            }));
566        self.defer(|_| activate());
567        subscription
568    }
569
570    /// Register a listener to be called when nothing in the window has focus.
571    /// This typically happens when the node that was focused is removed from the tree,
572    /// and this callback lets you chose a default place to restore the users focus.
573    /// Returns a subscription and persists until the subscription is dropped.
574    pub fn on_focus_lost(
575        &mut self,
576        window: &mut Window,
577        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
578    ) -> Subscription {
579        let view = self.weak_entity();
580        let (subscription, activate) = window.focus_lost_listeners.insert(
581            (),
582            Box::new(move |window, cx| {
583                view.update(cx, |view, cx| listener(view, window, cx))
584                    .is_ok()
585            }),
586        );
587        self.defer(|_| activate());
588        subscription
589    }
590
591    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
592    /// Returns a subscription and persists until the subscription is dropped.
593    pub fn on_focus_out(
594        &mut self,
595        handle: &FocusHandle,
596        window: &mut Window,
597        mut listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<T>) + 'static,
598    ) -> Subscription {
599        let view = self.weak_entity();
600        let focus_id = handle.id;
601        let (subscription, activate) =
602            window.new_focus_listener(Box::new(move |event, window, cx| {
603                view.update(cx, |view, cx| {
604                    if let Some(blurred_id) = event.previous_focus_path.last().copied() {
605                        if event.is_focus_out(focus_id) {
606                            let event = FocusOutEvent {
607                                blurred: WeakFocusHandle {
608                                    id: blurred_id,
609                                    handles: Arc::downgrade(&cx.focus_handles),
610                                },
611                            };
612                            listener(view, event, window, cx)
613                        }
614                    }
615                })
616                .is_ok()
617            }));
618        self.defer(|_| activate());
619        subscription
620    }
621
622    /// Schedule a future to be run asynchronously.
623    /// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
624    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
625    /// The returned future will be polled on the main thread.
626    #[track_caller]
627    pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R>
628    where
629        R: 'static,
630        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
631    {
632        let view = self.weak_entity();
633        window.spawn(self, async move |cx| f(view, cx).await)
634    }
635
636    /// Register a callback to be invoked when the given global state changes.
637    pub fn observe_global_in<G: Global>(
638        &mut self,
639        window: &Window,
640        mut f: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
641    ) -> Subscription {
642        let window_handle = window.handle;
643        let view = self.weak_entity();
644        let (subscription, activate) = self.global_observers.insert(
645            TypeId::of::<G>(),
646            Box::new(move |cx| {
647                window_handle
648                    .update(cx, |_, window, cx| {
649                        view.update(cx, |view, cx| f(view, window, cx)).is_ok()
650                    })
651                    .unwrap_or(false)
652            }),
653        );
654        self.defer(move |_| activate());
655        subscription
656    }
657
658    /// Register a callback to be invoked when the given Action type is dispatched to the window.
659    pub fn on_action(
660        &mut self,
661        action_type: TypeId,
662        window: &mut Window,
663        listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<T>) + 'static,
664    ) {
665        let handle = self.weak_entity();
666        window.on_action(action_type, move |action, phase, window, cx| {
667            handle
668                .update(cx, |view, cx| {
669                    listener(view, action, phase, window, cx);
670                })
671                .ok();
672        });
673    }
674
675    /// Move focus to the current view, assuming it implements [`Focusable`].
676    pub fn focus_self(&mut self, window: &mut Window)
677    where
678        T: Focusable,
679    {
680        let view = self.entity();
681        window.defer(self, move |window, cx| {
682            view.read(cx).focus_handle(cx).focus(window)
683        })
684    }
685}
686
687impl<T> Context<'_, T> {
688    /// Emit an event of the specified type, which can be handled by other entities that have subscribed via `subscribe` methods on their respective contexts.
689    pub fn emit<Evt>(&mut self, event: Evt)
690    where
691        T: EventEmitter<Evt>,
692        Evt: 'static,
693    {
694        self.app.pending_effects.push_back(Effect::Emit {
695            emitter: self.entity_state.entity_id,
696            event_type: TypeId::of::<Evt>(),
697            event: Box::new(event),
698        });
699    }
700}
701
702impl<T> AppContext for Context<'_, T> {
703    type Result<U> = U;
704
705    fn new<U: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<U>) -> U) -> Entity<U> {
706        self.app.new(build_entity)
707    }
708
709    fn reserve_entity<U: 'static>(&mut self) -> Reservation<U> {
710        self.app.reserve_entity()
711    }
712
713    fn insert_entity<U: 'static>(
714        &mut self,
715        reservation: Reservation<U>,
716        build_entity: impl FnOnce(&mut Context<U>) -> U,
717    ) -> Self::Result<Entity<U>> {
718        self.app.insert_entity(reservation, build_entity)
719    }
720
721    fn update_entity<U: 'static, R>(
722        &mut self,
723        handle: &Entity<U>,
724        update: impl FnOnce(&mut U, &mut Context<U>) -> R,
725    ) -> R {
726        self.app.update_entity(handle, update)
727    }
728
729    fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> Self::Result<super::GpuiBorrow<'a, E>>
730    where
731        E: 'static,
732    {
733        self.app.as_mut(handle)
734    }
735
736    fn read_entity<U, R>(
737        &self,
738        handle: &Entity<U>,
739        read: impl FnOnce(&U, &App) -> R,
740    ) -> Self::Result<R>
741    where
742        U: 'static,
743    {
744        self.app.read_entity(handle, read)
745    }
746
747    fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
748    where
749        F: FnOnce(AnyView, &mut Window, &mut App) -> R,
750    {
751        self.app.update_window(window, update)
752    }
753
754    fn read_window<U, R>(
755        &self,
756        window: &WindowHandle<U>,
757        read: impl FnOnce(Entity<U>, &App) -> R,
758    ) -> Result<R>
759    where
760        U: 'static,
761    {
762        self.app.read_window(window, read)
763    }
764
765    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
766    where
767        R: Send + 'static,
768    {
769        self.app.background_executor.spawn(future)
770    }
771
772    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
773    where
774        G: Global,
775    {
776        self.app.read_global(callback)
777    }
778}
779
780impl<T> Borrow<App> for Context<'_, T> {
781    fn borrow(&self) -> &App {
782        self.app
783    }
784}
785
786impl<T> BorrowMut<App> for Context<'_, T> {
787    fn borrow_mut(&mut self) -> &mut App {
788        self.app
789    }
790}