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