1pub mod action;
2mod callback_collection;
3mod menu;
4pub(crate) mod ref_counts;
5#[cfg(any(test, feature = "test-support"))]
6pub mod test_app_context;
7pub(crate) mod window;
8mod window_input_handler;
9
10use std::{
11 any::{type_name, Any, TypeId},
12 cell::RefCell,
13 fmt::{self, Debug},
14 hash::{Hash, Hasher},
15 marker::PhantomData,
16 mem,
17 ops::{Deref, DerefMut, Range},
18 path::{Path, PathBuf},
19 pin::Pin,
20 rc::{self, Rc},
21 sync::{Arc, Weak},
22 time::Duration,
23};
24
25use anyhow::{anyhow, Context, Result};
26use parking_lot::Mutex;
27use postage::oneshot;
28use smol::prelude::*;
29use util::ResultExt;
30use uuid::Uuid;
31
32pub use action::*;
33use callback_collection::CallbackCollection;
34use collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
35pub use menu::*;
36use platform::Event;
37#[cfg(any(test, feature = "test-support"))]
38use ref_counts::LeakDetector;
39#[cfg(any(test, feature = "test-support"))]
40pub use test_app_context::{ContextHandle, TestAppContext};
41use window_input_handler::WindowInputHandler;
42
43use crate::{
44 elements::{AnyElement, AnyRootElement, RootElement},
45 executor::{self, Task},
46 json,
47 keymap_matcher::{self, Binding, KeymapContext, KeymapMatcher, Keystroke, MatchResult},
48 platform::{
49 self, FontSystem, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent, MouseButton,
50 PathPromptOptions, Platform, PromptLevel, WindowBounds, WindowOptions,
51 },
52 util::post_inc,
53 window::{Window, WindowContext},
54 AssetCache, AssetSource, ClipboardItem, FontCache, MouseRegionId,
55};
56
57use self::ref_counts::RefCounts;
58
59pub trait Entity: 'static {
60 type Event;
61
62 fn release(&mut self, _: &mut AppContext) {}
63 fn app_will_quit(
64 &mut self,
65 _: &mut AppContext,
66 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
67 None
68 }
69}
70
71pub trait View: Entity + Sized {
72 fn ui_name() -> &'static str;
73 fn render(&mut self, cx: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self>;
74 fn focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
75 fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
76 fn key_down(&mut self, _: &KeyDownEvent, _: &mut ViewContext<Self>) -> bool {
77 false
78 }
79 fn key_up(&mut self, _: &KeyUpEvent, _: &mut ViewContext<Self>) -> bool {
80 false
81 }
82 fn modifiers_changed(&mut self, _: &ModifiersChangedEvent, _: &mut ViewContext<Self>) -> bool {
83 false
84 }
85
86 fn update_keymap_context(&self, keymap: &mut keymap_matcher::KeymapContext, _: &AppContext) {
87 Self::reset_to_default_keymap_context(keymap);
88 }
89
90 fn reset_to_default_keymap_context(keymap: &mut keymap_matcher::KeymapContext) {
91 keymap.clear();
92 keymap.add_identifier(Self::ui_name());
93 }
94
95 fn debug_json(&self, _: &AppContext) -> serde_json::Value {
96 serde_json::Value::Null
97 }
98
99 fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
100 None
101 }
102 fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
103 None
104 }
105 fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
106 None
107 }
108 fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
109 fn replace_text_in_range(
110 &mut self,
111 _: Option<Range<usize>>,
112 _: &str,
113 _: &mut ViewContext<Self>,
114 ) {
115 }
116 fn replace_and_mark_text_in_range(
117 &mut self,
118 _: Option<Range<usize>>,
119 _: &str,
120 _: Option<Range<usize>>,
121 _: &mut ViewContext<Self>,
122 ) {
123 }
124}
125
126pub trait BorrowAppContext {
127 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T;
128 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T;
129}
130
131pub trait BorrowWindowContext {
132 fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T;
133 fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T;
134}
135
136#[derive(Clone)]
137pub struct App(Rc<RefCell<AppContext>>);
138
139impl App {
140 pub fn new(asset_source: impl AssetSource) -> Result<Self> {
141 let platform = platform::current::platform();
142 let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
143 let foreground_platform = platform::current::foreground_platform(foreground.clone());
144 let app = Self(Rc::new(RefCell::new(AppContext::new(
145 foreground,
146 Arc::new(executor::Background::new()),
147 platform.clone(),
148 foreground_platform.clone(),
149 Arc::new(FontCache::new(platform.fonts())),
150 Default::default(),
151 asset_source,
152 ))));
153
154 foreground_platform.on_quit(Box::new({
155 let cx = app.0.clone();
156 move || {
157 cx.borrow_mut().quit();
158 }
159 }));
160 setup_menu_handlers(foreground_platform.as_ref(), &app);
161
162 app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
163 Ok(app)
164 }
165
166 pub fn background(&self) -> Arc<executor::Background> {
167 self.0.borrow().background().clone()
168 }
169
170 pub fn on_become_active<F>(self, mut callback: F) -> Self
171 where
172 F: 'static + FnMut(&mut AppContext),
173 {
174 let cx = self.0.clone();
175 self.0
176 .borrow_mut()
177 .foreground_platform
178 .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
179 self
180 }
181
182 pub fn on_resign_active<F>(self, mut callback: F) -> Self
183 where
184 F: 'static + FnMut(&mut AppContext),
185 {
186 let cx = self.0.clone();
187 self.0
188 .borrow_mut()
189 .foreground_platform
190 .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
191 self
192 }
193
194 pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
195 where
196 F: 'static + FnMut(&mut AppContext),
197 {
198 let cx = self.0.clone();
199 self.0
200 .borrow_mut()
201 .foreground_platform
202 .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
203 self
204 }
205
206 /// Handle the application being re-activated when no windows are open.
207 pub fn on_reopen<F>(&mut self, mut callback: F) -> &mut Self
208 where
209 F: 'static + FnMut(&mut AppContext),
210 {
211 let cx = self.0.clone();
212 self.0
213 .borrow_mut()
214 .foreground_platform
215 .on_reopen(Box::new(move || callback(&mut *cx.borrow_mut())));
216 self
217 }
218
219 pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
220 where
221 F: 'static + FnMut(Event, &mut AppContext) -> bool,
222 {
223 let cx = self.0.clone();
224 self.0
225 .borrow_mut()
226 .foreground_platform
227 .on_event(Box::new(move |event| {
228 callback(event, &mut *cx.borrow_mut())
229 }));
230 self
231 }
232
233 pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
234 where
235 F: 'static + FnMut(Vec<String>, &mut AppContext),
236 {
237 let cx = self.0.clone();
238 self.0
239 .borrow_mut()
240 .foreground_platform
241 .on_open_urls(Box::new(move |urls| callback(urls, &mut *cx.borrow_mut())));
242 self
243 }
244
245 pub fn run<F>(self, on_finish_launching: F)
246 where
247 F: 'static + FnOnce(&mut AppContext),
248 {
249 let platform = self.0.borrow().foreground_platform.clone();
250 platform.run(Box::new(move || {
251 let mut cx = self.0.borrow_mut();
252 let cx = &mut *cx;
253 crate::views::init(cx);
254 on_finish_launching(cx);
255 }))
256 }
257
258 pub fn platform(&self) -> Arc<dyn Platform> {
259 self.0.borrow().platform.clone()
260 }
261
262 pub fn font_cache(&self) -> Arc<FontCache> {
263 self.0.borrow().font_cache.clone()
264 }
265
266 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
267 let mut state = self.0.borrow_mut();
268 let result = state.update(callback);
269 state.pending_notifications.clear();
270 result
271 }
272
273 fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
274 &mut self,
275 window_id: usize,
276 callback: F,
277 ) -> Option<T> {
278 let mut state = self.0.borrow_mut();
279 let result = state.update_window(window_id, callback);
280 state.pending_notifications.clear();
281 result
282 }
283}
284
285#[derive(Clone)]
286pub struct AsyncAppContext(Rc<RefCell<AppContext>>);
287
288impl AsyncAppContext {
289 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
290 where
291 F: FnOnce(AsyncAppContext) -> Fut,
292 Fut: 'static + Future<Output = T>,
293 T: 'static,
294 {
295 self.0.borrow().foreground.spawn(f(self.clone()))
296 }
297
298 pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
299 callback(&*self.0.borrow())
300 }
301
302 pub fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
303 self.0.borrow_mut().update(callback)
304 }
305
306 pub fn read_window<T, F: FnOnce(&WindowContext) -> T>(
307 &self,
308 window_id: usize,
309 callback: F,
310 ) -> Option<T> {
311 self.0.borrow_mut().read_window(window_id, callback)
312 }
313
314 pub fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
315 &mut self,
316 window_id: usize,
317 callback: F,
318 ) -> Option<T> {
319 self.0.borrow_mut().update_window(window_id, callback)
320 }
321
322 pub fn debug_elements(&self, window_id: usize) -> Option<json::Value> {
323 self.0.borrow().read_window(window_id, |cx| {
324 let root_view = cx.window.root_view();
325 let root_element = cx.window.rendered_views.get(&root_view.id())?;
326 root_element.debug(cx).log_err()
327 })?
328 }
329
330 pub fn dispatch_action(
331 &mut self,
332 window_id: usize,
333 view_id: usize,
334 action: &dyn Action,
335 ) -> Result<()> {
336 self.0
337 .borrow_mut()
338 .update_window(window_id, |window| {
339 window.handle_dispatch_action_from_effect(Some(view_id), action);
340 })
341 .ok_or_else(|| anyhow!("window not found"))
342 }
343
344 pub fn has_window(&self, window_id: usize) -> bool {
345 self.read(|cx| cx.windows.contains_key(&window_id))
346 }
347
348 pub fn window_is_active(&self, window_id: usize) -> bool {
349 self.read(|cx| cx.windows.get(&window_id).map_or(false, |w| w.is_active))
350 }
351
352 pub fn root_view(&self, window_id: usize) -> Option<AnyViewHandle> {
353 self.read(|cx| cx.windows.get(&window_id).map(|w| w.root_view().clone()))
354 }
355
356 pub fn window_ids(&self) -> Vec<usize> {
357 self.read(|cx| cx.windows.keys().copied().collect())
358 }
359
360 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
361 where
362 T: Entity,
363 F: FnOnce(&mut ModelContext<T>) -> T,
364 {
365 self.update(|cx| cx.add_model(build_model))
366 }
367
368 pub fn add_window<T, F>(
369 &mut self,
370 window_options: WindowOptions,
371 build_root_view: F,
372 ) -> (usize, ViewHandle<T>)
373 where
374 T: View,
375 F: FnOnce(&mut ViewContext<T>) -> T,
376 {
377 self.update(|cx| cx.add_window(window_options, build_root_view))
378 }
379
380 pub fn remove_window(&mut self, window_id: usize) {
381 self.update_window(window_id, |cx| cx.remove_window());
382 }
383
384 pub fn activate_window(&mut self, window_id: usize) {
385 self.update_window(window_id, |cx| cx.activate_window());
386 }
387
388 // TODO: Can we eliminate this method and move it to WindowContext then call it with update_window?s
389 pub fn prompt(
390 &mut self,
391 window_id: usize,
392 level: PromptLevel,
393 msg: &str,
394 answers: &[&str],
395 ) -> Option<oneshot::Receiver<usize>> {
396 self.update_window(window_id, |cx| cx.prompt(level, msg, answers))
397 }
398
399 pub fn platform(&self) -> Arc<dyn Platform> {
400 self.0.borrow().platform().clone()
401 }
402
403 pub fn foreground(&self) -> Rc<executor::Foreground> {
404 self.0.borrow().foreground.clone()
405 }
406
407 pub fn background(&self) -> Arc<executor::Background> {
408 self.0.borrow().background.clone()
409 }
410}
411
412impl BorrowAppContext for AsyncAppContext {
413 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
414 self.0.borrow().read_with(f)
415 }
416
417 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
418 self.0.borrow_mut().update(f)
419 }
420}
421
422type ActionCallback = dyn FnMut(&mut dyn AnyView, &dyn Action, &mut WindowContext, usize);
423type GlobalActionCallback = dyn FnMut(&dyn Action, &mut AppContext);
424
425type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool>;
426type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
427type ObservationCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
428type GlobalObservationCallback = Box<dyn FnMut(&mut AppContext)>;
429type FocusObservationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
430type ReleaseObservationCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
431type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut AppContext)>;
432type WindowActivationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
433type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
434type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, Uuid, &mut WindowContext) -> bool>;
435type KeystrokeCallback =
436 Box<dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut WindowContext) -> bool>;
437type ActiveLabeledTasksCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
438type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
439type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
440
441pub struct AppContext {
442 models: HashMap<usize, Box<dyn AnyModel>>,
443 views: HashMap<(usize, usize), Box<dyn AnyView>>,
444 views_metadata: HashMap<(usize, usize), ViewMetadata>,
445 pub(crate) parents: HashMap<(usize, usize), ParentId>,
446 windows: HashMap<usize, Window>,
447 globals: HashMap<TypeId, Box<dyn Any>>,
448 element_states: HashMap<ElementStateId, Box<dyn Any>>,
449 background: Arc<executor::Background>,
450 ref_counts: Arc<Mutex<RefCounts>>,
451
452 weak_self: Option<rc::Weak<RefCell<Self>>>,
453 platform: Arc<dyn Platform>,
454 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
455 pub asset_cache: Arc<AssetCache>,
456 font_system: Arc<dyn FontSystem>,
457 pub font_cache: Arc<FontCache>,
458 action_deserializers: HashMap<&'static str, (TypeId, DeserializeActionCallback)>,
459 capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
460 // Entity Types -> { Action Types -> Action Handlers }
461 actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
462 // Action Types -> Action Handlers
463 global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
464 keystroke_matcher: KeymapMatcher,
465 next_entity_id: usize,
466 next_window_id: usize,
467 next_subscription_id: usize,
468 frame_count: usize,
469
470 subscriptions: CallbackCollection<usize, SubscriptionCallback>,
471 global_subscriptions: CallbackCollection<TypeId, GlobalSubscriptionCallback>,
472 observations: CallbackCollection<usize, ObservationCallback>,
473 global_observations: CallbackCollection<TypeId, GlobalObservationCallback>,
474 focus_observations: CallbackCollection<usize, FocusObservationCallback>,
475 release_observations: CallbackCollection<usize, ReleaseObservationCallback>,
476 action_dispatch_observations: CallbackCollection<(), ActionObservationCallback>,
477 window_activation_observations: CallbackCollection<usize, WindowActivationCallback>,
478 window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>,
479 window_bounds_observations: CallbackCollection<usize, WindowBoundsCallback>,
480 keystroke_observations: CallbackCollection<usize, KeystrokeCallback>,
481 active_labeled_task_observations: CallbackCollection<(), ActiveLabeledTasksCallback>,
482
483 foreground: Rc<executor::Foreground>,
484 pending_effects: VecDeque<Effect>,
485 pending_notifications: HashSet<usize>,
486 pending_global_notifications: HashSet<TypeId>,
487 pending_flushes: usize,
488 flushing_effects: bool,
489 halt_action_dispatch: bool,
490 next_labeled_task_id: usize,
491 active_labeled_tasks: BTreeMap<usize, &'static str>,
492}
493
494impl AppContext {
495 fn new(
496 foreground: Rc<executor::Foreground>,
497 background: Arc<executor::Background>,
498 platform: Arc<dyn platform::Platform>,
499 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
500 font_cache: Arc<FontCache>,
501 ref_counts: RefCounts,
502 asset_source: impl AssetSource,
503 ) -> Self {
504 Self {
505 models: Default::default(),
506 views: Default::default(),
507 views_metadata: Default::default(),
508 parents: Default::default(),
509 windows: Default::default(),
510 globals: Default::default(),
511 element_states: Default::default(),
512 ref_counts: Arc::new(Mutex::new(ref_counts)),
513 background,
514
515 weak_self: None,
516 font_system: platform.fonts(),
517 platform,
518 foreground_platform,
519 font_cache,
520 asset_cache: Arc::new(AssetCache::new(asset_source)),
521 action_deserializers: Default::default(),
522 capture_actions: Default::default(),
523 actions: Default::default(),
524 global_actions: Default::default(),
525 keystroke_matcher: KeymapMatcher::default(),
526 next_entity_id: 0,
527 next_window_id: 0,
528 next_subscription_id: 0,
529 frame_count: 0,
530 subscriptions: Default::default(),
531 global_subscriptions: Default::default(),
532 observations: Default::default(),
533 focus_observations: Default::default(),
534 release_observations: Default::default(),
535 global_observations: Default::default(),
536 window_activation_observations: Default::default(),
537 window_fullscreen_observations: Default::default(),
538 window_bounds_observations: Default::default(),
539 keystroke_observations: Default::default(),
540 action_dispatch_observations: Default::default(),
541 active_labeled_task_observations: Default::default(),
542 foreground,
543 pending_effects: VecDeque::new(),
544 pending_notifications: Default::default(),
545 pending_global_notifications: Default::default(),
546 pending_flushes: 0,
547 flushing_effects: false,
548 halt_action_dispatch: false,
549 next_labeled_task_id: 0,
550 active_labeled_tasks: Default::default(),
551 }
552 }
553
554 pub fn background(&self) -> &Arc<executor::Background> {
555 &self.background
556 }
557
558 pub fn font_cache(&self) -> &Arc<FontCache> {
559 &self.font_cache
560 }
561
562 pub fn platform(&self) -> &Arc<dyn Platform> {
563 &self.platform
564 }
565
566 pub fn has_global<T: 'static>(&self) -> bool {
567 self.globals.contains_key(&TypeId::of::<T>())
568 }
569
570 pub fn global<T: 'static>(&self) -> &T {
571 if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
572 global.downcast_ref().unwrap()
573 } else {
574 panic!("no global has been added for {}", type_name::<T>());
575 }
576 }
577
578 pub fn upgrade(&self) -> App {
579 App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
580 }
581
582 fn quit(&mut self) {
583 let mut futures = Vec::new();
584
585 self.update(|cx| {
586 for model_id in cx.models.keys().copied().collect::<Vec<_>>() {
587 let mut model = cx.models.remove(&model_id).unwrap();
588 futures.extend(model.app_will_quit(cx));
589 cx.models.insert(model_id, model);
590 }
591
592 for view_id in cx.views.keys().copied().collect::<Vec<_>>() {
593 let mut view = cx.views.remove(&view_id).unwrap();
594 futures.extend(view.app_will_quit(cx));
595 cx.views.insert(view_id, view);
596 }
597 });
598
599 self.windows.clear();
600 self.flush_effects();
601
602 let futures = futures::future::join_all(futures);
603 if self
604 .background
605 .block_with_timeout(Duration::from_millis(100), futures)
606 .is_err()
607 {
608 log::error!("timed out waiting on app_will_quit");
609 }
610 }
611
612 pub fn foreground(&self) -> &Rc<executor::Foreground> {
613 &self.foreground
614 }
615
616 pub fn deserialize_action(
617 &self,
618 name: &str,
619 argument: Option<&str>,
620 ) -> Result<Box<dyn Action>> {
621 let callback = self
622 .action_deserializers
623 .get(name)
624 .ok_or_else(|| anyhow!("unknown action {}", name))?
625 .1;
626 callback(argument.unwrap_or("{}"))
627 .with_context(|| format!("invalid data for action {}", name))
628 }
629
630 pub fn add_action<A, V, F, R>(&mut self, handler: F)
631 where
632 A: Action,
633 V: View,
634 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
635 {
636 self.add_action_internal(handler, false)
637 }
638
639 pub fn capture_action<A, V, F>(&mut self, handler: F)
640 where
641 A: Action,
642 V: View,
643 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
644 {
645 self.add_action_internal(handler, true)
646 }
647
648 fn add_action_internal<A, V, F, R>(&mut self, mut handler: F, capture: bool)
649 where
650 A: Action,
651 V: View,
652 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
653 {
654 let handler = Box::new(
655 move |view: &mut dyn AnyView,
656 action: &dyn Action,
657 cx: &mut WindowContext,
658 view_id: usize| {
659 let action = action.as_any().downcast_ref().unwrap();
660 let mut cx = ViewContext::mutable(cx, view_id);
661 handler(
662 view.as_any_mut()
663 .downcast_mut()
664 .expect("downcast is type safe"),
665 action,
666 &mut cx,
667 );
668 },
669 );
670
671 self.action_deserializers
672 .entry(A::qualified_name())
673 .or_insert((TypeId::of::<A>(), A::from_json_str));
674
675 let actions = if capture {
676 &mut self.capture_actions
677 } else {
678 &mut self.actions
679 };
680
681 actions
682 .entry(TypeId::of::<V>())
683 .or_default()
684 .entry(TypeId::of::<A>())
685 .or_default()
686 .push(handler);
687 }
688
689 pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
690 where
691 A: Action,
692 V: View,
693 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
694 {
695 self.add_action(move |view, action, cx| {
696 if let Some(task) = handler(view, action, cx) {
697 task.detach_and_log_err(cx);
698 }
699 })
700 }
701
702 pub fn add_global_action<A, F>(&mut self, mut handler: F)
703 where
704 A: Action,
705 F: 'static + FnMut(&A, &mut AppContext),
706 {
707 let handler = Box::new(move |action: &dyn Action, cx: &mut AppContext| {
708 let action = action.as_any().downcast_ref().unwrap();
709 handler(action, cx);
710 });
711
712 self.action_deserializers
713 .entry(A::qualified_name())
714 .or_insert((TypeId::of::<A>(), A::from_json_str));
715
716 if self
717 .global_actions
718 .insert(TypeId::of::<A>(), handler)
719 .is_some()
720 {
721 panic!(
722 "registered multiple global handlers for {}",
723 type_name::<A>()
724 );
725 }
726 }
727
728 pub fn view_ui_name(&self, window_id: usize, view_id: usize) -> Option<&'static str> {
729 Some(self.views.get(&(window_id, view_id))?.ui_name())
730 }
731
732 pub fn view_type_id(&self, window_id: usize, view_id: usize) -> Option<TypeId> {
733 self.views_metadata
734 .get(&(window_id, view_id))
735 .map(|metadata| metadata.type_id)
736 }
737
738 pub fn active_labeled_tasks<'a>(
739 &'a self,
740 ) -> impl DoubleEndedIterator<Item = &'static str> + 'a {
741 self.active_labeled_tasks.values().cloned()
742 }
743
744 pub(crate) fn start_frame(&mut self) {
745 self.frame_count += 1;
746 }
747
748 pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
749 self.pending_flushes += 1;
750 let result = callback(self);
751 self.flush_effects();
752 result
753 }
754
755 pub fn read_window<T, F: FnOnce(&WindowContext) -> T>(
756 &self,
757 window_id: usize,
758 callback: F,
759 ) -> Option<T> {
760 let window = self.windows.get(&window_id)?;
761 let window_context = WindowContext::immutable(self, &window, window_id);
762 Some(callback(&window_context))
763 }
764
765 pub fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
766 &mut self,
767 window_id: usize,
768 callback: F,
769 ) -> Option<T> {
770 self.update(|app_context| {
771 let mut window = app_context.windows.remove(&window_id)?;
772 let mut window_context = WindowContext::mutable(app_context, &mut window, window_id);
773 let result = callback(&mut window_context);
774 if !window_context.removed {
775 app_context.windows.insert(window_id, window);
776 }
777 Some(result)
778 })
779 }
780
781 pub fn update_active_window<T, F: FnOnce(&mut WindowContext) -> T>(
782 &mut self,
783 callback: F,
784 ) -> Option<T> {
785 self.platform
786 .main_window_id()
787 .and_then(|id| self.update_window(id, callback))
788 }
789
790 pub fn prompt_for_paths(
791 &self,
792 options: PathPromptOptions,
793 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
794 self.foreground_platform.prompt_for_paths(options)
795 }
796
797 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
798 self.foreground_platform.prompt_for_new_path(directory)
799 }
800
801 pub fn reveal_path(&self, path: &Path) {
802 self.foreground_platform.reveal_path(path)
803 }
804
805 pub fn emit_global<E: Any>(&mut self, payload: E) {
806 self.pending_effects.push_back(Effect::GlobalEvent {
807 payload: Box::new(payload),
808 });
809 }
810
811 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
812 where
813 E: Entity,
814 E::Event: 'static,
815 H: Handle<E>,
816 F: 'static + FnMut(H, &E::Event, &mut Self),
817 {
818 self.subscribe_internal(handle, move |handle, event, cx| {
819 callback(handle, event, cx);
820 true
821 })
822 }
823
824 pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
825 where
826 E: Any,
827 F: 'static + FnMut(&E, &mut Self),
828 {
829 let subscription_id = post_inc(&mut self.next_subscription_id);
830 let type_id = TypeId::of::<E>();
831 self.pending_effects.push_back(Effect::GlobalSubscription {
832 type_id,
833 subscription_id,
834 callback: Box::new(move |payload, cx| {
835 let payload = payload.downcast_ref().expect("downcast is type safe");
836 callback(payload, cx)
837 }),
838 });
839 Subscription::GlobalSubscription(
840 self.global_subscriptions
841 .subscribe(type_id, subscription_id),
842 )
843 }
844
845 pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
846 where
847 E: Entity,
848 E::Event: 'static,
849 H: Handle<E>,
850 F: 'static + FnMut(H, &mut Self),
851 {
852 self.observe_internal(handle, move |handle, cx| {
853 callback(handle, cx);
854 true
855 })
856 }
857
858 fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
859 where
860 E: Entity,
861 E::Event: 'static,
862 H: Handle<E>,
863 F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
864 {
865 let subscription_id = post_inc(&mut self.next_subscription_id);
866 let emitter = handle.downgrade();
867 self.pending_effects.push_back(Effect::Subscription {
868 entity_id: handle.id(),
869 subscription_id,
870 callback: Box::new(move |payload, cx| {
871 if let Some(emitter) = H::upgrade_from(&emitter, cx) {
872 let payload = payload.downcast_ref().expect("downcast is type safe");
873 callback(emitter, payload, cx)
874 } else {
875 false
876 }
877 }),
878 });
879 Subscription::Subscription(self.subscriptions.subscribe(handle.id(), subscription_id))
880 }
881
882 fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
883 where
884 E: Entity,
885 E::Event: 'static,
886 H: Handle<E>,
887 F: 'static + FnMut(H, &mut Self) -> bool,
888 {
889 let subscription_id = post_inc(&mut self.next_subscription_id);
890 let observed = handle.downgrade();
891 let entity_id = handle.id();
892 self.pending_effects.push_back(Effect::Observation {
893 entity_id,
894 subscription_id,
895 callback: Box::new(move |cx| {
896 if let Some(observed) = H::upgrade_from(&observed, cx) {
897 callback(observed, cx)
898 } else {
899 false
900 }
901 }),
902 });
903 Subscription::Observation(self.observations.subscribe(entity_id, subscription_id))
904 }
905
906 fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
907 where
908 F: 'static + FnMut(ViewHandle<V>, bool, &mut WindowContext) -> bool,
909 V: View,
910 {
911 let subscription_id = post_inc(&mut self.next_subscription_id);
912 let observed = handle.downgrade();
913 let view_id = handle.id();
914
915 self.pending_effects.push_back(Effect::FocusObservation {
916 view_id,
917 subscription_id,
918 callback: Box::new(move |focused, cx| {
919 if let Some(observed) = observed.upgrade(cx) {
920 callback(observed, focused, cx)
921 } else {
922 false
923 }
924 }),
925 });
926 Subscription::FocusObservation(self.focus_observations.subscribe(view_id, subscription_id))
927 }
928
929 pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
930 where
931 G: Any,
932 F: 'static + FnMut(&mut AppContext),
933 {
934 let type_id = TypeId::of::<G>();
935 let id = post_inc(&mut self.next_subscription_id);
936
937 self.global_observations.add_callback(
938 type_id,
939 id,
940 Box::new(move |cx: &mut AppContext| observe(cx)),
941 );
942 Subscription::GlobalObservation(self.global_observations.subscribe(type_id, id))
943 }
944
945 pub fn observe_default_global<G, F>(&mut self, observe: F) -> Subscription
946 where
947 G: Any + Default,
948 F: 'static + FnMut(&mut AppContext),
949 {
950 if !self.has_global::<G>() {
951 self.set_global(G::default());
952 }
953 self.observe_global::<G, F>(observe)
954 }
955
956 pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
957 where
958 E: Entity,
959 E::Event: 'static,
960 H: Handle<E>,
961 F: 'static + FnOnce(&E, &mut Self),
962 {
963 let id = post_inc(&mut self.next_subscription_id);
964 let mut callback = Some(callback);
965 self.release_observations.add_callback(
966 handle.id(),
967 id,
968 Box::new(move |released, cx| {
969 let released = released.downcast_ref().unwrap();
970 if let Some(callback) = callback.take() {
971 callback(released, cx)
972 }
973 }),
974 );
975 Subscription::ReleaseObservation(self.release_observations.subscribe(handle.id(), id))
976 }
977
978 pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
979 where
980 F: 'static + FnMut(TypeId, &mut AppContext),
981 {
982 let subscription_id = post_inc(&mut self.next_subscription_id);
983 self.action_dispatch_observations
984 .add_callback((), subscription_id, Box::new(callback));
985 Subscription::ActionObservation(
986 self.action_dispatch_observations
987 .subscribe((), subscription_id),
988 )
989 }
990
991 fn observe_active_labeled_tasks<F>(&mut self, callback: F) -> Subscription
992 where
993 F: 'static + FnMut(&mut AppContext) -> bool,
994 {
995 let subscription_id = post_inc(&mut self.next_subscription_id);
996 self.active_labeled_task_observations
997 .add_callback((), subscription_id, Box::new(callback));
998 Subscription::ActiveLabeledTasksObservation(
999 self.active_labeled_task_observations
1000 .subscribe((), subscription_id),
1001 )
1002 }
1003
1004 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut AppContext)) {
1005 self.pending_effects.push_back(Effect::Deferred {
1006 callback: Box::new(callback),
1007 after_window_update: false,
1008 })
1009 }
1010
1011 pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut AppContext)) {
1012 self.pending_effects.push_back(Effect::Deferred {
1013 callback: Box::new(callback),
1014 after_window_update: true,
1015 })
1016 }
1017
1018 fn notify_model(&mut self, model_id: usize) {
1019 if self.pending_notifications.insert(model_id) {
1020 self.pending_effects
1021 .push_back(Effect::ModelNotification { model_id });
1022 }
1023 }
1024
1025 fn notify_view(&mut self, window_id: usize, view_id: usize) {
1026 if self.pending_notifications.insert(view_id) {
1027 self.pending_effects
1028 .push_back(Effect::ViewNotification { window_id, view_id });
1029 }
1030 }
1031
1032 fn notify_global(&mut self, type_id: TypeId) {
1033 if self.pending_global_notifications.insert(type_id) {
1034 self.pending_effects
1035 .push_back(Effect::GlobalNotification { type_id });
1036 }
1037 }
1038
1039 pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1040 self.action_deserializers.keys().copied()
1041 }
1042
1043 pub fn is_action_available(&self, action: &dyn Action) -> bool {
1044 let mut available_in_window = false;
1045 let action_type = action.as_any().type_id();
1046 if let Some(window_id) = self.platform.main_window_id() {
1047 available_in_window = self
1048 .read_window(window_id, |cx| {
1049 if let Some(focused_view_id) = cx.focused_view_id() {
1050 for view_id in cx.ancestors(focused_view_id) {
1051 if let Some(view_metadata) =
1052 cx.views_metadata.get(&(window_id, view_id))
1053 {
1054 if let Some(actions) = cx.actions.get(&view_metadata.type_id) {
1055 if actions.contains_key(&action_type) {
1056 return true;
1057 }
1058 }
1059 }
1060 }
1061 }
1062 false
1063 })
1064 .unwrap_or(false);
1065 }
1066 available_in_window || self.global_actions.contains_key(&action_type)
1067 }
1068
1069 fn actions_mut(
1070 &mut self,
1071 capture_phase: bool,
1072 ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1073 if capture_phase {
1074 &mut self.capture_actions
1075 } else {
1076 &mut self.actions
1077 }
1078 }
1079
1080 fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1081 self.update(|this| {
1082 if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1083 handler(action, this);
1084 this.global_actions.insert(name, handler);
1085 true
1086 } else {
1087 false
1088 }
1089 })
1090 }
1091
1092 pub fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
1093 self.keystroke_matcher.add_bindings(bindings);
1094 }
1095
1096 pub fn clear_bindings(&mut self) {
1097 self.keystroke_matcher.clear_bindings();
1098 }
1099
1100 pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1101 let type_id = TypeId::of::<T>();
1102 self.update(|this| {
1103 if let Entry::Vacant(entry) = this.globals.entry(type_id) {
1104 entry.insert(Box::new(T::default()));
1105 this.notify_global(type_id);
1106 }
1107 });
1108 self.globals.get(&type_id).unwrap().downcast_ref().unwrap()
1109 }
1110
1111 pub fn set_global<T: 'static>(&mut self, state: T) {
1112 self.update(|this| {
1113 let type_id = TypeId::of::<T>();
1114 this.globals.insert(type_id, Box::new(state));
1115 this.notify_global(type_id);
1116 });
1117 }
1118
1119 pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1120 where
1121 T: 'static + Default,
1122 F: FnOnce(&mut T, &mut AppContext) -> U,
1123 {
1124 self.update(|mut this| {
1125 Self::update_default_global_internal(&mut this, |global, cx| update(global, cx))
1126 })
1127 }
1128
1129 fn update_default_global_internal<C, T, F, U>(this: &mut C, update: F) -> U
1130 where
1131 C: DerefMut<Target = AppContext>,
1132 T: 'static + Default,
1133 F: FnOnce(&mut T, &mut C) -> U,
1134 {
1135 let type_id = TypeId::of::<T>();
1136 let mut state = this
1137 .globals
1138 .remove(&type_id)
1139 .unwrap_or_else(|| Box::new(T::default()));
1140 let result = update(state.downcast_mut().unwrap(), this);
1141 this.globals.insert(type_id, state);
1142 this.notify_global(type_id);
1143 result
1144 }
1145
1146 pub fn update_global<T, F, U>(&mut self, update: F) -> U
1147 where
1148 T: 'static,
1149 F: FnOnce(&mut T, &mut AppContext) -> U,
1150 {
1151 self.update(|mut this| {
1152 Self::update_global_internal(&mut this, |global, cx| update(global, cx))
1153 })
1154 }
1155
1156 fn update_global_internal<C, T, F, U>(this: &mut C, update: F) -> U
1157 where
1158 C: DerefMut<Target = AppContext>,
1159 T: 'static,
1160 F: FnOnce(&mut T, &mut C) -> U,
1161 {
1162 let type_id = TypeId::of::<T>();
1163 if let Some(mut state) = this.globals.remove(&type_id) {
1164 let result = update(state.downcast_mut().unwrap(), this);
1165 this.globals.insert(type_id, state);
1166 this.notify_global(type_id);
1167 result
1168 } else {
1169 panic!("No global added for {}", std::any::type_name::<T>());
1170 }
1171 }
1172
1173 pub fn clear_globals(&mut self) {
1174 self.globals.clear();
1175 }
1176
1177 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1178 where
1179 T: Entity,
1180 F: FnOnce(&mut ModelContext<T>) -> T,
1181 {
1182 self.update(|this| {
1183 let model_id = post_inc(&mut this.next_entity_id);
1184 let handle = ModelHandle::new(model_id, &this.ref_counts);
1185 let mut cx = ModelContext::new(this, model_id);
1186 let model = build_model(&mut cx);
1187 this.models.insert(model_id, Box::new(model));
1188 handle
1189 })
1190 }
1191
1192 pub fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1193 if let Some(model) = self.models.get(&handle.model_id) {
1194 model
1195 .as_any()
1196 .downcast_ref()
1197 .expect("downcast is type safe")
1198 } else {
1199 panic!("circular model reference");
1200 }
1201 }
1202
1203 fn update_model<T: Entity, V>(
1204 &mut self,
1205 handle: &ModelHandle<T>,
1206 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
1207 ) -> V {
1208 if let Some(mut model) = self.models.remove(&handle.model_id) {
1209 self.update(|this| {
1210 let mut cx = ModelContext::new(this, handle.model_id);
1211 let result = update(
1212 model
1213 .as_any_mut()
1214 .downcast_mut()
1215 .expect("downcast is type safe"),
1216 &mut cx,
1217 );
1218 this.models.insert(handle.model_id, model);
1219 result
1220 })
1221 } else {
1222 panic!("circular model update");
1223 }
1224 }
1225
1226 fn upgrade_model_handle<T: Entity>(
1227 &self,
1228 handle: &WeakModelHandle<T>,
1229 ) -> Option<ModelHandle<T>> {
1230 if self.ref_counts.lock().is_entity_alive(handle.model_id) {
1231 Some(ModelHandle::new(handle.model_id, &self.ref_counts))
1232 } else {
1233 None
1234 }
1235 }
1236
1237 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
1238 self.ref_counts.lock().is_entity_alive(handle.model_id)
1239 }
1240
1241 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
1242 if self.ref_counts.lock().is_entity_alive(handle.model_id) {
1243 Some(AnyModelHandle::new(
1244 handle.model_id,
1245 handle.model_type,
1246 self.ref_counts.clone(),
1247 ))
1248 } else {
1249 None
1250 }
1251 }
1252
1253 pub fn add_window<V, F>(
1254 &mut self,
1255 window_options: WindowOptions,
1256 build_root_view: F,
1257 ) -> (usize, ViewHandle<V>)
1258 where
1259 V: View,
1260 F: FnOnce(&mut ViewContext<V>) -> V,
1261 {
1262 self.update(|this| {
1263 let window_id = post_inc(&mut this.next_window_id);
1264 let platform_window =
1265 this.platform
1266 .open_window(window_id, window_options, this.foreground.clone());
1267 let window = this.build_window(window_id, platform_window, build_root_view);
1268 let root_view = window.root_view().clone().downcast::<V>().unwrap();
1269 this.windows.insert(window_id, window);
1270 (window_id, root_view)
1271 })
1272 }
1273
1274 pub fn add_status_bar_item<V, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<V>)
1275 where
1276 V: View,
1277 F: FnOnce(&mut ViewContext<V>) -> V,
1278 {
1279 self.update(|this| {
1280 let window_id = post_inc(&mut this.next_window_id);
1281 let platform_window = this.platform.add_status_item(window_id);
1282 let window = this.build_window(window_id, platform_window, build_root_view);
1283 let root_view = window.root_view().clone().downcast::<V>().unwrap();
1284
1285 this.windows.insert(window_id, window);
1286 this.update_window(window_id, |cx| {
1287 root_view.update(cx, |view, cx| view.focus_in(cx.handle().into_any(), cx))
1288 });
1289
1290 (window_id, root_view)
1291 })
1292 }
1293
1294 pub fn build_window<V, F>(
1295 &mut self,
1296 window_id: usize,
1297 mut platform_window: Box<dyn platform::Window>,
1298 build_root_view: F,
1299 ) -> Window
1300 where
1301 V: View,
1302 F: FnOnce(&mut ViewContext<V>) -> V,
1303 {
1304 {
1305 let mut app = self.upgrade();
1306
1307 platform_window.on_event(Box::new(move |event| {
1308 app.update_window(window_id, |cx| {
1309 if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
1310 if cx.dispatch_keystroke(keystroke) {
1311 return true;
1312 }
1313 }
1314
1315 cx.dispatch_event(event, false)
1316 })
1317 .unwrap_or(false)
1318 }));
1319 }
1320
1321 {
1322 let mut app = self.upgrade();
1323 platform_window.on_active_status_change(Box::new(move |is_active| {
1324 app.update(|cx| cx.window_changed_active_status(window_id, is_active))
1325 }));
1326 }
1327
1328 {
1329 let mut app = self.upgrade();
1330 platform_window.on_resize(Box::new(move || {
1331 app.update(|cx| cx.window_was_resized(window_id))
1332 }));
1333 }
1334
1335 {
1336 let mut app = self.upgrade();
1337 platform_window.on_moved(Box::new(move || {
1338 app.update(|cx| cx.window_was_moved(window_id))
1339 }));
1340 }
1341
1342 {
1343 let mut app = self.upgrade();
1344 platform_window.on_fullscreen(Box::new(move |is_fullscreen| {
1345 app.update(|cx| cx.window_was_fullscreen_changed(window_id, is_fullscreen))
1346 }));
1347 }
1348
1349 {
1350 let mut app = self.upgrade();
1351 platform_window.on_close(Box::new(move || {
1352 app.update(|cx| cx.update_window(window_id, |cx| cx.remove_window()));
1353 }));
1354 }
1355
1356 {
1357 let mut app = self.upgrade();
1358 platform_window
1359 .on_appearance_changed(Box::new(move || app.update(|cx| cx.refresh_windows())));
1360 }
1361
1362 platform_window.set_input_handler(Box::new(WindowInputHandler {
1363 app: self.upgrade().0,
1364 window_id,
1365 }));
1366
1367 let mut window = Window::new(window_id, platform_window, self, build_root_view);
1368 let scene = WindowContext::mutable(self, &mut window, window_id)
1369 .build_scene()
1370 .expect("initial scene should not error");
1371 window.platform_window.present_scene(scene);
1372 window
1373 }
1374
1375 pub fn replace_root_view<V, F>(
1376 &mut self,
1377 window_id: usize,
1378 build_root_view: F,
1379 ) -> Option<ViewHandle<V>>
1380 where
1381 V: View,
1382 F: FnOnce(&mut ViewContext<V>) -> V,
1383 {
1384 self.update_window(window_id, |cx| cx.replace_root_view(build_root_view))
1385 }
1386
1387 pub fn add_view<S, F>(&mut self, parent: &AnyViewHandle, build_view: F) -> ViewHandle<S>
1388 where
1389 S: View,
1390 F: FnOnce(&mut ViewContext<S>) -> S,
1391 {
1392 self.update_window(parent.window_id, |cx| {
1393 cx.build_and_insert_view(ParentId::View(parent.view_id), |cx| Some(build_view(cx)))
1394 .unwrap()
1395 })
1396 .unwrap()
1397 }
1398
1399 pub fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1400 if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1401 view.as_any().downcast_ref().expect("downcast is type safe")
1402 } else {
1403 panic!("circular view reference for type {}", type_name::<T>());
1404 }
1405 }
1406
1407 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1408 if self.ref_counts.lock().is_entity_alive(handle.view_id) {
1409 Some(ViewHandle::new(
1410 handle.window_id,
1411 handle.view_id,
1412 &self.ref_counts,
1413 ))
1414 } else {
1415 None
1416 }
1417 }
1418
1419 fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
1420 if self.ref_counts.lock().is_entity_alive(handle.view_id) {
1421 Some(AnyViewHandle::new(
1422 handle.window_id,
1423 handle.view_id,
1424 handle.view_type,
1425 self.ref_counts.clone(),
1426 ))
1427 } else {
1428 None
1429 }
1430 }
1431
1432 fn remove_dropped_entities(&mut self) {
1433 loop {
1434 let (dropped_models, dropped_views, dropped_element_states) =
1435 self.ref_counts.lock().take_dropped();
1436 if dropped_models.is_empty()
1437 && dropped_views.is_empty()
1438 && dropped_element_states.is_empty()
1439 {
1440 break;
1441 }
1442
1443 for model_id in dropped_models {
1444 self.subscriptions.remove(model_id);
1445 self.observations.remove(model_id);
1446 let mut model = self.models.remove(&model_id).unwrap();
1447 model.release(self);
1448 self.pending_effects
1449 .push_back(Effect::ModelRelease { model_id, model });
1450 }
1451
1452 for (window_id, view_id) in dropped_views {
1453 self.subscriptions.remove(view_id);
1454 self.observations.remove(view_id);
1455 self.views_metadata.remove(&(window_id, view_id));
1456 let mut view = self.views.remove(&(window_id, view_id)).unwrap();
1457 view.release(self);
1458 let change_focus_to = self.windows.get_mut(&window_id).and_then(|window| {
1459 window
1460 .invalidation
1461 .get_or_insert_with(Default::default)
1462 .removed
1463 .push(view_id);
1464 if window.focused_view_id == Some(view_id) {
1465 Some(window.root_view().id())
1466 } else {
1467 None
1468 }
1469 });
1470 self.parents.remove(&(window_id, view_id));
1471
1472 if let Some(view_id) = change_focus_to {
1473 self.handle_focus_effect(window_id, Some(view_id));
1474 }
1475
1476 self.pending_effects
1477 .push_back(Effect::ViewRelease { view_id, view });
1478 }
1479
1480 for key in dropped_element_states {
1481 self.element_states.remove(&key);
1482 }
1483 }
1484 }
1485
1486 fn flush_effects(&mut self) {
1487 self.pending_flushes = self.pending_flushes.saturating_sub(1);
1488 let mut after_window_update_callbacks = Vec::new();
1489
1490 if !self.flushing_effects && self.pending_flushes == 0 {
1491 self.flushing_effects = true;
1492
1493 let mut refreshing = false;
1494 loop {
1495 if let Some(effect) = self.pending_effects.pop_front() {
1496 match effect {
1497 Effect::Subscription {
1498 entity_id,
1499 subscription_id,
1500 callback,
1501 } => self
1502 .subscriptions
1503 .add_callback(entity_id, subscription_id, callback),
1504
1505 Effect::Event { entity_id, payload } => {
1506 let mut subscriptions = self.subscriptions.clone();
1507 subscriptions
1508 .emit(entity_id, |callback| callback(payload.as_ref(), self))
1509 }
1510
1511 Effect::GlobalSubscription {
1512 type_id,
1513 subscription_id,
1514 callback,
1515 } => self.global_subscriptions.add_callback(
1516 type_id,
1517 subscription_id,
1518 callback,
1519 ),
1520
1521 Effect::GlobalEvent { payload } => self.emit_global_event(payload),
1522
1523 Effect::Observation {
1524 entity_id,
1525 subscription_id,
1526 callback,
1527 } => self
1528 .observations
1529 .add_callback(entity_id, subscription_id, callback),
1530
1531 Effect::ModelNotification { model_id } => {
1532 let mut observations = self.observations.clone();
1533 observations.emit(model_id, |callback| callback(self));
1534 }
1535
1536 Effect::ViewNotification { window_id, view_id } => {
1537 self.handle_view_notification_effect(window_id, view_id)
1538 }
1539
1540 Effect::GlobalNotification { type_id } => {
1541 let mut subscriptions = self.global_observations.clone();
1542 subscriptions.emit(type_id, |callback| {
1543 callback(self);
1544 true
1545 });
1546 }
1547
1548 Effect::Deferred {
1549 callback,
1550 after_window_update,
1551 } => {
1552 if after_window_update {
1553 after_window_update_callbacks.push(callback);
1554 } else {
1555 callback(self)
1556 }
1557 }
1558
1559 Effect::ModelRelease { model_id, model } => {
1560 self.handle_entity_release_effect(model_id, model.as_any())
1561 }
1562
1563 Effect::ViewRelease { view_id, view } => {
1564 self.handle_entity_release_effect(view_id, view.as_any())
1565 }
1566
1567 Effect::Focus { window_id, view_id } => {
1568 self.handle_focus_effect(window_id, view_id);
1569 }
1570
1571 Effect::FocusObservation {
1572 view_id,
1573 subscription_id,
1574 callback,
1575 } => {
1576 self.focus_observations.add_callback(
1577 view_id,
1578 subscription_id,
1579 callback,
1580 );
1581 }
1582
1583 Effect::ResizeWindow { window_id } => {
1584 if let Some(window) = self.windows.get_mut(&window_id) {
1585 window
1586 .invalidation
1587 .get_or_insert(WindowInvalidation::default());
1588 }
1589 self.handle_window_moved(window_id);
1590 }
1591
1592 Effect::MoveWindow { window_id } => {
1593 self.handle_window_moved(window_id);
1594 }
1595
1596 Effect::WindowActivationObservation {
1597 window_id,
1598 subscription_id,
1599 callback,
1600 } => self.window_activation_observations.add_callback(
1601 window_id,
1602 subscription_id,
1603 callback,
1604 ),
1605
1606 Effect::ActivateWindow {
1607 window_id,
1608 is_active,
1609 } => self.handle_window_activation_effect(window_id, is_active),
1610
1611 Effect::WindowFullscreenObservation {
1612 window_id,
1613 subscription_id,
1614 callback,
1615 } => self.window_fullscreen_observations.add_callback(
1616 window_id,
1617 subscription_id,
1618 callback,
1619 ),
1620
1621 Effect::FullscreenWindow {
1622 window_id,
1623 is_fullscreen,
1624 } => self.handle_fullscreen_effect(window_id, is_fullscreen),
1625
1626 Effect::WindowBoundsObservation {
1627 window_id,
1628 subscription_id,
1629 callback,
1630 } => self.window_bounds_observations.add_callback(
1631 window_id,
1632 subscription_id,
1633 callback,
1634 ),
1635
1636 Effect::RefreshWindows => {
1637 refreshing = true;
1638 }
1639
1640 Effect::ActionDispatchNotification { action_id } => {
1641 self.handle_action_dispatch_notification_effect(action_id)
1642 }
1643 Effect::WindowShouldCloseSubscription {
1644 window_id,
1645 callback,
1646 } => {
1647 self.handle_window_should_close_subscription_effect(window_id, callback)
1648 }
1649 Effect::Keystroke {
1650 window_id,
1651 keystroke,
1652 handled_by,
1653 result,
1654 } => self.handle_keystroke_effect(window_id, keystroke, handled_by, result),
1655 Effect::ActiveLabeledTasksChanged => {
1656 self.handle_active_labeled_tasks_changed_effect()
1657 }
1658 Effect::ActiveLabeledTasksObservation {
1659 subscription_id,
1660 callback,
1661 } => self.active_labeled_task_observations.add_callback(
1662 (),
1663 subscription_id,
1664 callback,
1665 ),
1666 }
1667 self.pending_notifications.clear();
1668 self.remove_dropped_entities();
1669 } else {
1670 self.remove_dropped_entities();
1671
1672 if refreshing {
1673 self.perform_window_refresh();
1674 } else {
1675 self.update_windows();
1676 }
1677
1678 if self.pending_effects.is_empty() {
1679 for callback in after_window_update_callbacks.drain(..) {
1680 callback(self);
1681 }
1682
1683 if self.pending_effects.is_empty() {
1684 self.flushing_effects = false;
1685 self.pending_notifications.clear();
1686 self.pending_global_notifications.clear();
1687 break;
1688 }
1689 }
1690
1691 refreshing = false;
1692 }
1693 }
1694 }
1695 }
1696
1697 fn update_windows(&mut self) {
1698 let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1699 for window_id in window_ids {
1700 self.update_window(window_id, |cx| {
1701 if let Some(mut invalidation) = cx.window.invalidation.take() {
1702 let appearance = cx.window.platform_window.appearance();
1703 cx.invalidate(&mut invalidation, appearance);
1704 if let Some(scene) = cx.build_scene().log_err() {
1705 cx.window.platform_window.present_scene(scene);
1706 }
1707 }
1708 });
1709 }
1710 }
1711
1712 fn window_was_resized(&mut self, window_id: usize) {
1713 self.pending_effects
1714 .push_back(Effect::ResizeWindow { window_id });
1715 }
1716
1717 fn window_was_moved(&mut self, window_id: usize) {
1718 self.pending_effects
1719 .push_back(Effect::MoveWindow { window_id });
1720 }
1721
1722 fn window_was_fullscreen_changed(&mut self, window_id: usize, is_fullscreen: bool) {
1723 self.pending_effects.push_back(Effect::FullscreenWindow {
1724 window_id,
1725 is_fullscreen,
1726 });
1727 }
1728
1729 fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
1730 self.pending_effects.push_back(Effect::ActivateWindow {
1731 window_id,
1732 is_active,
1733 });
1734 }
1735
1736 fn keystroke(
1737 &mut self,
1738 window_id: usize,
1739 keystroke: Keystroke,
1740 handled_by: Option<Box<dyn Action>>,
1741 result: MatchResult,
1742 ) {
1743 self.pending_effects.push_back(Effect::Keystroke {
1744 window_id,
1745 keystroke,
1746 handled_by,
1747 result,
1748 });
1749 }
1750
1751 pub fn refresh_windows(&mut self) {
1752 self.pending_effects.push_back(Effect::RefreshWindows);
1753 }
1754
1755 fn perform_window_refresh(&mut self) {
1756 let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1757 for window_id in window_ids {
1758 self.update_window(window_id, |cx| {
1759 let mut invalidation = cx.window.invalidation.take().unwrap_or_default();
1760 invalidation
1761 .updated
1762 .extend(cx.window.rendered_views.keys().copied());
1763 cx.invalidate(&mut invalidation, cx.window.platform_window.appearance());
1764 cx.refreshing = true;
1765 if let Some(scene) = cx.build_scene().log_err() {
1766 cx.window.platform_window.present_scene(scene);
1767 }
1768 });
1769 }
1770 }
1771
1772 fn emit_global_event(&mut self, payload: Box<dyn Any>) {
1773 let type_id = (&*payload).type_id();
1774
1775 let mut subscriptions = self.global_subscriptions.clone();
1776 subscriptions.emit(type_id, |callback| {
1777 callback(payload.as_ref(), self);
1778 true //Always alive
1779 });
1780 }
1781
1782 fn handle_view_notification_effect(
1783 &mut self,
1784 observed_window_id: usize,
1785 observed_view_id: usize,
1786 ) {
1787 let view_key = (observed_window_id, observed_view_id);
1788 if let Some((view, mut view_metadata)) = self
1789 .views
1790 .remove(&view_key)
1791 .zip(self.views_metadata.remove(&view_key))
1792 {
1793 if let Some(window) = self.windows.get_mut(&observed_window_id) {
1794 window
1795 .invalidation
1796 .get_or_insert_with(Default::default)
1797 .updated
1798 .insert(observed_view_id);
1799 }
1800
1801 view.update_keymap_context(&mut view_metadata.keymap_context, self);
1802 self.views.insert(view_key, view);
1803 self.views_metadata.insert(view_key, view_metadata);
1804
1805 let mut observations = self.observations.clone();
1806 observations.emit(observed_view_id, |callback| callback(self));
1807 }
1808 }
1809
1810 fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
1811 self.release_observations
1812 .clone()
1813 .emit(entity_id, |callback| {
1814 callback(entity, self);
1815 // Release observations happen one time. So clear the callback by returning false
1816 false
1817 })
1818 }
1819
1820 fn handle_fullscreen_effect(&mut self, window_id: usize, is_fullscreen: bool) {
1821 self.update_window(window_id, |cx| {
1822 cx.window.is_fullscreen = is_fullscreen;
1823
1824 let mut fullscreen_observations = cx.window_fullscreen_observations.clone();
1825 fullscreen_observations.emit(window_id, |callback| callback(is_fullscreen, cx));
1826
1827 if let Some(uuid) = cx.window_display_uuid() {
1828 let bounds = cx.window_bounds();
1829 let mut bounds_observations = cx.window_bounds_observations.clone();
1830 bounds_observations.emit(window_id, |callback| callback(bounds, uuid, cx));
1831 }
1832
1833 Some(())
1834 });
1835 }
1836
1837 fn handle_keystroke_effect(
1838 &mut self,
1839 window_id: usize,
1840 keystroke: Keystroke,
1841 handled_by: Option<Box<dyn Action>>,
1842 result: MatchResult,
1843 ) {
1844 self.update_window(window_id, |cx| {
1845 let mut observations = cx.keystroke_observations.clone();
1846 observations.emit(window_id, move |callback| {
1847 callback(&keystroke, &result, handled_by.as_ref(), cx)
1848 });
1849 });
1850 }
1851
1852 fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
1853 self.update_window(window_id, |cx| {
1854 if cx.window.is_active == active {
1855 return;
1856 }
1857 cx.window.is_active = active;
1858
1859 if let Some(focused_id) = cx.window.focused_view_id {
1860 for view_id in cx.ancestors(focused_id).collect::<Vec<_>>() {
1861 cx.update_any_view(view_id, |view, cx| {
1862 if active {
1863 view.focus_in(focused_id, cx, view_id);
1864 } else {
1865 view.focus_out(focused_id, cx, view_id);
1866 }
1867 });
1868 }
1869 }
1870
1871 let mut observations = cx.window_activation_observations.clone();
1872 observations.emit(window_id, |callback| callback(active, cx));
1873 });
1874 }
1875
1876 fn handle_focus_effect(&mut self, window_id: usize, mut focused_id: Option<usize>) {
1877 let mut blurred_id = None;
1878 self.update_window(window_id, |cx| {
1879 if cx.window.focused_view_id == focused_id {
1880 focused_id = None;
1881 return;
1882 }
1883 blurred_id = cx.window.focused_view_id;
1884 cx.window.focused_view_id = focused_id;
1885
1886 let blurred_parents = blurred_id
1887 .map(|blurred_id| cx.ancestors(blurred_id).collect::<Vec<_>>())
1888 .unwrap_or_default();
1889 let focused_parents = focused_id
1890 .map(|focused_id| cx.ancestors(focused_id).collect::<Vec<_>>())
1891 .unwrap_or_default();
1892
1893 if let Some(blurred_id) = blurred_id {
1894 for view_id in blurred_parents.iter().copied() {
1895 if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
1896 view.focus_out(blurred_id, cx, view_id);
1897 cx.views.insert((window_id, view_id), view);
1898 }
1899 }
1900
1901 let mut subscriptions = cx.focus_observations.clone();
1902 subscriptions.emit(blurred_id, |callback| callback(false, cx));
1903 }
1904
1905 if let Some(focused_id) = focused_id {
1906 for view_id in focused_parents {
1907 if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
1908 view.focus_in(focused_id, cx, view_id);
1909 cx.views.insert((window_id, view_id), view);
1910 }
1911 }
1912
1913 let mut subscriptions = cx.focus_observations.clone();
1914 subscriptions.emit(focused_id, |callback| callback(true, cx));
1915 }
1916 });
1917 }
1918
1919 fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
1920 self.action_dispatch_observations
1921 .clone()
1922 .emit((), |callback| {
1923 callback(action_id, self);
1924 true
1925 });
1926 }
1927
1928 fn handle_window_should_close_subscription_effect(
1929 &mut self,
1930 window_id: usize,
1931 mut callback: WindowShouldCloseSubscriptionCallback,
1932 ) {
1933 let mut app = self.upgrade();
1934 if let Some(window) = self.windows.get_mut(&window_id) {
1935 window
1936 .platform_window
1937 .on_should_close(Box::new(move || app.update(|cx| callback(cx))))
1938 }
1939 }
1940
1941 fn handle_window_moved(&mut self, window_id: usize) {
1942 self.update_window(window_id, |cx| {
1943 if let Some(display) = cx.window_display_uuid() {
1944 let bounds = cx.window_bounds();
1945 cx.window_bounds_observations
1946 .clone()
1947 .emit(window_id, move |callback| {
1948 callback(bounds, display, cx);
1949 true
1950 });
1951 }
1952 });
1953 }
1954
1955 fn handle_active_labeled_tasks_changed_effect(&mut self) {
1956 self.active_labeled_task_observations
1957 .clone()
1958 .emit((), move |callback| {
1959 callback(self);
1960 true
1961 });
1962 }
1963
1964 pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
1965 self.pending_effects
1966 .push_back(Effect::Focus { window_id, view_id });
1967 }
1968
1969 fn spawn_internal<F, Fut, T>(&mut self, task_name: Option<&'static str>, f: F) -> Task<T>
1970 where
1971 F: FnOnce(AsyncAppContext) -> Fut,
1972 Fut: 'static + Future<Output = T>,
1973 T: 'static,
1974 {
1975 let label_id = task_name.map(|task_name| {
1976 let id = post_inc(&mut self.next_labeled_task_id);
1977 self.active_labeled_tasks.insert(id, task_name);
1978 self.pending_effects
1979 .push_back(Effect::ActiveLabeledTasksChanged);
1980 id
1981 });
1982
1983 let future = f(self.to_async());
1984 let cx = self.to_async();
1985 self.foreground.spawn(async move {
1986 let result = future.await;
1987 let mut cx = cx.0.borrow_mut();
1988
1989 if let Some(completed_label_id) = label_id {
1990 cx.active_labeled_tasks.remove(&completed_label_id);
1991 cx.pending_effects
1992 .push_back(Effect::ActiveLabeledTasksChanged);
1993 }
1994 cx.flush_effects();
1995 result
1996 })
1997 }
1998
1999 pub fn spawn_labeled<F, Fut, T>(&mut self, task_name: &'static str, f: F) -> Task<T>
2000 where
2001 F: FnOnce(AsyncAppContext) -> Fut,
2002 Fut: 'static + Future<Output = T>,
2003 T: 'static,
2004 {
2005 self.spawn_internal(Some(task_name), f)
2006 }
2007
2008 pub fn spawn<F, Fut, T>(&mut self, f: F) -> Task<T>
2009 where
2010 F: FnOnce(AsyncAppContext) -> Fut,
2011 Fut: 'static + Future<Output = T>,
2012 T: 'static,
2013 {
2014 self.spawn_internal(None, f)
2015 }
2016
2017 pub fn to_async(&self) -> AsyncAppContext {
2018 AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2019 }
2020
2021 pub fn write_to_clipboard(&self, item: ClipboardItem) {
2022 self.platform.write_to_clipboard(item);
2023 }
2024
2025 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2026 self.platform.read_from_clipboard()
2027 }
2028
2029 #[cfg(any(test, feature = "test-support"))]
2030 pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2031 self.ref_counts.lock().leak_detector.clone()
2032 }
2033}
2034
2035impl BorrowAppContext for AppContext {
2036 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
2037 f(self)
2038 }
2039
2040 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
2041 f(self)
2042 }
2043}
2044
2045#[derive(Debug)]
2046pub enum ParentId {
2047 View(usize),
2048 Root,
2049}
2050
2051struct ViewMetadata {
2052 type_id: TypeId,
2053 keymap_context: KeymapContext,
2054}
2055
2056#[derive(Default, Clone)]
2057pub struct WindowInvalidation {
2058 pub updated: HashSet<usize>,
2059 pub removed: Vec<usize>,
2060}
2061
2062pub enum Effect {
2063 Subscription {
2064 entity_id: usize,
2065 subscription_id: usize,
2066 callback: SubscriptionCallback,
2067 },
2068 Event {
2069 entity_id: usize,
2070 payload: Box<dyn Any>,
2071 },
2072 GlobalSubscription {
2073 type_id: TypeId,
2074 subscription_id: usize,
2075 callback: GlobalSubscriptionCallback,
2076 },
2077 GlobalEvent {
2078 payload: Box<dyn Any>,
2079 },
2080 Observation {
2081 entity_id: usize,
2082 subscription_id: usize,
2083 callback: ObservationCallback,
2084 },
2085 ModelNotification {
2086 model_id: usize,
2087 },
2088 ViewNotification {
2089 window_id: usize,
2090 view_id: usize,
2091 },
2092 Deferred {
2093 callback: Box<dyn FnOnce(&mut AppContext)>,
2094 after_window_update: bool,
2095 },
2096 GlobalNotification {
2097 type_id: TypeId,
2098 },
2099 ModelRelease {
2100 model_id: usize,
2101 model: Box<dyn AnyModel>,
2102 },
2103 ViewRelease {
2104 view_id: usize,
2105 view: Box<dyn AnyView>,
2106 },
2107 Focus {
2108 window_id: usize,
2109 view_id: Option<usize>,
2110 },
2111 FocusObservation {
2112 view_id: usize,
2113 subscription_id: usize,
2114 callback: FocusObservationCallback,
2115 },
2116 ResizeWindow {
2117 window_id: usize,
2118 },
2119 MoveWindow {
2120 window_id: usize,
2121 },
2122 ActivateWindow {
2123 window_id: usize,
2124 is_active: bool,
2125 },
2126 WindowActivationObservation {
2127 window_id: usize,
2128 subscription_id: usize,
2129 callback: WindowActivationCallback,
2130 },
2131 FullscreenWindow {
2132 window_id: usize,
2133 is_fullscreen: bool,
2134 },
2135 WindowFullscreenObservation {
2136 window_id: usize,
2137 subscription_id: usize,
2138 callback: WindowFullscreenCallback,
2139 },
2140 WindowBoundsObservation {
2141 window_id: usize,
2142 subscription_id: usize,
2143 callback: WindowBoundsCallback,
2144 },
2145 Keystroke {
2146 window_id: usize,
2147 keystroke: Keystroke,
2148 handled_by: Option<Box<dyn Action>>,
2149 result: MatchResult,
2150 },
2151 RefreshWindows,
2152 ActionDispatchNotification {
2153 action_id: TypeId,
2154 },
2155 WindowShouldCloseSubscription {
2156 window_id: usize,
2157 callback: WindowShouldCloseSubscriptionCallback,
2158 },
2159 ActiveLabeledTasksChanged,
2160 ActiveLabeledTasksObservation {
2161 subscription_id: usize,
2162 callback: ActiveLabeledTasksCallback,
2163 },
2164}
2165
2166impl Debug for Effect {
2167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2168 match self {
2169 Effect::Subscription {
2170 entity_id,
2171 subscription_id,
2172 ..
2173 } => f
2174 .debug_struct("Effect::Subscribe")
2175 .field("entity_id", entity_id)
2176 .field("subscription_id", subscription_id)
2177 .finish(),
2178 Effect::Event { entity_id, .. } => f
2179 .debug_struct("Effect::Event")
2180 .field("entity_id", entity_id)
2181 .finish(),
2182 Effect::GlobalSubscription {
2183 type_id,
2184 subscription_id,
2185 ..
2186 } => f
2187 .debug_struct("Effect::Subscribe")
2188 .field("type_id", type_id)
2189 .field("subscription_id", subscription_id)
2190 .finish(),
2191 Effect::GlobalEvent { payload, .. } => f
2192 .debug_struct("Effect::GlobalEvent")
2193 .field("type_id", &(&*payload).type_id())
2194 .finish(),
2195 Effect::Observation {
2196 entity_id,
2197 subscription_id,
2198 ..
2199 } => f
2200 .debug_struct("Effect::Observation")
2201 .field("entity_id", entity_id)
2202 .field("subscription_id", subscription_id)
2203 .finish(),
2204 Effect::ModelNotification { model_id } => f
2205 .debug_struct("Effect::ModelNotification")
2206 .field("model_id", model_id)
2207 .finish(),
2208 Effect::ViewNotification { window_id, view_id } => f
2209 .debug_struct("Effect::ViewNotification")
2210 .field("window_id", window_id)
2211 .field("view_id", view_id)
2212 .finish(),
2213 Effect::GlobalNotification { type_id } => f
2214 .debug_struct("Effect::GlobalNotification")
2215 .field("type_id", type_id)
2216 .finish(),
2217 Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
2218 Effect::ModelRelease { model_id, .. } => f
2219 .debug_struct("Effect::ModelRelease")
2220 .field("model_id", model_id)
2221 .finish(),
2222 Effect::ViewRelease { view_id, .. } => f
2223 .debug_struct("Effect::ViewRelease")
2224 .field("view_id", view_id)
2225 .finish(),
2226 Effect::Focus { window_id, view_id } => f
2227 .debug_struct("Effect::Focus")
2228 .field("window_id", window_id)
2229 .field("view_id", view_id)
2230 .finish(),
2231 Effect::FocusObservation {
2232 view_id,
2233 subscription_id,
2234 ..
2235 } => f
2236 .debug_struct("Effect::FocusObservation")
2237 .field("view_id", view_id)
2238 .field("subscription_id", subscription_id)
2239 .finish(),
2240 Effect::ActionDispatchNotification { action_id, .. } => f
2241 .debug_struct("Effect::ActionDispatchNotification")
2242 .field("action_id", action_id)
2243 .finish(),
2244 Effect::ResizeWindow { window_id } => f
2245 .debug_struct("Effect::RefreshWindow")
2246 .field("window_id", window_id)
2247 .finish(),
2248 Effect::MoveWindow { window_id } => f
2249 .debug_struct("Effect::MoveWindow")
2250 .field("window_id", window_id)
2251 .finish(),
2252 Effect::WindowActivationObservation {
2253 window_id,
2254 subscription_id,
2255 ..
2256 } => f
2257 .debug_struct("Effect::WindowActivationObservation")
2258 .field("window_id", window_id)
2259 .field("subscription_id", subscription_id)
2260 .finish(),
2261 Effect::ActivateWindow {
2262 window_id,
2263 is_active,
2264 } => f
2265 .debug_struct("Effect::ActivateWindow")
2266 .field("window_id", window_id)
2267 .field("is_active", is_active)
2268 .finish(),
2269 Effect::FullscreenWindow {
2270 window_id,
2271 is_fullscreen,
2272 } => f
2273 .debug_struct("Effect::FullscreenWindow")
2274 .field("window_id", window_id)
2275 .field("is_fullscreen", is_fullscreen)
2276 .finish(),
2277 Effect::WindowFullscreenObservation {
2278 window_id,
2279 subscription_id,
2280 callback: _,
2281 } => f
2282 .debug_struct("Effect::WindowFullscreenObservation")
2283 .field("window_id", window_id)
2284 .field("subscription_id", subscription_id)
2285 .finish(),
2286
2287 Effect::WindowBoundsObservation {
2288 window_id,
2289 subscription_id,
2290 callback: _,
2291 } => f
2292 .debug_struct("Effect::WindowBoundsObservation")
2293 .field("window_id", window_id)
2294 .field("subscription_id", subscription_id)
2295 .finish(),
2296 Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2297 Effect::WindowShouldCloseSubscription { window_id, .. } => f
2298 .debug_struct("Effect::WindowShouldCloseSubscription")
2299 .field("window_id", window_id)
2300 .finish(),
2301 Effect::Keystroke {
2302 window_id,
2303 keystroke,
2304 handled_by,
2305 result,
2306 } => f
2307 .debug_struct("Effect::Keystroke")
2308 .field("window_id", window_id)
2309 .field("keystroke", keystroke)
2310 .field(
2311 "keystroke",
2312 &handled_by.as_ref().map(|handled_by| handled_by.name()),
2313 )
2314 .field("result", result)
2315 .finish(),
2316 Effect::ActiveLabeledTasksChanged => {
2317 f.debug_struct("Effect::ActiveLabeledTasksChanged").finish()
2318 }
2319 Effect::ActiveLabeledTasksObservation {
2320 subscription_id,
2321 callback: _,
2322 } => f
2323 .debug_struct("Effect::ActiveLabeledTasksObservation")
2324 .field("subscription_id", subscription_id)
2325 .finish(),
2326 }
2327 }
2328}
2329
2330pub trait AnyModel {
2331 fn as_any(&self) -> &dyn Any;
2332 fn as_any_mut(&mut self) -> &mut dyn Any;
2333 fn release(&mut self, cx: &mut AppContext);
2334 fn app_will_quit(
2335 &mut self,
2336 cx: &mut AppContext,
2337 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2338}
2339
2340impl<T> AnyModel for T
2341where
2342 T: Entity,
2343{
2344 fn as_any(&self) -> &dyn Any {
2345 self
2346 }
2347
2348 fn as_any_mut(&mut self) -> &mut dyn Any {
2349 self
2350 }
2351
2352 fn release(&mut self, cx: &mut AppContext) {
2353 self.release(cx);
2354 }
2355
2356 fn app_will_quit(
2357 &mut self,
2358 cx: &mut AppContext,
2359 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2360 self.app_will_quit(cx)
2361 }
2362}
2363
2364pub trait AnyView {
2365 fn as_any(&self) -> &dyn Any;
2366 fn as_any_mut(&mut self) -> &mut dyn Any;
2367 fn release(&mut self, cx: &mut AppContext);
2368 fn app_will_quit(
2369 &mut self,
2370 cx: &mut AppContext,
2371 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2372 fn ui_name(&self) -> &'static str;
2373 fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement>;
2374 fn focus_in<'a, 'b>(&mut self, focused_id: usize, cx: &mut WindowContext<'a>, view_id: usize);
2375 fn focus_out(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize);
2376 fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2377 fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2378 fn modifiers_changed(
2379 &mut self,
2380 event: &ModifiersChangedEvent,
2381 cx: &mut WindowContext,
2382 view_id: usize,
2383 ) -> bool;
2384 fn update_keymap_context(&self, keymap: &mut KeymapContext, cx: &AppContext);
2385 fn debug_json(&self, cx: &WindowContext) -> serde_json::Value;
2386
2387 fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String>;
2388 fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2389 fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2390 fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize);
2391 fn replace_text_in_range(
2392 &mut self,
2393 range: Option<Range<usize>>,
2394 text: &str,
2395 cx: &mut WindowContext,
2396 view_id: usize,
2397 );
2398 fn replace_and_mark_text_in_range(
2399 &mut self,
2400 range: Option<Range<usize>>,
2401 new_text: &str,
2402 new_selected_range: Option<Range<usize>>,
2403 cx: &mut WindowContext,
2404 view_id: usize,
2405 );
2406 fn any_handle(&self, window_id: usize, view_id: usize, cx: &AppContext) -> AnyViewHandle {
2407 AnyViewHandle::new(
2408 window_id,
2409 view_id,
2410 self.as_any().type_id(),
2411 cx.ref_counts.clone(),
2412 )
2413 }
2414}
2415
2416impl<V> AnyView for V
2417where
2418 V: View,
2419{
2420 fn as_any(&self) -> &dyn Any {
2421 self
2422 }
2423
2424 fn as_any_mut(&mut self) -> &mut dyn Any {
2425 self
2426 }
2427
2428 fn release(&mut self, cx: &mut AppContext) {
2429 self.release(cx);
2430 }
2431
2432 fn app_will_quit(
2433 &mut self,
2434 cx: &mut AppContext,
2435 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2436 self.app_will_quit(cx)
2437 }
2438
2439 fn ui_name(&self) -> &'static str {
2440 V::ui_name()
2441 }
2442
2443 fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement> {
2444 let mut view_context = ViewContext::mutable(cx, view_id);
2445 let element = V::render(self, &mut view_context);
2446 let view = WeakViewHandle::new(cx.window_id, view_id);
2447 Box::new(RootElement::new(element, view))
2448 }
2449
2450 fn focus_in(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize) {
2451 let mut cx = ViewContext::mutable(cx, view_id);
2452 let focused_view_handle: AnyViewHandle = if view_id == focused_id {
2453 cx.handle().into_any()
2454 } else {
2455 let focused_type = cx
2456 .views_metadata
2457 .get(&(cx.window_id, focused_id))
2458 .unwrap()
2459 .type_id;
2460 AnyViewHandle::new(
2461 cx.window_id,
2462 focused_id,
2463 focused_type,
2464 cx.ref_counts.clone(),
2465 )
2466 };
2467 View::focus_in(self, focused_view_handle, &mut cx);
2468 }
2469
2470 fn focus_out(&mut self, blurred_id: usize, cx: &mut WindowContext, view_id: usize) {
2471 let mut cx = ViewContext::mutable(cx, view_id);
2472 let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
2473 cx.handle().into_any()
2474 } else {
2475 let blurred_type = cx
2476 .views_metadata
2477 .get(&(cx.window_id, blurred_id))
2478 .unwrap()
2479 .type_id;
2480 AnyViewHandle::new(
2481 cx.window_id,
2482 blurred_id,
2483 blurred_type,
2484 cx.ref_counts.clone(),
2485 )
2486 };
2487 View::focus_out(self, blurred_view_handle, &mut cx);
2488 }
2489
2490 fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2491 let mut cx = ViewContext::mutable(cx, view_id);
2492 View::key_down(self, event, &mut cx)
2493 }
2494
2495 fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2496 let mut cx = ViewContext::mutable(cx, view_id);
2497 View::key_up(self, event, &mut cx)
2498 }
2499
2500 fn modifiers_changed(
2501 &mut self,
2502 event: &ModifiersChangedEvent,
2503 cx: &mut WindowContext,
2504 view_id: usize,
2505 ) -> bool {
2506 let mut cx = ViewContext::mutable(cx, view_id);
2507 View::modifiers_changed(self, event, &mut cx)
2508 }
2509
2510 fn update_keymap_context(&self, keymap: &mut KeymapContext, cx: &AppContext) {
2511 View::update_keymap_context(self, keymap, cx)
2512 }
2513
2514 fn debug_json(&self, cx: &WindowContext) -> serde_json::Value {
2515 View::debug_json(self, cx)
2516 }
2517
2518 fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String> {
2519 View::text_for_range(self, range, cx)
2520 }
2521
2522 fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2523 View::selected_text_range(self, cx)
2524 }
2525
2526 fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2527 View::marked_text_range(self, cx)
2528 }
2529
2530 fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize) {
2531 let mut cx = ViewContext::mutable(cx, view_id);
2532 View::unmark_text(self, &mut cx)
2533 }
2534
2535 fn replace_text_in_range(
2536 &mut self,
2537 range: Option<Range<usize>>,
2538 text: &str,
2539 cx: &mut WindowContext,
2540 view_id: usize,
2541 ) {
2542 let mut cx = ViewContext::mutable(cx, view_id);
2543 View::replace_text_in_range(self, range, text, &mut cx)
2544 }
2545
2546 fn replace_and_mark_text_in_range(
2547 &mut self,
2548 range: Option<Range<usize>>,
2549 new_text: &str,
2550 new_selected_range: Option<Range<usize>>,
2551 cx: &mut WindowContext,
2552 view_id: usize,
2553 ) {
2554 let mut cx = ViewContext::mutable(cx, view_id);
2555 View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
2556 }
2557}
2558
2559pub struct ModelContext<'a, T: ?Sized> {
2560 app: &'a mut AppContext,
2561 model_id: usize,
2562 model_type: PhantomData<T>,
2563 halt_stream: bool,
2564}
2565
2566impl<'a, T: Entity> ModelContext<'a, T> {
2567 fn new(app: &'a mut AppContext, model_id: usize) -> Self {
2568 Self {
2569 app,
2570 model_id,
2571 model_type: PhantomData,
2572 halt_stream: false,
2573 }
2574 }
2575
2576 pub fn background(&self) -> &Arc<executor::Background> {
2577 &self.app.background
2578 }
2579
2580 pub fn halt_stream(&mut self) {
2581 self.halt_stream = true;
2582 }
2583
2584 pub fn model_id(&self) -> usize {
2585 self.model_id
2586 }
2587
2588 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2589 where
2590 S: Entity,
2591 F: FnOnce(&mut ModelContext<S>) -> S,
2592 {
2593 self.app.add_model(build_model)
2594 }
2595
2596 pub fn emit(&mut self, payload: T::Event) {
2597 self.app.pending_effects.push_back(Effect::Event {
2598 entity_id: self.model_id,
2599 payload: Box::new(payload),
2600 });
2601 }
2602
2603 pub fn notify(&mut self) {
2604 self.app.notify_model(self.model_id);
2605 }
2606
2607 pub fn subscribe<S: Entity, F>(
2608 &mut self,
2609 handle: &ModelHandle<S>,
2610 mut callback: F,
2611 ) -> Subscription
2612 where
2613 S::Event: 'static,
2614 F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2615 {
2616 let subscriber = self.weak_handle();
2617 self.app
2618 .subscribe_internal(handle, move |emitter, event, cx| {
2619 if let Some(subscriber) = subscriber.upgrade(cx) {
2620 subscriber.update(cx, |subscriber, cx| {
2621 callback(subscriber, emitter, event, cx);
2622 });
2623 true
2624 } else {
2625 false
2626 }
2627 })
2628 }
2629
2630 pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2631 where
2632 S: Entity,
2633 F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2634 {
2635 let observer = self.weak_handle();
2636 self.app.observe_internal(handle, move |observed, cx| {
2637 if let Some(observer) = observer.upgrade(cx) {
2638 observer.update(cx, |observer, cx| {
2639 callback(observer, observed, cx);
2640 });
2641 true
2642 } else {
2643 false
2644 }
2645 })
2646 }
2647
2648 pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
2649 where
2650 G: Any,
2651 F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2652 {
2653 let observer = self.weak_handle();
2654 self.app.observe_global::<G, _>(move |cx| {
2655 if let Some(observer) = observer.upgrade(cx) {
2656 observer.update(cx, |observer, cx| callback(observer, cx));
2657 }
2658 })
2659 }
2660
2661 pub fn observe_release<S, F>(
2662 &mut self,
2663 handle: &ModelHandle<S>,
2664 mut callback: F,
2665 ) -> Subscription
2666 where
2667 S: Entity,
2668 F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
2669 {
2670 let observer = self.weak_handle();
2671 self.app.observe_release(handle, move |released, cx| {
2672 if let Some(observer) = observer.upgrade(cx) {
2673 observer.update(cx, |observer, cx| {
2674 callback(observer, released, cx);
2675 });
2676 }
2677 })
2678 }
2679
2680 pub fn handle(&self) -> ModelHandle<T> {
2681 ModelHandle::new(self.model_id, &self.app.ref_counts)
2682 }
2683
2684 pub fn weak_handle(&self) -> WeakModelHandle<T> {
2685 WeakModelHandle::new(self.model_id)
2686 }
2687
2688 pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
2689 where
2690 F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2691 Fut: 'static + Future<Output = S>,
2692 S: 'static,
2693 {
2694 let handle = self.handle();
2695 self.app.spawn(|cx| f(handle, cx))
2696 }
2697
2698 pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
2699 where
2700 F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2701 Fut: 'static + Future<Output = S>,
2702 S: 'static,
2703 {
2704 let handle = self.weak_handle();
2705 self.app.spawn(|cx| f(handle, cx))
2706 }
2707}
2708
2709impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2710 fn as_ref(&self) -> &AppContext {
2711 &self.app
2712 }
2713}
2714
2715impl<M> AsMut<AppContext> for ModelContext<'_, M> {
2716 fn as_mut(&mut self) -> &mut AppContext {
2717 self.app
2718 }
2719}
2720
2721impl<M> BorrowAppContext for ModelContext<'_, M> {
2722 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
2723 self.app.read_with(f)
2724 }
2725
2726 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
2727 self.app.update(f)
2728 }
2729}
2730
2731impl<M> Deref for ModelContext<'_, M> {
2732 type Target = AppContext;
2733
2734 fn deref(&self) -> &Self::Target {
2735 self.app
2736 }
2737}
2738
2739impl<M> DerefMut for ModelContext<'_, M> {
2740 fn deref_mut(&mut self) -> &mut Self::Target {
2741 &mut self.app
2742 }
2743}
2744
2745pub struct ViewContext<'a, 'b, T: ?Sized> {
2746 window_context: Reference<'b, WindowContext<'a>>,
2747 view_id: usize,
2748 view_type: PhantomData<T>,
2749}
2750
2751impl<'a, 'b, T: View> Deref for ViewContext<'a, 'b, T> {
2752 type Target = WindowContext<'a>;
2753
2754 fn deref(&self) -> &Self::Target {
2755 &self.window_context
2756 }
2757}
2758
2759impl<T: View> DerefMut for ViewContext<'_, '_, T> {
2760 fn deref_mut(&mut self) -> &mut Self::Target {
2761 &mut self.window_context
2762 }
2763}
2764
2765impl<'a, 'b, V: View> ViewContext<'a, 'b, V> {
2766 pub(crate) fn mutable(window_context: &'b mut WindowContext<'a>, view_id: usize) -> Self {
2767 Self {
2768 window_context: Reference::Mutable(window_context),
2769 view_id,
2770 view_type: PhantomData,
2771 }
2772 }
2773
2774 pub(crate) fn immutable(window_context: &'b WindowContext<'a>, view_id: usize) -> Self {
2775 Self {
2776 window_context: Reference::Immutable(window_context),
2777 view_id,
2778 view_type: PhantomData,
2779 }
2780 }
2781
2782 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2783 &mut self.window_context
2784 }
2785
2786 pub fn handle(&self) -> ViewHandle<V> {
2787 ViewHandle::new(
2788 self.window_id,
2789 self.view_id,
2790 &self.window_context.ref_counts,
2791 )
2792 }
2793
2794 pub fn weak_handle(&self) -> WeakViewHandle<V> {
2795 WeakViewHandle::new(self.window_id, self.view_id)
2796 }
2797
2798 pub fn parent(&self) -> Option<usize> {
2799 self.window_context.parent(self.view_id)
2800 }
2801
2802 pub fn window_id(&self) -> usize {
2803 self.window_id
2804 }
2805
2806 pub fn view_id(&self) -> usize {
2807 self.view_id
2808 }
2809
2810 pub fn foreground(&self) -> &Rc<executor::Foreground> {
2811 self.window_context.foreground()
2812 }
2813
2814 pub fn background_executor(&self) -> &Arc<executor::Background> {
2815 &self.window_context.background
2816 }
2817
2818 pub fn platform(&self) -> &Arc<dyn Platform> {
2819 self.window_context.platform()
2820 }
2821
2822 pub fn prompt_for_paths(
2823 &self,
2824 options: PathPromptOptions,
2825 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2826 self.window_context.prompt_for_paths(options)
2827 }
2828
2829 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2830 self.window_context.prompt_for_new_path(directory)
2831 }
2832
2833 pub fn reveal_path(&self, path: &Path) {
2834 self.window_context.reveal_path(path)
2835 }
2836
2837 pub fn focus(&mut self, handle: &AnyViewHandle) {
2838 self.window_context
2839 .focus(handle.window_id, Some(handle.view_id));
2840 }
2841
2842 pub fn focus_self(&mut self) {
2843 let window_id = self.window_id;
2844 let view_id = self.view_id;
2845 self.window_context.focus(window_id, Some(view_id));
2846 }
2847
2848 pub fn is_self_focused(&self) -> bool {
2849 self.window.focused_view_id == Some(self.view_id)
2850 }
2851
2852 pub fn is_parent_view_focused(&self) -> bool {
2853 if let Some(parent_view_id) = self.ancestors(self.view_id).next().clone() {
2854 self.focused_view_id() == Some(parent_view_id)
2855 } else {
2856 false
2857 }
2858 }
2859
2860 pub fn focus_parent_view(&mut self) {
2861 let next = self.ancestors(self.view_id).next().clone();
2862 if let Some(parent_view_id) = next {
2863 let window_id = self.window_id;
2864 self.window_context.focus(window_id, Some(parent_view_id));
2865 }
2866 }
2867
2868 pub fn is_child(&self, view: impl Into<AnyViewHandle>) -> bool {
2869 let view = view.into();
2870 if self.window_id != view.window_id {
2871 return false;
2872 }
2873 self.ancestors(view.view_id)
2874 .skip(1) // Skip self id
2875 .any(|parent| parent == self.view_id)
2876 }
2877
2878 pub fn blur(&mut self) {
2879 let window_id = self.window_id;
2880 self.window_context.focus(window_id, None);
2881 }
2882
2883 pub fn on_window_should_close<F>(&mut self, mut callback: F)
2884 where
2885 F: 'static + FnMut(&mut V, &mut ViewContext<V>) -> bool,
2886 {
2887 let window_id = self.window_id;
2888 let view = self.weak_handle();
2889 self.pending_effects
2890 .push_back(Effect::WindowShouldCloseSubscription {
2891 window_id,
2892 callback: Box::new(move |cx| {
2893 cx.update_window(window_id, |cx| {
2894 if let Some(view) = view.upgrade(cx) {
2895 view.update(cx, |view, cx| callback(view, cx))
2896 } else {
2897 true
2898 }
2899 })
2900 .unwrap_or(true)
2901 }),
2902 });
2903 }
2904
2905 pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2906 where
2907 S: View,
2908 F: FnOnce(&mut ViewContext<S>) -> S,
2909 {
2910 self.window_context
2911 .build_and_insert_view(ParentId::View(self.view_id), |cx| Some(build_view(cx)))
2912 .unwrap()
2913 }
2914
2915 pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2916 where
2917 S: View,
2918 F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2919 {
2920 self.window_context
2921 .build_and_insert_view(ParentId::View(self.view_id), build_view)
2922 }
2923
2924 pub fn reparent(&mut self, view_handle: &AnyViewHandle) {
2925 if self.window_id != view_handle.window_id {
2926 panic!("Can't reparent view to a view from a different window");
2927 }
2928 self.parents
2929 .remove(&(view_handle.window_id, view_handle.view_id));
2930 let new_parent_id = self.view_id;
2931 self.parents.insert(
2932 (view_handle.window_id, view_handle.view_id),
2933 ParentId::View(new_parent_id),
2934 );
2935 }
2936
2937 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2938 where
2939 E: Entity,
2940 E::Event: 'static,
2941 H: Handle<E>,
2942 F: 'static + FnMut(&mut V, H, &E::Event, &mut ViewContext<V>),
2943 {
2944 let subscriber = self.weak_handle();
2945 self.window_context
2946 .subscribe_internal(handle, move |emitter, event, cx| {
2947 if let Some(subscriber) = subscriber.upgrade(cx) {
2948 subscriber.update(cx, |subscriber, cx| {
2949 callback(subscriber, emitter, event, cx);
2950 });
2951 true
2952 } else {
2953 false
2954 }
2955 })
2956 }
2957
2958 pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2959 where
2960 E: Entity,
2961 H: Handle<E>,
2962 F: 'static + FnMut(&mut V, H, &mut ViewContext<V>),
2963 {
2964 let window_id = self.window_id;
2965 let observer = self.weak_handle();
2966 self.window_context
2967 .observe_internal(handle, move |observed, cx| {
2968 cx.update_window(window_id, |cx| {
2969 if let Some(observer) = observer.upgrade(cx) {
2970 observer.update(cx, |observer, cx| {
2971 callback(observer, observed, cx);
2972 });
2973 true
2974 } else {
2975 false
2976 }
2977 })
2978 .unwrap_or(false)
2979 })
2980 }
2981
2982 pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
2983 where
2984 G: Any,
2985 F: 'static + FnMut(&mut V, &mut ViewContext<V>),
2986 {
2987 let window_id = self.window_id;
2988 let observer = self.weak_handle();
2989 self.window_context.observe_global::<G, _>(move |cx| {
2990 cx.update_window(window_id, |cx| {
2991 if let Some(observer) = observer.upgrade(cx) {
2992 observer.update(cx, |observer, cx| callback(observer, cx));
2993 }
2994 });
2995 })
2996 }
2997
2998 pub fn observe_focus<F, W>(&mut self, handle: &ViewHandle<W>, mut callback: F) -> Subscription
2999 where
3000 F: 'static + FnMut(&mut V, ViewHandle<W>, bool, &mut ViewContext<V>),
3001 W: View,
3002 {
3003 let observer = self.weak_handle();
3004 self.window_context
3005 .observe_focus(handle, move |observed, focused, cx| {
3006 if let Some(observer) = observer.upgrade(cx) {
3007 observer.update(cx, |observer, cx| {
3008 callback(observer, observed, focused, cx);
3009 });
3010 true
3011 } else {
3012 false
3013 }
3014 })
3015 }
3016
3017 pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3018 where
3019 E: Entity,
3020 H: Handle<E>,
3021 F: 'static + FnMut(&mut V, &E, &mut ViewContext<V>),
3022 {
3023 let window_id = self.window_id;
3024 let observer = self.weak_handle();
3025 self.window_context
3026 .observe_release(handle, move |released, cx| {
3027 cx.update_window(window_id, |cx| {
3028 if let Some(observer) = observer.upgrade(cx) {
3029 observer.update(cx, |observer, cx| {
3030 callback(observer, released, cx);
3031 });
3032 }
3033 });
3034 })
3035 }
3036
3037 pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3038 where
3039 F: 'static + FnMut(&mut V, TypeId, &mut ViewContext<V>),
3040 {
3041 let window_id = self.window_id;
3042 let observer = self.weak_handle();
3043 self.window_context.observe_actions(move |action_id, cx| {
3044 cx.update_window(window_id, |cx| {
3045 if let Some(observer) = observer.upgrade(cx) {
3046 observer.update(cx, |observer, cx| {
3047 callback(observer, action_id, cx);
3048 });
3049 }
3050 });
3051 })
3052 }
3053
3054 pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3055 where
3056 F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3057 {
3058 let observer = self.weak_handle();
3059 self.window_context
3060 .observe_window_activation(move |active, cx| {
3061 if let Some(observer) = observer.upgrade(cx) {
3062 observer.update(cx, |observer, cx| {
3063 callback(observer, active, cx);
3064 });
3065 true
3066 } else {
3067 false
3068 }
3069 })
3070 }
3071
3072 pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3073 where
3074 F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3075 {
3076 let observer = self.weak_handle();
3077 self.window_context.observe_fullscreen(move |active, cx| {
3078 if let Some(observer) = observer.upgrade(cx) {
3079 observer.update(cx, |observer, cx| {
3080 callback(observer, active, cx);
3081 });
3082 true
3083 } else {
3084 false
3085 }
3086 })
3087 }
3088
3089 pub fn observe_keystrokes<F>(&mut self, mut callback: F) -> Subscription
3090 where
3091 F: 'static
3092 + FnMut(
3093 &mut V,
3094 &Keystroke,
3095 Option<&Box<dyn Action>>,
3096 &MatchResult,
3097 &mut ViewContext<V>,
3098 ) -> bool,
3099 {
3100 let observer = self.weak_handle();
3101 self.window_context
3102 .observe_keystrokes(move |keystroke, result, handled_by, cx| {
3103 if let Some(observer) = observer.upgrade(cx) {
3104 observer.update(cx, |observer, cx| {
3105 callback(observer, keystroke, handled_by, result, cx);
3106 });
3107 true
3108 } else {
3109 false
3110 }
3111 })
3112 }
3113
3114 pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
3115 where
3116 F: 'static + FnMut(&mut V, WindowBounds, Uuid, &mut ViewContext<V>),
3117 {
3118 let observer = self.weak_handle();
3119 self.window_context
3120 .observe_window_bounds(move |bounds, display, cx| {
3121 if let Some(observer) = observer.upgrade(cx) {
3122 observer.update(cx, |observer, cx| {
3123 callback(observer, bounds, display, cx);
3124 });
3125 true
3126 } else {
3127 false
3128 }
3129 })
3130 }
3131
3132 pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
3133 where
3134 F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3135 {
3136 let window_id = self.window_id;
3137 let observer = self.weak_handle();
3138 self.window_context.observe_active_labeled_tasks(move |cx| {
3139 cx.update_window(window_id, |cx| {
3140 if let Some(observer) = observer.upgrade(cx) {
3141 observer.update(cx, |observer, cx| {
3142 callback(observer, cx);
3143 });
3144 true
3145 } else {
3146 false
3147 }
3148 })
3149 .unwrap_or(false)
3150 })
3151 }
3152
3153 pub fn emit(&mut self, payload: V::Event) {
3154 self.window_context
3155 .pending_effects
3156 .push_back(Effect::Event {
3157 entity_id: self.view_id,
3158 payload: Box::new(payload),
3159 });
3160 }
3161
3162 pub fn notify(&mut self) {
3163 let window_id = self.window_id;
3164 let view_id = self.view_id;
3165 self.window_context.notify_view(window_id, view_id);
3166 }
3167
3168 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>)) {
3169 let handle = self.handle();
3170 self.window_context
3171 .defer(move |cx| handle.update(cx, |view, cx| callback(view, cx)))
3172 }
3173
3174 pub fn after_window_update(
3175 &mut self,
3176 callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>),
3177 ) {
3178 let window_id = self.window_id;
3179 let handle = self.handle();
3180 self.window_context.after_window_update(move |cx| {
3181 cx.update_window(window_id, |cx| {
3182 handle.update(cx, |view, cx| {
3183 callback(view, cx);
3184 })
3185 });
3186 })
3187 }
3188
3189 pub fn propagate_action(&mut self) {
3190 self.window_context.halt_action_dispatch = false;
3191 }
3192
3193 pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
3194 where
3195 F: FnOnce(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3196 Fut: 'static + Future<Output = S>,
3197 S: 'static,
3198 {
3199 let handle = self.weak_handle();
3200 self.window_context
3201 .spawn_labeled(task_label, |cx| f(handle, cx))
3202 }
3203
3204 pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
3205 where
3206 F: FnOnce(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3207 Fut: 'static + Future<Output = S>,
3208 S: 'static,
3209 {
3210 let handle = self.weak_handle();
3211 self.window_context.spawn(|cx| f(handle, cx))
3212 }
3213
3214 pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3215 let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3216 MouseState {
3217 hovered: self.window.hovered_region_ids.contains(®ion_id),
3218 clicked: self
3219 .window
3220 .clicked_region_ids
3221 .get(®ion_id)
3222 .and_then(|_| self.window.clicked_button),
3223 accessed_hovered: false,
3224 accessed_clicked: false,
3225 }
3226 }
3227
3228 pub fn element_state<Tag: 'static, T: 'static>(
3229 &mut self,
3230 element_id: usize,
3231 initial: T,
3232 ) -> ElementStateHandle<T> {
3233 let id = ElementStateId {
3234 view_id: self.view_id(),
3235 element_id,
3236 tag: TypeId::of::<Tag>(),
3237 };
3238 self.element_states
3239 .entry(id)
3240 .or_insert_with(|| Box::new(initial));
3241 ElementStateHandle::new(id, self.frame_count, &self.ref_counts)
3242 }
3243
3244 pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3245 &mut self,
3246 element_id: usize,
3247 ) -> ElementStateHandle<T> {
3248 self.element_state::<Tag, T>(element_id, T::default())
3249 }
3250}
3251
3252impl<V> BorrowAppContext for ViewContext<'_, '_, V> {
3253 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3254 BorrowAppContext::read_with(&*self.window_context, f)
3255 }
3256
3257 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3258 BorrowAppContext::update(&mut *self.window_context, f)
3259 }
3260}
3261
3262impl<V> BorrowWindowContext for ViewContext<'_, '_, V> {
3263 fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3264 BorrowWindowContext::read_with(&*self.window_context, window_id, f)
3265 }
3266
3267 fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3268 BorrowWindowContext::update(&mut *self.window_context, window_id, f)
3269 }
3270}
3271
3272pub struct EventContext<'a, 'b, 'c, V: View> {
3273 view_context: &'c mut ViewContext<'a, 'b, V>,
3274 pub(crate) handled: bool,
3275}
3276
3277impl<'a, 'b, 'c, V: View> EventContext<'a, 'b, 'c, V> {
3278 pub(crate) fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
3279 EventContext {
3280 view_context,
3281 handled: true,
3282 }
3283 }
3284
3285 pub fn propagate_event(&mut self) {
3286 self.handled = false;
3287 }
3288}
3289
3290impl<'a, 'b, 'c, V: View> Deref for EventContext<'a, 'b, 'c, V> {
3291 type Target = ViewContext<'a, 'b, V>;
3292
3293 fn deref(&self) -> &Self::Target {
3294 &self.view_context
3295 }
3296}
3297
3298impl<V: View> DerefMut for EventContext<'_, '_, '_, V> {
3299 fn deref_mut(&mut self) -> &mut Self::Target {
3300 &mut self.view_context
3301 }
3302}
3303
3304impl<V: View> BorrowAppContext for EventContext<'_, '_, '_, V> {
3305 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3306 BorrowAppContext::read_with(&*self.view_context, f)
3307 }
3308
3309 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3310 BorrowAppContext::update(&mut *self.view_context, f)
3311 }
3312}
3313
3314impl<V: View> BorrowWindowContext for EventContext<'_, '_, '_, V> {
3315 fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3316 BorrowWindowContext::read_with(&*self.view_context, window_id, f)
3317 }
3318
3319 fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3320 BorrowWindowContext::update(&mut *self.view_context, window_id, f)
3321 }
3322}
3323
3324pub(crate) enum Reference<'a, T> {
3325 Immutable(&'a T),
3326 Mutable(&'a mut T),
3327}
3328
3329impl<'a, T> Deref for Reference<'a, T> {
3330 type Target = T;
3331
3332 fn deref(&self) -> &Self::Target {
3333 match self {
3334 Reference::Immutable(target) => target,
3335 Reference::Mutable(target) => target,
3336 }
3337 }
3338}
3339
3340impl<'a, T> DerefMut for Reference<'a, T> {
3341 fn deref_mut(&mut self) -> &mut Self::Target {
3342 match self {
3343 Reference::Immutable(_) => {
3344 panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
3345 }
3346 Reference::Mutable(target) => target,
3347 }
3348 }
3349}
3350
3351#[derive(Debug, Clone, Default)]
3352pub struct MouseState {
3353 pub(crate) hovered: bool,
3354 pub(crate) clicked: Option<MouseButton>,
3355 pub(crate) accessed_hovered: bool,
3356 pub(crate) accessed_clicked: bool,
3357}
3358
3359impl MouseState {
3360 pub fn hovered(&mut self) -> bool {
3361 self.accessed_hovered = true;
3362 self.hovered
3363 }
3364
3365 pub fn clicked(&mut self) -> Option<MouseButton> {
3366 self.accessed_clicked = true;
3367 self.clicked
3368 }
3369
3370 pub fn accessed_hovered(&self) -> bool {
3371 self.accessed_hovered
3372 }
3373
3374 pub fn accessed_clicked(&self) -> bool {
3375 self.accessed_clicked
3376 }
3377}
3378
3379pub trait Handle<T> {
3380 type Weak: 'static;
3381 fn id(&self) -> usize;
3382 fn location(&self) -> EntityLocation;
3383 fn downgrade(&self) -> Self::Weak;
3384 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3385 where
3386 Self: Sized;
3387}
3388
3389pub trait WeakHandle {
3390 fn id(&self) -> usize;
3391}
3392
3393#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3394pub enum EntityLocation {
3395 Model(usize),
3396 View(usize, usize),
3397}
3398
3399pub struct ModelHandle<T: Entity> {
3400 any_handle: AnyModelHandle,
3401 model_type: PhantomData<T>,
3402}
3403
3404impl<T: Entity> Deref for ModelHandle<T> {
3405 type Target = AnyModelHandle;
3406
3407 fn deref(&self) -> &Self::Target {
3408 &self.any_handle
3409 }
3410}
3411
3412impl<T: Entity> ModelHandle<T> {
3413 fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3414 Self {
3415 any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
3416 model_type: PhantomData,
3417 }
3418 }
3419
3420 pub fn downgrade(&self) -> WeakModelHandle<T> {
3421 WeakModelHandle::new(self.model_id)
3422 }
3423
3424 pub fn id(&self) -> usize {
3425 self.model_id
3426 }
3427
3428 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3429 cx.read_model(self)
3430 }
3431
3432 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3433 where
3434 C: BorrowAppContext,
3435 F: FnOnce(&T, &AppContext) -> S,
3436 {
3437 cx.read_with(|cx| read(self.read(cx), cx))
3438 }
3439
3440 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3441 where
3442 C: BorrowAppContext,
3443 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3444 {
3445 let mut update = Some(update);
3446 cx.update(|cx| {
3447 cx.update_model(self, &mut |model, cx| {
3448 let update = update.take().unwrap();
3449 update(model, cx)
3450 })
3451 })
3452 }
3453}
3454
3455impl<T: Entity> Clone for ModelHandle<T> {
3456 fn clone(&self) -> Self {
3457 Self::new(self.model_id, &self.ref_counts)
3458 }
3459}
3460
3461impl<T: Entity> PartialEq for ModelHandle<T> {
3462 fn eq(&self, other: &Self) -> bool {
3463 self.model_id == other.model_id
3464 }
3465}
3466
3467impl<T: Entity> Eq for ModelHandle<T> {}
3468
3469impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3470 fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3471 self.model_id == other.model_id
3472 }
3473}
3474
3475impl<T: Entity> Hash for ModelHandle<T> {
3476 fn hash<H: Hasher>(&self, state: &mut H) {
3477 self.model_id.hash(state);
3478 }
3479}
3480
3481impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3482 fn borrow(&self) -> &usize {
3483 &self.model_id
3484 }
3485}
3486
3487impl<T: Entity> Debug for ModelHandle<T> {
3488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3489 f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3490 .field(&self.model_id)
3491 .finish()
3492 }
3493}
3494
3495unsafe impl<T: Entity> Send for ModelHandle<T> {}
3496unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3497
3498impl<T: Entity> Handle<T> for ModelHandle<T> {
3499 type Weak = WeakModelHandle<T>;
3500
3501 fn id(&self) -> usize {
3502 self.model_id
3503 }
3504
3505 fn location(&self) -> EntityLocation {
3506 EntityLocation::Model(self.model_id)
3507 }
3508
3509 fn downgrade(&self) -> Self::Weak {
3510 self.downgrade()
3511 }
3512
3513 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3514 where
3515 Self: Sized,
3516 {
3517 weak.upgrade(cx)
3518 }
3519}
3520
3521pub struct WeakModelHandle<T> {
3522 any_handle: AnyWeakModelHandle,
3523 model_type: PhantomData<T>,
3524}
3525
3526impl<T> WeakModelHandle<T> {
3527 pub fn into_any(self) -> AnyWeakModelHandle {
3528 self.any_handle
3529 }
3530}
3531
3532impl<T> Deref for WeakModelHandle<T> {
3533 type Target = AnyWeakModelHandle;
3534
3535 fn deref(&self) -> &Self::Target {
3536 &self.any_handle
3537 }
3538}
3539
3540impl<T> WeakHandle for WeakModelHandle<T> {
3541 fn id(&self) -> usize {
3542 self.model_id
3543 }
3544}
3545
3546unsafe impl<T> Send for WeakModelHandle<T> {}
3547unsafe impl<T> Sync for WeakModelHandle<T> {}
3548
3549impl<T: Entity> WeakModelHandle<T> {
3550 fn new(model_id: usize) -> Self {
3551 Self {
3552 any_handle: AnyWeakModelHandle {
3553 model_id,
3554 model_type: TypeId::of::<T>(),
3555 },
3556 model_type: PhantomData,
3557 }
3558 }
3559
3560 pub fn id(&self) -> usize {
3561 self.model_id
3562 }
3563
3564 pub fn is_upgradable(&self, cx: &impl BorrowAppContext) -> bool {
3565 cx.read_with(|cx| cx.model_handle_is_upgradable(self))
3566 }
3567
3568 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<T>> {
3569 cx.read_with(|cx| cx.upgrade_model_handle(self))
3570 }
3571}
3572
3573impl<T> Hash for WeakModelHandle<T> {
3574 fn hash<H: Hasher>(&self, state: &mut H) {
3575 self.model_id.hash(state)
3576 }
3577}
3578
3579impl<T> PartialEq for WeakModelHandle<T> {
3580 fn eq(&self, other: &Self) -> bool {
3581 self.model_id == other.model_id
3582 }
3583}
3584
3585impl<T> Eq for WeakModelHandle<T> {}
3586
3587impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
3588 fn eq(&self, other: &ModelHandle<T>) -> bool {
3589 self.model_id == other.model_id
3590 }
3591}
3592
3593impl<T> Clone for WeakModelHandle<T> {
3594 fn clone(&self) -> Self {
3595 Self {
3596 any_handle: self.any_handle.clone(),
3597 model_type: PhantomData,
3598 }
3599 }
3600}
3601
3602impl<T> Copy for WeakModelHandle<T> {}
3603
3604#[repr(transparent)]
3605pub struct ViewHandle<T> {
3606 any_handle: AnyViewHandle,
3607 view_type: PhantomData<T>,
3608}
3609
3610impl<T> Deref for ViewHandle<T> {
3611 type Target = AnyViewHandle;
3612
3613 fn deref(&self) -> &Self::Target {
3614 &self.any_handle
3615 }
3616}
3617
3618impl<T: View> ViewHandle<T> {
3619 fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3620 Self {
3621 any_handle: AnyViewHandle::new(
3622 window_id,
3623 view_id,
3624 TypeId::of::<T>(),
3625 ref_counts.clone(),
3626 ),
3627 view_type: PhantomData,
3628 }
3629 }
3630
3631 pub fn downgrade(&self) -> WeakViewHandle<T> {
3632 WeakViewHandle::new(self.window_id, self.view_id)
3633 }
3634
3635 pub fn into_any(self) -> AnyViewHandle {
3636 self.any_handle
3637 }
3638
3639 pub fn window_id(&self) -> usize {
3640 self.window_id
3641 }
3642
3643 pub fn id(&self) -> usize {
3644 self.view_id
3645 }
3646
3647 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3648 cx.read_view(self)
3649 }
3650
3651 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3652 where
3653 C: BorrowWindowContext,
3654 F: FnOnce(&T, &ViewContext<T>) -> S,
3655 {
3656 cx.read_with(self.window_id, |cx| {
3657 let cx = ViewContext::immutable(cx, self.view_id);
3658 read(cx.read_view(self), &cx)
3659 })
3660 }
3661
3662 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3663 where
3664 C: BorrowWindowContext,
3665 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3666 {
3667 let mut update = Some(update);
3668
3669 cx.update(self.window_id, |cx| {
3670 cx.update_view(self, &mut |view, cx| {
3671 let update = update.take().unwrap();
3672 update(view, cx)
3673 })
3674 })
3675 }
3676
3677 pub fn is_focused(&self, cx: &WindowContext) -> bool {
3678 cx.focused_view_id() == Some(self.view_id)
3679 }
3680}
3681
3682impl<T: View> Clone for ViewHandle<T> {
3683 fn clone(&self) -> Self {
3684 ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3685 }
3686}
3687
3688impl<T> PartialEq for ViewHandle<T> {
3689 fn eq(&self, other: &Self) -> bool {
3690 self.window_id == other.window_id && self.view_id == other.view_id
3691 }
3692}
3693
3694impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3695 fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3696 self.window_id == other.window_id && self.view_id == other.view_id
3697 }
3698}
3699
3700impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3701 fn eq(&self, other: &ViewHandle<T>) -> bool {
3702 self.window_id == other.window_id && self.view_id == other.view_id
3703 }
3704}
3705
3706impl<T> Eq for ViewHandle<T> {}
3707
3708impl<T> Hash for ViewHandle<T> {
3709 fn hash<H: Hasher>(&self, state: &mut H) {
3710 self.window_id.hash(state);
3711 self.view_id.hash(state);
3712 }
3713}
3714
3715impl<T> Debug for ViewHandle<T> {
3716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3717 f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3718 .field("window_id", &self.window_id)
3719 .field("view_id", &self.view_id)
3720 .finish()
3721 }
3722}
3723
3724impl<T: View> Handle<T> for ViewHandle<T> {
3725 type Weak = WeakViewHandle<T>;
3726
3727 fn id(&self) -> usize {
3728 self.view_id
3729 }
3730
3731 fn location(&self) -> EntityLocation {
3732 EntityLocation::View(self.window_id, self.view_id)
3733 }
3734
3735 fn downgrade(&self) -> Self::Weak {
3736 self.downgrade()
3737 }
3738
3739 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3740 where
3741 Self: Sized,
3742 {
3743 weak.upgrade(cx)
3744 }
3745}
3746
3747pub struct AnyViewHandle {
3748 window_id: usize,
3749 view_id: usize,
3750 view_type: TypeId,
3751 ref_counts: Arc<Mutex<RefCounts>>,
3752
3753 #[cfg(any(test, feature = "test-support"))]
3754 handle_id: usize,
3755}
3756
3757impl AnyViewHandle {
3758 fn new(
3759 window_id: usize,
3760 view_id: usize,
3761 view_type: TypeId,
3762 ref_counts: Arc<Mutex<RefCounts>>,
3763 ) -> Self {
3764 ref_counts.lock().inc_view(window_id, view_id);
3765
3766 #[cfg(any(test, feature = "test-support"))]
3767 let handle_id = ref_counts
3768 .lock()
3769 .leak_detector
3770 .lock()
3771 .handle_created(None, view_id);
3772
3773 Self {
3774 window_id,
3775 view_id,
3776 view_type,
3777 ref_counts,
3778 #[cfg(any(test, feature = "test-support"))]
3779 handle_id,
3780 }
3781 }
3782
3783 pub fn window_id(&self) -> usize {
3784 self.window_id
3785 }
3786
3787 pub fn id(&self) -> usize {
3788 self.view_id
3789 }
3790
3791 pub fn is<T: 'static>(&self) -> bool {
3792 TypeId::of::<T>() == self.view_type
3793 }
3794
3795 pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3796 if self.is::<T>() {
3797 Some(ViewHandle {
3798 any_handle: self,
3799 view_type: PhantomData,
3800 })
3801 } else {
3802 None
3803 }
3804 }
3805
3806 pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
3807 if self.is::<T>() {
3808 Some(unsafe { mem::transmute(self) })
3809 } else {
3810 None
3811 }
3812 }
3813
3814 pub fn downgrade(&self) -> AnyWeakViewHandle {
3815 AnyWeakViewHandle {
3816 window_id: self.window_id,
3817 view_id: self.view_id,
3818 view_type: self.view_type,
3819 }
3820 }
3821
3822 pub fn view_type(&self) -> TypeId {
3823 self.view_type
3824 }
3825
3826 pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a>) -> serde_json::Value {
3827 cx.views
3828 .get(&(self.window_id, self.view_id))
3829 .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
3830 }
3831}
3832
3833impl Clone for AnyViewHandle {
3834 fn clone(&self) -> Self {
3835 Self::new(
3836 self.window_id,
3837 self.view_id,
3838 self.view_type,
3839 self.ref_counts.clone(),
3840 )
3841 }
3842}
3843
3844impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
3845 fn eq(&self, other: &ViewHandle<T>) -> bool {
3846 self.window_id == other.window_id && self.view_id == other.view_id
3847 }
3848}
3849
3850impl Drop for AnyViewHandle {
3851 fn drop(&mut self) {
3852 self.ref_counts
3853 .lock()
3854 .dec_view(self.window_id, self.view_id);
3855 #[cfg(any(test, feature = "test-support"))]
3856 self.ref_counts
3857 .lock()
3858 .leak_detector
3859 .lock()
3860 .handle_dropped(self.view_id, self.handle_id);
3861 }
3862}
3863
3864pub struct AnyModelHandle {
3865 model_id: usize,
3866 model_type: TypeId,
3867 ref_counts: Arc<Mutex<RefCounts>>,
3868
3869 #[cfg(any(test, feature = "test-support"))]
3870 handle_id: usize,
3871}
3872
3873impl AnyModelHandle {
3874 fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3875 ref_counts.lock().inc_model(model_id);
3876
3877 #[cfg(any(test, feature = "test-support"))]
3878 let handle_id = ref_counts
3879 .lock()
3880 .leak_detector
3881 .lock()
3882 .handle_created(None, model_id);
3883
3884 Self {
3885 model_id,
3886 model_type,
3887 ref_counts,
3888
3889 #[cfg(any(test, feature = "test-support"))]
3890 handle_id,
3891 }
3892 }
3893
3894 pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3895 if self.is::<T>() {
3896 Some(ModelHandle {
3897 any_handle: self,
3898 model_type: PhantomData,
3899 })
3900 } else {
3901 None
3902 }
3903 }
3904
3905 pub fn downgrade(&self) -> AnyWeakModelHandle {
3906 AnyWeakModelHandle {
3907 model_id: self.model_id,
3908 model_type: self.model_type,
3909 }
3910 }
3911
3912 pub fn is<T: Entity>(&self) -> bool {
3913 self.model_type == TypeId::of::<T>()
3914 }
3915
3916 pub fn model_type(&self) -> TypeId {
3917 self.model_type
3918 }
3919}
3920
3921impl Clone for AnyModelHandle {
3922 fn clone(&self) -> Self {
3923 Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3924 }
3925}
3926
3927impl Drop for AnyModelHandle {
3928 fn drop(&mut self) {
3929 let mut ref_counts = self.ref_counts.lock();
3930 ref_counts.dec_model(self.model_id);
3931
3932 #[cfg(any(test, feature = "test-support"))]
3933 ref_counts
3934 .leak_detector
3935 .lock()
3936 .handle_dropped(self.model_id, self.handle_id);
3937 }
3938}
3939
3940#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
3941pub struct AnyWeakModelHandle {
3942 model_id: usize,
3943 model_type: TypeId,
3944}
3945
3946impl AnyWeakModelHandle {
3947 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyModelHandle> {
3948 cx.read_with(|cx| cx.upgrade_any_model_handle(self))
3949 }
3950
3951 pub fn model_type(&self) -> TypeId {
3952 self.model_type
3953 }
3954
3955 fn is<T: 'static>(&self) -> bool {
3956 TypeId::of::<T>() == self.model_type
3957 }
3958
3959 pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
3960 if self.is::<T>() {
3961 let result = Some(WeakModelHandle {
3962 any_handle: self,
3963 model_type: PhantomData,
3964 });
3965
3966 result
3967 } else {
3968 None
3969 }
3970 }
3971}
3972
3973#[derive(Debug, Copy)]
3974pub struct WeakViewHandle<T> {
3975 any_handle: AnyWeakViewHandle,
3976 view_type: PhantomData<T>,
3977}
3978
3979impl<T> WeakHandle for WeakViewHandle<T> {
3980 fn id(&self) -> usize {
3981 self.view_id
3982 }
3983}
3984
3985impl<V: View> WeakViewHandle<V> {
3986 fn new(window_id: usize, view_id: usize) -> Self {
3987 Self {
3988 any_handle: AnyWeakViewHandle {
3989 window_id,
3990 view_id,
3991 view_type: TypeId::of::<V>(),
3992 },
3993 view_type: PhantomData,
3994 }
3995 }
3996
3997 pub fn id(&self) -> usize {
3998 self.view_id
3999 }
4000
4001 pub fn window_id(&self) -> usize {
4002 self.window_id
4003 }
4004
4005 pub fn into_any(self) -> AnyWeakViewHandle {
4006 self.any_handle
4007 }
4008
4009 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ViewHandle<V>> {
4010 cx.read_with(|cx| cx.upgrade_view_handle(self))
4011 }
4012
4013 pub fn read_with<T>(
4014 &self,
4015 cx: &AsyncAppContext,
4016 read: impl FnOnce(&V, &ViewContext<V>) -> T,
4017 ) -> Result<T> {
4018 cx.read(|cx| {
4019 let handle = cx
4020 .upgrade_view_handle(self)
4021 .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4022 cx.read_window(self.window_id, |cx| handle.read_with(cx, read))
4023 .ok_or_else(|| anyhow!("window was removed"))
4024 })
4025 }
4026
4027 pub fn update<T>(
4028 &self,
4029 cx: &mut AsyncAppContext,
4030 update: impl FnOnce(&mut V, &mut ViewContext<V>) -> T,
4031 ) -> Result<T> {
4032 cx.update(|cx| {
4033 let handle = cx
4034 .upgrade_view_handle(self)
4035 .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4036 cx.update_window(self.window_id, |cx| handle.update(cx, update))
4037 .ok_or_else(|| anyhow!("window was removed"))
4038 })
4039 }
4040}
4041
4042impl<T> Deref for WeakViewHandle<T> {
4043 type Target = AnyWeakViewHandle;
4044
4045 fn deref(&self) -> &Self::Target {
4046 &self.any_handle
4047 }
4048}
4049
4050impl<T> Clone for WeakViewHandle<T> {
4051 fn clone(&self) -> Self {
4052 Self {
4053 any_handle: self.any_handle.clone(),
4054 view_type: PhantomData,
4055 }
4056 }
4057}
4058
4059impl<T> PartialEq for WeakViewHandle<T> {
4060 fn eq(&self, other: &Self) -> bool {
4061 self.window_id == other.window_id && self.view_id == other.view_id
4062 }
4063}
4064
4065impl<T> Eq for WeakViewHandle<T> {}
4066
4067impl<T> Hash for WeakViewHandle<T> {
4068 fn hash<H: Hasher>(&self, state: &mut H) {
4069 self.any_handle.hash(state);
4070 }
4071}
4072
4073#[derive(Debug, Clone, Copy)]
4074pub struct AnyWeakViewHandle {
4075 window_id: usize,
4076 view_id: usize,
4077 view_type: TypeId,
4078}
4079
4080impl AnyWeakViewHandle {
4081 pub fn id(&self) -> usize {
4082 self.view_id
4083 }
4084
4085 fn is<T: 'static>(&self) -> bool {
4086 TypeId::of::<T>() == self.view_type
4087 }
4088
4089 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyViewHandle> {
4090 cx.read_with(|cx| cx.upgrade_any_view_handle(self))
4091 }
4092
4093 pub fn downcast<T: View>(self) -> Option<WeakViewHandle<T>> {
4094 if self.is::<T>() {
4095 Some(WeakViewHandle {
4096 any_handle: self,
4097 view_type: PhantomData,
4098 })
4099 } else {
4100 None
4101 }
4102 }
4103}
4104
4105impl Hash for AnyWeakViewHandle {
4106 fn hash<H: Hasher>(&self, state: &mut H) {
4107 self.window_id.hash(state);
4108 self.view_id.hash(state);
4109 self.view_type.hash(state);
4110 }
4111}
4112
4113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4114pub struct ElementStateId {
4115 view_id: usize,
4116 element_id: usize,
4117 tag: TypeId,
4118}
4119
4120pub struct ElementStateHandle<T> {
4121 value_type: PhantomData<T>,
4122 id: ElementStateId,
4123 ref_counts: Weak<Mutex<RefCounts>>,
4124}
4125
4126impl<T: 'static> ElementStateHandle<T> {
4127 fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4128 ref_counts.lock().inc_element_state(id, frame_id);
4129 Self {
4130 value_type: PhantomData,
4131 id,
4132 ref_counts: Arc::downgrade(ref_counts),
4133 }
4134 }
4135
4136 pub fn id(&self) -> ElementStateId {
4137 self.id
4138 }
4139
4140 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4141 cx.element_states
4142 .get(&self.id)
4143 .unwrap()
4144 .downcast_ref()
4145 .unwrap()
4146 }
4147
4148 pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4149 where
4150 C: DerefMut<Target = D>,
4151 D: DerefMut<Target = AppContext>,
4152 {
4153 let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4154 let result = f(element_state.downcast_mut().unwrap(), cx);
4155 cx.deref_mut().element_states.insert(self.id, element_state);
4156 result
4157 }
4158}
4159
4160impl<T> Drop for ElementStateHandle<T> {
4161 fn drop(&mut self) {
4162 if let Some(ref_counts) = self.ref_counts.upgrade() {
4163 ref_counts.lock().dec_element_state(self.id);
4164 }
4165 }
4166}
4167
4168#[must_use]
4169pub enum Subscription {
4170 Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4171 Observation(callback_collection::Subscription<usize, ObservationCallback>),
4172 GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4173 GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4174 FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4175 WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
4176 WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
4177 WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
4178 KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
4179 ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4180 ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4181 ActiveLabeledTasksObservation(
4182 callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4183 ),
4184}
4185
4186impl Subscription {
4187 pub fn id(&self) -> usize {
4188 match self {
4189 Subscription::Subscription(subscription) => subscription.id(),
4190 Subscription::Observation(subscription) => subscription.id(),
4191 Subscription::GlobalSubscription(subscription) => subscription.id(),
4192 Subscription::GlobalObservation(subscription) => subscription.id(),
4193 Subscription::FocusObservation(subscription) => subscription.id(),
4194 Subscription::WindowActivationObservation(subscription) => subscription.id(),
4195 Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4196 Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4197 Subscription::KeystrokeObservation(subscription) => subscription.id(),
4198 Subscription::ReleaseObservation(subscription) => subscription.id(),
4199 Subscription::ActionObservation(subscription) => subscription.id(),
4200 Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4201 }
4202 }
4203
4204 pub fn detach(&mut self) {
4205 match self {
4206 Subscription::Subscription(subscription) => subscription.detach(),
4207 Subscription::GlobalSubscription(subscription) => subscription.detach(),
4208 Subscription::Observation(subscription) => subscription.detach(),
4209 Subscription::GlobalObservation(subscription) => subscription.detach(),
4210 Subscription::FocusObservation(subscription) => subscription.detach(),
4211 Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4212 Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4213 Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4214 Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4215 Subscription::ReleaseObservation(subscription) => subscription.detach(),
4216 Subscription::ActionObservation(subscription) => subscription.detach(),
4217 Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4218 }
4219 }
4220}
4221
4222#[cfg(test)]
4223mod tests {
4224 use super::*;
4225 use crate::{
4226 actions,
4227 elements::*,
4228 impl_actions,
4229 platform::{MouseButton, MouseButtonEvent},
4230 window::ChildView,
4231 };
4232 use itertools::Itertools;
4233 use postage::{sink::Sink, stream::Stream};
4234 use serde::Deserialize;
4235 use smol::future::poll_once;
4236 use std::{
4237 cell::Cell,
4238 sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4239 };
4240
4241 #[crate::test(self)]
4242 fn test_model_handles(cx: &mut AppContext) {
4243 struct Model {
4244 other: Option<ModelHandle<Model>>,
4245 events: Vec<String>,
4246 }
4247
4248 impl Entity for Model {
4249 type Event = usize;
4250 }
4251
4252 impl Model {
4253 fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4254 if let Some(other) = other.as_ref() {
4255 cx.observe(other, |me, _, _| {
4256 me.events.push("notified".into());
4257 })
4258 .detach();
4259 cx.subscribe(other, |me, _, event, _| {
4260 me.events.push(format!("observed event {}", event));
4261 })
4262 .detach();
4263 }
4264
4265 Self {
4266 other,
4267 events: Vec::new(),
4268 }
4269 }
4270 }
4271
4272 let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4273 let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4274 assert_eq!(cx.models.len(), 2);
4275
4276 handle_1.update(cx, |model, cx| {
4277 model.events.push("updated".into());
4278 cx.emit(1);
4279 cx.notify();
4280 cx.emit(2);
4281 });
4282 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4283 assert_eq!(
4284 handle_2.read(cx).events,
4285 vec![
4286 "observed event 1".to_string(),
4287 "notified".to_string(),
4288 "observed event 2".to_string(),
4289 ]
4290 );
4291
4292 handle_2.update(cx, |model, _| {
4293 drop(handle_1);
4294 model.other.take();
4295 });
4296
4297 assert_eq!(cx.models.len(), 1);
4298 assert!(cx.subscriptions.is_empty());
4299 assert!(cx.observations.is_empty());
4300 }
4301
4302 #[crate::test(self)]
4303 fn test_model_events(cx: &mut AppContext) {
4304 #[derive(Default)]
4305 struct Model {
4306 events: Vec<usize>,
4307 }
4308
4309 impl Entity for Model {
4310 type Event = usize;
4311 }
4312
4313 let handle_1 = cx.add_model(|_| Model::default());
4314 let handle_2 = cx.add_model(|_| Model::default());
4315
4316 handle_1.update(cx, |_, cx| {
4317 cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4318 model.events.push(*event);
4319
4320 cx.subscribe(&emitter, |model, _, event, _| {
4321 model.events.push(*event * 2);
4322 })
4323 .detach();
4324 })
4325 .detach();
4326 });
4327
4328 handle_2.update(cx, |_, c| c.emit(7));
4329 assert_eq!(handle_1.read(cx).events, vec![7]);
4330
4331 handle_2.update(cx, |_, c| c.emit(5));
4332 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4333 }
4334
4335 #[crate::test(self)]
4336 fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4337 #[derive(Default)]
4338 struct Model;
4339
4340 impl Entity for Model {
4341 type Event = ();
4342 }
4343
4344 let events = Rc::new(RefCell::new(Vec::new()));
4345 cx.add_model(|cx| {
4346 drop(cx.subscribe(&cx.handle(), {
4347 let events = events.clone();
4348 move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4349 }));
4350 cx.subscribe(&cx.handle(), {
4351 let events = events.clone();
4352 move |_, _, _, _| events.borrow_mut().push("before emit")
4353 })
4354 .detach();
4355 cx.emit(());
4356 cx.subscribe(&cx.handle(), {
4357 let events = events.clone();
4358 move |_, _, _, _| events.borrow_mut().push("after emit")
4359 })
4360 .detach();
4361 Model
4362 });
4363 assert_eq!(*events.borrow(), ["before emit"]);
4364 }
4365
4366 #[crate::test(self)]
4367 fn test_observe_and_notify_from_model(cx: &mut AppContext) {
4368 #[derive(Default)]
4369 struct Model {
4370 count: usize,
4371 events: Vec<usize>,
4372 }
4373
4374 impl Entity for Model {
4375 type Event = ();
4376 }
4377
4378 let handle_1 = cx.add_model(|_| Model::default());
4379 let handle_2 = cx.add_model(|_| Model::default());
4380
4381 handle_1.update(cx, |_, c| {
4382 c.observe(&handle_2, move |model, observed, c| {
4383 model.events.push(observed.read(c).count);
4384 c.observe(&observed, |model, observed, c| {
4385 model.events.push(observed.read(c).count * 2);
4386 })
4387 .detach();
4388 })
4389 .detach();
4390 });
4391
4392 handle_2.update(cx, |model, c| {
4393 model.count = 7;
4394 c.notify()
4395 });
4396 assert_eq!(handle_1.read(cx).events, vec![7]);
4397
4398 handle_2.update(cx, |model, c| {
4399 model.count = 5;
4400 c.notify()
4401 });
4402 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4403 }
4404
4405 #[crate::test(self)]
4406 fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4407 #[derive(Default)]
4408 struct Model;
4409
4410 impl Entity for Model {
4411 type Event = ();
4412 }
4413
4414 let events = Rc::new(RefCell::new(Vec::new()));
4415 cx.add_model(|cx| {
4416 drop(cx.observe(&cx.handle(), {
4417 let events = events.clone();
4418 move |_, _, _| events.borrow_mut().push("dropped before flush")
4419 }));
4420 cx.observe(&cx.handle(), {
4421 let events = events.clone();
4422 move |_, _, _| events.borrow_mut().push("before notify")
4423 })
4424 .detach();
4425 cx.notify();
4426 cx.observe(&cx.handle(), {
4427 let events = events.clone();
4428 move |_, _, _| events.borrow_mut().push("after notify")
4429 })
4430 .detach();
4431 Model
4432 });
4433 assert_eq!(*events.borrow(), ["before notify"]);
4434 }
4435
4436 #[crate::test(self)]
4437 fn test_defer_and_after_window_update(cx: &mut TestAppContext) {
4438 struct View {
4439 render_count: usize,
4440 }
4441
4442 impl Entity for View {
4443 type Event = usize;
4444 }
4445
4446 impl super::View for View {
4447 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4448 post_inc(&mut self.render_count);
4449 Empty::new().into_any()
4450 }
4451
4452 fn ui_name() -> &'static str {
4453 "View"
4454 }
4455 }
4456
4457 let (_, view) = cx.add_window(|_| View { render_count: 0 });
4458 let called_defer = Rc::new(AtomicBool::new(false));
4459 let called_after_window_update = Rc::new(AtomicBool::new(false));
4460
4461 view.update(cx, |this, cx| {
4462 assert_eq!(this.render_count, 1);
4463 cx.defer({
4464 let called_defer = called_defer.clone();
4465 move |this, _| {
4466 assert_eq!(this.render_count, 1);
4467 called_defer.store(true, SeqCst);
4468 }
4469 });
4470 cx.after_window_update({
4471 let called_after_window_update = called_after_window_update.clone();
4472 move |this, cx| {
4473 assert_eq!(this.render_count, 2);
4474 called_after_window_update.store(true, SeqCst);
4475 cx.notify();
4476 }
4477 });
4478 assert!(!called_defer.load(SeqCst));
4479 assert!(!called_after_window_update.load(SeqCst));
4480 cx.notify();
4481 });
4482
4483 assert!(called_defer.load(SeqCst));
4484 assert!(called_after_window_update.load(SeqCst));
4485 assert_eq!(view.read_with(cx, |view, _| view.render_count), 3);
4486 }
4487
4488 #[crate::test(self)]
4489 fn test_view_handles(cx: &mut TestAppContext) {
4490 struct View {
4491 other: Option<ViewHandle<View>>,
4492 events: Vec<String>,
4493 }
4494
4495 impl Entity for View {
4496 type Event = usize;
4497 }
4498
4499 impl super::View for View {
4500 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4501 Empty::new().into_any()
4502 }
4503
4504 fn ui_name() -> &'static str {
4505 "View"
4506 }
4507 }
4508
4509 impl View {
4510 fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4511 if let Some(other) = other.as_ref() {
4512 cx.subscribe(other, |me, _, event, _| {
4513 me.events.push(format!("observed event {}", event));
4514 })
4515 .detach();
4516 }
4517 Self {
4518 other,
4519 events: Vec::new(),
4520 }
4521 }
4522 }
4523
4524 let (_, root_view) = cx.add_window(|cx| View::new(None, cx));
4525 let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
4526 let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
4527 assert_eq!(cx.read(|cx| cx.views.len()), 3);
4528
4529 handle_1.update(cx, |view, cx| {
4530 view.events.push("updated".into());
4531 cx.emit(1);
4532 cx.emit(2);
4533 });
4534 handle_1.read_with(cx, |view, _| {
4535 assert_eq!(view.events, vec!["updated".to_string()]);
4536 });
4537 handle_2.read_with(cx, |view, _| {
4538 assert_eq!(
4539 view.events,
4540 vec![
4541 "observed event 1".to_string(),
4542 "observed event 2".to_string(),
4543 ]
4544 );
4545 });
4546
4547 handle_2.update(cx, |view, _| {
4548 drop(handle_1);
4549 view.other.take();
4550 });
4551
4552 cx.read(|cx| {
4553 assert_eq!(cx.views.len(), 2);
4554 assert!(cx.subscriptions.is_empty());
4555 assert!(cx.observations.is_empty());
4556 });
4557 }
4558
4559 #[crate::test(self)]
4560 fn test_add_window(cx: &mut AppContext) {
4561 struct View {
4562 mouse_down_count: Arc<AtomicUsize>,
4563 }
4564
4565 impl Entity for View {
4566 type Event = ();
4567 }
4568
4569 impl super::View for View {
4570 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
4571 enum Handler {}
4572 let mouse_down_count = self.mouse_down_count.clone();
4573 MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new())
4574 .on_down(MouseButton::Left, move |_, _, _| {
4575 mouse_down_count.fetch_add(1, SeqCst);
4576 })
4577 .into_any()
4578 }
4579
4580 fn ui_name() -> &'static str {
4581 "View"
4582 }
4583 }
4584
4585 let mouse_down_count = Arc::new(AtomicUsize::new(0));
4586 let (window_id, _) = cx.add_window(Default::default(), |_| View {
4587 mouse_down_count: mouse_down_count.clone(),
4588 });
4589
4590 cx.update_window(window_id, |cx| {
4591 // Ensure window's root element is in a valid lifecycle state.
4592 cx.dispatch_event(
4593 Event::MouseDown(MouseButtonEvent {
4594 position: Default::default(),
4595 button: MouseButton::Left,
4596 modifiers: Default::default(),
4597 click_count: 1,
4598 }),
4599 false,
4600 );
4601 assert_eq!(mouse_down_count.load(SeqCst), 1);
4602 });
4603 }
4604
4605 #[crate::test(self)]
4606 fn test_entity_release_hooks(cx: &mut AppContext) {
4607 struct Model {
4608 released: Rc<Cell<bool>>,
4609 }
4610
4611 struct View {
4612 released: Rc<Cell<bool>>,
4613 }
4614
4615 impl Entity for Model {
4616 type Event = ();
4617
4618 fn release(&mut self, _: &mut AppContext) {
4619 self.released.set(true);
4620 }
4621 }
4622
4623 impl Entity for View {
4624 type Event = ();
4625
4626 fn release(&mut self, _: &mut AppContext) {
4627 self.released.set(true);
4628 }
4629 }
4630
4631 impl super::View for View {
4632 fn ui_name() -> &'static str {
4633 "View"
4634 }
4635
4636 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4637 Empty::new().into_any()
4638 }
4639 }
4640
4641 let model_released = Rc::new(Cell::new(false));
4642 let model_release_observed = Rc::new(Cell::new(false));
4643 let view_released = Rc::new(Cell::new(false));
4644 let view_release_observed = Rc::new(Cell::new(false));
4645
4646 let model = cx.add_model(|_| Model {
4647 released: model_released.clone(),
4648 });
4649 let (window_id, view) = cx.add_window(Default::default(), |_| View {
4650 released: view_released.clone(),
4651 });
4652 assert!(!model_released.get());
4653 assert!(!view_released.get());
4654
4655 cx.observe_release(&model, {
4656 let model_release_observed = model_release_observed.clone();
4657 move |_, _| model_release_observed.set(true)
4658 })
4659 .detach();
4660 cx.observe_release(&view, {
4661 let view_release_observed = view_release_observed.clone();
4662 move |_, _| view_release_observed.set(true)
4663 })
4664 .detach();
4665
4666 cx.update(move |_| {
4667 drop(model);
4668 });
4669 assert!(model_released.get());
4670 assert!(model_release_observed.get());
4671
4672 drop(view);
4673 cx.update_window(window_id, |cx| cx.remove_window());
4674 assert!(view_released.get());
4675 assert!(view_release_observed.get());
4676 }
4677
4678 #[crate::test(self)]
4679 fn test_view_events(cx: &mut TestAppContext) {
4680 struct Model;
4681
4682 impl Entity for Model {
4683 type Event = String;
4684 }
4685
4686 let (_, handle_1) = cx.add_window(|_| TestView::default());
4687 let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
4688 let handle_3 = cx.add_model(|_| Model);
4689
4690 handle_1.update(cx, |_, cx| {
4691 cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4692 me.events.push(event.clone());
4693
4694 cx.subscribe(&emitter, |me, _, event, _| {
4695 me.events.push(format!("{event} from inner"));
4696 })
4697 .detach();
4698 })
4699 .detach();
4700
4701 cx.subscribe(&handle_3, |me, _, event, _| {
4702 me.events.push(event.clone());
4703 })
4704 .detach();
4705 });
4706
4707 handle_2.update(cx, |_, c| c.emit("7".into()));
4708 handle_1.read_with(cx, |view, _| assert_eq!(view.events, ["7"]));
4709
4710 handle_2.update(cx, |_, c| c.emit("5".into()));
4711 handle_1.read_with(cx, |view, _| {
4712 assert_eq!(view.events, ["7", "5", "5 from inner"])
4713 });
4714
4715 handle_3.update(cx, |_, c| c.emit("9".into()));
4716 handle_1.read_with(cx, |view, _| {
4717 assert_eq!(view.events, ["7", "5", "5 from inner", "9"])
4718 });
4719 }
4720
4721 #[crate::test(self)]
4722 fn test_global_events(cx: &mut AppContext) {
4723 #[derive(Clone, Debug, Eq, PartialEq)]
4724 struct GlobalEvent(u64);
4725
4726 let events = Rc::new(RefCell::new(Vec::new()));
4727 let first_subscription;
4728 let second_subscription;
4729
4730 {
4731 let events = events.clone();
4732 first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4733 events.borrow_mut().push(("First", e.clone()));
4734 });
4735 }
4736
4737 {
4738 let events = events.clone();
4739 second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4740 events.borrow_mut().push(("Second", e.clone()));
4741 });
4742 }
4743
4744 cx.update(|cx| {
4745 cx.emit_global(GlobalEvent(1));
4746 cx.emit_global(GlobalEvent(2));
4747 });
4748
4749 drop(first_subscription);
4750
4751 cx.update(|cx| {
4752 cx.emit_global(GlobalEvent(3));
4753 });
4754
4755 drop(second_subscription);
4756
4757 cx.update(|cx| {
4758 cx.emit_global(GlobalEvent(4));
4759 });
4760
4761 assert_eq!(
4762 &*events.borrow(),
4763 &[
4764 ("First", GlobalEvent(1)),
4765 ("Second", GlobalEvent(1)),
4766 ("First", GlobalEvent(2)),
4767 ("Second", GlobalEvent(2)),
4768 ("Second", GlobalEvent(3)),
4769 ]
4770 );
4771 }
4772
4773 #[crate::test(self)]
4774 fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
4775 let events = Rc::new(RefCell::new(Vec::new()));
4776 cx.update(|cx| {
4777 {
4778 let events = events.clone();
4779 drop(cx.subscribe_global(move |_: &(), _| {
4780 events.borrow_mut().push("dropped before emit");
4781 }));
4782 }
4783
4784 {
4785 let events = events.clone();
4786 cx.subscribe_global(move |_: &(), _| {
4787 events.borrow_mut().push("before emit");
4788 })
4789 .detach();
4790 }
4791
4792 cx.emit_global(());
4793
4794 {
4795 let events = events.clone();
4796 cx.subscribe_global(move |_: &(), _| {
4797 events.borrow_mut().push("after emit");
4798 })
4799 .detach();
4800 }
4801 });
4802
4803 assert_eq!(*events.borrow(), ["before emit"]);
4804 }
4805
4806 #[crate::test(self)]
4807 fn test_global_nested_events(cx: &mut AppContext) {
4808 #[derive(Clone, Debug, Eq, PartialEq)]
4809 struct GlobalEvent(u64);
4810
4811 let events = Rc::new(RefCell::new(Vec::new()));
4812
4813 {
4814 let events = events.clone();
4815 cx.subscribe_global(move |e: &GlobalEvent, cx| {
4816 events.borrow_mut().push(("Outer", e.clone()));
4817
4818 if e.0 == 1 {
4819 let events = events.clone();
4820 cx.subscribe_global(move |e: &GlobalEvent, _| {
4821 events.borrow_mut().push(("Inner", e.clone()));
4822 })
4823 .detach();
4824 }
4825 })
4826 .detach();
4827 }
4828
4829 cx.update(|cx| {
4830 cx.emit_global(GlobalEvent(1));
4831 cx.emit_global(GlobalEvent(2));
4832 cx.emit_global(GlobalEvent(3));
4833 });
4834 cx.update(|cx| {
4835 cx.emit_global(GlobalEvent(4));
4836 });
4837
4838 assert_eq!(
4839 &*events.borrow(),
4840 &[
4841 ("Outer", GlobalEvent(1)),
4842 ("Outer", GlobalEvent(2)),
4843 ("Outer", GlobalEvent(3)),
4844 ("Outer", GlobalEvent(4)),
4845 ("Inner", GlobalEvent(4)),
4846 ]
4847 );
4848 }
4849
4850 #[crate::test(self)]
4851 fn test_global(cx: &mut AppContext) {
4852 type Global = usize;
4853
4854 let observation_count = Rc::new(RefCell::new(0));
4855 let subscription = cx.observe_global::<Global, _>({
4856 let observation_count = observation_count.clone();
4857 move |_| {
4858 *observation_count.borrow_mut() += 1;
4859 }
4860 });
4861
4862 assert!(!cx.has_global::<Global>());
4863 assert_eq!(cx.default_global::<Global>(), &0);
4864 assert_eq!(*observation_count.borrow(), 1);
4865 assert!(cx.has_global::<Global>());
4866 assert_eq!(
4867 cx.update_global::<Global, _, _>(|global, _| {
4868 *global = 1;
4869 "Update Result"
4870 }),
4871 "Update Result"
4872 );
4873 assert_eq!(*observation_count.borrow(), 2);
4874 assert_eq!(cx.global::<Global>(), &1);
4875
4876 drop(subscription);
4877 cx.update_global::<Global, _, _>(|global, _| {
4878 *global = 2;
4879 });
4880 assert_eq!(*observation_count.borrow(), 2);
4881
4882 type OtherGlobal = f32;
4883
4884 let observation_count = Rc::new(RefCell::new(0));
4885 cx.observe_global::<OtherGlobal, _>({
4886 let observation_count = observation_count.clone();
4887 move |_| {
4888 *observation_count.borrow_mut() += 1;
4889 }
4890 })
4891 .detach();
4892
4893 assert_eq!(
4894 cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
4895 assert_eq!(global, &0.0);
4896 *global = 2.0;
4897 "Default update result"
4898 }),
4899 "Default update result"
4900 );
4901 assert_eq!(cx.global::<OtherGlobal>(), &2.0);
4902 assert_eq!(*observation_count.borrow(), 1);
4903 }
4904
4905 #[crate::test(self)]
4906 fn test_dropping_subscribers(cx: &mut TestAppContext) {
4907 struct Model;
4908
4909 impl Entity for Model {
4910 type Event = ();
4911 }
4912
4913 let (_, root_view) = cx.add_window(|_| TestView::default());
4914 let observing_view = cx.add_view(&root_view, |_| TestView::default());
4915 let emitting_view = cx.add_view(&root_view, |_| TestView::default());
4916 let observing_model = cx.add_model(|_| Model);
4917 let observed_model = cx.add_model(|_| Model);
4918
4919 observing_view.update(cx, |_, cx| {
4920 cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4921 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4922 });
4923 observing_model.update(cx, |_, cx| {
4924 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4925 });
4926
4927 cx.update(|_| {
4928 drop(observing_view);
4929 drop(observing_model);
4930 });
4931
4932 emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
4933 observed_model.update(cx, |_, cx| cx.emit(()));
4934 }
4935
4936 #[crate::test(self)]
4937 fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4938 let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
4939 drop(cx.subscribe(&cx.handle(), {
4940 move |this, _, _, _| this.events.push("dropped before flush".into())
4941 }));
4942 cx.subscribe(&cx.handle(), {
4943 move |this, _, _, _| this.events.push("before emit".into())
4944 })
4945 .detach();
4946 cx.emit("the event".into());
4947 cx.subscribe(&cx.handle(), {
4948 move |this, _, _, _| this.events.push("after emit".into())
4949 })
4950 .detach();
4951 TestView { events: Vec::new() }
4952 });
4953
4954 assert_eq!(view.read(cx).events, ["before emit"]);
4955 }
4956
4957 #[crate::test(self)]
4958 fn test_observe_and_notify_from_view(cx: &mut TestAppContext) {
4959 #[derive(Default)]
4960 struct Model {
4961 state: String,
4962 }
4963
4964 impl Entity for Model {
4965 type Event = ();
4966 }
4967
4968 let (_, view) = cx.add_window(|_| TestView::default());
4969 let model = cx.add_model(|_| Model {
4970 state: "old-state".into(),
4971 });
4972
4973 view.update(cx, |_, c| {
4974 c.observe(&model, |me, observed, cx| {
4975 me.events.push(observed.read(cx).state.clone())
4976 })
4977 .detach();
4978 });
4979
4980 model.update(cx, |model, cx| {
4981 model.state = "new-state".into();
4982 cx.notify();
4983 });
4984 view.read_with(cx, |view, _| assert_eq!(view.events, ["new-state"]));
4985 }
4986
4987 #[crate::test(self)]
4988 fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4989 let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
4990 drop(cx.observe(&cx.handle(), {
4991 move |this, _, _| this.events.push("dropped before flush".into())
4992 }));
4993 cx.observe(&cx.handle(), {
4994 move |this, _, _| this.events.push("before notify".into())
4995 })
4996 .detach();
4997 cx.notify();
4998 cx.observe(&cx.handle(), {
4999 move |this, _, _| this.events.push("after notify".into())
5000 })
5001 .detach();
5002 TestView { events: Vec::new() }
5003 });
5004
5005 assert_eq!(view.read(cx).events, ["before notify"]);
5006 }
5007
5008 #[crate::test(self)]
5009 fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut TestAppContext) {
5010 struct Model;
5011 impl Entity for Model {
5012 type Event = ();
5013 }
5014
5015 let model = cx.add_model(|_| Model);
5016 let (_, view) = cx.add_window(|_| TestView::default());
5017
5018 view.update(cx, |_, cx| {
5019 model.update(cx, |_, cx| cx.notify());
5020 drop(cx.observe(&model, move |this, _, _| {
5021 this.events.push("model notified".into());
5022 }));
5023 model.update(cx, |_, cx| cx.notify());
5024 });
5025
5026 for _ in 0..3 {
5027 model.update(cx, |_, cx| cx.notify());
5028 }
5029 view.read_with(cx, |view, _| assert_eq!(view.events, Vec::<&str>::new()));
5030 }
5031
5032 #[crate::test(self)]
5033 fn test_dropping_observers(cx: &mut TestAppContext) {
5034 struct Model;
5035
5036 impl Entity for Model {
5037 type Event = ();
5038 }
5039
5040 let (_, root_view) = cx.add_window(|_| TestView::default());
5041 let observing_view = cx.add_view(&root_view, |_| TestView::default());
5042 let observing_model = cx.add_model(|_| Model);
5043 let observed_model = cx.add_model(|_| Model);
5044
5045 observing_view.update(cx, |_, cx| {
5046 cx.observe(&observed_model, |_, _, _| {}).detach();
5047 });
5048 observing_model.update(cx, |_, cx| {
5049 cx.observe(&observed_model, |_, _, _| {}).detach();
5050 });
5051
5052 cx.update(|_| {
5053 drop(observing_view);
5054 drop(observing_model);
5055 });
5056
5057 observed_model.update(cx, |_, cx| cx.notify());
5058 }
5059
5060 #[crate::test(self)]
5061 fn test_dropping_subscriptions_during_callback(cx: &mut TestAppContext) {
5062 struct Model;
5063
5064 impl Entity for Model {
5065 type Event = u64;
5066 }
5067
5068 // Events
5069 let observing_model = cx.add_model(|_| Model);
5070 let observed_model = cx.add_model(|_| Model);
5071
5072 let events = Rc::new(RefCell::new(Vec::new()));
5073
5074 observing_model.update(cx, |_, cx| {
5075 let events = events.clone();
5076 let subscription = Rc::new(RefCell::new(None));
5077 *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5078 let subscription = subscription.clone();
5079 move |_, _, e, _| {
5080 subscription.borrow_mut().take();
5081 events.borrow_mut().push(*e);
5082 }
5083 }));
5084 });
5085
5086 observed_model.update(cx, |_, cx| {
5087 cx.emit(1);
5088 cx.emit(2);
5089 });
5090
5091 assert_eq!(*events.borrow(), [1]);
5092
5093 // Global Events
5094 #[derive(Clone, Debug, Eq, PartialEq)]
5095 struct GlobalEvent(u64);
5096
5097 let events = Rc::new(RefCell::new(Vec::new()));
5098
5099 {
5100 let events = events.clone();
5101 let subscription = Rc::new(RefCell::new(None));
5102 *subscription.borrow_mut() = Some(cx.subscribe_global({
5103 let subscription = subscription.clone();
5104 move |e: &GlobalEvent, _| {
5105 subscription.borrow_mut().take();
5106 events.borrow_mut().push(e.clone());
5107 }
5108 }));
5109 }
5110
5111 cx.update(|cx| {
5112 cx.emit_global(GlobalEvent(1));
5113 cx.emit_global(GlobalEvent(2));
5114 });
5115
5116 assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5117
5118 // Model Observation
5119 let observing_model = cx.add_model(|_| Model);
5120 let observed_model = cx.add_model(|_| Model);
5121
5122 let observation_count = Rc::new(RefCell::new(0));
5123
5124 observing_model.update(cx, |_, cx| {
5125 let observation_count = observation_count.clone();
5126 let subscription = Rc::new(RefCell::new(None));
5127 *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5128 let subscription = subscription.clone();
5129 move |_, _, _| {
5130 subscription.borrow_mut().take();
5131 *observation_count.borrow_mut() += 1;
5132 }
5133 }));
5134 });
5135
5136 observed_model.update(cx, |_, cx| {
5137 cx.notify();
5138 });
5139
5140 observed_model.update(cx, |_, cx| {
5141 cx.notify();
5142 });
5143
5144 assert_eq!(*observation_count.borrow(), 1);
5145
5146 // View Observation
5147 struct View;
5148
5149 impl Entity for View {
5150 type Event = ();
5151 }
5152
5153 impl super::View for View {
5154 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5155 Empty::new().into_any()
5156 }
5157
5158 fn ui_name() -> &'static str {
5159 "View"
5160 }
5161 }
5162
5163 let (_, root_view) = cx.add_window(|_| View);
5164 let observing_view = cx.add_view(&root_view, |_| View);
5165 let observed_view = cx.add_view(&root_view, |_| View);
5166
5167 let observation_count = Rc::new(RefCell::new(0));
5168 observing_view.update(cx, |_, cx| {
5169 let observation_count = observation_count.clone();
5170 let subscription = Rc::new(RefCell::new(None));
5171 *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5172 let subscription = subscription.clone();
5173 move |_, _, _| {
5174 subscription.borrow_mut().take();
5175 *observation_count.borrow_mut() += 1;
5176 }
5177 }));
5178 });
5179
5180 observed_view.update(cx, |_, cx| {
5181 cx.notify();
5182 });
5183
5184 observed_view.update(cx, |_, cx| {
5185 cx.notify();
5186 });
5187
5188 assert_eq!(*observation_count.borrow(), 1);
5189
5190 // Global Observation
5191 let observation_count = Rc::new(RefCell::new(0));
5192 let subscription = Rc::new(RefCell::new(None));
5193 *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5194 let observation_count = observation_count.clone();
5195 let subscription = subscription.clone();
5196 move |_| {
5197 subscription.borrow_mut().take();
5198 *observation_count.borrow_mut() += 1;
5199 }
5200 }));
5201
5202 cx.update(|cx| {
5203 cx.default_global::<()>();
5204 cx.set_global(());
5205 });
5206 assert_eq!(*observation_count.borrow(), 1);
5207 }
5208
5209 #[crate::test(self)]
5210 fn test_focus(cx: &mut TestAppContext) {
5211 struct View {
5212 name: String,
5213 events: Arc<Mutex<Vec<String>>>,
5214 }
5215
5216 impl Entity for View {
5217 type Event = ();
5218 }
5219
5220 impl super::View for View {
5221 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5222 Empty::new().into_any()
5223 }
5224
5225 fn ui_name() -> &'static str {
5226 "View"
5227 }
5228
5229 fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5230 if cx.handle().id() == focused.id() {
5231 self.events.lock().push(format!("{} focused", &self.name));
5232 }
5233 }
5234
5235 fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5236 if cx.handle().id() == blurred.id() {
5237 self.events.lock().push(format!("{} blurred", &self.name));
5238 }
5239 }
5240 }
5241
5242 let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5243 let (window_id, view_1) = cx.add_window(|_| View {
5244 events: view_events.clone(),
5245 name: "view 1".to_string(),
5246 });
5247 let view_2 = cx.add_view(&view_1, |_| View {
5248 events: view_events.clone(),
5249 name: "view 2".to_string(),
5250 });
5251
5252 let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5253 view_1.update(cx, |_, cx| {
5254 cx.observe_focus(&view_2, {
5255 let observed_events = observed_events.clone();
5256 move |this, view, focused, cx| {
5257 let label = if focused { "focus" } else { "blur" };
5258 observed_events.lock().push(format!(
5259 "{} observed {}'s {}",
5260 this.name,
5261 view.read(cx).name,
5262 label
5263 ))
5264 }
5265 })
5266 .detach();
5267 });
5268 view_2.update(cx, |_, cx| {
5269 cx.observe_focus(&view_1, {
5270 let observed_events = observed_events.clone();
5271 move |this, view, focused, cx| {
5272 let label = if focused { "focus" } else { "blur" };
5273 observed_events.lock().push(format!(
5274 "{} observed {}'s {}",
5275 this.name,
5276 view.read(cx).name,
5277 label
5278 ))
5279 }
5280 })
5281 .detach();
5282 });
5283 assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5284 assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5285
5286 view_1.update(cx, |_, cx| {
5287 // Ensure focus events are sent for all intermediate focuses
5288 cx.focus(&view_2);
5289 cx.focus(&view_1);
5290 cx.focus(&view_2);
5291 });
5292
5293 cx.read_window(window_id, |cx| {
5294 assert!(cx.is_child_focused(&view_1));
5295 assert!(!cx.is_child_focused(&view_2));
5296 });
5297 assert_eq!(
5298 mem::take(&mut *view_events.lock()),
5299 [
5300 "view 1 blurred",
5301 "view 2 focused",
5302 "view 2 blurred",
5303 "view 1 focused",
5304 "view 1 blurred",
5305 "view 2 focused"
5306 ],
5307 );
5308 assert_eq!(
5309 mem::take(&mut *observed_events.lock()),
5310 [
5311 "view 2 observed view 1's blur",
5312 "view 1 observed view 2's focus",
5313 "view 1 observed view 2's blur",
5314 "view 2 observed view 1's focus",
5315 "view 2 observed view 1's blur",
5316 "view 1 observed view 2's focus"
5317 ]
5318 );
5319
5320 view_1.update(cx, |_, cx| cx.focus(&view_1));
5321 cx.read_window(window_id, |cx| {
5322 assert!(!cx.is_child_focused(&view_1));
5323 assert!(!cx.is_child_focused(&view_2));
5324 });
5325 assert_eq!(
5326 mem::take(&mut *view_events.lock()),
5327 ["view 2 blurred", "view 1 focused"],
5328 );
5329 assert_eq!(
5330 mem::take(&mut *observed_events.lock()),
5331 [
5332 "view 1 observed view 2's blur",
5333 "view 2 observed view 1's focus"
5334 ]
5335 );
5336
5337 view_1.update(cx, |_, cx| cx.focus(&view_2));
5338 assert_eq!(
5339 mem::take(&mut *view_events.lock()),
5340 ["view 1 blurred", "view 2 focused"],
5341 );
5342 assert_eq!(
5343 mem::take(&mut *observed_events.lock()),
5344 [
5345 "view 2 observed view 1's blur",
5346 "view 1 observed view 2's focus"
5347 ]
5348 );
5349
5350 view_1.update(cx, |_, _| drop(view_2));
5351 assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5352 assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5353 }
5354
5355 #[crate::test(self)]
5356 fn test_deserialize_actions(cx: &mut AppContext) {
5357 #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5358 pub struct ComplexAction {
5359 arg: String,
5360 count: usize,
5361 }
5362
5363 actions!(test::something, [SimpleAction]);
5364 impl_actions!(test::something, [ComplexAction]);
5365
5366 cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
5367 cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
5368
5369 let action1 = cx
5370 .deserialize_action(
5371 "test::something::ComplexAction",
5372 Some(r#"{"arg": "a", "count": 5}"#),
5373 )
5374 .unwrap();
5375 let action2 = cx
5376 .deserialize_action("test::something::SimpleAction", None)
5377 .unwrap();
5378 assert_eq!(
5379 action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
5380 &ComplexAction {
5381 arg: "a".to_string(),
5382 count: 5,
5383 }
5384 );
5385 assert_eq!(
5386 action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
5387 &SimpleAction
5388 );
5389 }
5390
5391 #[crate::test(self)]
5392 fn test_dispatch_action(cx: &mut AppContext) {
5393 struct ViewA {
5394 id: usize,
5395 }
5396
5397 impl Entity for ViewA {
5398 type Event = ();
5399 }
5400
5401 impl View for ViewA {
5402 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5403 Empty::new().into_any()
5404 }
5405
5406 fn ui_name() -> &'static str {
5407 "View"
5408 }
5409 }
5410
5411 struct ViewB {
5412 id: usize,
5413 }
5414
5415 impl Entity for ViewB {
5416 type Event = ();
5417 }
5418
5419 impl View for ViewB {
5420 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5421 Empty::new().into_any()
5422 }
5423
5424 fn ui_name() -> &'static str {
5425 "View"
5426 }
5427 }
5428
5429 #[derive(Clone, Default, Deserialize, PartialEq)]
5430 pub struct Action(pub String);
5431
5432 impl_actions!(test, [Action]);
5433
5434 let actions = Rc::new(RefCell::new(Vec::new()));
5435
5436 cx.add_global_action({
5437 let actions = actions.clone();
5438 move |_: &Action, _: &mut AppContext| {
5439 actions.borrow_mut().push("global".to_string());
5440 }
5441 });
5442
5443 cx.add_action({
5444 let actions = actions.clone();
5445 move |view: &mut ViewA, action: &Action, cx| {
5446 assert_eq!(action.0, "bar");
5447 cx.propagate_action();
5448 actions.borrow_mut().push(format!("{} a", view.id));
5449 }
5450 });
5451
5452 cx.add_action({
5453 let actions = actions.clone();
5454 move |view: &mut ViewA, _: &Action, cx| {
5455 if view.id != 1 {
5456 cx.add_view(|cx| {
5457 cx.propagate_action(); // Still works on a nested ViewContext
5458 ViewB { id: 5 }
5459 });
5460 }
5461 actions.borrow_mut().push(format!("{} b", view.id));
5462 }
5463 });
5464
5465 cx.add_action({
5466 let actions = actions.clone();
5467 move |view: &mut ViewB, _: &Action, cx| {
5468 cx.propagate_action();
5469 actions.borrow_mut().push(format!("{} c", view.id));
5470 }
5471 });
5472
5473 cx.add_action({
5474 let actions = actions.clone();
5475 move |view: &mut ViewB, _: &Action, cx| {
5476 cx.propagate_action();
5477 actions.borrow_mut().push(format!("{} d", view.id));
5478 }
5479 });
5480
5481 cx.capture_action({
5482 let actions = actions.clone();
5483 move |view: &mut ViewA, _: &Action, cx| {
5484 cx.propagate_action();
5485 actions.borrow_mut().push(format!("{} capture", view.id));
5486 }
5487 });
5488
5489 let observed_actions = Rc::new(RefCell::new(Vec::new()));
5490 cx.observe_actions({
5491 let observed_actions = observed_actions.clone();
5492 move |action_id, _| observed_actions.borrow_mut().push(action_id)
5493 })
5494 .detach();
5495
5496 let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5497 let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
5498 let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5499 let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5500
5501 cx.update_window(window_id, |cx| {
5502 cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5503 });
5504
5505 assert_eq!(
5506 *actions.borrow(),
5507 vec![
5508 "1 capture",
5509 "3 capture",
5510 "4 d",
5511 "4 c",
5512 "3 b",
5513 "3 a",
5514 "2 d",
5515 "2 c",
5516 "1 b"
5517 ]
5518 );
5519 assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
5520
5521 // Remove view_1, which doesn't propagate the action
5522
5523 let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
5524 let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5525 let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5526
5527 actions.borrow_mut().clear();
5528 cx.update_window(window_id, |cx| {
5529 cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5530 });
5531
5532 assert_eq!(
5533 *actions.borrow(),
5534 vec![
5535 "3 capture",
5536 "4 d",
5537 "4 c",
5538 "3 b",
5539 "3 a",
5540 "2 d",
5541 "2 c",
5542 "global"
5543 ]
5544 );
5545 assert_eq!(
5546 *observed_actions.borrow(),
5547 [Action::default().id(), Action::default().id()]
5548 );
5549 }
5550
5551 #[crate::test(self)]
5552 fn test_dispatch_keystroke(cx: &mut AppContext) {
5553 #[derive(Clone, Deserialize, PartialEq)]
5554 pub struct Action(String);
5555
5556 impl_actions!(test, [Action]);
5557
5558 struct View {
5559 id: usize,
5560 keymap_context: KeymapContext,
5561 }
5562
5563 impl Entity for View {
5564 type Event = ();
5565 }
5566
5567 impl super::View for View {
5568 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5569 Empty::new().into_any()
5570 }
5571
5572 fn ui_name() -> &'static str {
5573 "View"
5574 }
5575
5576 fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
5577 *keymap = self.keymap_context.clone();
5578 }
5579 }
5580
5581 impl View {
5582 fn new(id: usize) -> Self {
5583 View {
5584 id,
5585 keymap_context: KeymapContext::default(),
5586 }
5587 }
5588 }
5589
5590 let mut view_1 = View::new(1);
5591 let mut view_2 = View::new(2);
5592 let mut view_3 = View::new(3);
5593 view_1.keymap_context.add_identifier("a");
5594 view_2.keymap_context.add_identifier("a");
5595 view_2.keymap_context.add_identifier("b");
5596 view_3.keymap_context.add_identifier("a");
5597 view_3.keymap_context.add_identifier("b");
5598 view_3.keymap_context.add_identifier("c");
5599
5600 let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5601 let view_2 = cx.add_view(&view_1, |_| view_2);
5602 let _view_3 = cx.add_view(&view_2, |cx| {
5603 cx.focus_self();
5604 view_3
5605 });
5606
5607 // This binding only dispatches an action on view 2 because that view will have
5608 // "a" and "b" in its context, but not "c".
5609 cx.add_bindings(vec![Binding::new(
5610 "a",
5611 Action("a".to_string()),
5612 Some("a && b && !c"),
5613 )]);
5614
5615 cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
5616
5617 // This binding only dispatches an action on views 2 and 3, because they have
5618 // a parent view with a in its context
5619 cx.add_bindings(vec![Binding::new(
5620 "c",
5621 Action("c".to_string()),
5622 Some("b > c"),
5623 )]);
5624
5625 // This binding only dispatches an action on view 2, because they have
5626 // a parent view with a in its context
5627 cx.add_bindings(vec![Binding::new(
5628 "d",
5629 Action("d".to_string()),
5630 Some("a && !b > b"),
5631 )]);
5632
5633 let actions = Rc::new(RefCell::new(Vec::new()));
5634 cx.add_action({
5635 let actions = actions.clone();
5636 move |view: &mut View, action: &Action, cx| {
5637 actions
5638 .borrow_mut()
5639 .push(format!("{} {}", view.id, action.0));
5640
5641 if action.0 == "b" {
5642 cx.propagate_action();
5643 }
5644 }
5645 });
5646
5647 cx.add_global_action({
5648 let actions = actions.clone();
5649 move |action: &Action, _| {
5650 actions.borrow_mut().push(format!("global {}", action.0));
5651 }
5652 });
5653
5654 cx.update_window(window_id, |cx| {
5655 cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
5656 });
5657 assert_eq!(&*actions.borrow(), &["2 a"]);
5658 actions.borrow_mut().clear();
5659
5660 cx.update_window(window_id, |cx| {
5661 cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
5662 });
5663
5664 assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5665 actions.borrow_mut().clear();
5666
5667 cx.update_window(window_id, |cx| {
5668 cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
5669 });
5670 assert_eq!(&*actions.borrow(), &["3 c"]);
5671 actions.borrow_mut().clear();
5672
5673 cx.update_window(window_id, |cx| {
5674 cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
5675 });
5676 assert_eq!(&*actions.borrow(), &["2 d"]);
5677 actions.borrow_mut().clear();
5678 }
5679
5680 #[crate::test(self)]
5681 fn test_keystrokes_for_action(cx: &mut TestAppContext) {
5682 actions!(test, [Action1, Action2, GlobalAction]);
5683
5684 struct View1 {}
5685 struct View2 {}
5686
5687 impl Entity for View1 {
5688 type Event = ();
5689 }
5690 impl Entity for View2 {
5691 type Event = ();
5692 }
5693
5694 impl super::View for View1 {
5695 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5696 Empty::new().into_any()
5697 }
5698 fn ui_name() -> &'static str {
5699 "View1"
5700 }
5701 }
5702 impl super::View for View2 {
5703 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5704 Empty::new().into_any()
5705 }
5706 fn ui_name() -> &'static str {
5707 "View2"
5708 }
5709 }
5710
5711 let (_, view_1) = cx.add_window(|_| View1 {});
5712 let view_2 = cx.add_view(&view_1, |cx| {
5713 cx.focus_self();
5714 View2 {}
5715 });
5716
5717 cx.update(|cx| {
5718 cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
5719 cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
5720 cx.add_global_action(|_: &GlobalAction, _| {});
5721
5722 cx.add_bindings(vec![
5723 Binding::new("a", Action1, Some("View1")),
5724 Binding::new("b", Action2, Some("View1 > View2")),
5725 Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
5726 ]);
5727 });
5728
5729 // Here we update the views to ensure that, even if they are on the stack,
5730 // we can still retrieve keystrokes correctly.
5731 view_1.update(cx, |_, cx| {
5732 view_2.update(cx, |_, cx| {
5733 // Sanity check
5734 assert_eq!(
5735 cx.keystrokes_for_action(view_1.id(), &Action1)
5736 .unwrap()
5737 .as_slice(),
5738 &[Keystroke::parse("a").unwrap()]
5739 );
5740 assert_eq!(
5741 cx.keystrokes_for_action(view_2.id(), &Action2)
5742 .unwrap()
5743 .as_slice(),
5744 &[Keystroke::parse("b").unwrap()]
5745 );
5746
5747 // The 'a' keystroke propagates up the view tree from view_2
5748 // to view_1. The action, Action1, is handled by view_1.
5749 assert_eq!(
5750 cx.keystrokes_for_action(view_2.id(), &Action1)
5751 .unwrap()
5752 .as_slice(),
5753 &[Keystroke::parse("a").unwrap()]
5754 );
5755
5756 // Actions that are handled below the current view don't have bindings
5757 assert_eq!(cx.keystrokes_for_action(view_1.id(), &Action2), None);
5758
5759 // Actions that are handled in other branches of the tree should not have a binding
5760 assert_eq!(cx.keystrokes_for_action(view_2.id(), &GlobalAction), None);
5761
5762 // Check that global actions do not have a binding, even if a binding does exist in another view
5763 assert_eq!(
5764 &available_actions(view_1.id(), cx),
5765 &[
5766 ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5767 ("test::GlobalAction", vec![])
5768 ],
5769 );
5770
5771 // Check that view 1 actions and bindings are available even when called from view 2
5772 assert_eq!(
5773 &available_actions(view_2.id(), cx),
5774 &[
5775 ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5776 ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
5777 ("test::GlobalAction", vec![]),
5778 ],
5779 );
5780 });
5781 });
5782
5783 // Produces a list of actions and key bindings
5784 fn available_actions(
5785 view_id: usize,
5786 cx: &WindowContext,
5787 ) -> Vec<(&'static str, Vec<Keystroke>)> {
5788 cx.available_actions(view_id)
5789 .map(|(action_name, _, bindings)| {
5790 (
5791 action_name,
5792 bindings
5793 .iter()
5794 .map(|binding| binding.keystrokes()[0].clone())
5795 .collect::<Vec<_>>(),
5796 )
5797 })
5798 .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
5799 .collect()
5800 }
5801 }
5802
5803 #[crate::test(self)]
5804 async fn test_model_condition(cx: &mut TestAppContext) {
5805 struct Counter(usize);
5806
5807 impl super::Entity for Counter {
5808 type Event = ();
5809 }
5810
5811 impl Counter {
5812 fn inc(&mut self, cx: &mut ModelContext<Self>) {
5813 self.0 += 1;
5814 cx.notify();
5815 }
5816 }
5817
5818 let model = cx.add_model(|_| Counter(0));
5819
5820 let condition1 = model.condition(cx, |model, _| model.0 == 2);
5821 let condition2 = model.condition(cx, |model, _| model.0 == 3);
5822 smol::pin!(condition1, condition2);
5823
5824 model.update(cx, |model, cx| model.inc(cx));
5825 assert_eq!(poll_once(&mut condition1).await, None);
5826 assert_eq!(poll_once(&mut condition2).await, None);
5827
5828 model.update(cx, |model, cx| model.inc(cx));
5829 assert_eq!(poll_once(&mut condition1).await, Some(()));
5830 assert_eq!(poll_once(&mut condition2).await, None);
5831
5832 model.update(cx, |model, cx| model.inc(cx));
5833 assert_eq!(poll_once(&mut condition2).await, Some(()));
5834
5835 model.update(cx, |_, cx| cx.notify());
5836 }
5837
5838 #[crate::test(self)]
5839 #[should_panic]
5840 async fn test_model_condition_timeout(cx: &mut TestAppContext) {
5841 struct Model;
5842
5843 impl super::Entity for Model {
5844 type Event = ();
5845 }
5846
5847 let model = cx.add_model(|_| Model);
5848 model.condition(cx, |_, _| false).await;
5849 }
5850
5851 #[crate::test(self)]
5852 #[should_panic(expected = "model dropped with pending condition")]
5853 async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
5854 struct Model;
5855
5856 impl super::Entity for Model {
5857 type Event = ();
5858 }
5859
5860 let model = cx.add_model(|_| Model);
5861 let condition = model.condition(cx, |_, _| false);
5862 cx.update(|_| drop(model));
5863 condition.await;
5864 }
5865
5866 #[crate::test(self)]
5867 async fn test_view_condition(cx: &mut TestAppContext) {
5868 struct Counter(usize);
5869
5870 impl super::Entity for Counter {
5871 type Event = ();
5872 }
5873
5874 impl super::View for Counter {
5875 fn ui_name() -> &'static str {
5876 "test view"
5877 }
5878
5879 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5880 Empty::new().into_any()
5881 }
5882 }
5883
5884 impl Counter {
5885 fn inc(&mut self, cx: &mut ViewContext<Self>) {
5886 self.0 += 1;
5887 cx.notify();
5888 }
5889 }
5890
5891 let (_, view) = cx.add_window(|_| Counter(0));
5892
5893 let condition1 = view.condition(cx, |view, _| view.0 == 2);
5894 let condition2 = view.condition(cx, |view, _| view.0 == 3);
5895 smol::pin!(condition1, condition2);
5896
5897 view.update(cx, |view, cx| view.inc(cx));
5898 assert_eq!(poll_once(&mut condition1).await, None);
5899 assert_eq!(poll_once(&mut condition2).await, None);
5900
5901 view.update(cx, |view, cx| view.inc(cx));
5902 assert_eq!(poll_once(&mut condition1).await, Some(()));
5903 assert_eq!(poll_once(&mut condition2).await, None);
5904
5905 view.update(cx, |view, cx| view.inc(cx));
5906 assert_eq!(poll_once(&mut condition2).await, Some(()));
5907 view.update(cx, |_, cx| cx.notify());
5908 }
5909
5910 #[crate::test(self)]
5911 #[should_panic]
5912 async fn test_view_condition_timeout(cx: &mut TestAppContext) {
5913 let (_, view) = cx.add_window(|_| TestView::default());
5914 view.condition(cx, |_, _| false).await;
5915 }
5916
5917 #[crate::test(self)]
5918 #[should_panic(expected = "view dropped with pending condition")]
5919 async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
5920 let (_, root_view) = cx.add_window(|_| TestView::default());
5921 let view = cx.add_view(&root_view, |_| TestView::default());
5922
5923 let condition = view.condition(cx, |_, _| false);
5924 cx.update(|_| drop(view));
5925 condition.await;
5926 }
5927
5928 #[crate::test(self)]
5929 fn test_refresh_windows(cx: &mut AppContext) {
5930 struct View(usize);
5931
5932 impl super::Entity for View {
5933 type Event = ();
5934 }
5935
5936 impl super::View for View {
5937 fn ui_name() -> &'static str {
5938 "test view"
5939 }
5940
5941 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5942 Empty::new().into_any_named(format!("render count: {}", post_inc(&mut self.0)))
5943 }
5944 }
5945
5946 let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
5947 cx.update_window(window_id, |cx| {
5948 assert_eq!(
5949 cx.window.rendered_views[&root_view.id()].name(),
5950 Some("render count: 0")
5951 );
5952 });
5953
5954 let view = cx.add_view(&root_view, |cx| {
5955 cx.refresh_windows();
5956 View(0)
5957 });
5958
5959 cx.update_window(window_id, |cx| {
5960 assert_eq!(
5961 cx.window.rendered_views[&root_view.id()].name(),
5962 Some("render count: 1")
5963 );
5964 assert_eq!(
5965 cx.window.rendered_views[&view.id()].name(),
5966 Some("render count: 0")
5967 );
5968 });
5969
5970 cx.update(|cx| cx.refresh_windows());
5971
5972 cx.update_window(window_id, |cx| {
5973 assert_eq!(
5974 cx.window.rendered_views[&root_view.id()].name(),
5975 Some("render count: 2")
5976 );
5977 assert_eq!(
5978 cx.window.rendered_views[&view.id()].name(),
5979 Some("render count: 1")
5980 );
5981 });
5982
5983 cx.update(|cx| {
5984 cx.refresh_windows();
5985 drop(view);
5986 });
5987
5988 cx.update_window(window_id, |cx| {
5989 assert_eq!(
5990 cx.window.rendered_views[&root_view.id()].name(),
5991 Some("render count: 3")
5992 );
5993 assert_eq!(cx.window.rendered_views.len(), 1);
5994 });
5995 }
5996
5997 #[crate::test(self)]
5998 async fn test_labeled_tasks(cx: &mut TestAppContext) {
5999 assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6000 let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
6001 let task = cx
6002 .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
6003
6004 assert_eq!(
6005 Some("Test Label"),
6006 cx.update(|cx| cx.active_labeled_tasks().next())
6007 );
6008 sender
6009 .send(())
6010 .await
6011 .expect("Could not send message to complete task");
6012 task.await;
6013
6014 assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6015 }
6016
6017 #[crate::test(self)]
6018 async fn test_window_activation(cx: &mut TestAppContext) {
6019 struct View(&'static str);
6020
6021 impl super::Entity for View {
6022 type Event = ();
6023 }
6024
6025 impl super::View for View {
6026 fn ui_name() -> &'static str {
6027 "test view"
6028 }
6029
6030 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6031 Empty::new().into_any()
6032 }
6033 }
6034
6035 let events = Rc::new(RefCell::new(Vec::new()));
6036 let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6037 cx.observe_window_activation({
6038 let events = events.clone();
6039 move |this, active, _| events.borrow_mut().push((this.0, active))
6040 })
6041 .detach();
6042 View("window 1")
6043 });
6044 assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6045
6046 let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6047 cx.observe_window_activation({
6048 let events = events.clone();
6049 move |this, active, _| events.borrow_mut().push((this.0, active))
6050 })
6051 .detach();
6052 View("window 2")
6053 });
6054 assert_eq!(
6055 mem::take(&mut *events.borrow_mut()),
6056 [("window 1", false), ("window 2", true)]
6057 );
6058
6059 let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6060 cx.observe_window_activation({
6061 let events = events.clone();
6062 move |this, active, _| events.borrow_mut().push((this.0, active))
6063 })
6064 .detach();
6065 View("window 3")
6066 });
6067 assert_eq!(
6068 mem::take(&mut *events.borrow_mut()),
6069 [("window 2", false), ("window 3", true)]
6070 );
6071
6072 cx.simulate_window_activation(Some(window_2));
6073 assert_eq!(
6074 mem::take(&mut *events.borrow_mut()),
6075 [("window 3", false), ("window 2", true)]
6076 );
6077
6078 cx.simulate_window_activation(Some(window_1));
6079 assert_eq!(
6080 mem::take(&mut *events.borrow_mut()),
6081 [("window 2", false), ("window 1", true)]
6082 );
6083
6084 cx.simulate_window_activation(Some(window_3));
6085 assert_eq!(
6086 mem::take(&mut *events.borrow_mut()),
6087 [("window 1", false), ("window 3", true)]
6088 );
6089
6090 cx.simulate_window_activation(Some(window_3));
6091 assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6092 }
6093
6094 #[crate::test(self)]
6095 fn test_child_view(cx: &mut TestAppContext) {
6096 struct Child {
6097 rendered: Rc<Cell<bool>>,
6098 dropped: Rc<Cell<bool>>,
6099 }
6100
6101 impl super::Entity for Child {
6102 type Event = ();
6103 }
6104
6105 impl super::View for Child {
6106 fn ui_name() -> &'static str {
6107 "child view"
6108 }
6109
6110 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6111 self.rendered.set(true);
6112 Empty::new().into_any()
6113 }
6114 }
6115
6116 impl Drop for Child {
6117 fn drop(&mut self) {
6118 self.dropped.set(true);
6119 }
6120 }
6121
6122 struct Parent {
6123 child: Option<ViewHandle<Child>>,
6124 }
6125
6126 impl super::Entity for Parent {
6127 type Event = ();
6128 }
6129
6130 impl super::View for Parent {
6131 fn ui_name() -> &'static str {
6132 "parent view"
6133 }
6134
6135 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6136 if let Some(child) = self.child.as_ref() {
6137 ChildView::new(child, cx).into_any()
6138 } else {
6139 Empty::new().into_any()
6140 }
6141 }
6142 }
6143
6144 let child_rendered = Rc::new(Cell::new(false));
6145 let child_dropped = Rc::new(Cell::new(false));
6146 let (_, root_view) = cx.add_window(|cx| Parent {
6147 child: Some(cx.add_view(|_| Child {
6148 rendered: child_rendered.clone(),
6149 dropped: child_dropped.clone(),
6150 })),
6151 });
6152 assert!(child_rendered.take());
6153 assert!(!child_dropped.take());
6154
6155 root_view.update(cx, |view, cx| {
6156 view.child.take();
6157 cx.notify();
6158 });
6159 assert!(!child_rendered.take());
6160 assert!(child_dropped.take());
6161 }
6162
6163 #[derive(Default)]
6164 struct TestView {
6165 events: Vec<String>,
6166 }
6167
6168 impl Entity for TestView {
6169 type Event = String;
6170 }
6171
6172 impl View for TestView {
6173 fn ui_name() -> &'static str {
6174 "TestView"
6175 }
6176
6177 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6178 Empty::new().into_any()
6179 }
6180 }
6181}