Skip to main content

gpui/app/
context.rs

1use crate::{
2    AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, EntityId, EventEmitter,
3    FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Priority, Reservation,
4    SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
5    WindowVisibility,
6};
7use anyhow::Result;
8use futures::FutureExt;
9use gpui_util::Deferred;
10use std::{
11    any::{Any, TypeId},
12    borrow::{Borrow, BorrowMut},
13    future::Future,
14    ops,
15    sync::Arc,
16};
17
18use super::{App, AsyncWindowContext, Entity, KeystrokeEvent};
19
20/// A mutable handle to the [`App`] that also knows which entity `T` you are working on.
21///
22/// GPUI passes a `Context<T>` to every callback that works on an entity. [`Entity::update`]
23/// and [`WeakEntity::update`] pass one to their closure, and render methods receive one as
24/// their last argument. Because `Context<T>` dereferences to [`App`], you can use any `App`
25/// method through it. The methods on `Context<T>` itself need the entity: [`Context::notify`],
26/// [`Context::emit`], [`Context::observe`], [`Context::subscribe`], [`Context::listener`] and
27/// [`Context::spawn`].
28///
29/// Use the context of the entity you're changing for anything about that entity, and use
30/// `&mut App` for work that spans the application. See
31/// [contexts](crate::_documentation::concepts::contexts) for when you get each kind of context.
32///
33/// # Examples
34///
35/// ```
36/// # use gpui::{AppContext, Context, TestApp};
37/// struct Clock {
38///     ticks: u64,
39/// }
40///
41/// impl Clock {
42///     fn tick(&mut self, cx: &mut Context<Self>) {
43///         self.ticks += 1;
44///         cx.notify();
45///     }
46/// }
47///
48/// # let mut app = TestApp::new();
49/// # app.update(|cx| {
50/// let clock = cx.new(|_cx| Clock { ticks: 0 });
51/// clock.update(cx, |clock, cx| clock.tick(cx));
52/// assert_eq!(clock.read(cx).ticks, 1);
53/// # });
54/// ```
55pub struct Context<'a, T> {
56    app: &'a mut App,
57    entity_state: WeakEntity<T>,
58}
59
60impl<'a, T> ops::Deref for Context<'a, T> {
61    type Target = App;
62
63    fn deref(&self) -> &Self::Target {
64        self.app
65    }
66}
67
68impl<'a, T> ops::DerefMut for Context<'a, T> {
69    fn deref_mut(&mut self) -> &mut Self::Target {
70        self.app
71    }
72}
73
74impl<'a, T: 'static> Context<'a, T> {
75    pub(crate) fn new_context(app: &'a mut App, entity_state: WeakEntity<T>) -> Self {
76        Self { app, entity_state }
77    }
78
79    /// Returns the id of the entity this context works on.
80    pub fn entity_id(&self) -> EntityId {
81        self.entity_state.entity_id
82    }
83
84    /// Returns a strong handle to the entity this context works on.
85    ///
86    /// The handle keeps the entity alive. Use [`Context::weak_entity`] when a callback should not
87    /// keep it alive.
88    pub fn entity(&self) -> Entity<T> {
89        self.weak_entity()
90            .upgrade()
91            .expect("The entity must be alive if we have a entity context")
92    }
93
94    /// Returns a weak handle to the entity this context works on.
95    ///
96    /// Store the weak handle in callbacks and tasks that can outlive the current update. Upgrade it
97    /// when you need the entity, and handle the case where it has been released.
98    pub fn weak_entity(&self) -> WeakEntity<T> {
99        self.entity_state.clone()
100    }
101
102    /// Calls `on_notify` whenever `entity` calls [`Context::notify`].
103    ///
104    /// Use this to keep one entity in step with another. When `entity` changes, your callback can
105    /// read it and update your own state. The callback receives this entity mutably, a handle to the
106    /// observed entity, and a context for this entity. It runs after the update that called `notify`
107    /// finishes. Several notifications before that point deliver the callback once.
108    ///
109    /// The callback stays registered while the returned [`Subscription`] is alive. Keep it in a field
110    /// so the callback lasts as long as your entity, or call [`Subscription::detach`] to keep it for as
111    /// long as both entities exist. Once this entity is released, the callback is never called again.
112    ///
113    /// # Examples
114    ///
115    /// ```
116    /// # use gpui::{AppContext, Context, TestApp};
117    /// struct Counter {
118    ///     count: usize,
119    /// }
120    ///
121    /// struct Label {
122    ///     text: String,
123    /// }
124    ///
125    /// # let mut app = TestApp::new();
126    /// # let (counter, label) = app.update(|cx| {
127    /// let counter = cx.new(|_cx| Counter { count: 0 });
128    /// let label = cx.new(|cx: &mut Context<Label>| {
129    ///     cx.observe(&counter, |label, counter, cx| {
130    ///         label.text = counter.read(cx).count.to_string();
131    ///     })
132    ///     .detach();
133    ///     Label { text: String::new() }
134    /// });
135    /// (counter, label)
136    /// # });
137    /// # app.update(|cx| {
138    /// counter.update(cx, |counter, cx| {
139    ///     counter.count = 21;
140    ///     cx.notify();
141    /// });
142    /// # });
143    /// # app.read(|cx| assert_eq!(label.read(cx).text, "21"));
144    /// ```
145    ///
146    /// See [ownership and data flow](crate::_documentation::concepts::ownership).
147    pub fn observe<W>(
148        &mut self,
149        entity: &Entity<W>,
150        mut on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<T>) + 'static,
151    ) -> Subscription
152    where
153        T: 'static,
154        W: 'static,
155    {
156        let observer = self.weak_entity();
157        self.app.observe_internal(entity, move |entity, cx| {
158            invoke_observer(&observer, entity, cx, &mut on_notify)
159        })
160    }
161
162    /// Calls `on_event` whenever this entity calls [`Context::notify`].
163    ///
164    /// It runs after the update that called `notify` finishes. Keep the returned
165    /// [`Subscription`] alive for as long as you want the callback to run.
166    pub fn observe_self(
167        &mut self,
168        mut on_event: impl FnMut(&mut T, &mut Context<T>) + 'static,
169    ) -> Subscription
170    where
171        T: 'static,
172    {
173        let this = self.entity();
174        self.app.observe(&this, move |this, cx| {
175            this.update(cx, |this, cx| on_event(this, cx))
176        })
177    }
178
179    /// Calls `on_event` whenever `entity` emits an event of type `Evt`.
180    ///
181    /// The emitting entity must implement [`EventEmitter<Evt>`](crate::EventEmitter). Events are
182    /// delivered after the update that emitted them finishes, in the order they were emitted. Each event
183    /// type needs its own subscription. The callback receives this entity mutably, a handle to the
184    /// emitting entity, the event, and a context for this entity.
185    ///
186    /// Keep the returned [`Subscription`] in a field, or call [`Subscription::detach`] to keep the
187    /// callback for as long as both entities exist.
188    ///
189    /// # Examples
190    ///
191    /// ```
192    /// # use gpui::{AppContext, Context, EventEmitter, TestApp};
193    /// struct Downloader;
194    ///
195    /// enum DownloadEvent {
196    ///     Finished { bytes: usize },
197    /// }
198    ///
199    /// impl EventEmitter<DownloadEvent> for Downloader {}
200    ///
201    /// struct StatusBar {
202    ///     message: String,
203    /// }
204    ///
205    /// # let mut app = TestApp::new();
206    /// # let (downloader, status) = app.update(|cx| {
207    /// let downloader = cx.new(|_cx| Downloader);
208    ///
209    /// let status = cx.new(|cx: &mut Context<StatusBar>| {
210    ///     cx.subscribe(&downloader, |status, _downloader, event: &DownloadEvent, _cx| match event {
211    ///         DownloadEvent::Finished { bytes } => {
212    ///             status.message = format!("Downloaded {bytes} bytes");
213    ///         }
214    ///     })
215    ///     .detach();
216    ///     StatusBar { message: String::new() }
217    /// });
218    /// (downloader, status)
219    /// # });
220    /// # app.update(|cx| {
221    /// downloader.update(cx, |_downloader, cx| {
222    ///     cx.emit(DownloadEvent::Finished { bytes: 512 });
223    /// });
224    /// # });
225    /// # app.read(|cx| assert_eq!(status.read(cx).message, "Downloaded 512 bytes"));
226    /// ```
227    pub fn subscribe<T2, Evt>(
228        &mut self,
229        entity: &Entity<T2>,
230        mut on_event: impl FnMut(&mut T, Entity<T2>, &Evt, &mut Context<T>) + 'static,
231    ) -> Subscription
232    where
233        T: 'static,
234        T2: 'static + EventEmitter<Evt>,
235        Evt: 'static,
236    {
237        let subscriber = self.weak_entity();
238        self.app
239            .subscribe_internal(entity, move |entity, event, cx| {
240                invoke_subscriber(&subscriber, entity, event, cx, &mut on_event)
241            })
242    }
243
244    /// Calls `on_event` whenever this entity emits an event of type `Evt`.
245    ///
246    /// This is [`Context::subscribe`] for events that this entity emits itself. Keep the returned
247    /// [`Subscription`] alive for as long as you want the callback to run.
248    pub fn subscribe_self<Evt>(
249        &mut self,
250        mut on_event: impl FnMut(&mut T, &Evt, &mut Context<T>) + 'static,
251    ) -> Subscription
252    where
253        T: 'static + EventEmitter<Evt>,
254        Evt: 'static,
255    {
256        let this = self.entity();
257        self.app.subscribe(&this, move |this, evt, cx| {
258            this.update(cx, |this, cx| on_event(this, evt, cx))
259        })
260    }
261
262    /// Calls `on_release` when GPUI releases this entity.
263    ///
264    /// GPUI releases an entity at the end of the update in which its last strong handle was dropped.
265    /// The callback runs then, while the value still exists, and receives it mutably together with the
266    /// app. Use it to tear down resources the entity holds outside GPUI.
267    ///
268    /// The callback stays registered while the returned [`Subscription`] is alive. Dropping the
269    /// subscription cancels the callback. Call [`Subscription::detach`] to keep it until the entity is
270    /// released.
271    pub fn on_release(&self, on_release: impl FnOnce(&mut T, &mut App) + 'static) -> Subscription
272    where
273        T: 'static,
274    {
275        let (subscription, activate) = self.app.release_listeners.insert(
276            self.entity_state.entity_id,
277            Box::new(move |this, cx| {
278                let this = this.downcast_mut().expect("invalid entity type");
279                on_release(this, cx);
280            }),
281        );
282        activate();
283        subscription
284    }
285
286    /// Calls `on_release` when `entity` is released.
287    ///
288    /// The callback receives this entity mutably and the released value. It doesn't run if this entity
289    /// has been released too. The callback stays registered while the returned [`Subscription`] is
290    /// alive.
291    pub fn observe_release<T2>(
292        &self,
293        entity: &Entity<T2>,
294        on_release: impl FnOnce(&mut T, &mut T2, &mut Context<T>) + 'static,
295    ) -> Subscription
296    where
297        T: Any,
298        T2: 'static,
299    {
300        let entity_id = entity.entity_id();
301        let this = self.weak_entity();
302        let (subscription, activate) = self.app.release_listeners.insert(
303            entity_id,
304            Box::new(move |entity, cx| {
305                let entity = entity.downcast_mut().expect("invalid entity type");
306                if let Some(this) = this.upgrade() {
307                    this.update(cx, |this, cx| on_release(this, entity, cx));
308                }
309            }),
310        );
311        activate();
312        subscription
313    }
314
315    /// Calls `f` whenever the global of type `G` is set or updated.
316    ///
317    /// `f` runs after the update that changed the global finishes. It doesn't receive the value, so
318    /// read it with [`App::global`]. Keep the returned [`Subscription`] alive for as long as you want
319    /// the callback to run. To also receive a window, use [`Context::observe_global_in`].
320    pub fn observe_global<G: 'static>(
321        &mut self,
322        mut f: impl FnMut(&mut T, &mut Context<T>) + 'static,
323    ) -> Subscription
324    where
325        T: 'static,
326    {
327        let handle = self.weak_entity();
328        let (subscription, activate) = self.global_observers.insert(
329            TypeId::of::<G>(),
330            Box::new(move |cx| handle.update(cx, |view, cx| f(view, cx)).is_ok()),
331        );
332        self.defer(move |_| activate());
333        subscription
334    }
335
336    /// Calls `on_restart` when the application is about to restart.
337    ///
338    /// The callback doesn't run if this entity has been released. Keep the returned [`Subscription`]
339    /// alive for as long as you want the callback to run.
340    pub fn on_app_restart(
341        &self,
342        mut on_restart: impl FnMut(&mut T, &mut App) + 'static,
343    ) -> Subscription
344    where
345        T: 'static,
346    {
347        let handle = self.weak_entity();
348        self.app.on_app_restart(move |cx| {
349            handle.update(cx, |entity, cx| on_restart(entity, cx)).ok();
350        })
351    }
352
353    /// Calls `on_quit` when the application quits, and waits for the future it returns.
354    ///
355    /// GPUI polls the returned future for up to [`SHUTDOWN_TIMEOUT`](crate::SHUTDOWN_TIMEOUT) while the
356    /// app quits. Use this to save state before the process exits. The callback doesn't run if this
357    /// entity has been released.
358    pub fn on_app_quit<Fut>(
359        &self,
360        mut on_quit: impl FnMut(&mut T, &mut Context<T>) -> Fut + 'static,
361    ) -> Subscription
362    where
363        Fut: 'static + Future<Output = ()>,
364        T: 'static,
365    {
366        let handle = self.weak_entity();
367        self.app.on_app_quit(move |cx| {
368            let future = handle.update(cx, |entity, cx| on_quit(entity, cx)).ok();
369            async move {
370                if let Some(future) = future {
371                    future.await;
372                }
373            }
374            .boxed_local()
375        })
376    }
377
378    /// Marks this entity as changed, so that the windows showing it are redrawn and its observers are
379    /// called.
380    ///
381    /// GPUI doesn't watch your fields: call `notify` after changing state that affects rendering or that
382    /// observers registered with [`Context::observe`] care about. The effects run when the current
383    /// update finishes, not during this call, and several notifications in one update are delivered
384    /// once.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// # use gpui::{AppContext, Context, TestApp};
390    /// struct Counter {
391    ///     count: usize,
392    /// }
393    ///
394    /// impl Counter {
395    ///     fn increment(&mut self, cx: &mut Context<Self>) {
396    ///         self.count += 1;
397    ///         cx.notify();
398    ///     }
399    /// }
400    ///
401    /// # let mut app = TestApp::new();
402    /// # let counter = app.update(|cx| cx.new(|_| Counter { count: 0 }));
403    /// # app.update(|cx| counter.update(cx, |counter, cx| counter.increment(cx)));
404    /// # app.read(|cx| assert_eq!(counter.read(cx).count, 1));
405    /// ```
406    ///
407    /// See [ownership and data flow](crate::_documentation::concepts::ownership).
408    pub fn notify(&mut self) {
409        self.app.notify(self.entity_state.entity_id);
410    }
411
412    /// Runs the future returned by `f` on the main thread, with a weak handle to this entity.
413    ///
414    /// `f` receives a [`WeakEntity<T>`] for this entity and an [`AsyncApp`]. Use the weak handle to
415    /// reach the entity after an `.await`. Its `update` returns an error if the entity has been released
416    /// in the meantime. Use the [`AsyncApp`] to reach the rest of the app.
417    ///
418    /// The returned [`Task`] cancels the future when it's dropped. Keep it in a field to cancel the work
419    /// when this entity changes, or call [`Task::detach`] to let it continue after the local handle
420    /// is gone. Detaching does not guarantee completion during shutdown. For work that needs a
421    /// window, use [`Context::spawn_in`]. Use [`AppContext::background_spawn`] inside the future
422    /// for work on the background executor; see [`BackgroundExecutor`](crate::BackgroundExecutor)
423    /// for platform differences.
424    ///
425    /// # Examples
426    ///
427    /// ```
428    /// # use gpui::{AppContext, Context, TestApp};
429    /// struct Search {
430    ///     results: Vec<String>,
431    /// }
432    ///
433    /// impl Search {
434    ///     fn run(&mut self, query: String, cx: &mut Context<Self>) {
435    ///         cx.spawn(async move |search, cx| {
436    ///             // A real app would await a network request here.
437    ///             let results = vec![format!("result for {query}")];
438    ///             search
439    ///                 .update(cx, |search, cx| {
440    ///                     search.results = results;
441    ///                     cx.notify();
442    ///                 })
443    ///                 .ok();
444    ///         })
445    ///         .detach();
446    ///     }
447    /// }
448    ///
449    /// # let mut app = TestApp::new();
450    /// # let search = app.update(|cx| cx.new(|_cx| Search { results: Vec::new() }));
451    /// app.update(|cx| {
452    ///     search.update(cx, |search, cx| search.run("gpui".to_string(), cx));
453    /// });
454    /// // `TestApp::update` runs the task before it returns.
455    /// app.read(|cx| assert_eq!(search.read(cx).results[0], "result for gpui"));
456    /// ```
457    ///
458    /// See [async work](crate::_documentation::guides::async_work).
459    #[track_caller]
460    #[inline(always)]
461    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
462    where
463        T: 'static,
464        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncApp) -> R + 'static,
465        R: 'static,
466    {
467        let this = self.weak_entity();
468        self.app.spawn(async move |cx| f(this, cx).await)
469    }
470
471    /// Wraps `f` in an event handler that receives this entity mutably.
472    ///
473    /// Element event handlers receive the event, a [`Window`] and an [`App`], but not your entity.
474    /// `listener` returns a handler that calls `f` with the entity, the event, the window and a context
475    /// for the entity. Pass the result to an element's handler method, such as `on_click`.
476    ///
477    /// The handler holds a weak handle to the entity, so an element that is still registered doesn't
478    /// keep its view alive. If the entity has been released, the handler does nothing. Call
479    /// [`Context::notify`] inside `f` to redraw the window after you change state.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use gpui::{Context, MouseButton, TestApp, Window, div, point, prelude::*, px};
485    ///
486    /// struct Counter {
487    ///     count: usize,
488    /// }
489    ///
490    /// impl Render for Counter {
491    ///     fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
492    ///         div()
493    ///             .id("button")
494    ///             .size_full()
495    ///             .on_click(cx.listener(|counter, _event, _window, cx| {
496    ///                 counter.count += 1;
497    ///                 cx.notify();
498    ///             }))
499    ///     }
500    /// }
501    ///
502    /// let mut app = TestApp::new();
503    /// let mut window = app.open_window(|_window, _cx| Counter { count: 0 });
504    ///
505    /// window.simulate_click(point(px(10.), px(10.)), MouseButton::Left);
506    /// window.simulate_click(point(px(10.), px(10.)), MouseButton::Left);
507    ///
508    /// assert_eq!(window.read(|counter, _cx| counter.count), 2);
509    /// ```
510    ///
511    /// See [ownership and data flow](crate::_documentation::concepts::ownership).
512    #[inline(always)]
513    pub fn listener<E: ?Sized>(
514        &self,
515        listener: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
516    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
517        let view = self.entity().downgrade();
518        move |event: &E, window: &mut Window, cx: &mut App| {
519            invoke_listener(&view, window, cx, &|view, window, cx| {
520                listener(view, event, window, cx);
521            });
522        }
523    }
524
525    /// Wraps `f` in a closure that receives this entity mutably and returns a value.
526    ///
527    /// Use this when the caller needs the handler's return value. For event handlers, prefer
528    /// [`Context::listener`]. The returned closure holds a strong handle to this entity, so it
529    /// keeps the entity alive for as long as the closure exists.
530    pub fn processor<E, R>(
531        &self,
532        f: impl Fn(&mut T, E, &mut Window, &mut Context<T>) -> R + 'static,
533    ) -> impl Fn(E, &mut Window, &mut App) -> R + 'static {
534        let view = self.entity();
535        move |e: E, window: &mut Window, cx: &mut App| {
536            view.update(cx, |view, cx| f(view, e, window, cx))
537        }
538    }
539
540    /// Returns a guard that calls `f` with this entity when the guard is dropped.
541    ///
542    /// The guard is returned as a `Deferred`. Call `abort` on it to cancel the callback. If the entity
543    /// has been released by the time the guard is dropped, `f` doesn't run.
544    ///
545    /// # Panics
546    ///
547    /// Panics if the guard is dropped while the app is already borrowed, for example inside another
548    /// update of the same app, and the entity is still alive. Drop the guard from a later update instead.
549    pub fn on_drop(
550        &self,
551        f: impl FnOnce(&mut T, &mut Context<T>) + 'static,
552    ) -> Deferred<impl FnOnce()> {
553        let this = self.weak_entity();
554        let mut cx = self.to_async();
555        gpui_util::defer(move || {
556            this.update(&mut cx, f).ok();
557        })
558    }
559
560    /// Focuses `view` in `window`.
561    ///
562    /// `W` must implement [`Focusable`]. The focus change uses the focus handle that `view` returns.
563    pub fn focus_view<W: Focusable>(&mut self, view: &Entity<W>, window: &mut Window) {
564        window.focus(&view.focus_handle(self), self);
565    }
566
567    /// Runs `f` with this entity and `window` on the next frame of `window`.
568    ///
569    /// The callback runs once, during the next frame. It doesn't run if this entity has been released.
570    pub fn on_next_frame(
571        &self,
572        window: &mut Window,
573        f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
574    ) where
575        T: 'static,
576    {
577        let view = self.entity();
578        window.on_next_frame(move |window, cx| view.update(cx, |view, cx| f(view, window, cx)));
579    }
580
581    /// Runs `f` with this entity and `window` at the end of the current effect cycle.
582    ///
583    /// Use it to change this entity from code that is still on the stack, such as a method called from
584    /// inside this entity's own update. The callback runs after the outermost update finishes, when the
585    /// entity is no longer borrowed. It doesn't run if this entity has been released.
586    pub fn defer_in(
587        &mut self,
588        window: &Window,
589        f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
590    ) {
591        let view = self.weak_entity();
592        let entity_id = self.entity_id();
593        self.ensure_window(entity_id, window.handle.id);
594        self.app.defer(move |cx| {
595            cx.with_window(entity_id, |window, cx| {
596                view.update(cx, |view, cx| f(view, window, cx)).ok();
597            });
598        });
599    }
600
601    /// Calls `on_notify` when `observed` calls [`Context::notify`], and passes it the window.
602    ///
603    /// Pass the window that displays this entity. If that window has been closed, the callback
604    /// does not run.
605    pub fn observe_in<V2>(
606        &mut self,
607        observed: &Entity<V2>,
608        window: &mut Window,
609        mut on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<T>) + 'static,
610    ) -> Subscription
611    where
612        V2: 'static,
613        T: 'static,
614    {
615        let observed_id = observed.entity_id();
616        let observed = observed.downgrade();
617        let observer = self.weak_entity();
618        let observer_id = self.entity_id();
619        self.ensure_window(observer_id, window.handle.id);
620        self.new_observer(
621            observed_id,
622            Box::new(move |cx| invoke_observer_in(&observer, &observed, cx, &mut on_notify)),
623        )
624    }
625
626    /// Calls `on_event` when `emitter` emits an event of type `Evt`, and passes it the window.
627    ///
628    /// Pass the window that displays this entity. If that window has been closed, the callback
629    /// does not run.
630    pub fn subscribe_in<Emitter, Evt>(
631        &mut self,
632        emitter: &Entity<Emitter>,
633        window: &Window,
634        mut on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<T>) + 'static,
635    ) -> Subscription
636    where
637        Emitter: EventEmitter<Evt>,
638        Evt: 'static,
639    {
640        let emitter = emitter.downgrade();
641        let subscriber = self.weak_entity();
642        let subscriber_id = self.entity_id();
643        self.ensure_window(subscriber_id, window.handle.id);
644        self.new_subscription(
645            emitter.entity_id(),
646            (
647                TypeId::of::<Evt>(),
648                Box::new(move |event, cx| {
649                    invoke_subscriber_in(&subscriber, &emitter, event, cx, &mut on_event)
650                }),
651            ),
652        )
653    }
654
655    /// Calls `on_release` with the window when this entity is released.
656    ///
657    /// The callback doesn't run if the window was closed before this entity was released.
658    pub fn on_release_in(
659        &mut self,
660        window: &Window,
661        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
662    ) -> Subscription {
663        let entity = self.entity();
664        self.app.observe_release_in(&entity, window, on_release)
665    }
666
667    /// Calls `on_release` when `observed` is released, and passes it the window.
668    ///
669    /// The callback does not run if `window` has been closed, or if this entity has been released.
670    pub fn observe_release_in<T2>(
671        &self,
672        observed: &Entity<T2>,
673        window: &Window,
674        mut on_release: impl FnMut(&mut T, &mut T2, &mut Window, &mut Context<T>) + 'static,
675    ) -> Subscription
676    where
677        T: 'static,
678        T2: 'static,
679    {
680        let observer = self.weak_entity();
681        self.app
682            .observe_release_in(observed, window, move |observed, window, cx| {
683                observer
684                    .update(cx, |observer, cx| {
685                        on_release(observer, observed, window, cx)
686                    })
687                    .ok();
688            })
689    }
690
691    /// Calls `callback` when the bounds of `window` change.
692    ///
693    /// Keep the returned [`Subscription`] alive for as long as you want the callback to run. The callback
694    /// stops once this entity is released.
695    pub fn observe_window_bounds(
696        &self,
697        window: &mut Window,
698        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
699    ) -> Subscription {
700        let view = self.weak_entity();
701        let (subscription, activate) = window.bounds_observers.insert(
702            (),
703            Box::new(move |window, cx| {
704                view.update(cx, |view, cx| callback(view, window, cx))
705                    .is_ok()
706            }),
707        );
708        activate();
709        subscription
710    }
711
712    /// Calls `callback` when `window` becomes active or inactive.
713    ///
714    /// Keep the returned [`Subscription`] alive for as long as you want the callback to run. The callback
715    /// stops once this entity is released.
716    pub fn observe_window_activation(
717        &self,
718        window: &mut Window,
719        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
720    ) -> Subscription {
721        let view = self.weak_entity();
722        let (subscription, activate) = window.activation_observers.insert(
723            (),
724            Box::new(move |window, cx| {
725                view.update(cx, |view, cx| callback(view, window, cx))
726                    .is_ok()
727            }),
728        );
729        activate();
730        subscription
731    }
732
733    /// Registers a callback to be invoked when the window's visibility changes
734    /// (see [`WindowVisibility`]).
735    pub fn observe_window_visibility(
736        &self,
737        window: &mut Window,
738        mut callback: impl FnMut(&mut T, WindowVisibility, &mut Window, &mut Context<T>) + 'static,
739    ) -> Subscription {
740        let view = self.weak_entity();
741        let (subscription, activate) = window.visibility_observers.insert(
742            (),
743            Box::new(move |visibility, window, cx| {
744                view.update(cx, |view, cx| callback(view, visibility, window, cx))
745                    .is_ok()
746            }),
747        );
748        activate();
749        subscription
750    }
751
752    /// Calls `callback` when the system appearance changes between light and dark.
753    ///
754    /// Keep the returned [`Subscription`] alive for as long as you want the callback to run. The callback
755    /// stops once this entity is released.
756    pub fn observe_window_appearance(
757        &self,
758        window: &mut Window,
759        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
760    ) -> Subscription {
761        let view = self.weak_entity();
762        let (subscription, activate) = window.appearance_observers.insert(
763            (),
764            Box::new(move |window, cx| {
765                view.update(cx, |view, cx| callback(view, window, cx))
766                    .is_ok()
767            }),
768        );
769        activate();
770        subscription
771    }
772
773    /// Registers a callback invoked when the window moves to another display
774    /// or its display's refresh interval changes. See
775    /// [`Window::observe_window_display`].
776    pub fn observe_window_display(
777        &self,
778        window: &mut Window,
779        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
780    ) -> Subscription {
781        let view = self.weak_entity();
782        let (subscription, activate) = window.display_observers.insert(
783            (),
784            Box::new(move |window, cx| {
785                view.update(cx, |view, cx| callback(view, window, cx))
786                    .is_ok()
787            }),
788        );
789        activate();
790        subscription
791    }
792
793    /// Calls `callback` when the window's titlebar button layout changes.
794    ///
795    /// Keep the returned [`Subscription`] alive for as long as you want the callback to run. The callback
796    /// stops once this entity is released.
797    pub fn observe_button_layout_changed(
798        &self,
799        window: &mut Window,
800        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
801    ) -> Subscription {
802        let view = self.weak_entity();
803        let (subscription, activate) = window.button_layout_observers.insert(
804            (),
805            Box::new(move |window, cx| {
806                view.update(cx, |view, cx| callback(view, window, cx))
807                    .is_ok()
808            }),
809        );
810        activate();
811        subscription
812    }
813
814    /// Calls `f` with this entity for each keystroke that [`App::observe_keystrokes`] observes.
815    ///
816    /// The keystroke's `action` is set when a key binding handled it. Keep the returned
817    /// [`Subscription`] alive for as long as you want the callback to run.
818    pub fn observe_keystrokes(
819        &mut self,
820        mut f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<T>) + 'static,
821    ) -> Subscription {
822        fn inner(
823            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
824            handler: KeystrokeObserver,
825        ) -> Subscription {
826            let (subscription, activate) = keystroke_observers.insert((), handler);
827            activate();
828            subscription
829        }
830
831        let view = self.weak_entity();
832        inner(
833            &self.keystroke_observers,
834            Box::new(move |event, window, cx| {
835                if let Some(view) = view.upgrade() {
836                    view.update(cx, |view, cx| f(view, event, window, cx));
837                    true
838                } else {
839                    false
840                }
841            }),
842        )
843    }
844
845    /// Calls `callback` when the pending input of `window` changes.
846    ///
847    /// Pending input is a partly typed key sequence, such as the first key of a multi-key binding. The
848    /// callback runs when the sequence starts, grows, or is cleared. Keep the returned [`Subscription`]
849    /// alive for as long as you want the callback to run.
850    pub fn observe_pending_input(
851        &self,
852        window: &mut Window,
853        mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
854    ) -> Subscription {
855        let view = self.weak_entity();
856        let (subscription, activate) = window.pending_input_observers.insert(
857            (),
858            Box::new(move |window, cx| {
859                view.update(cx, |view, cx| callback(view, window, cx))
860                    .is_ok()
861            }),
862        );
863        activate();
864        subscription
865    }
866
867    /// Calls `listener` when `handle` becomes the focused element.
868    ///
869    /// The listener doesn't run when focus moves into a descendant of `handle`. Use [`Context::on_focus_in`]
870    /// to hear about that as well. Keep the returned [`Subscription`] alive for as long as you want the
871    /// listener to run.
872    pub fn on_focus(
873        &mut self,
874        handle: &FocusHandle,
875        window: &mut Window,
876        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
877    ) -> Subscription {
878        let view = self.weak_entity();
879        let focus_id = handle.id;
880        let (subscription, activate) =
881            window.new_focus_listener(Box::new(move |event, window, cx| {
882                view.update(cx, |view, cx| {
883                    if event.previous_focus_path.last() != Some(&focus_id)
884                        && event.current_focus_path.last() == Some(&focus_id)
885                    {
886                        listener(view, window, cx)
887                    }
888                })
889                .is_ok()
890            }));
891        self.defer(|_| activate());
892        subscription
893    }
894
895    /// Calls `listener` when focus moves into `handle` or one of its descendants.
896    ///
897    /// The listener doesn't run when focus was already inside `handle` and moves to another descendant.
898    /// Keep the returned [`Subscription`] alive for as long as you want the listener to run.
899    pub fn on_focus_in(
900        &mut self,
901        handle: &FocusHandle,
902        window: &mut Window,
903        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
904    ) -> Subscription {
905        let view = self.weak_entity();
906        let focus_id = handle.id;
907        let (subscription, activate) =
908            window.new_focus_listener(Box::new(move |event, window, cx| {
909                view.update(cx, |view, cx| {
910                    if event.is_focus_in(focus_id) {
911                        listener(view, window, cx)
912                    }
913                })
914                .is_ok()
915            }));
916        self.defer(|_| activate());
917        subscription
918    }
919
920    /// Calls `listener` when `handle` stops being the focused element.
921    ///
922    /// The listener also runs when focus moves from `handle` to one of its descendants, since `handle`
923    /// is no longer the focused element. Use [`Context::on_focus_out`] to hear only about focus leaving
924    /// `handle` and its descendants. Keep the returned [`Subscription`] alive for as long as you want the
925    /// listener to run.
926    pub fn on_blur(
927        &mut self,
928        handle: &FocusHandle,
929        window: &mut Window,
930        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
931    ) -> Subscription {
932        let view = self.weak_entity();
933        let focus_id = handle.id;
934        let (subscription, activate) =
935            window.new_focus_listener(Box::new(move |event, window, cx| {
936                view.update(cx, |view, cx| {
937                    if event.previous_focus_path.last() == Some(&focus_id)
938                        && event.current_focus_path.last() != Some(&focus_id)
939                    {
940                        listener(view, window, cx)
941                    }
942                })
943                .is_ok()
944            }));
945        self.defer(|_| activate());
946        subscription
947    }
948
949    /// Calls `listener` when no element in `window` has focus.
950    ///
951    /// This happens when the focused element is removed from the tree. Use it to move focus to a sensible
952    /// default. Keep the returned [`Subscription`] alive for as long as you want the listener to run.
953    pub fn on_focus_lost(
954        &mut self,
955        window: &mut Window,
956        mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
957    ) -> Subscription {
958        let view = self.weak_entity();
959        let (subscription, activate) = window.focus_lost_listeners.insert(
960            (),
961            Box::new(move |window, cx| {
962                view.update(cx, |view, cx| listener(view, window, cx))
963                    .is_ok()
964            }),
965        );
966        self.defer(|_| activate());
967        subscription
968    }
969
970    /// Calls `listener` when focus leaves `handle` or one of its descendants.
971    ///
972    /// The listener receives a [`FocusOutEvent`] that says which element lost focus. Keep the returned
973    /// [`Subscription`] alive for as long as you want the listener to run.
974    pub fn on_focus_out(
975        &mut self,
976        handle: &FocusHandle,
977        window: &mut Window,
978        mut listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<T>) + 'static,
979    ) -> Subscription {
980        let view = self.weak_entity();
981        let focus_id = handle.id;
982        let (subscription, activate) =
983            window.new_focus_listener(Box::new(move |event, window, cx| {
984                view.update(cx, |view, cx| {
985                    if let Some(blurred_id) = event.previous_focus_path.last().copied()
986                        && event.is_focus_out(focus_id)
987                    {
988                        let event = FocusOutEvent {
989                            blurred: WeakFocusHandle {
990                                id: blurred_id,
991                                handles: Arc::downgrade(&cx.focus_handles),
992                            },
993                        };
994                        listener(view, event, window, cx)
995                    }
996                })
997                .is_ok()
998            }));
999        self.defer(|_| activate());
1000        subscription
1001    }
1002
1003    /// Runs the future returned by `f` on the main thread, with a weak handle to this entity and a window
1004    /// context.
1005    ///
1006    /// `f` receives an [`AsyncWindowContext`] for `window`, so the future can reach it after an
1007    /// `.await`. Window operations through the context return errors once the window has closed.
1008    ///
1009    /// The returned [`Task`] cancels the future when it's dropped. Call [`Task::detach`] to let the future
1010    /// run to completion.
1011    #[track_caller]
1012    #[inline(always)]
1013    pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R>
1014    where
1015        R: 'static,
1016        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
1017    {
1018        let view = self.weak_entity();
1019        window.spawn(self, async move |cx| f(view, cx).await)
1020    }
1021
1022    /// Runs the future returned by `f` on the main thread at `priority`, with a weak handle to this entity
1023    /// and a window context.
1024    ///
1025    /// The returned [`Task`] cancels the future when it is dropped.
1026    #[track_caller]
1027    #[inline(always)]
1028    pub fn spawn_in_with_priority<AsyncFn, R>(
1029        &self,
1030        priority: Priority,
1031        window: &Window,
1032        f: AsyncFn,
1033    ) -> Task<R>
1034    where
1035        R: 'static,
1036        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
1037    {
1038        let view = self.weak_entity();
1039        window.spawn_with_priority(priority, self, async move |cx| f(view, cx).await)
1040    }
1041
1042    /// Calls `f` with the window whenever the global of type `G` is set or updated.
1043    ///
1044    /// Pass the window this entity is shown in. If that window is unavailable, for example during a nested
1045    /// update of it, the callback is skipped for that change and stays registered. The callback stops
1046    /// once this entity is released.
1047    pub fn observe_global_in<G: Global>(
1048        &mut self,
1049        window: &Window,
1050        mut f: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
1051    ) -> Subscription {
1052        let window_handle = window.handle;
1053        let view = self.weak_entity();
1054        let (subscription, activate) = self.global_observers.insert(
1055            TypeId::of::<G>(),
1056            Box::new(move |cx| {
1057                // If the entity has been dropped, remove this observer.
1058                if view.upgrade().is_none() {
1059                    return false;
1060                }
1061                // If the window is unavailable (e.g. temporarily taken during a
1062                // nested update, or already closed), skip this notification but
1063                // keep the observer alive so it can fire on future changes.
1064                let Ok(entity_alive) = window_handle.update(cx, |_, window, cx| {
1065                    view.update(cx, |view, cx| f(view, window, cx)).is_ok()
1066                }) else {
1067                    return true;
1068                };
1069                entity_alive
1070            }),
1071        );
1072        self.defer(move |_| activate());
1073        subscription
1074    }
1075
1076    /// Calls `listener` when an action of type `action_type` is dispatched to `window`.
1077    ///
1078    /// Pass `TypeId::of::<A>()` for the action type `A`. The listener receives the action as `&dyn Any`
1079    /// together with the [`DispatchPhase`], so it can tell capture from bubble. It also gets the window and
1080    /// a context for this entity.
1081    ///
1082    /// Like [`Window::on_action`], the listener is registered for the next frame only. Call this during
1083    /// paint, on every frame that should handle the action.
1084    pub fn on_action(
1085        &mut self,
1086        action_type: TypeId,
1087        window: &mut Window,
1088        listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<T>) + 'static,
1089    ) {
1090        let handle = self.weak_entity();
1091        window.on_action(action_type, move |action, phase, window, cx| {
1092            handle
1093                .update(cx, |view, cx| {
1094                    listener(view, action, phase, window, cx);
1095                })
1096                .ok();
1097        });
1098    }
1099
1100    /// Focuses this entity's focus handle in `window`.
1101    ///
1102    /// This entity must implement [`Focusable`]. The focus change happens at the end of the current effect
1103    /// cycle.
1104    pub fn focus_self(&mut self, window: &mut Window)
1105    where
1106        T: Focusable,
1107    {
1108        let view = self.entity();
1109        window.defer(self, move |window, cx| {
1110            view.read(cx).focus_handle(cx).focus(window, cx)
1111        })
1112    }
1113}
1114
1115impl<T> Context<'_, T> {
1116    /// Emits `event` from this entity to its subscribers.
1117    ///
1118    /// Subscribers registered with [`Context::subscribe`] or [`App::subscribe`] for this event type
1119    /// receive it after the current update finishes, in the order the events were emitted. Emitting an
1120    /// event that nobody subscribed to does nothing. This entity must implement [`EventEmitter<Evt>`](crate::EventEmitter).
1121    ///
1122    /// # Examples
1123    ///
1124    /// ```
1125    /// # use gpui::{AppContext, Context, EventEmitter, TestApp};
1126    /// struct Button;
1127    ///
1128    /// struct Clicked {
1129    ///     times: usize,
1130    /// }
1131    ///
1132    /// impl EventEmitter<Clicked> for Button {}
1133    ///
1134    /// struct Tally {
1135    ///     clicks: usize,
1136    /// }
1137    ///
1138    /// # let mut app = TestApp::new();
1139    /// # let (button, tally) = app.update(|cx| {
1140    /// let button = cx.new(|_cx| Button);
1141    /// let tally = cx.new(|cx: &mut Context<Tally>| {
1142    ///     cx.subscribe(&button, |tally, _button, event: &Clicked, _cx| {
1143    ///         tally.clicks += event.times;
1144    ///     })
1145    ///     .detach();
1146    ///     Tally { clicks: 0 }
1147    /// });
1148    /// (button, tally)
1149    /// # });
1150    /// # app.update(|cx| {
1151    /// button.update(cx, |_button, cx| {
1152    ///     cx.emit(Clicked { times: 2 });
1153    ///     cx.emit(Clicked { times: 1 });
1154    /// });
1155    /// # });
1156    /// # app.read(|cx| assert_eq!(tally.read(cx).clicks, 3));
1157    /// ```
1158    ///
1159    /// See [ownership and data flow](crate::_documentation::concepts::ownership).
1160    pub fn emit<Evt>(&mut self, event: Evt)
1161    where
1162        T: EventEmitter<Evt>,
1163        Evt: 'static,
1164    {
1165        self.app.emit(&self.entity(), event);
1166    }
1167}
1168
1169impl<T> AppContext for Context<'_, T> {
1170    #[inline]
1171    fn new<U: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<U>) -> U) -> Entity<U> {
1172        self.app.new(build_entity)
1173    }
1174
1175    #[inline]
1176    fn reserve_entity<U: 'static>(&mut self) -> Reservation<U> {
1177        self.app.reserve_entity()
1178    }
1179
1180    #[inline]
1181    fn insert_entity<U: 'static>(
1182        &mut self,
1183        reservation: Reservation<U>,
1184        build_entity: impl FnOnce(&mut Context<U>) -> U,
1185    ) -> Entity<U> {
1186        self.app.insert_entity(reservation, build_entity)
1187    }
1188
1189    #[inline]
1190    fn update_entity<U: 'static, R>(
1191        &mut self,
1192        handle: &Entity<U>,
1193        update: impl FnOnce(&mut U, &mut Context<U>) -> R,
1194    ) -> R {
1195        self.app.update_entity(handle, update)
1196    }
1197
1198    #[inline]
1199    fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> super::GpuiBorrow<'a, E>
1200    where
1201        E: 'static,
1202    {
1203        self.app.as_mut(handle)
1204    }
1205
1206    #[inline]
1207    fn read_entity<U, R>(&self, handle: &Entity<U>, read: impl FnOnce(&U, &App) -> R) -> R
1208    where
1209        U: 'static,
1210    {
1211        self.app.read_entity(handle, read)
1212    }
1213
1214    #[inline]
1215    fn notify(&mut self, entity_id: EntityId) {
1216        self.app.notify(entity_id)
1217    }
1218
1219    #[inline]
1220    fn emit<EntityType, EventType>(&mut self, entity: &Entity<EntityType>, event: EventType)
1221    where
1222        EntityType: EventEmitter<EventType>,
1223        EventType: 'static,
1224    {
1225        self.app.emit(entity, event)
1226    }
1227
1228    #[inline]
1229    fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
1230    where
1231        F: FnOnce(AnyView, &mut Window, &mut App) -> R,
1232    {
1233        self.app.update_window(window, update)
1234    }
1235
1236    #[inline]
1237    fn with_window<R>(
1238        &mut self,
1239        entity_id: EntityId,
1240        f: impl FnOnce(&mut Window, &mut App) -> R,
1241    ) -> Option<R> {
1242        self.app.with_window(entity_id, f)
1243    }
1244
1245    #[inline]
1246    fn read_window<U, R>(
1247        &self,
1248        window: &WindowHandle<U>,
1249        read: impl FnOnce(Entity<U>, &App) -> R,
1250    ) -> Result<R>
1251    where
1252        U: 'static,
1253    {
1254        self.app.read_window(window, read)
1255    }
1256
1257    #[inline]
1258    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
1259    where
1260        R: Send + 'static,
1261    {
1262        self.app.background_executor.spawn(future)
1263    }
1264
1265    #[inline]
1266    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
1267    where
1268        G: Global,
1269    {
1270        self.app.read_global(callback)
1271    }
1272
1273    #[inline]
1274    fn insert_global_entity<E: 'static>(&mut self, entity: Entity<E>) {
1275        self.app.insert_global_entity(entity)
1276    }
1277
1278    #[inline]
1279    fn remove_global_entity<E: 'static>(&mut self, entity: &Entity<E>) {
1280        self.app.remove_global_entity(entity)
1281    }
1282
1283    #[inline]
1284    fn global_entities<E: 'static>(&self) -> impl Iterator<Item = Entity<E>> {
1285        self.app.global_entities()
1286    }
1287}
1288
1289impl<T> Borrow<App> for Context<'_, T> {
1290    fn borrow(&self) -> &App {
1291        self.app
1292    }
1293}
1294
1295impl<T> BorrowMut<App> for Context<'_, T> {
1296    fn borrow_mut(&mut self) -> &mut App {
1297        self.app
1298    }
1299}
1300
1301#[inline(never)]
1302fn invoke_observer<T: 'static, W: 'static>(
1303    observer: &WeakEntity<T>,
1304    observed: Entity<W>,
1305    cx: &mut App,
1306    on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Context<T>),
1307) -> bool {
1308    if let Some(observer) = observer.upgrade() {
1309        observer.update(cx, |observer, cx| on_notify(observer, observed, cx));
1310        true
1311    } else {
1312        false
1313    }
1314}
1315
1316#[inline(never)]
1317fn invoke_subscriber<T: 'static, Emitter: 'static, Event: 'static>(
1318    subscriber: &WeakEntity<T>,
1319    emitter: Entity<Emitter>,
1320    event: &Event,
1321    cx: &mut App,
1322    on_event: &mut dyn FnMut(&mut T, Entity<Emitter>, &Event, &mut Context<T>),
1323) -> bool {
1324    if let Some(subscriber) = subscriber.upgrade() {
1325        subscriber.update(cx, |subscriber, cx| {
1326            on_event(subscriber, emitter, event, cx)
1327        });
1328        true
1329    } else {
1330        false
1331    }
1332}
1333
1334#[inline(never)]
1335fn invoke_observer_in<T: 'static, W: 'static>(
1336    observer: &WeakEntity<T>,
1337    observed: &WeakEntity<W>,
1338    cx: &mut App,
1339    on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Window, &mut Context<T>),
1340) -> bool {
1341    let Some((observer, observed)) = observer.upgrade().zip(observed.upgrade()) else {
1342        return false;
1343    };
1344    cx.with_window(observer.entity_id(), |window, cx| {
1345        observer.update(cx, |observer, cx| {
1346            on_notify(observer, observed, window, cx);
1347        });
1348    });
1349    true
1350}
1351
1352#[inline(never)]
1353fn invoke_subscriber_in<T: 'static, Emitter: 'static, Event: 'static>(
1354    subscriber: &WeakEntity<T>,
1355    emitter: &WeakEntity<Emitter>,
1356    event: &dyn Any,
1357    cx: &mut App,
1358    on_event: &mut dyn FnMut(&mut T, &Entity<Emitter>, &Event, &mut Window, &mut Context<T>),
1359) -> bool {
1360    let Some((subscriber, emitter)) = subscriber.upgrade().zip(emitter.upgrade()) else {
1361        return false;
1362    };
1363    let event = event.downcast_ref().expect("invalid event type");
1364    cx.with_window(subscriber.entity_id(), |window, cx| {
1365        subscriber.update(cx, |subscriber, cx| {
1366            on_event(subscriber, &emitter, event, window, cx);
1367        });
1368    });
1369    true
1370}
1371
1372#[inline(never)]
1373fn invoke_listener<T: 'static>(
1374    view: &WeakEntity<T>,
1375    window: &mut Window,
1376    cx: &mut App,
1377    listener: &dyn Fn(&mut T, &mut Window, &mut Context<T>),
1378) {
1379    view.update(cx, |view, cx| listener(view, window, cx)).ok();
1380}