Skip to main content

gpui/app/
context.rs

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