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