1use crate::{
2 elements::ElementBox,
3 executor::{self, Task},
4 keymap::{self, Keystroke},
5 platform::{self, CursorStyle, Platform, PromptLevel, WindowOptions},
6 presenter::Presenter,
7 util::post_inc,
8 AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
9};
10use anyhow::{anyhow, Result};
11use keymap::MatchResult;
12use lazy_static::lazy_static;
13use parking_lot::Mutex;
14use platform::Event;
15use postage::oneshot;
16use smol::prelude::*;
17use std::{
18 any::{self, type_name, Any, TypeId},
19 cell::RefCell,
20 collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque},
21 fmt::{self, Debug},
22 hash::{Hash, Hasher},
23 marker::PhantomData,
24 mem,
25 ops::{Deref, DerefMut},
26 path::{Path, PathBuf},
27 pin::Pin,
28 rc::{self, Rc},
29 sync::{
30 atomic::{AtomicUsize, Ordering::SeqCst},
31 Arc, Weak,
32 },
33 time::Duration,
34};
35
36pub trait Entity: 'static {
37 type Event;
38
39 fn release(&mut self, _: &mut MutableAppContext) {}
40 fn app_will_quit(
41 &mut self,
42 _: &mut MutableAppContext,
43 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
44 None
45 }
46}
47
48pub trait View: Entity + Sized {
49 fn ui_name() -> &'static str;
50 fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
51 fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
52 fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
53 fn keymap_context(&self, _: &AppContext) -> keymap::Context {
54 Self::default_keymap_context()
55 }
56 fn default_keymap_context() -> keymap::Context {
57 let mut cx = keymap::Context::default();
58 cx.set.insert(Self::ui_name().into());
59 cx
60 }
61}
62
63pub trait ReadModel {
64 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
65}
66
67pub trait ReadModelWith {
68 fn read_model_with<E: Entity, T>(
69 &self,
70 handle: &ModelHandle<E>,
71 read: &mut dyn FnMut(&E, &AppContext) -> T,
72 ) -> T;
73}
74
75pub trait UpdateModel {
76 fn update_model<T: Entity, O>(
77 &mut self,
78 handle: &ModelHandle<T>,
79 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
80 ) -> O;
81}
82
83pub trait UpgradeModelHandle {
84 fn upgrade_model_handle<T: Entity>(
85 &self,
86 handle: &WeakModelHandle<T>,
87 ) -> Option<ModelHandle<T>>;
88
89 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
90
91 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
92}
93
94pub trait UpgradeViewHandle {
95 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
96}
97
98pub trait ReadView {
99 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
100}
101
102pub trait ReadViewWith {
103 fn read_view_with<V, T>(
104 &self,
105 handle: &ViewHandle<V>,
106 read: &mut dyn FnMut(&V, &AppContext) -> T,
107 ) -> T
108 where
109 V: View;
110}
111
112pub trait UpdateView {
113 fn update_view<T, S>(
114 &mut self,
115 handle: &ViewHandle<T>,
116 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
117 ) -> S
118 where
119 T: View;
120}
121
122pub trait ElementStateContext: DerefMut<Target = MutableAppContext> {
123 fn current_view_id(&self) -> usize;
124
125 fn element_state<Tag: 'static, T: 'static + Default>(
126 &mut self,
127 element_id: usize,
128 ) -> ElementStateHandle<T> {
129 let id = ElementStateId {
130 view_id: self.current_view_id(),
131 element_id,
132 tag: TypeId::of::<Tag>(),
133 };
134 self.cx
135 .element_states
136 .entry(id)
137 .or_insert_with(|| Box::new(T::default()));
138 ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
139 }
140}
141
142pub trait Action: 'static + AnyAction {
143 type Argument: 'static + Clone;
144}
145
146pub trait AnyAction {
147 fn id(&self) -> TypeId;
148 fn name(&self) -> &'static str;
149 fn as_any(&self) -> &dyn Any;
150 fn boxed_clone(&self) -> Box<dyn AnyAction>;
151 fn boxed_clone_as_any(&self) -> Box<dyn Any>;
152}
153
154#[macro_export]
155macro_rules! action {
156 ($name:ident, $arg:ty) => {
157 #[derive(Clone)]
158 pub struct $name(pub $arg);
159
160 impl $crate::Action for $name {
161 type Argument = $arg;
162 }
163
164 impl $crate::AnyAction for $name {
165 fn id(&self) -> std::any::TypeId {
166 std::any::TypeId::of::<$name>()
167 }
168
169 fn name(&self) -> &'static str {
170 stringify!($name)
171 }
172
173 fn as_any(&self) -> &dyn std::any::Any {
174 self
175 }
176
177 fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
178 Box::new(self.clone())
179 }
180
181 fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
182 Box::new(self.clone())
183 }
184 }
185 };
186
187 ($name:ident) => {
188 #[derive(Clone, Debug, Eq, PartialEq)]
189 pub struct $name;
190
191 impl $crate::Action for $name {
192 type Argument = ();
193 }
194
195 impl $crate::AnyAction for $name {
196 fn id(&self) -> std::any::TypeId {
197 std::any::TypeId::of::<$name>()
198 }
199
200 fn name(&self) -> &'static str {
201 stringify!($name)
202 }
203
204 fn as_any(&self) -> &dyn std::any::Any {
205 self
206 }
207
208 fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
209 Box::new(self.clone())
210 }
211
212 fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
213 Box::new(self.clone())
214 }
215 }
216 };
217}
218
219pub struct Menu<'a> {
220 pub name: &'a str,
221 pub items: Vec<MenuItem<'a>>,
222}
223
224pub enum MenuItem<'a> {
225 Action {
226 name: &'a str,
227 keystroke: Option<&'a str>,
228 action: Box<dyn AnyAction>,
229 },
230 Separator,
231}
232
233#[derive(Clone)]
234pub struct App(Rc<RefCell<MutableAppContext>>);
235
236#[derive(Clone)]
237pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
238
239#[cfg(any(test, feature = "test-support"))]
240pub struct TestAppContext {
241 cx: Rc<RefCell<MutableAppContext>>,
242 foreground_platform: Rc<platform::test::ForegroundPlatform>,
243}
244
245impl App {
246 pub fn new(asset_source: impl AssetSource) -> Result<Self> {
247 let platform = platform::current::platform();
248 let foreground_platform = platform::current::foreground_platform();
249 let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
250 let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
251 foreground,
252 Arc::new(executor::Background::new()),
253 platform.clone(),
254 foreground_platform.clone(),
255 Arc::new(FontCache::new(platform.fonts())),
256 Default::default(),
257 asset_source,
258 ))));
259
260 foreground_platform.on_quit(Box::new({
261 let cx = app.0.clone();
262 move || {
263 cx.borrow_mut().quit();
264 }
265 }));
266 foreground_platform.on_menu_command(Box::new({
267 let cx = app.0.clone();
268 move |action| {
269 let mut cx = cx.borrow_mut();
270 if let Some(key_window_id) = cx.cx.platform.key_window_id() {
271 if let Some((presenter, _)) =
272 cx.presenters_and_platform_windows.get(&key_window_id)
273 {
274 let presenter = presenter.clone();
275 let path = presenter.borrow().dispatch_path(cx.as_ref());
276 cx.dispatch_action_any(key_window_id, &path, action);
277 } else {
278 cx.dispatch_global_action_any(action);
279 }
280 } else {
281 cx.dispatch_global_action_any(action);
282 }
283 }
284 }));
285
286 app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
287 Ok(app)
288 }
289
290 pub fn background(&self) -> Arc<executor::Background> {
291 self.0.borrow().background().clone()
292 }
293
294 pub fn on_become_active<F>(self, mut callback: F) -> Self
295 where
296 F: 'static + FnMut(&mut MutableAppContext),
297 {
298 let cx = self.0.clone();
299 self.0
300 .borrow_mut()
301 .foreground_platform
302 .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
303 self
304 }
305
306 pub fn on_resign_active<F>(self, mut callback: F) -> Self
307 where
308 F: 'static + FnMut(&mut MutableAppContext),
309 {
310 let cx = self.0.clone();
311 self.0
312 .borrow_mut()
313 .foreground_platform
314 .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
315 self
316 }
317
318 pub fn on_quit<F>(self, mut callback: F) -> Self
319 where
320 F: 'static + FnMut(&mut MutableAppContext),
321 {
322 let cx = self.0.clone();
323 self.0
324 .borrow_mut()
325 .foreground_platform
326 .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
327 self
328 }
329
330 pub fn on_event<F>(self, mut callback: F) -> Self
331 where
332 F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
333 {
334 let cx = self.0.clone();
335 self.0
336 .borrow_mut()
337 .foreground_platform
338 .on_event(Box::new(move |event| {
339 callback(event, &mut *cx.borrow_mut())
340 }));
341 self
342 }
343
344 pub fn on_open_files<F>(self, mut callback: F) -> Self
345 where
346 F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
347 {
348 let cx = self.0.clone();
349 self.0
350 .borrow_mut()
351 .foreground_platform
352 .on_open_files(Box::new(move |paths| {
353 callback(paths, &mut *cx.borrow_mut())
354 }));
355 self
356 }
357
358 pub fn run<F>(self, on_finish_launching: F)
359 where
360 F: 'static + FnOnce(&mut MutableAppContext),
361 {
362 let platform = self.0.borrow().foreground_platform.clone();
363 platform.run(Box::new(move || {
364 let mut cx = self.0.borrow_mut();
365 let cx = &mut *cx;
366 crate::views::init(cx);
367 on_finish_launching(cx);
368 }))
369 }
370
371 pub fn platform(&self) -> Arc<dyn Platform> {
372 self.0.borrow().platform()
373 }
374
375 pub fn font_cache(&self) -> Arc<FontCache> {
376 self.0.borrow().cx.font_cache.clone()
377 }
378
379 fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
380 let mut state = self.0.borrow_mut();
381 let result = state.update(callback);
382 state.pending_notifications.clear();
383 result
384 }
385}
386
387#[cfg(any(test, feature = "test-support"))]
388impl TestAppContext {
389 pub fn new(
390 foreground_platform: Rc<platform::test::ForegroundPlatform>,
391 platform: Arc<dyn Platform>,
392 foreground: Rc<executor::Foreground>,
393 background: Arc<executor::Background>,
394 font_cache: Arc<FontCache>,
395 leak_detector: Arc<Mutex<LeakDetector>>,
396 first_entity_id: usize,
397 ) -> Self {
398 let mut cx = MutableAppContext::new(
399 foreground.clone(),
400 background,
401 platform,
402 foreground_platform.clone(),
403 font_cache,
404 RefCounts {
405 #[cfg(any(test, feature = "test-support"))]
406 leak_detector,
407 ..Default::default()
408 },
409 (),
410 );
411 cx.next_entity_id = first_entity_id;
412 let cx = TestAppContext {
413 cx: Rc::new(RefCell::new(cx)),
414 foreground_platform,
415 };
416 cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
417 cx
418 }
419
420 pub fn dispatch_action<A: Action>(
421 &self,
422 window_id: usize,
423 responder_chain: Vec<usize>,
424 action: A,
425 ) {
426 self.cx
427 .borrow_mut()
428 .dispatch_action_any(window_id, &responder_chain, &action);
429 }
430
431 pub fn dispatch_global_action<A: Action>(&self, action: A) {
432 self.cx.borrow_mut().dispatch_global_action(action);
433 }
434
435 pub fn dispatch_keystroke(
436 &self,
437 window_id: usize,
438 responder_chain: Vec<usize>,
439 keystroke: &Keystroke,
440 ) -> Result<bool> {
441 let mut state = self.cx.borrow_mut();
442 state.dispatch_keystroke(window_id, responder_chain, keystroke)
443 }
444
445 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
446 where
447 T: Entity,
448 F: FnOnce(&mut ModelContext<T>) -> T,
449 {
450 self.cx.borrow_mut().add_model(build_model)
451 }
452
453 pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
454 where
455 T: View,
456 F: FnOnce(&mut ViewContext<T>) -> T,
457 {
458 self.cx
459 .borrow_mut()
460 .add_window(Default::default(), build_root_view)
461 }
462
463 pub fn window_ids(&self) -> Vec<usize> {
464 self.cx.borrow().window_ids().collect()
465 }
466
467 pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
468 self.cx.borrow().root_view(window_id)
469 }
470
471 pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
472 where
473 T: View,
474 F: FnOnce(&mut ViewContext<T>) -> T,
475 {
476 self.cx.borrow_mut().add_view(window_id, build_view)
477 }
478
479 pub fn add_option_view<T, F>(
480 &mut self,
481 window_id: usize,
482 build_view: F,
483 ) -> Option<ViewHandle<T>>
484 where
485 T: View,
486 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
487 {
488 self.cx.borrow_mut().add_option_view(window_id, build_view)
489 }
490
491 pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
492 callback(self.cx.borrow().as_ref())
493 }
494
495 pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
496 let mut state = self.cx.borrow_mut();
497 // Don't increment pending flushes in order to effects to be flushed before the callback
498 // completes, which is helpful in tests.
499 let result = callback(&mut *state);
500 // Flush effects after the callback just in case there are any. This can happen in edge
501 // cases such as the closure dropping handles.
502 state.flush_effects();
503 result
504 }
505
506 pub fn to_async(&self) -> AsyncAppContext {
507 AsyncAppContext(self.cx.clone())
508 }
509
510 pub fn font_cache(&self) -> Arc<FontCache> {
511 self.cx.borrow().cx.font_cache.clone()
512 }
513
514 pub fn foreground_platform(&self) -> Rc<platform::test::ForegroundPlatform> {
515 self.foreground_platform.clone()
516 }
517
518 pub fn platform(&self) -> Arc<dyn platform::Platform> {
519 self.cx.borrow().cx.platform.clone()
520 }
521
522 pub fn foreground(&self) -> Rc<executor::Foreground> {
523 self.cx.borrow().foreground().clone()
524 }
525
526 pub fn background(&self) -> Arc<executor::Background> {
527 self.cx.borrow().background().clone()
528 }
529
530 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
531 where
532 F: FnOnce(AsyncAppContext) -> Fut,
533 Fut: 'static + Future<Output = T>,
534 T: 'static,
535 {
536 self.cx.borrow_mut().spawn(f)
537 }
538
539 pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
540 self.foreground_platform.simulate_new_path_selection(result);
541 }
542
543 pub fn did_prompt_for_new_path(&self) -> bool {
544 self.foreground_platform.as_ref().did_prompt_for_new_path()
545 }
546
547 pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
548 use postage::prelude::Sink as _;
549
550 let mut state = self.cx.borrow_mut();
551 let (_, window) = state
552 .presenters_and_platform_windows
553 .get_mut(&window_id)
554 .unwrap();
555 let test_window = window
556 .as_any_mut()
557 .downcast_mut::<platform::test::Window>()
558 .unwrap();
559 let mut done_tx = test_window
560 .last_prompt
561 .take()
562 .expect("prompt was not called");
563 let _ = done_tx.try_send(answer);
564 }
565
566 #[cfg(any(test, feature = "test-support"))]
567 pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
568 self.cx.borrow().leak_detector()
569 }
570}
571
572impl AsyncAppContext {
573 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
574 where
575 F: FnOnce(AsyncAppContext) -> Fut,
576 Fut: 'static + Future<Output = T>,
577 T: 'static,
578 {
579 self.0.borrow().foreground.spawn(f(self.clone()))
580 }
581
582 pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
583 callback(self.0.borrow().as_ref())
584 }
585
586 pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
587 self.0.borrow_mut().update(callback)
588 }
589
590 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
591 where
592 T: Entity,
593 F: FnOnce(&mut ModelContext<T>) -> T,
594 {
595 self.update(|cx| cx.add_model(build_model))
596 }
597
598 pub fn platform(&self) -> Arc<dyn Platform> {
599 self.0.borrow().platform()
600 }
601
602 pub fn foreground(&self) -> Rc<executor::Foreground> {
603 self.0.borrow().foreground.clone()
604 }
605
606 pub fn background(&self) -> Arc<executor::Background> {
607 self.0.borrow().cx.background.clone()
608 }
609}
610
611impl UpdateModel for AsyncAppContext {
612 fn update_model<E: Entity, O>(
613 &mut self,
614 handle: &ModelHandle<E>,
615 update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
616 ) -> O {
617 self.0.borrow_mut().update_model(handle, update)
618 }
619}
620
621impl UpgradeModelHandle for AsyncAppContext {
622 fn upgrade_model_handle<T: Entity>(
623 &self,
624 handle: &WeakModelHandle<T>,
625 ) -> Option<ModelHandle<T>> {
626 self.0.borrow().upgrade_model_handle(handle)
627 }
628
629 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
630 self.0.borrow().model_handle_is_upgradable(handle)
631 }
632
633 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
634 self.0.borrow().upgrade_any_model_handle(handle)
635 }
636}
637
638impl UpgradeViewHandle for AsyncAppContext {
639 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
640 self.0.borrow_mut().upgrade_view_handle(handle)
641 }
642}
643
644impl ReadModelWith for AsyncAppContext {
645 fn read_model_with<E: Entity, T>(
646 &self,
647 handle: &ModelHandle<E>,
648 read: &mut dyn FnMut(&E, &AppContext) -> T,
649 ) -> T {
650 let cx = self.0.borrow();
651 let cx = cx.as_ref();
652 read(handle.read(cx), cx)
653 }
654}
655
656impl UpdateView for AsyncAppContext {
657 fn update_view<T, S>(
658 &mut self,
659 handle: &ViewHandle<T>,
660 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
661 ) -> S
662 where
663 T: View,
664 {
665 self.0.borrow_mut().update_view(handle, update)
666 }
667}
668
669impl ReadViewWith for AsyncAppContext {
670 fn read_view_with<V, T>(
671 &self,
672 handle: &ViewHandle<V>,
673 read: &mut dyn FnMut(&V, &AppContext) -> T,
674 ) -> T
675 where
676 V: View,
677 {
678 let cx = self.0.borrow();
679 let cx = cx.as_ref();
680 read(handle.read(cx), cx)
681 }
682}
683
684#[cfg(any(test, feature = "test-support"))]
685impl UpdateModel for TestAppContext {
686 fn update_model<T: Entity, O>(
687 &mut self,
688 handle: &ModelHandle<T>,
689 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
690 ) -> O {
691 self.cx.borrow_mut().update_model(handle, update)
692 }
693}
694
695#[cfg(any(test, feature = "test-support"))]
696impl ReadModelWith for TestAppContext {
697 fn read_model_with<E: Entity, T>(
698 &self,
699 handle: &ModelHandle<E>,
700 read: &mut dyn FnMut(&E, &AppContext) -> T,
701 ) -> T {
702 let cx = self.cx.borrow();
703 let cx = cx.as_ref();
704 read(handle.read(cx), cx)
705 }
706}
707
708#[cfg(any(test, feature = "test-support"))]
709impl UpdateView for TestAppContext {
710 fn update_view<T, S>(
711 &mut self,
712 handle: &ViewHandle<T>,
713 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
714 ) -> S
715 where
716 T: View,
717 {
718 self.cx.borrow_mut().update_view(handle, update)
719 }
720}
721
722#[cfg(any(test, feature = "test-support"))]
723impl ReadViewWith for TestAppContext {
724 fn read_view_with<V, T>(
725 &self,
726 handle: &ViewHandle<V>,
727 read: &mut dyn FnMut(&V, &AppContext) -> T,
728 ) -> T
729 where
730 V: View,
731 {
732 let cx = self.cx.borrow();
733 let cx = cx.as_ref();
734 read(handle.read(cx), cx)
735 }
736}
737
738type ActionCallback =
739 dyn FnMut(&mut dyn AnyView, &dyn AnyAction, &mut MutableAppContext, usize, usize);
740type GlobalActionCallback = dyn FnMut(&dyn AnyAction, &mut MutableAppContext);
741
742type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
743type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
744type ReleaseObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
745
746pub struct MutableAppContext {
747 weak_self: Option<rc::Weak<RefCell<Self>>>,
748 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
749 assets: Arc<AssetCache>,
750 cx: AppContext,
751 capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
752 actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
753 global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
754 keystroke_matcher: keymap::Matcher,
755 next_entity_id: usize,
756 next_window_id: usize,
757 next_subscription_id: usize,
758 frame_count: usize,
759 subscriptions: Arc<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>,
760 observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>,
761 release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
762 presenters_and_platform_windows:
763 HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
764 debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
765 foreground: Rc<executor::Foreground>,
766 pending_effects: VecDeque<Effect>,
767 pending_notifications: HashSet<usize>,
768 pending_flushes: usize,
769 flushing_effects: bool,
770 next_cursor_style_handle_id: Arc<AtomicUsize>,
771 halt_action_dispatch: bool,
772}
773
774impl MutableAppContext {
775 fn new(
776 foreground: Rc<executor::Foreground>,
777 background: Arc<executor::Background>,
778 platform: Arc<dyn platform::Platform>,
779 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
780 font_cache: Arc<FontCache>,
781 ref_counts: RefCounts,
782 asset_source: impl AssetSource,
783 ) -> Self {
784 Self {
785 weak_self: None,
786 foreground_platform,
787 assets: Arc::new(AssetCache::new(asset_source)),
788 cx: AppContext {
789 models: Default::default(),
790 views: Default::default(),
791 windows: Default::default(),
792 app_states: Default::default(),
793 element_states: Default::default(),
794 ref_counts: Arc::new(Mutex::new(ref_counts)),
795 background,
796 font_cache,
797 platform,
798 },
799 capture_actions: HashMap::new(),
800 actions: HashMap::new(),
801 global_actions: HashMap::new(),
802 keystroke_matcher: keymap::Matcher::default(),
803 next_entity_id: 0,
804 next_window_id: 0,
805 next_subscription_id: 0,
806 frame_count: 0,
807 subscriptions: Default::default(),
808 observations: Default::default(),
809 release_observations: Default::default(),
810 presenters_and_platform_windows: HashMap::new(),
811 debug_elements_callbacks: HashMap::new(),
812 foreground,
813 pending_effects: VecDeque::new(),
814 pending_notifications: HashSet::new(),
815 pending_flushes: 0,
816 flushing_effects: false,
817 next_cursor_style_handle_id: Default::default(),
818 halt_action_dispatch: false,
819 }
820 }
821
822 pub fn upgrade(&self) -> App {
823 App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
824 }
825
826 pub fn quit(&mut self) {
827 let mut futures = Vec::new();
828 for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
829 let mut model = self.cx.models.remove(&model_id).unwrap();
830 futures.extend(model.app_will_quit(self));
831 self.cx.models.insert(model_id, model);
832 }
833
834 for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
835 let mut view = self.cx.views.remove(&view_id).unwrap();
836 futures.extend(view.app_will_quit(self));
837 self.cx.views.insert(view_id, view);
838 }
839
840 self.remove_all_windows();
841
842 let futures = futures::future::join_all(futures);
843 if self
844 .background
845 .block_with_timeout(Duration::from_millis(100), futures)
846 .is_err()
847 {
848 log::error!("timed out waiting on app_will_quit");
849 }
850 }
851
852 pub fn remove_all_windows(&mut self) {
853 for (window_id, _) in self.cx.windows.drain() {
854 self.presenters_and_platform_windows.remove(&window_id);
855 self.debug_elements_callbacks.remove(&window_id);
856 }
857 self.flush_effects();
858 }
859
860 pub fn platform(&self) -> Arc<dyn platform::Platform> {
861 self.cx.platform.clone()
862 }
863
864 pub fn font_cache(&self) -> &Arc<FontCache> {
865 &self.cx.font_cache
866 }
867
868 pub fn foreground(&self) -> &Rc<executor::Foreground> {
869 &self.foreground
870 }
871
872 pub fn background(&self) -> &Arc<executor::Background> {
873 &self.cx.background
874 }
875
876 pub fn on_debug_elements<F>(&mut self, window_id: usize, callback: F)
877 where
878 F: 'static + Fn(&AppContext) -> crate::json::Value,
879 {
880 self.debug_elements_callbacks
881 .insert(window_id, Box::new(callback));
882 }
883
884 pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
885 self.debug_elements_callbacks
886 .get(&window_id)
887 .map(|debug_elements| debug_elements(&self.cx))
888 }
889
890 pub fn add_action<A, V, F>(&mut self, handler: F)
891 where
892 A: Action,
893 V: View,
894 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
895 {
896 self.add_action_internal(handler, false)
897 }
898
899 pub fn capture_action<A, V, F>(&mut self, handler: F)
900 where
901 A: Action,
902 V: View,
903 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
904 {
905 self.add_action_internal(handler, true)
906 }
907
908 fn add_action_internal<A, V, F>(&mut self, mut handler: F, capture: bool)
909 where
910 A: Action,
911 V: View,
912 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
913 {
914 let handler = Box::new(
915 move |view: &mut dyn AnyView,
916 action: &dyn AnyAction,
917 cx: &mut MutableAppContext,
918 window_id: usize,
919 view_id: usize| {
920 let action = action.as_any().downcast_ref().unwrap();
921 let mut cx = ViewContext::new(cx, window_id, view_id);
922 handler(
923 view.as_any_mut()
924 .downcast_mut()
925 .expect("downcast is type safe"),
926 action,
927 &mut cx,
928 );
929 },
930 );
931
932 let actions = if capture {
933 &mut self.capture_actions
934 } else {
935 &mut self.actions
936 };
937
938 actions
939 .entry(TypeId::of::<V>())
940 .or_default()
941 .entry(TypeId::of::<A>())
942 .or_default()
943 .push(handler);
944 }
945
946 pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
947 where
948 A: Action,
949 V: View,
950 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
951 {
952 self.add_action(move |view, action, cx| {
953 handler(view, action, cx).map(|task| task.detach_and_log_err(cx));
954 })
955 }
956
957 pub fn add_global_action<A, F>(&mut self, mut handler: F)
958 where
959 A: Action,
960 F: 'static + FnMut(&A, &mut MutableAppContext),
961 {
962 let handler = Box::new(move |action: &dyn AnyAction, cx: &mut MutableAppContext| {
963 let action = action.as_any().downcast_ref().unwrap();
964 handler(action, cx);
965 });
966
967 if self
968 .global_actions
969 .insert(TypeId::of::<A>(), handler)
970 .is_some()
971 {
972 panic!("registered multiple global handlers for the same action type");
973 }
974 }
975
976 pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
977 self.cx.windows.keys().cloned()
978 }
979
980 pub fn activate_window(&self, window_id: usize) {
981 if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
982 window.activate()
983 }
984 }
985
986 pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
987 self.cx
988 .windows
989 .get(&window_id)
990 .and_then(|window| window.root_view.clone().downcast::<T>())
991 }
992
993 pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
994 self.cx.root_view_id(window_id)
995 }
996
997 pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
998 self.cx.focused_view_id(window_id)
999 }
1000
1001 pub fn render_view(
1002 &mut self,
1003 window_id: usize,
1004 view_id: usize,
1005 titlebar_height: f32,
1006 refreshing: bool,
1007 ) -> Result<ElementBox> {
1008 let mut view = self
1009 .cx
1010 .views
1011 .remove(&(window_id, view_id))
1012 .ok_or(anyhow!("view not found"))?;
1013 let element = view.render(window_id, view_id, titlebar_height, refreshing, self);
1014 self.cx.views.insert((window_id, view_id), view);
1015 Ok(element)
1016 }
1017
1018 pub fn render_views(
1019 &mut self,
1020 window_id: usize,
1021 titlebar_height: f32,
1022 ) -> HashMap<usize, ElementBox> {
1023 self.start_frame();
1024 let view_ids = self
1025 .views
1026 .keys()
1027 .filter_map(|(win_id, view_id)| {
1028 if *win_id == window_id {
1029 Some(*view_id)
1030 } else {
1031 None
1032 }
1033 })
1034 .collect::<Vec<_>>();
1035 view_ids
1036 .into_iter()
1037 .map(|view_id| {
1038 (
1039 view_id,
1040 self.render_view(window_id, view_id, titlebar_height, false)
1041 .unwrap(),
1042 )
1043 })
1044 .collect()
1045 }
1046
1047 pub(crate) fn start_frame(&mut self) {
1048 self.frame_count += 1;
1049 }
1050
1051 pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
1052 self.pending_flushes += 1;
1053 let result = callback(self);
1054 self.flush_effects();
1055 result
1056 }
1057
1058 pub fn set_menus(&mut self, menus: Vec<Menu>) {
1059 self.foreground_platform.set_menus(menus);
1060 }
1061
1062 fn prompt(
1063 &self,
1064 window_id: usize,
1065 level: PromptLevel,
1066 msg: &str,
1067 answers: &[&str],
1068 ) -> oneshot::Receiver<usize> {
1069 let (_, window) = &self.presenters_and_platform_windows[&window_id];
1070 window.prompt(level, msg, answers)
1071 }
1072
1073 pub fn prompt_for_paths(
1074 &self,
1075 options: PathPromptOptions,
1076 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1077 self.foreground_platform.prompt_for_paths(options)
1078 }
1079
1080 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1081 self.foreground_platform.prompt_for_new_path(directory)
1082 }
1083
1084 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1085 where
1086 E: Entity,
1087 E::Event: 'static,
1088 H: Handle<E>,
1089 F: 'static + FnMut(H, &E::Event, &mut Self),
1090 {
1091 self.subscribe_internal(handle, move |handle, event, cx| {
1092 callback(handle, event, cx);
1093 true
1094 })
1095 }
1096
1097 pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1098 where
1099 E: Entity,
1100 E::Event: 'static,
1101 H: Handle<E>,
1102 F: 'static + FnMut(H, &mut Self),
1103 {
1104 self.observe_internal(handle, move |handle, cx| {
1105 callback(handle, cx);
1106 true
1107 })
1108 }
1109
1110 pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1111 where
1112 E: Entity,
1113 E::Event: 'static,
1114 H: Handle<E>,
1115 F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1116 {
1117 let id = post_inc(&mut self.next_subscription_id);
1118 let emitter = handle.downgrade();
1119 self.subscriptions
1120 .lock()
1121 .entry(handle.id())
1122 .or_default()
1123 .insert(
1124 id,
1125 Box::new(move |payload, cx| {
1126 if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1127 let payload = payload.downcast_ref().expect("downcast is type safe");
1128 callback(emitter, payload, cx)
1129 } else {
1130 false
1131 }
1132 }),
1133 );
1134 Subscription::Subscription {
1135 id,
1136 entity_id: handle.id(),
1137 subscriptions: Some(Arc::downgrade(&self.subscriptions)),
1138 }
1139 }
1140
1141 fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1142 where
1143 E: Entity,
1144 E::Event: 'static,
1145 H: Handle<E>,
1146 F: 'static + FnMut(H, &mut Self) -> bool,
1147 {
1148 let id = post_inc(&mut self.next_subscription_id);
1149 let observed = handle.downgrade();
1150 self.observations
1151 .lock()
1152 .entry(handle.id())
1153 .or_default()
1154 .insert(
1155 id,
1156 Box::new(move |cx| {
1157 if let Some(observed) = H::upgrade_from(&observed, cx) {
1158 callback(observed, cx)
1159 } else {
1160 false
1161 }
1162 }),
1163 );
1164 Subscription::Observation {
1165 id,
1166 entity_id: handle.id(),
1167 observations: Some(Arc::downgrade(&self.observations)),
1168 }
1169 }
1170
1171 pub fn observe_release<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1172 where
1173 E: Entity,
1174 E::Event: 'static,
1175 H: Handle<E>,
1176 F: 'static + FnMut(&mut Self),
1177 {
1178 let id = post_inc(&mut self.next_subscription_id);
1179 self.release_observations
1180 .lock()
1181 .entry(handle.id())
1182 .or_default()
1183 .insert(id, Box::new(move |cx| callback(cx)));
1184 Subscription::ReleaseObservation {
1185 id,
1186 entity_id: handle.id(),
1187 observations: Some(Arc::downgrade(&self.release_observations)),
1188 }
1189 }
1190
1191 fn defer(&mut self, callback: Box<dyn FnOnce(&mut MutableAppContext)>) {
1192 self.pending_effects.push_back(Effect::Deferred(callback))
1193 }
1194
1195 pub(crate) fn notify_model(&mut self, model_id: usize) {
1196 if self.pending_notifications.insert(model_id) {
1197 self.pending_effects
1198 .push_back(Effect::ModelNotification { model_id });
1199 }
1200 }
1201
1202 pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1203 if self.pending_notifications.insert(view_id) {
1204 self.pending_effects
1205 .push_back(Effect::ViewNotification { window_id, view_id });
1206 }
1207 }
1208
1209 pub fn dispatch_action<A: Action>(
1210 &mut self,
1211 window_id: usize,
1212 responder_chain: Vec<usize>,
1213 action: &A,
1214 ) {
1215 self.dispatch_action_any(window_id, &responder_chain, action);
1216 }
1217
1218 pub(crate) fn dispatch_action_any(
1219 &mut self,
1220 window_id: usize,
1221 path: &[usize],
1222 action: &dyn AnyAction,
1223 ) -> bool {
1224 self.update(|this| {
1225 this.halt_action_dispatch = false;
1226 for (capture_phase, view_id) in path
1227 .iter()
1228 .map(|view_id| (true, *view_id))
1229 .chain(path.iter().rev().map(|view_id| (false, *view_id)))
1230 {
1231 if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
1232 let type_id = view.as_any().type_id();
1233
1234 if let Some((name, mut handlers)) = this
1235 .actions_mut(capture_phase)
1236 .get_mut(&type_id)
1237 .and_then(|h| h.remove_entry(&action.id()))
1238 {
1239 for handler in handlers.iter_mut().rev() {
1240 this.halt_action_dispatch = true;
1241 handler(view.as_mut(), action, this, window_id, view_id);
1242 if this.halt_action_dispatch {
1243 break;
1244 }
1245 }
1246 this.actions_mut(capture_phase)
1247 .get_mut(&type_id)
1248 .unwrap()
1249 .insert(name, handlers);
1250 }
1251
1252 this.cx.views.insert((window_id, view_id), view);
1253
1254 if this.halt_action_dispatch {
1255 break;
1256 }
1257 }
1258 }
1259
1260 if !this.halt_action_dispatch {
1261 this.dispatch_global_action_any(action);
1262 }
1263 this.halt_action_dispatch
1264 })
1265 }
1266
1267 fn actions_mut(
1268 &mut self,
1269 capture_phase: bool,
1270 ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1271 if capture_phase {
1272 &mut self.capture_actions
1273 } else {
1274 &mut self.actions
1275 }
1276 }
1277
1278 pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1279 self.dispatch_global_action_any(&action);
1280 }
1281
1282 fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) -> bool {
1283 self.update(|this| {
1284 if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1285 handler(action, this);
1286 this.global_actions.insert(name, handler);
1287 true
1288 } else {
1289 false
1290 }
1291 })
1292 }
1293
1294 pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1295 self.keystroke_matcher.add_bindings(bindings);
1296 }
1297
1298 pub fn dispatch_keystroke(
1299 &mut self,
1300 window_id: usize,
1301 responder_chain: Vec<usize>,
1302 keystroke: &Keystroke,
1303 ) -> Result<bool> {
1304 let mut context_chain = Vec::new();
1305 for view_id in &responder_chain {
1306 if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1307 context_chain.push(view.keymap_context(self.as_ref()));
1308 } else {
1309 return Err(anyhow!(
1310 "View {} in responder chain does not exist",
1311 view_id
1312 ));
1313 }
1314 }
1315
1316 let mut pending = false;
1317 for (i, cx) in context_chain.iter().enumerate().rev() {
1318 match self
1319 .keystroke_matcher
1320 .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1321 {
1322 MatchResult::None => {}
1323 MatchResult::Pending => pending = true,
1324 MatchResult::Action(action) => {
1325 if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1326 {
1327 self.keystroke_matcher.clear_pending();
1328 return Ok(true);
1329 }
1330 }
1331 }
1332 }
1333
1334 Ok(pending)
1335 }
1336
1337 pub fn add_app_state<T: 'static>(&mut self, state: T) {
1338 self.cx
1339 .app_states
1340 .insert(TypeId::of::<T>(), Box::new(state));
1341 }
1342
1343 pub fn update_app_state<T: 'static, F, U>(&mut self, update: F) -> U
1344 where
1345 F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1346 {
1347 let type_id = TypeId::of::<T>();
1348 let mut state = self
1349 .cx
1350 .app_states
1351 .remove(&type_id)
1352 .expect("no app state has been added for this type");
1353 let result = update(state.downcast_mut().unwrap(), self);
1354 self.cx.app_states.insert(type_id, state);
1355 result
1356 }
1357
1358 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1359 where
1360 T: Entity,
1361 F: FnOnce(&mut ModelContext<T>) -> T,
1362 {
1363 self.update(|this| {
1364 let model_id = post_inc(&mut this.next_entity_id);
1365 let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1366 let mut cx = ModelContext::new(this, model_id);
1367 let model = build_model(&mut cx);
1368 this.cx.models.insert(model_id, Box::new(model));
1369 handle
1370 })
1371 }
1372
1373 pub fn add_window<T, F>(
1374 &mut self,
1375 window_options: WindowOptions,
1376 build_root_view: F,
1377 ) -> (usize, ViewHandle<T>)
1378 where
1379 T: View,
1380 F: FnOnce(&mut ViewContext<T>) -> T,
1381 {
1382 self.update(|this| {
1383 let window_id = post_inc(&mut this.next_window_id);
1384 let root_view = this.add_view(window_id, build_root_view);
1385
1386 this.cx.windows.insert(
1387 window_id,
1388 Window {
1389 root_view: root_view.clone().into(),
1390 focused_view_id: root_view.id(),
1391 invalidation: None,
1392 },
1393 );
1394 this.open_platform_window(window_id, window_options);
1395 root_view.update(this, |view, cx| {
1396 view.on_focus(cx);
1397 cx.notify();
1398 });
1399
1400 (window_id, root_view)
1401 })
1402 }
1403
1404 pub fn remove_window(&mut self, window_id: usize) {
1405 self.cx.windows.remove(&window_id);
1406 self.presenters_and_platform_windows.remove(&window_id);
1407 self.debug_elements_callbacks.remove(&window_id);
1408 self.flush_effects();
1409 }
1410
1411 fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1412 let mut window =
1413 self.cx
1414 .platform
1415 .open_window(window_id, window_options, self.foreground.clone());
1416 let presenter = Rc::new(RefCell::new(
1417 self.build_presenter(window_id, window.titlebar_height()),
1418 ));
1419
1420 {
1421 let mut app = self.upgrade();
1422 let presenter = presenter.clone();
1423 window.on_event(Box::new(move |event| {
1424 app.update(|cx| {
1425 if let Event::KeyDown { keystroke, .. } = &event {
1426 if cx
1427 .dispatch_keystroke(
1428 window_id,
1429 presenter.borrow().dispatch_path(cx.as_ref()),
1430 keystroke,
1431 )
1432 .unwrap()
1433 {
1434 return;
1435 }
1436 }
1437
1438 presenter.borrow_mut().dispatch_event(event, cx);
1439 })
1440 }));
1441 }
1442
1443 {
1444 let mut app = self.upgrade();
1445 window.on_resize(Box::new(move || {
1446 app.update(|cx| cx.resize_window(window_id))
1447 }));
1448 }
1449
1450 {
1451 let mut app = self.upgrade();
1452 window.on_close(Box::new(move || {
1453 app.update(|cx| cx.remove_window(window_id));
1454 }));
1455 }
1456
1457 self.presenters_and_platform_windows
1458 .insert(window_id, (presenter.clone(), window));
1459
1460 self.on_debug_elements(window_id, move |cx| {
1461 presenter.borrow().debug_elements(cx).unwrap()
1462 });
1463 }
1464
1465 pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
1466 Presenter::new(
1467 window_id,
1468 titlebar_height,
1469 self.cx.font_cache.clone(),
1470 TextLayoutCache::new(self.cx.platform.fonts()),
1471 self.assets.clone(),
1472 self,
1473 )
1474 }
1475
1476 pub fn build_render_context<V: View>(
1477 &mut self,
1478 window_id: usize,
1479 view_id: usize,
1480 titlebar_height: f32,
1481 refreshing: bool,
1482 ) -> RenderContext<V> {
1483 RenderContext {
1484 app: self,
1485 titlebar_height,
1486 refreshing,
1487 window_id,
1488 view_id,
1489 view_type: PhantomData,
1490 }
1491 }
1492
1493 pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1494 where
1495 T: View,
1496 F: FnOnce(&mut ViewContext<T>) -> T,
1497 {
1498 self.add_option_view(window_id, |cx| Some(build_view(cx)))
1499 .unwrap()
1500 }
1501
1502 pub fn add_option_view<T, F>(
1503 &mut self,
1504 window_id: usize,
1505 build_view: F,
1506 ) -> Option<ViewHandle<T>>
1507 where
1508 T: View,
1509 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1510 {
1511 self.update(|this| {
1512 let view_id = post_inc(&mut this.next_entity_id);
1513 let mut cx = ViewContext::new(this, window_id, view_id);
1514 let handle = if let Some(view) = build_view(&mut cx) {
1515 this.cx.views.insert((window_id, view_id), Box::new(view));
1516 if let Some(window) = this.cx.windows.get_mut(&window_id) {
1517 window
1518 .invalidation
1519 .get_or_insert_with(Default::default)
1520 .updated
1521 .insert(view_id);
1522 }
1523 Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
1524 } else {
1525 None
1526 };
1527 handle
1528 })
1529 }
1530
1531 fn remove_dropped_entities(&mut self) {
1532 loop {
1533 let (dropped_models, dropped_views, dropped_element_states) =
1534 self.cx.ref_counts.lock().take_dropped();
1535 if dropped_models.is_empty()
1536 && dropped_views.is_empty()
1537 && dropped_element_states.is_empty()
1538 {
1539 break;
1540 }
1541
1542 for model_id in dropped_models {
1543 self.subscriptions.lock().remove(&model_id);
1544 self.observations.lock().remove(&model_id);
1545 let mut model = self.cx.models.remove(&model_id).unwrap();
1546 model.release(self);
1547 self.pending_effects.push_back(Effect::Release {
1548 entity_id: model_id,
1549 });
1550 }
1551
1552 for (window_id, view_id) in dropped_views {
1553 self.subscriptions.lock().remove(&view_id);
1554 self.observations.lock().remove(&view_id);
1555 let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1556 view.release(self);
1557 let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1558 window
1559 .invalidation
1560 .get_or_insert_with(Default::default)
1561 .removed
1562 .push(view_id);
1563 if window.focused_view_id == view_id {
1564 Some(window.root_view.id())
1565 } else {
1566 None
1567 }
1568 });
1569
1570 if let Some(view_id) = change_focus_to {
1571 self.focus(window_id, view_id);
1572 }
1573
1574 self.pending_effects
1575 .push_back(Effect::Release { entity_id: view_id });
1576 }
1577
1578 for key in dropped_element_states {
1579 self.cx.element_states.remove(&key);
1580 }
1581 }
1582 }
1583
1584 fn flush_effects(&mut self) {
1585 self.pending_flushes = self.pending_flushes.saturating_sub(1);
1586
1587 if !self.flushing_effects && self.pending_flushes == 0 {
1588 self.flushing_effects = true;
1589
1590 let mut refreshing = false;
1591 loop {
1592 if let Some(effect) = self.pending_effects.pop_front() {
1593 match effect {
1594 Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1595 Effect::ModelNotification { model_id } => {
1596 self.notify_model_observers(model_id)
1597 }
1598 Effect::ViewNotification { window_id, view_id } => {
1599 self.notify_view_observers(window_id, view_id)
1600 }
1601 Effect::Deferred(callback) => callback(self),
1602 Effect::Release { entity_id } => self.notify_release_observers(entity_id),
1603 Effect::Focus { window_id, view_id } => {
1604 self.focus(window_id, view_id);
1605 }
1606 Effect::ResizeWindow { window_id } => {
1607 if let Some(window) = self.cx.windows.get_mut(&window_id) {
1608 window
1609 .invalidation
1610 .get_or_insert(WindowInvalidation::default());
1611 }
1612 }
1613 Effect::RefreshWindows => {
1614 refreshing = true;
1615 }
1616 }
1617 self.pending_notifications.clear();
1618 self.remove_dropped_entities();
1619 } else {
1620 self.remove_dropped_entities();
1621 if refreshing {
1622 self.perform_window_refresh();
1623 } else {
1624 self.update_windows();
1625 }
1626
1627 if self.pending_effects.is_empty() {
1628 self.flushing_effects = false;
1629 self.pending_notifications.clear();
1630 break;
1631 } else {
1632 refreshing = false;
1633 }
1634 }
1635 }
1636 }
1637 }
1638
1639 fn update_windows(&mut self) {
1640 let mut invalidations = HashMap::new();
1641 for (window_id, window) in &mut self.cx.windows {
1642 if let Some(invalidation) = window.invalidation.take() {
1643 invalidations.insert(*window_id, invalidation);
1644 }
1645 }
1646
1647 for (window_id, invalidation) in invalidations {
1648 if let Some((presenter, mut window)) =
1649 self.presenters_and_platform_windows.remove(&window_id)
1650 {
1651 {
1652 let mut presenter = presenter.borrow_mut();
1653 presenter.invalidate(invalidation, self);
1654 let scene =
1655 presenter.build_scene(window.size(), window.scale_factor(), false, self);
1656 window.present_scene(scene);
1657 }
1658 self.presenters_and_platform_windows
1659 .insert(window_id, (presenter, window));
1660 }
1661 }
1662 }
1663
1664 fn resize_window(&mut self, window_id: usize) {
1665 self.pending_effects
1666 .push_back(Effect::ResizeWindow { window_id });
1667 }
1668
1669 pub fn refresh_windows(&mut self) {
1670 self.pending_effects.push_back(Effect::RefreshWindows);
1671 }
1672
1673 fn perform_window_refresh(&mut self) {
1674 let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1675 for (window_id, (presenter, window)) in &mut presenters {
1676 let invalidation = self
1677 .cx
1678 .windows
1679 .get_mut(&window_id)
1680 .unwrap()
1681 .invalidation
1682 .take();
1683 let mut presenter = presenter.borrow_mut();
1684 presenter.refresh(invalidation, self);
1685 let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
1686 window.present_scene(scene);
1687 }
1688 self.presenters_and_platform_windows = presenters;
1689 }
1690
1691 pub fn set_cursor_style(&mut self, style: CursorStyle) -> CursorStyleHandle {
1692 self.platform.set_cursor_style(style);
1693 let id = self.next_cursor_style_handle_id.fetch_add(1, SeqCst);
1694 CursorStyleHandle {
1695 id,
1696 next_cursor_style_handle_id: self.next_cursor_style_handle_id.clone(),
1697 platform: self.platform(),
1698 }
1699 }
1700
1701 fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1702 let callbacks = self.subscriptions.lock().remove(&entity_id);
1703 if let Some(callbacks) = callbacks {
1704 for (id, mut callback) in callbacks {
1705 let alive = callback(payload.as_ref(), self);
1706 if alive {
1707 self.subscriptions
1708 .lock()
1709 .entry(entity_id)
1710 .or_default()
1711 .insert(id, callback);
1712 }
1713 }
1714 }
1715 }
1716
1717 fn notify_model_observers(&mut self, observed_id: usize) {
1718 let callbacks = self.observations.lock().remove(&observed_id);
1719 if let Some(callbacks) = callbacks {
1720 if self.cx.models.contains_key(&observed_id) {
1721 for (id, mut callback) in callbacks {
1722 let alive = callback(self);
1723 if alive {
1724 self.observations
1725 .lock()
1726 .entry(observed_id)
1727 .or_default()
1728 .insert(id, callback);
1729 }
1730 }
1731 }
1732 }
1733 }
1734
1735 fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1736 if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1737 window
1738 .invalidation
1739 .get_or_insert_with(Default::default)
1740 .updated
1741 .insert(observed_view_id);
1742 }
1743
1744 let callbacks = self.observations.lock().remove(&observed_view_id);
1745 if let Some(callbacks) = callbacks {
1746 if self
1747 .cx
1748 .views
1749 .contains_key(&(observed_window_id, observed_view_id))
1750 {
1751 for (id, mut callback) in callbacks {
1752 let alive = callback(self);
1753 if alive {
1754 self.observations
1755 .lock()
1756 .entry(observed_view_id)
1757 .or_default()
1758 .insert(id, callback);
1759 }
1760 }
1761 }
1762 }
1763 }
1764
1765 fn notify_release_observers(&mut self, entity_id: usize) {
1766 let callbacks = self.release_observations.lock().remove(&entity_id);
1767 if let Some(callbacks) = callbacks {
1768 for (_, mut callback) in callbacks {
1769 callback(self);
1770 }
1771 }
1772 }
1773
1774 fn focus(&mut self, window_id: usize, focused_id: usize) {
1775 if self
1776 .cx
1777 .windows
1778 .get(&window_id)
1779 .map(|w| w.focused_view_id)
1780 .map_or(false, |cur_focused| cur_focused == focused_id)
1781 {
1782 return;
1783 }
1784
1785 self.update(|this| {
1786 let blurred_id = this.cx.windows.get_mut(&window_id).map(|window| {
1787 let blurred_id = window.focused_view_id;
1788 window.focused_view_id = focused_id;
1789 blurred_id
1790 });
1791
1792 if let Some(blurred_id) = blurred_id {
1793 if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
1794 blurred_view.on_blur(this, window_id, blurred_id);
1795 this.cx.views.insert((window_id, blurred_id), blurred_view);
1796 }
1797 }
1798
1799 if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
1800 focused_view.on_focus(this, window_id, focused_id);
1801 this.cx.views.insert((window_id, focused_id), focused_view);
1802 }
1803 })
1804 }
1805
1806 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1807 where
1808 F: FnOnce(AsyncAppContext) -> Fut,
1809 Fut: 'static + Future<Output = T>,
1810 T: 'static,
1811 {
1812 let future = f(self.to_async());
1813 let cx = self.to_async();
1814 self.foreground.spawn(async move {
1815 let result = future.await;
1816 cx.0.borrow_mut().flush_effects();
1817 result
1818 })
1819 }
1820
1821 pub fn to_async(&self) -> AsyncAppContext {
1822 AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1823 }
1824
1825 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1826 self.cx.platform.write_to_clipboard(item);
1827 }
1828
1829 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1830 self.cx.platform.read_from_clipboard()
1831 }
1832
1833 #[cfg(any(test, feature = "test-support"))]
1834 pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
1835 self.cx.ref_counts.lock().leak_detector.clone()
1836 }
1837}
1838
1839impl ReadModel for MutableAppContext {
1840 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1841 if let Some(model) = self.cx.models.get(&handle.model_id) {
1842 model
1843 .as_any()
1844 .downcast_ref()
1845 .expect("downcast is type safe")
1846 } else {
1847 panic!("circular model reference");
1848 }
1849 }
1850}
1851
1852impl UpdateModel for MutableAppContext {
1853 fn update_model<T: Entity, V>(
1854 &mut self,
1855 handle: &ModelHandle<T>,
1856 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
1857 ) -> V {
1858 if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1859 self.update(|this| {
1860 let mut cx = ModelContext::new(this, handle.model_id);
1861 let result = update(
1862 model
1863 .as_any_mut()
1864 .downcast_mut()
1865 .expect("downcast is type safe"),
1866 &mut cx,
1867 );
1868 this.cx.models.insert(handle.model_id, model);
1869 result
1870 })
1871 } else {
1872 panic!("circular model update");
1873 }
1874 }
1875}
1876
1877impl UpgradeModelHandle for MutableAppContext {
1878 fn upgrade_model_handle<T: Entity>(
1879 &self,
1880 handle: &WeakModelHandle<T>,
1881 ) -> Option<ModelHandle<T>> {
1882 self.cx.upgrade_model_handle(handle)
1883 }
1884
1885 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
1886 self.cx.model_handle_is_upgradable(handle)
1887 }
1888
1889 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
1890 self.cx.upgrade_any_model_handle(handle)
1891 }
1892}
1893
1894impl UpgradeViewHandle for MutableAppContext {
1895 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1896 self.cx.upgrade_view_handle(handle)
1897 }
1898}
1899
1900impl ReadView for MutableAppContext {
1901 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1902 if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1903 view.as_any().downcast_ref().expect("downcast is type safe")
1904 } else {
1905 panic!("circular view reference");
1906 }
1907 }
1908}
1909
1910impl UpdateView for MutableAppContext {
1911 fn update_view<T, S>(
1912 &mut self,
1913 handle: &ViewHandle<T>,
1914 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
1915 ) -> S
1916 where
1917 T: View,
1918 {
1919 self.update(|this| {
1920 let mut view = this
1921 .cx
1922 .views
1923 .remove(&(handle.window_id, handle.view_id))
1924 .expect("circular view update");
1925
1926 let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
1927 let result = update(
1928 view.as_any_mut()
1929 .downcast_mut()
1930 .expect("downcast is type safe"),
1931 &mut cx,
1932 );
1933 this.cx
1934 .views
1935 .insert((handle.window_id, handle.view_id), view);
1936 result
1937 })
1938 }
1939}
1940
1941impl AsRef<AppContext> for MutableAppContext {
1942 fn as_ref(&self) -> &AppContext {
1943 &self.cx
1944 }
1945}
1946
1947impl Deref for MutableAppContext {
1948 type Target = AppContext;
1949
1950 fn deref(&self) -> &Self::Target {
1951 &self.cx
1952 }
1953}
1954
1955pub struct AppContext {
1956 models: HashMap<usize, Box<dyn AnyModel>>,
1957 views: HashMap<(usize, usize), Box<dyn AnyView>>,
1958 windows: HashMap<usize, Window>,
1959 app_states: HashMap<TypeId, Box<dyn Any>>,
1960 element_states: HashMap<ElementStateId, Box<dyn Any>>,
1961 background: Arc<executor::Background>,
1962 ref_counts: Arc<Mutex<RefCounts>>,
1963 font_cache: Arc<FontCache>,
1964 platform: Arc<dyn Platform>,
1965}
1966
1967impl AppContext {
1968 pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1969 self.windows
1970 .get(&window_id)
1971 .map(|window| window.root_view.id())
1972 }
1973
1974 pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1975 self.windows
1976 .get(&window_id)
1977 .map(|window| window.focused_view_id)
1978 }
1979
1980 pub fn background(&self) -> &Arc<executor::Background> {
1981 &self.background
1982 }
1983
1984 pub fn font_cache(&self) -> &Arc<FontCache> {
1985 &self.font_cache
1986 }
1987
1988 pub fn platform(&self) -> &Arc<dyn Platform> {
1989 &self.platform
1990 }
1991
1992 pub fn app_state<T: 'static>(&self) -> &T {
1993 self.app_states
1994 .get(&TypeId::of::<T>())
1995 .expect("no app state has been added for this type")
1996 .downcast_ref()
1997 .unwrap()
1998 }
1999}
2000
2001impl ReadModel for AppContext {
2002 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2003 if let Some(model) = self.models.get(&handle.model_id) {
2004 model
2005 .as_any()
2006 .downcast_ref()
2007 .expect("downcast should be type safe")
2008 } else {
2009 panic!("circular model reference");
2010 }
2011 }
2012}
2013
2014impl UpgradeModelHandle for AppContext {
2015 fn upgrade_model_handle<T: Entity>(
2016 &self,
2017 handle: &WeakModelHandle<T>,
2018 ) -> Option<ModelHandle<T>> {
2019 if self.models.contains_key(&handle.model_id) {
2020 Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2021 } else {
2022 None
2023 }
2024 }
2025
2026 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2027 self.models.contains_key(&handle.model_id)
2028 }
2029
2030 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2031 if self.models.contains_key(&handle.model_id) {
2032 Some(AnyModelHandle::new(
2033 handle.model_id,
2034 handle.model_type,
2035 self.ref_counts.clone(),
2036 ))
2037 } else {
2038 None
2039 }
2040 }
2041}
2042
2043impl UpgradeViewHandle for AppContext {
2044 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2045 if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2046 Some(ViewHandle::new(
2047 handle.window_id,
2048 handle.view_id,
2049 &self.ref_counts,
2050 ))
2051 } else {
2052 None
2053 }
2054 }
2055}
2056
2057impl ReadView for AppContext {
2058 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2059 if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2060 view.as_any()
2061 .downcast_ref()
2062 .expect("downcast should be type safe")
2063 } else {
2064 panic!("circular view reference");
2065 }
2066 }
2067}
2068
2069struct Window {
2070 root_view: AnyViewHandle,
2071 focused_view_id: usize,
2072 invalidation: Option<WindowInvalidation>,
2073}
2074
2075#[derive(Default, Clone)]
2076pub struct WindowInvalidation {
2077 pub updated: HashSet<usize>,
2078 pub removed: Vec<usize>,
2079}
2080
2081pub enum Effect {
2082 Event {
2083 entity_id: usize,
2084 payload: Box<dyn Any>,
2085 },
2086 ModelNotification {
2087 model_id: usize,
2088 },
2089 ViewNotification {
2090 window_id: usize,
2091 view_id: usize,
2092 },
2093 Deferred(Box<dyn FnOnce(&mut MutableAppContext)>),
2094 Release {
2095 entity_id: usize,
2096 },
2097 Focus {
2098 window_id: usize,
2099 view_id: usize,
2100 },
2101 ResizeWindow {
2102 window_id: usize,
2103 },
2104 RefreshWindows,
2105}
2106
2107impl Debug for Effect {
2108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2109 match self {
2110 Effect::Event { entity_id, .. } => f
2111 .debug_struct("Effect::Event")
2112 .field("entity_id", entity_id)
2113 .finish(),
2114 Effect::ModelNotification { model_id } => f
2115 .debug_struct("Effect::ModelNotification")
2116 .field("model_id", model_id)
2117 .finish(),
2118 Effect::ViewNotification { window_id, view_id } => f
2119 .debug_struct("Effect::ViewNotification")
2120 .field("window_id", window_id)
2121 .field("view_id", view_id)
2122 .finish(),
2123 Effect::Deferred(_) => f.debug_struct("Effect::Deferred").finish(),
2124 Effect::Release { entity_id } => f
2125 .debug_struct("Effect::Release")
2126 .field("entity_id", entity_id)
2127 .finish(),
2128 Effect::Focus { window_id, view_id } => f
2129 .debug_struct("Effect::Focus")
2130 .field("window_id", window_id)
2131 .field("view_id", view_id)
2132 .finish(),
2133 Effect::ResizeWindow { window_id } => f
2134 .debug_struct("Effect::RefreshWindow")
2135 .field("window_id", window_id)
2136 .finish(),
2137 Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2138 }
2139 }
2140}
2141
2142pub trait AnyModel {
2143 fn as_any(&self) -> &dyn Any;
2144 fn as_any_mut(&mut self) -> &mut dyn Any;
2145 fn release(&mut self, cx: &mut MutableAppContext);
2146 fn app_will_quit(
2147 &mut self,
2148 cx: &mut MutableAppContext,
2149 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2150}
2151
2152impl<T> AnyModel for T
2153where
2154 T: Entity,
2155{
2156 fn as_any(&self) -> &dyn Any {
2157 self
2158 }
2159
2160 fn as_any_mut(&mut self) -> &mut dyn Any {
2161 self
2162 }
2163
2164 fn release(&mut self, cx: &mut MutableAppContext) {
2165 self.release(cx);
2166 }
2167
2168 fn app_will_quit(
2169 &mut self,
2170 cx: &mut MutableAppContext,
2171 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2172 self.app_will_quit(cx)
2173 }
2174}
2175
2176pub trait AnyView {
2177 fn as_any(&self) -> &dyn Any;
2178 fn as_any_mut(&mut self) -> &mut dyn Any;
2179 fn release(&mut self, cx: &mut MutableAppContext);
2180 fn app_will_quit(
2181 &mut self,
2182 cx: &mut MutableAppContext,
2183 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2184 fn ui_name(&self) -> &'static str;
2185 fn render<'a>(
2186 &mut self,
2187 window_id: usize,
2188 view_id: usize,
2189 titlebar_height: f32,
2190 refreshing: bool,
2191 cx: &mut MutableAppContext,
2192 ) -> ElementBox;
2193 fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2194 fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2195 fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2196}
2197
2198impl<T> AnyView for T
2199where
2200 T: View,
2201{
2202 fn as_any(&self) -> &dyn Any {
2203 self
2204 }
2205
2206 fn as_any_mut(&mut self) -> &mut dyn Any {
2207 self
2208 }
2209
2210 fn release(&mut self, cx: &mut MutableAppContext) {
2211 self.release(cx);
2212 }
2213
2214 fn app_will_quit(
2215 &mut self,
2216 cx: &mut MutableAppContext,
2217 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2218 self.app_will_quit(cx)
2219 }
2220
2221 fn ui_name(&self) -> &'static str {
2222 T::ui_name()
2223 }
2224
2225 fn render<'a>(
2226 &mut self,
2227 window_id: usize,
2228 view_id: usize,
2229 titlebar_height: f32,
2230 refreshing: bool,
2231 cx: &mut MutableAppContext,
2232 ) -> ElementBox {
2233 View::render(
2234 self,
2235 &mut RenderContext {
2236 window_id,
2237 view_id,
2238 app: cx,
2239 view_type: PhantomData::<T>,
2240 titlebar_height,
2241 refreshing,
2242 },
2243 )
2244 }
2245
2246 fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2247 let mut cx = ViewContext::new(cx, window_id, view_id);
2248 View::on_focus(self, &mut cx);
2249 }
2250
2251 fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2252 let mut cx = ViewContext::new(cx, window_id, view_id);
2253 View::on_blur(self, &mut cx);
2254 }
2255
2256 fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2257 View::keymap_context(self, cx)
2258 }
2259}
2260
2261pub struct ModelContext<'a, T: ?Sized> {
2262 app: &'a mut MutableAppContext,
2263 model_id: usize,
2264 model_type: PhantomData<T>,
2265 halt_stream: bool,
2266}
2267
2268impl<'a, T: Entity> ModelContext<'a, T> {
2269 fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2270 Self {
2271 app,
2272 model_id,
2273 model_type: PhantomData,
2274 halt_stream: false,
2275 }
2276 }
2277
2278 pub fn background(&self) -> &Arc<executor::Background> {
2279 &self.app.cx.background
2280 }
2281
2282 pub fn halt_stream(&mut self) {
2283 self.halt_stream = true;
2284 }
2285
2286 pub fn model_id(&self) -> usize {
2287 self.model_id
2288 }
2289
2290 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2291 where
2292 S: Entity,
2293 F: FnOnce(&mut ModelContext<S>) -> S,
2294 {
2295 self.app.add_model(build_model)
2296 }
2297
2298 pub fn emit(&mut self, payload: T::Event) {
2299 self.app.pending_effects.push_back(Effect::Event {
2300 entity_id: self.model_id,
2301 payload: Box::new(payload),
2302 });
2303 }
2304
2305 pub fn notify(&mut self) {
2306 self.app.notify_model(self.model_id);
2307 }
2308
2309 pub fn subscribe<S: Entity, F>(
2310 &mut self,
2311 handle: &ModelHandle<S>,
2312 mut callback: F,
2313 ) -> Subscription
2314 where
2315 S::Event: 'static,
2316 F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2317 {
2318 let subscriber = self.weak_handle();
2319 self.app
2320 .subscribe_internal(handle, move |emitter, event, cx| {
2321 if let Some(subscriber) = subscriber.upgrade(cx) {
2322 subscriber.update(cx, |subscriber, cx| {
2323 callback(subscriber, emitter, event, cx);
2324 });
2325 true
2326 } else {
2327 false
2328 }
2329 })
2330 }
2331
2332 pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2333 where
2334 S: Entity,
2335 F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2336 {
2337 let observer = self.weak_handle();
2338 self.app.observe_internal(handle, move |observed, cx| {
2339 if let Some(observer) = observer.upgrade(cx) {
2340 observer.update(cx, |observer, cx| {
2341 callback(observer, observed, cx);
2342 });
2343 true
2344 } else {
2345 false
2346 }
2347 })
2348 }
2349
2350 pub fn observe_release<S, F>(
2351 &mut self,
2352 handle: &ModelHandle<S>,
2353 mut callback: F,
2354 ) -> Subscription
2355 where
2356 S: Entity,
2357 F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2358 {
2359 let observer = self.weak_handle();
2360 self.app.observe_release(handle, move |cx| {
2361 if let Some(observer) = observer.upgrade(cx) {
2362 observer.update(cx, |observer, cx| {
2363 callback(observer, cx);
2364 });
2365 }
2366 })
2367 }
2368
2369 pub fn handle(&self) -> ModelHandle<T> {
2370 ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2371 }
2372
2373 pub fn weak_handle(&self) -> WeakModelHandle<T> {
2374 WeakModelHandle::new(self.model_id)
2375 }
2376
2377 pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2378 where
2379 F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2380 Fut: 'static + Future<Output = S>,
2381 S: 'static,
2382 {
2383 let handle = self.handle();
2384 self.app.spawn(|cx| f(handle, cx))
2385 }
2386
2387 pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2388 where
2389 F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2390 Fut: 'static + Future<Output = S>,
2391 S: 'static,
2392 {
2393 let handle = self.weak_handle();
2394 self.app.spawn(|cx| f(handle, cx))
2395 }
2396}
2397
2398impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2399 fn as_ref(&self) -> &AppContext {
2400 &self.app.cx
2401 }
2402}
2403
2404impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2405 fn as_mut(&mut self) -> &mut MutableAppContext {
2406 self.app
2407 }
2408}
2409
2410impl<M> ReadModel for ModelContext<'_, M> {
2411 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2412 self.app.read_model(handle)
2413 }
2414}
2415
2416impl<M> UpdateModel for ModelContext<'_, M> {
2417 fn update_model<T: Entity, V>(
2418 &mut self,
2419 handle: &ModelHandle<T>,
2420 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2421 ) -> V {
2422 self.app.update_model(handle, update)
2423 }
2424}
2425
2426impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2427 fn upgrade_model_handle<T: Entity>(
2428 &self,
2429 handle: &WeakModelHandle<T>,
2430 ) -> Option<ModelHandle<T>> {
2431 self.cx.upgrade_model_handle(handle)
2432 }
2433
2434 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2435 self.cx.model_handle_is_upgradable(handle)
2436 }
2437
2438 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2439 self.cx.upgrade_any_model_handle(handle)
2440 }
2441}
2442
2443impl<M> Deref for ModelContext<'_, M> {
2444 type Target = MutableAppContext;
2445
2446 fn deref(&self) -> &Self::Target {
2447 &self.app
2448 }
2449}
2450
2451impl<M> DerefMut for ModelContext<'_, M> {
2452 fn deref_mut(&mut self) -> &mut Self::Target {
2453 &mut self.app
2454 }
2455}
2456
2457pub struct ViewContext<'a, T: ?Sized> {
2458 app: &'a mut MutableAppContext,
2459 window_id: usize,
2460 view_id: usize,
2461 view_type: PhantomData<T>,
2462}
2463
2464impl<'a, T: View> ViewContext<'a, T> {
2465 fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2466 Self {
2467 app,
2468 window_id,
2469 view_id,
2470 view_type: PhantomData,
2471 }
2472 }
2473
2474 pub fn handle(&self) -> ViewHandle<T> {
2475 ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2476 }
2477
2478 pub fn weak_handle(&self) -> WeakViewHandle<T> {
2479 WeakViewHandle::new(self.window_id, self.view_id)
2480 }
2481
2482 pub fn window_id(&self) -> usize {
2483 self.window_id
2484 }
2485
2486 pub fn view_id(&self) -> usize {
2487 self.view_id
2488 }
2489
2490 pub fn foreground(&self) -> &Rc<executor::Foreground> {
2491 self.app.foreground()
2492 }
2493
2494 pub fn background_executor(&self) -> &Arc<executor::Background> {
2495 &self.app.cx.background
2496 }
2497
2498 pub fn platform(&self) -> Arc<dyn Platform> {
2499 self.app.platform()
2500 }
2501
2502 pub fn prompt(
2503 &self,
2504 level: PromptLevel,
2505 msg: &str,
2506 answers: &[&str],
2507 ) -> oneshot::Receiver<usize> {
2508 self.app.prompt(self.window_id, level, msg, answers)
2509 }
2510
2511 pub fn prompt_for_paths(
2512 &self,
2513 options: PathPromptOptions,
2514 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2515 self.app.prompt_for_paths(options)
2516 }
2517
2518 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2519 self.app.prompt_for_new_path(directory)
2520 }
2521
2522 pub fn debug_elements(&self) -> crate::json::Value {
2523 self.app.debug_elements(self.window_id).unwrap()
2524 }
2525
2526 pub fn focus<S>(&mut self, handle: S)
2527 where
2528 S: Into<AnyViewHandle>,
2529 {
2530 let handle = handle.into();
2531 self.app.pending_effects.push_back(Effect::Focus {
2532 window_id: handle.window_id,
2533 view_id: handle.view_id,
2534 });
2535 }
2536
2537 pub fn focus_self(&mut self) {
2538 self.app.pending_effects.push_back(Effect::Focus {
2539 window_id: self.window_id,
2540 view_id: self.view_id,
2541 });
2542 }
2543
2544 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2545 where
2546 S: Entity,
2547 F: FnOnce(&mut ModelContext<S>) -> S,
2548 {
2549 self.app.add_model(build_model)
2550 }
2551
2552 pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2553 where
2554 S: View,
2555 F: FnOnce(&mut ViewContext<S>) -> S,
2556 {
2557 self.app.add_view(self.window_id, build_view)
2558 }
2559
2560 pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2561 where
2562 S: View,
2563 F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2564 {
2565 self.app.add_option_view(self.window_id, build_view)
2566 }
2567
2568 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2569 where
2570 E: Entity,
2571 E::Event: 'static,
2572 H: Handle<E>,
2573 F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2574 {
2575 let subscriber = self.weak_handle();
2576 self.app
2577 .subscribe_internal(handle, move |emitter, event, cx| {
2578 if let Some(subscriber) = subscriber.upgrade(cx) {
2579 subscriber.update(cx, |subscriber, cx| {
2580 callback(subscriber, emitter, event, cx);
2581 });
2582 true
2583 } else {
2584 false
2585 }
2586 })
2587 }
2588
2589 pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2590 where
2591 E: Entity,
2592 H: Handle<E>,
2593 F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2594 {
2595 let observer = self.weak_handle();
2596 self.app.observe_internal(handle, move |observed, cx| {
2597 if let Some(observer) = observer.upgrade(cx) {
2598 observer.update(cx, |observer, cx| {
2599 callback(observer, observed, cx);
2600 });
2601 true
2602 } else {
2603 false
2604 }
2605 })
2606 }
2607
2608 pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2609 where
2610 E: Entity,
2611 H: Handle<E>,
2612 F: 'static + FnMut(&mut T, &mut ViewContext<T>),
2613 {
2614 let observer = self.weak_handle();
2615 self.app.observe_release(handle, move |cx| {
2616 if let Some(observer) = observer.upgrade(cx) {
2617 observer.update(cx, |observer, cx| {
2618 callback(observer, cx);
2619 });
2620 }
2621 })
2622 }
2623
2624 pub fn emit(&mut self, payload: T::Event) {
2625 self.app.pending_effects.push_back(Effect::Event {
2626 entity_id: self.view_id,
2627 payload: Box::new(payload),
2628 });
2629 }
2630
2631 pub fn notify(&mut self) {
2632 self.app.notify_view(self.window_id, self.view_id);
2633 }
2634
2635 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
2636 let handle = self.handle();
2637 self.app.defer(Box::new(move |cx| {
2638 handle.update(cx, |view, cx| {
2639 callback(view, cx);
2640 })
2641 }))
2642 }
2643
2644 pub fn propagate_action(&mut self) {
2645 self.app.halt_action_dispatch = false;
2646 }
2647
2648 pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2649 where
2650 F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2651 Fut: 'static + Future<Output = S>,
2652 S: 'static,
2653 {
2654 let handle = self.handle();
2655 self.app.spawn(|cx| f(handle, cx))
2656 }
2657
2658 pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2659 where
2660 F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2661 Fut: 'static + Future<Output = S>,
2662 S: 'static,
2663 {
2664 let handle = self.weak_handle();
2665 self.app.spawn(|cx| f(handle, cx))
2666 }
2667}
2668
2669pub struct RenderContext<'a, T: View> {
2670 pub app: &'a mut MutableAppContext,
2671 pub titlebar_height: f32,
2672 pub refreshing: bool,
2673 window_id: usize,
2674 view_id: usize,
2675 view_type: PhantomData<T>,
2676}
2677
2678impl<'a, T: View> RenderContext<'a, T> {
2679 pub fn handle(&self) -> WeakViewHandle<T> {
2680 WeakViewHandle::new(self.window_id, self.view_id)
2681 }
2682
2683 pub fn view_id(&self) -> usize {
2684 self.view_id
2685 }
2686}
2687
2688impl AsRef<AppContext> for &AppContext {
2689 fn as_ref(&self) -> &AppContext {
2690 self
2691 }
2692}
2693
2694impl<V: View> Deref for RenderContext<'_, V> {
2695 type Target = MutableAppContext;
2696
2697 fn deref(&self) -> &Self::Target {
2698 self.app
2699 }
2700}
2701
2702impl<V: View> DerefMut for RenderContext<'_, V> {
2703 fn deref_mut(&mut self) -> &mut Self::Target {
2704 self.app
2705 }
2706}
2707
2708impl<V: View> ReadModel for RenderContext<'_, V> {
2709 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2710 self.app.read_model(handle)
2711 }
2712}
2713
2714impl<V: View> UpdateModel for RenderContext<'_, V> {
2715 fn update_model<T: Entity, O>(
2716 &mut self,
2717 handle: &ModelHandle<T>,
2718 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2719 ) -> O {
2720 self.app.update_model(handle, update)
2721 }
2722}
2723
2724impl<V: View> ReadView for RenderContext<'_, V> {
2725 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2726 self.app.read_view(handle)
2727 }
2728}
2729
2730impl<V: View> ElementStateContext for RenderContext<'_, V> {
2731 fn current_view_id(&self) -> usize {
2732 self.view_id
2733 }
2734}
2735
2736impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2737 fn as_ref(&self) -> &AppContext {
2738 &self.app.cx
2739 }
2740}
2741
2742impl<M> Deref for ViewContext<'_, M> {
2743 type Target = MutableAppContext;
2744
2745 fn deref(&self) -> &Self::Target {
2746 &self.app
2747 }
2748}
2749
2750impl<M> DerefMut for ViewContext<'_, M> {
2751 fn deref_mut(&mut self) -> &mut Self::Target {
2752 &mut self.app
2753 }
2754}
2755
2756impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2757 fn as_mut(&mut self) -> &mut MutableAppContext {
2758 self.app
2759 }
2760}
2761
2762impl<V> ReadModel for ViewContext<'_, V> {
2763 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2764 self.app.read_model(handle)
2765 }
2766}
2767
2768impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2769 fn upgrade_model_handle<T: Entity>(
2770 &self,
2771 handle: &WeakModelHandle<T>,
2772 ) -> Option<ModelHandle<T>> {
2773 self.cx.upgrade_model_handle(handle)
2774 }
2775
2776 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2777 self.cx.model_handle_is_upgradable(handle)
2778 }
2779
2780 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2781 self.cx.upgrade_any_model_handle(handle)
2782 }
2783}
2784
2785impl<V> UpgradeViewHandle for ViewContext<'_, V> {
2786 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2787 self.cx.upgrade_view_handle(handle)
2788 }
2789}
2790
2791impl<V: View> UpdateModel for ViewContext<'_, V> {
2792 fn update_model<T: Entity, O>(
2793 &mut self,
2794 handle: &ModelHandle<T>,
2795 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2796 ) -> O {
2797 self.app.update_model(handle, update)
2798 }
2799}
2800
2801impl<V: View> ReadView for ViewContext<'_, V> {
2802 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2803 self.app.read_view(handle)
2804 }
2805}
2806
2807impl<V: View> UpdateView for ViewContext<'_, V> {
2808 fn update_view<T, S>(
2809 &mut self,
2810 handle: &ViewHandle<T>,
2811 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2812 ) -> S
2813 where
2814 T: View,
2815 {
2816 self.app.update_view(handle, update)
2817 }
2818}
2819
2820impl<V: View> ElementStateContext for ViewContext<'_, V> {
2821 fn current_view_id(&self) -> usize {
2822 self.view_id
2823 }
2824}
2825
2826pub trait Handle<T> {
2827 type Weak: 'static;
2828 fn id(&self) -> usize;
2829 fn location(&self) -> EntityLocation;
2830 fn downgrade(&self) -> Self::Weak;
2831 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2832 where
2833 Self: Sized;
2834}
2835
2836#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2837pub enum EntityLocation {
2838 Model(usize),
2839 View(usize, usize),
2840}
2841
2842pub struct ModelHandle<T: Entity> {
2843 model_id: usize,
2844 model_type: PhantomData<T>,
2845 ref_counts: Arc<Mutex<RefCounts>>,
2846
2847 #[cfg(any(test, feature = "test-support"))]
2848 handle_id: usize,
2849}
2850
2851impl<T: Entity> ModelHandle<T> {
2852 fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2853 ref_counts.lock().inc_model(model_id);
2854
2855 #[cfg(any(test, feature = "test-support"))]
2856 let handle_id = ref_counts
2857 .lock()
2858 .leak_detector
2859 .lock()
2860 .handle_created(Some(type_name::<T>()), model_id);
2861
2862 Self {
2863 model_id,
2864 model_type: PhantomData,
2865 ref_counts: ref_counts.clone(),
2866
2867 #[cfg(any(test, feature = "test-support"))]
2868 handle_id,
2869 }
2870 }
2871
2872 pub fn downgrade(&self) -> WeakModelHandle<T> {
2873 WeakModelHandle::new(self.model_id)
2874 }
2875
2876 pub fn id(&self) -> usize {
2877 self.model_id
2878 }
2879
2880 pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2881 cx.read_model(self)
2882 }
2883
2884 pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2885 where
2886 C: ReadModelWith,
2887 F: FnOnce(&T, &AppContext) -> S,
2888 {
2889 let mut read = Some(read);
2890 cx.read_model_with(self, &mut |model, cx| {
2891 let read = read.take().unwrap();
2892 read(model, cx)
2893 })
2894 }
2895
2896 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2897 where
2898 C: UpdateModel,
2899 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2900 {
2901 let mut update = Some(update);
2902 cx.update_model(self, &mut |model, cx| {
2903 let update = update.take().unwrap();
2904 update(model, cx)
2905 })
2906 }
2907
2908 #[cfg(any(test, feature = "test-support"))]
2909 pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2910 use postage::prelude::{Sink as _, Stream as _};
2911
2912 let (mut tx, mut rx) = postage::mpsc::channel(1);
2913 let mut cx = cx.cx.borrow_mut();
2914 let subscription = cx.observe(self, move |_, _| {
2915 tx.try_send(()).ok();
2916 });
2917
2918 let duration = if std::env::var("CI").is_ok() {
2919 Duration::from_secs(5)
2920 } else {
2921 Duration::from_secs(1)
2922 };
2923
2924 async move {
2925 let notification = crate::util::timeout(duration, rx.recv())
2926 .await
2927 .expect("next notification timed out");
2928 drop(subscription);
2929 notification.expect("model dropped while test was waiting for its next notification")
2930 }
2931 }
2932
2933 #[cfg(any(test, feature = "test-support"))]
2934 pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2935 where
2936 T::Event: Clone,
2937 {
2938 use postage::prelude::{Sink as _, Stream as _};
2939
2940 let (mut tx, mut rx) = postage::mpsc::channel(1);
2941 let mut cx = cx.cx.borrow_mut();
2942 let subscription = cx.subscribe(self, move |_, event, _| {
2943 tx.blocking_send(event.clone()).ok();
2944 });
2945
2946 let duration = if std::env::var("CI").is_ok() {
2947 Duration::from_secs(5)
2948 } else {
2949 Duration::from_secs(1)
2950 };
2951
2952 async move {
2953 let event = crate::util::timeout(duration, rx.recv())
2954 .await
2955 .expect("next event timed out");
2956 drop(subscription);
2957 event.expect("model dropped while test was waiting for its next event")
2958 }
2959 }
2960
2961 #[cfg(any(test, feature = "test-support"))]
2962 pub fn condition(
2963 &self,
2964 cx: &TestAppContext,
2965 mut predicate: impl FnMut(&T, &AppContext) -> bool,
2966 ) -> impl Future<Output = ()> {
2967 use postage::prelude::{Sink as _, Stream as _};
2968
2969 let (tx, mut rx) = postage::mpsc::channel(1024);
2970
2971 let mut cx = cx.cx.borrow_mut();
2972 let subscriptions = (
2973 cx.observe(self, {
2974 let mut tx = tx.clone();
2975 move |_, _| {
2976 tx.blocking_send(()).ok();
2977 }
2978 }),
2979 cx.subscribe(self, {
2980 let mut tx = tx.clone();
2981 move |_, _, _| {
2982 tx.blocking_send(()).ok();
2983 }
2984 }),
2985 );
2986
2987 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2988 let handle = self.downgrade();
2989 let duration = if std::env::var("CI").is_ok() {
2990 Duration::from_secs(5)
2991 } else {
2992 Duration::from_secs(1)
2993 };
2994
2995 async move {
2996 crate::util::timeout(duration, async move {
2997 loop {
2998 {
2999 let cx = cx.borrow();
3000 let cx = cx.as_ref();
3001 if predicate(
3002 handle
3003 .upgrade(cx)
3004 .expect("model dropped with pending condition")
3005 .read(cx),
3006 cx,
3007 ) {
3008 break;
3009 }
3010 }
3011
3012 cx.borrow().foreground().start_waiting();
3013 rx.recv()
3014 .await
3015 .expect("model dropped with pending condition");
3016 cx.borrow().foreground().finish_waiting();
3017 }
3018 })
3019 .await
3020 .expect("condition timed out");
3021 drop(subscriptions);
3022 }
3023 }
3024}
3025
3026impl<T: Entity> Clone for ModelHandle<T> {
3027 fn clone(&self) -> Self {
3028 Self::new(self.model_id, &self.ref_counts)
3029 }
3030}
3031
3032impl<T: Entity> PartialEq for ModelHandle<T> {
3033 fn eq(&self, other: &Self) -> bool {
3034 self.model_id == other.model_id
3035 }
3036}
3037
3038impl<T: Entity> Eq for ModelHandle<T> {}
3039
3040impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3041 fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3042 self.model_id == other.model_id
3043 }
3044}
3045
3046impl<T: Entity> Hash for ModelHandle<T> {
3047 fn hash<H: Hasher>(&self, state: &mut H) {
3048 self.model_id.hash(state);
3049 }
3050}
3051
3052impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3053 fn borrow(&self) -> &usize {
3054 &self.model_id
3055 }
3056}
3057
3058impl<T: Entity> Debug for ModelHandle<T> {
3059 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3060 f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3061 .field(&self.model_id)
3062 .finish()
3063 }
3064}
3065
3066unsafe impl<T: Entity> Send for ModelHandle<T> {}
3067unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3068
3069impl<T: Entity> Drop for ModelHandle<T> {
3070 fn drop(&mut self) {
3071 let mut ref_counts = self.ref_counts.lock();
3072 ref_counts.dec_model(self.model_id);
3073
3074 #[cfg(any(test, feature = "test-support"))]
3075 ref_counts
3076 .leak_detector
3077 .lock()
3078 .handle_dropped(self.model_id, self.handle_id);
3079 }
3080}
3081
3082impl<T: Entity> Handle<T> for ModelHandle<T> {
3083 type Weak = WeakModelHandle<T>;
3084
3085 fn id(&self) -> usize {
3086 self.model_id
3087 }
3088
3089 fn location(&self) -> EntityLocation {
3090 EntityLocation::Model(self.model_id)
3091 }
3092
3093 fn downgrade(&self) -> Self::Weak {
3094 self.downgrade()
3095 }
3096
3097 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3098 where
3099 Self: Sized,
3100 {
3101 weak.upgrade(cx)
3102 }
3103}
3104
3105pub struct WeakModelHandle<T> {
3106 model_id: usize,
3107 model_type: PhantomData<T>,
3108}
3109
3110unsafe impl<T> Send for WeakModelHandle<T> {}
3111unsafe impl<T> Sync for WeakModelHandle<T> {}
3112
3113impl<T: Entity> WeakModelHandle<T> {
3114 fn new(model_id: usize) -> Self {
3115 Self {
3116 model_id,
3117 model_type: PhantomData,
3118 }
3119 }
3120
3121 pub fn id(&self) -> usize {
3122 self.model_id
3123 }
3124
3125 pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3126 cx.model_handle_is_upgradable(self)
3127 }
3128
3129 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3130 cx.upgrade_model_handle(self)
3131 }
3132}
3133
3134impl<T> Hash for WeakModelHandle<T> {
3135 fn hash<H: Hasher>(&self, state: &mut H) {
3136 self.model_id.hash(state)
3137 }
3138}
3139
3140impl<T> PartialEq for WeakModelHandle<T> {
3141 fn eq(&self, other: &Self) -> bool {
3142 self.model_id == other.model_id
3143 }
3144}
3145
3146impl<T> Eq for WeakModelHandle<T> {}
3147
3148impl<T> Clone for WeakModelHandle<T> {
3149 fn clone(&self) -> Self {
3150 Self {
3151 model_id: self.model_id,
3152 model_type: PhantomData,
3153 }
3154 }
3155}
3156
3157impl<T> Copy for WeakModelHandle<T> {}
3158
3159pub struct ViewHandle<T> {
3160 window_id: usize,
3161 view_id: usize,
3162 view_type: PhantomData<T>,
3163 ref_counts: Arc<Mutex<RefCounts>>,
3164 #[cfg(any(test, feature = "test-support"))]
3165 handle_id: usize,
3166}
3167
3168impl<T: View> ViewHandle<T> {
3169 fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3170 ref_counts.lock().inc_view(window_id, view_id);
3171 #[cfg(any(test, feature = "test-support"))]
3172 let handle_id = ref_counts
3173 .lock()
3174 .leak_detector
3175 .lock()
3176 .handle_created(Some(type_name::<T>()), view_id);
3177
3178 Self {
3179 window_id,
3180 view_id,
3181 view_type: PhantomData,
3182 ref_counts: ref_counts.clone(),
3183
3184 #[cfg(any(test, feature = "test-support"))]
3185 handle_id,
3186 }
3187 }
3188
3189 pub fn downgrade(&self) -> WeakViewHandle<T> {
3190 WeakViewHandle::new(self.window_id, self.view_id)
3191 }
3192
3193 pub fn window_id(&self) -> usize {
3194 self.window_id
3195 }
3196
3197 pub fn id(&self) -> usize {
3198 self.view_id
3199 }
3200
3201 pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3202 cx.read_view(self)
3203 }
3204
3205 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3206 where
3207 C: ReadViewWith,
3208 F: FnOnce(&T, &AppContext) -> S,
3209 {
3210 let mut read = Some(read);
3211 cx.read_view_with(self, &mut |view, cx| {
3212 let read = read.take().unwrap();
3213 read(view, cx)
3214 })
3215 }
3216
3217 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3218 where
3219 C: UpdateView,
3220 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3221 {
3222 let mut update = Some(update);
3223 cx.update_view(self, &mut |view, cx| {
3224 let update = update.take().unwrap();
3225 update(view, cx)
3226 })
3227 }
3228
3229 pub fn defer<C, F>(&self, cx: &mut C, update: F)
3230 where
3231 C: AsMut<MutableAppContext>,
3232 F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3233 {
3234 let this = self.clone();
3235 cx.as_mut().defer(Box::new(move |cx| {
3236 this.update(cx, |view, cx| update(view, cx));
3237 }));
3238 }
3239
3240 pub fn is_focused(&self, cx: &AppContext) -> bool {
3241 cx.focused_view_id(self.window_id)
3242 .map_or(false, |focused_id| focused_id == self.view_id)
3243 }
3244
3245 #[cfg(any(test, feature = "test-support"))]
3246 pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3247 use postage::prelude::{Sink as _, Stream as _};
3248
3249 let (mut tx, mut rx) = postage::mpsc::channel(1);
3250 let mut cx = cx.cx.borrow_mut();
3251 let subscription = cx.observe(self, move |_, _| {
3252 tx.try_send(()).ok();
3253 });
3254
3255 let duration = if std::env::var("CI").is_ok() {
3256 Duration::from_secs(5)
3257 } else {
3258 Duration::from_secs(1)
3259 };
3260
3261 async move {
3262 let notification = crate::util::timeout(duration, rx.recv())
3263 .await
3264 .expect("next notification timed out");
3265 drop(subscription);
3266 notification.expect("model dropped while test was waiting for its next notification")
3267 }
3268 }
3269
3270 #[cfg(any(test, feature = "test-support"))]
3271 pub fn condition(
3272 &self,
3273 cx: &TestAppContext,
3274 mut predicate: impl FnMut(&T, &AppContext) -> bool,
3275 ) -> impl Future<Output = ()> {
3276 use postage::prelude::{Sink as _, Stream as _};
3277
3278 let (tx, mut rx) = postage::mpsc::channel(1024);
3279
3280 let mut cx = cx.cx.borrow_mut();
3281 let subscriptions = self.update(&mut *cx, |_, cx| {
3282 (
3283 cx.observe(self, {
3284 let mut tx = tx.clone();
3285 move |_, _, _| {
3286 tx.blocking_send(()).ok();
3287 }
3288 }),
3289 cx.subscribe(self, {
3290 let mut tx = tx.clone();
3291 move |_, _, _, _| {
3292 tx.blocking_send(()).ok();
3293 }
3294 }),
3295 )
3296 });
3297
3298 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3299 let handle = self.downgrade();
3300 let duration = if std::env::var("CI").is_ok() {
3301 Duration::from_secs(2)
3302 } else {
3303 Duration::from_millis(500)
3304 };
3305
3306 async move {
3307 crate::util::timeout(duration, async move {
3308 loop {
3309 {
3310 let cx = cx.borrow();
3311 let cx = cx.as_ref();
3312 if predicate(
3313 handle
3314 .upgrade(cx)
3315 .expect("view dropped with pending condition")
3316 .read(cx),
3317 cx,
3318 ) {
3319 break;
3320 }
3321 }
3322
3323 cx.borrow().foreground().start_waiting();
3324 rx.recv()
3325 .await
3326 .expect("view dropped with pending condition");
3327 cx.borrow().foreground().finish_waiting();
3328 }
3329 })
3330 .await
3331 .expect("condition timed out");
3332 drop(subscriptions);
3333 }
3334 }
3335}
3336
3337impl<T: View> Clone for ViewHandle<T> {
3338 fn clone(&self) -> Self {
3339 ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3340 }
3341}
3342
3343impl<T> PartialEq for ViewHandle<T> {
3344 fn eq(&self, other: &Self) -> bool {
3345 self.window_id == other.window_id && self.view_id == other.view_id
3346 }
3347}
3348
3349impl<T> Eq for ViewHandle<T> {}
3350
3351impl<T> Debug for ViewHandle<T> {
3352 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3353 f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3354 .field("window_id", &self.window_id)
3355 .field("view_id", &self.view_id)
3356 .finish()
3357 }
3358}
3359
3360impl<T> Drop for ViewHandle<T> {
3361 fn drop(&mut self) {
3362 self.ref_counts
3363 .lock()
3364 .dec_view(self.window_id, self.view_id);
3365 #[cfg(any(test, feature = "test-support"))]
3366 self.ref_counts
3367 .lock()
3368 .leak_detector
3369 .lock()
3370 .handle_dropped(self.view_id, self.handle_id);
3371 }
3372}
3373
3374impl<T: View> Handle<T> for ViewHandle<T> {
3375 type Weak = WeakViewHandle<T>;
3376
3377 fn id(&self) -> usize {
3378 self.view_id
3379 }
3380
3381 fn location(&self) -> EntityLocation {
3382 EntityLocation::View(self.window_id, self.view_id)
3383 }
3384
3385 fn downgrade(&self) -> Self::Weak {
3386 self.downgrade()
3387 }
3388
3389 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3390 where
3391 Self: Sized,
3392 {
3393 weak.upgrade(cx)
3394 }
3395}
3396
3397pub struct AnyViewHandle {
3398 window_id: usize,
3399 view_id: usize,
3400 view_type: TypeId,
3401 type_name: &'static str,
3402 ref_counts: Arc<Mutex<RefCounts>>,
3403 #[cfg(any(test, feature = "test-support"))]
3404 handle_id: usize,
3405}
3406
3407impl AnyViewHandle {
3408 fn new(
3409 window_id: usize,
3410 view_id: usize,
3411 view_type: TypeId,
3412 type_name: &'static str,
3413 ref_counts: Arc<Mutex<RefCounts>>,
3414 ) -> Self {
3415 ref_counts.lock().inc_view(window_id, view_id);
3416
3417 #[cfg(any(test, feature = "test-support"))]
3418 let handle_id = ref_counts
3419 .lock()
3420 .leak_detector
3421 .lock()
3422 .handle_created(Some(type_name), view_id);
3423
3424 Self {
3425 window_id,
3426 view_id,
3427 view_type,
3428 type_name,
3429 ref_counts,
3430 #[cfg(any(test, feature = "test-support"))]
3431 handle_id,
3432 }
3433 }
3434
3435 pub fn id(&self) -> usize {
3436 self.view_id
3437 }
3438
3439 pub fn is<T: 'static>(&self) -> bool {
3440 TypeId::of::<T>() == self.view_type
3441 }
3442
3443 pub fn is_focused(&self, cx: &AppContext) -> bool {
3444 cx.focused_view_id(self.window_id)
3445 .map_or(false, |focused_id| focused_id == self.view_id)
3446 }
3447
3448 pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3449 if self.is::<T>() {
3450 let result = Some(ViewHandle {
3451 window_id: self.window_id,
3452 view_id: self.view_id,
3453 ref_counts: self.ref_counts.clone(),
3454 view_type: PhantomData,
3455 #[cfg(any(test, feature = "test-support"))]
3456 handle_id: self.handle_id,
3457 });
3458 unsafe {
3459 Arc::decrement_strong_count(&self.ref_counts);
3460 }
3461 std::mem::forget(self);
3462 result
3463 } else {
3464 None
3465 }
3466 }
3467}
3468
3469impl Clone for AnyViewHandle {
3470 fn clone(&self) -> Self {
3471 Self::new(
3472 self.window_id,
3473 self.view_id,
3474 self.view_type,
3475 self.type_name,
3476 self.ref_counts.clone(),
3477 )
3478 }
3479}
3480
3481impl From<&AnyViewHandle> for AnyViewHandle {
3482 fn from(handle: &AnyViewHandle) -> Self {
3483 handle.clone()
3484 }
3485}
3486
3487impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3488 fn from(handle: &ViewHandle<T>) -> Self {
3489 Self::new(
3490 handle.window_id,
3491 handle.view_id,
3492 TypeId::of::<T>(),
3493 any::type_name::<T>(),
3494 handle.ref_counts.clone(),
3495 )
3496 }
3497}
3498
3499impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3500 fn from(handle: ViewHandle<T>) -> Self {
3501 let any_handle = AnyViewHandle {
3502 window_id: handle.window_id,
3503 view_id: handle.view_id,
3504 view_type: TypeId::of::<T>(),
3505 type_name: any::type_name::<T>(),
3506 ref_counts: handle.ref_counts.clone(),
3507 #[cfg(any(test, feature = "test-support"))]
3508 handle_id: handle.handle_id,
3509 };
3510 unsafe {
3511 Arc::decrement_strong_count(&handle.ref_counts);
3512 }
3513 std::mem::forget(handle);
3514 any_handle
3515 }
3516}
3517
3518impl Drop for AnyViewHandle {
3519 fn drop(&mut self) {
3520 self.ref_counts
3521 .lock()
3522 .dec_view(self.window_id, self.view_id);
3523 #[cfg(any(test, feature = "test-support"))]
3524 self.ref_counts
3525 .lock()
3526 .leak_detector
3527 .lock()
3528 .handle_dropped(self.view_id, self.handle_id);
3529 }
3530}
3531
3532pub struct AnyModelHandle {
3533 model_id: usize,
3534 model_type: TypeId,
3535 ref_counts: Arc<Mutex<RefCounts>>,
3536
3537 #[cfg(any(test, feature = "test-support"))]
3538 handle_id: usize,
3539}
3540
3541impl AnyModelHandle {
3542 fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3543 ref_counts.lock().inc_model(model_id);
3544
3545 #[cfg(any(test, feature = "test-support"))]
3546 let handle_id = ref_counts
3547 .lock()
3548 .leak_detector
3549 .lock()
3550 .handle_created(None, model_id);
3551
3552 Self {
3553 model_id,
3554 model_type,
3555 ref_counts,
3556
3557 #[cfg(any(test, feature = "test-support"))]
3558 handle_id,
3559 }
3560 }
3561
3562 pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3563 if self.is::<T>() {
3564 let result = Some(ModelHandle {
3565 model_id: self.model_id,
3566 model_type: PhantomData,
3567 ref_counts: self.ref_counts.clone(),
3568
3569 #[cfg(any(test, feature = "test-support"))]
3570 handle_id: self.handle_id,
3571 });
3572 unsafe {
3573 Arc::decrement_strong_count(&self.ref_counts);
3574 }
3575 std::mem::forget(self);
3576 result
3577 } else {
3578 None
3579 }
3580 }
3581
3582 pub fn downgrade(&self) -> AnyWeakModelHandle {
3583 AnyWeakModelHandle {
3584 model_id: self.model_id,
3585 model_type: self.model_type,
3586 }
3587 }
3588
3589 pub fn is<T: Entity>(&self) -> bool {
3590 self.model_type == TypeId::of::<T>()
3591 }
3592}
3593
3594impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3595 fn from(handle: ModelHandle<T>) -> Self {
3596 Self::new(
3597 handle.model_id,
3598 TypeId::of::<T>(),
3599 handle.ref_counts.clone(),
3600 )
3601 }
3602}
3603
3604impl Clone for AnyModelHandle {
3605 fn clone(&self) -> Self {
3606 Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3607 }
3608}
3609
3610impl Drop for AnyModelHandle {
3611 fn drop(&mut self) {
3612 let mut ref_counts = self.ref_counts.lock();
3613 ref_counts.dec_model(self.model_id);
3614
3615 #[cfg(any(test, feature = "test-support"))]
3616 ref_counts
3617 .leak_detector
3618 .lock()
3619 .handle_dropped(self.model_id, self.handle_id);
3620 }
3621}
3622
3623pub struct AnyWeakModelHandle {
3624 model_id: usize,
3625 model_type: TypeId,
3626}
3627
3628impl AnyWeakModelHandle {
3629 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
3630 cx.upgrade_any_model_handle(self)
3631 }
3632}
3633
3634impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
3635 fn from(handle: WeakModelHandle<T>) -> Self {
3636 AnyWeakModelHandle {
3637 model_id: handle.model_id,
3638 model_type: TypeId::of::<T>(),
3639 }
3640 }
3641}
3642
3643pub struct WeakViewHandle<T> {
3644 window_id: usize,
3645 view_id: usize,
3646 view_type: PhantomData<T>,
3647}
3648
3649impl<T: View> WeakViewHandle<T> {
3650 fn new(window_id: usize, view_id: usize) -> Self {
3651 Self {
3652 window_id,
3653 view_id,
3654 view_type: PhantomData,
3655 }
3656 }
3657
3658 pub fn id(&self) -> usize {
3659 self.view_id
3660 }
3661
3662 pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3663 cx.upgrade_view_handle(self)
3664 }
3665}
3666
3667impl<T> Clone for WeakViewHandle<T> {
3668 fn clone(&self) -> Self {
3669 Self {
3670 window_id: self.window_id,
3671 view_id: self.view_id,
3672 view_type: PhantomData,
3673 }
3674 }
3675}
3676
3677impl<T> PartialEq for WeakViewHandle<T> {
3678 fn eq(&self, other: &Self) -> bool {
3679 self.window_id == other.window_id && self.view_id == other.view_id
3680 }
3681}
3682
3683impl<T> Eq for WeakViewHandle<T> {}
3684
3685impl<T> Hash for WeakViewHandle<T> {
3686 fn hash<H: Hasher>(&self, state: &mut H) {
3687 self.window_id.hash(state);
3688 self.view_id.hash(state);
3689 }
3690}
3691
3692#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3693pub struct ElementStateId {
3694 view_id: usize,
3695 element_id: usize,
3696 tag: TypeId,
3697}
3698
3699pub struct ElementStateHandle<T> {
3700 value_type: PhantomData<T>,
3701 id: ElementStateId,
3702 ref_counts: Weak<Mutex<RefCounts>>,
3703}
3704
3705impl<T: 'static> ElementStateHandle<T> {
3706 fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3707 ref_counts.lock().inc_element_state(id, frame_id);
3708 Self {
3709 value_type: PhantomData,
3710 id,
3711 ref_counts: Arc::downgrade(ref_counts),
3712 }
3713 }
3714
3715 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3716 cx.element_states
3717 .get(&self.id)
3718 .unwrap()
3719 .downcast_ref()
3720 .unwrap()
3721 }
3722
3723 pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3724 where
3725 C: DerefMut<Target = MutableAppContext>,
3726 {
3727 let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
3728 let result = f(element_state.downcast_mut().unwrap(), cx);
3729 cx.deref_mut()
3730 .cx
3731 .element_states
3732 .insert(self.id, element_state);
3733 result
3734 }
3735}
3736
3737impl<T> Drop for ElementStateHandle<T> {
3738 fn drop(&mut self) {
3739 if let Some(ref_counts) = self.ref_counts.upgrade() {
3740 ref_counts.lock().dec_element_state(self.id);
3741 }
3742 }
3743}
3744
3745pub struct CursorStyleHandle {
3746 id: usize,
3747 next_cursor_style_handle_id: Arc<AtomicUsize>,
3748 platform: Arc<dyn Platform>,
3749}
3750
3751impl Drop for CursorStyleHandle {
3752 fn drop(&mut self) {
3753 if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3754 self.platform.set_cursor_style(CursorStyle::Arrow);
3755 }
3756 }
3757}
3758
3759#[must_use]
3760pub enum Subscription {
3761 Subscription {
3762 id: usize,
3763 entity_id: usize,
3764 subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3765 },
3766 Observation {
3767 id: usize,
3768 entity_id: usize,
3769 observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3770 },
3771 ReleaseObservation {
3772 id: usize,
3773 entity_id: usize,
3774 observations:
3775 Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3776 },
3777}
3778
3779impl Subscription {
3780 pub fn detach(&mut self) {
3781 match self {
3782 Subscription::Subscription { subscriptions, .. } => {
3783 subscriptions.take();
3784 }
3785 Subscription::Observation { observations, .. } => {
3786 observations.take();
3787 }
3788 Subscription::ReleaseObservation { observations, .. } => {
3789 observations.take();
3790 }
3791 }
3792 }
3793}
3794
3795impl Drop for Subscription {
3796 fn drop(&mut self) {
3797 match self {
3798 Subscription::Observation {
3799 id,
3800 entity_id,
3801 observations,
3802 } => {
3803 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3804 if let Some(observations) = observations.lock().get_mut(entity_id) {
3805 observations.remove(id);
3806 }
3807 }
3808 }
3809 Subscription::ReleaseObservation {
3810 id,
3811 entity_id,
3812 observations,
3813 } => {
3814 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3815 if let Some(observations) = observations.lock().get_mut(entity_id) {
3816 observations.remove(id);
3817 }
3818 }
3819 }
3820 Subscription::Subscription {
3821 id,
3822 entity_id,
3823 subscriptions,
3824 } => {
3825 if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3826 if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3827 subscriptions.remove(id);
3828 }
3829 }
3830 }
3831 }
3832 }
3833}
3834
3835lazy_static! {
3836 static ref LEAK_BACKTRACE: bool =
3837 std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
3838}
3839
3840#[cfg(any(test, feature = "test-support"))]
3841#[derive(Default)]
3842pub struct LeakDetector {
3843 next_handle_id: usize,
3844 handle_backtraces: HashMap<
3845 usize,
3846 (
3847 Option<&'static str>,
3848 HashMap<usize, Option<backtrace::Backtrace>>,
3849 ),
3850 >,
3851}
3852
3853#[cfg(any(test, feature = "test-support"))]
3854impl LeakDetector {
3855 fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
3856 let handle_id = post_inc(&mut self.next_handle_id);
3857 let entry = self.handle_backtraces.entry(entity_id).or_default();
3858 let backtrace = if *LEAK_BACKTRACE {
3859 Some(backtrace::Backtrace::new_unresolved())
3860 } else {
3861 None
3862 };
3863 if let Some(type_name) = type_name {
3864 entry.0.get_or_insert(type_name);
3865 }
3866 entry.1.insert(handle_id, backtrace);
3867 handle_id
3868 }
3869
3870 fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
3871 if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
3872 assert!(backtraces.remove(&handle_id).is_some());
3873 if backtraces.is_empty() {
3874 self.handle_backtraces.remove(&entity_id);
3875 }
3876 }
3877 }
3878
3879 pub fn detect(&mut self) {
3880 let mut found_leaks = false;
3881 for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
3882 eprintln!(
3883 "leaked {} handles to {:?} {}",
3884 backtraces.len(),
3885 type_name.unwrap_or("entity"),
3886 id
3887 );
3888 for trace in backtraces.values_mut() {
3889 if let Some(trace) = trace {
3890 trace.resolve();
3891 eprintln!("{:?}", crate::util::CwdBacktrace(trace));
3892 }
3893 }
3894 found_leaks = true;
3895 }
3896
3897 let hint = if *LEAK_BACKTRACE {
3898 ""
3899 } else {
3900 " – set LEAK_BACKTRACE=1 for more information"
3901 };
3902 assert!(!found_leaks, "detected leaked handles{}", hint);
3903 }
3904}
3905
3906#[derive(Default)]
3907struct RefCounts {
3908 entity_counts: HashMap<usize, usize>,
3909 element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
3910 dropped_models: HashSet<usize>,
3911 dropped_views: HashSet<(usize, usize)>,
3912 dropped_element_states: HashSet<ElementStateId>,
3913
3914 #[cfg(any(test, feature = "test-support"))]
3915 leak_detector: Arc<Mutex<LeakDetector>>,
3916}
3917
3918struct ElementStateRefCount {
3919 ref_count: usize,
3920 frame_id: usize,
3921}
3922
3923impl RefCounts {
3924 fn inc_model(&mut self, model_id: usize) {
3925 match self.entity_counts.entry(model_id) {
3926 Entry::Occupied(mut entry) => {
3927 *entry.get_mut() += 1;
3928 }
3929 Entry::Vacant(entry) => {
3930 entry.insert(1);
3931 self.dropped_models.remove(&model_id);
3932 }
3933 }
3934 }
3935
3936 fn inc_view(&mut self, window_id: usize, view_id: usize) {
3937 match self.entity_counts.entry(view_id) {
3938 Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3939 Entry::Vacant(entry) => {
3940 entry.insert(1);
3941 self.dropped_views.remove(&(window_id, view_id));
3942 }
3943 }
3944 }
3945
3946 fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
3947 match self.element_state_counts.entry(id) {
3948 Entry::Occupied(mut entry) => {
3949 let entry = entry.get_mut();
3950 if entry.frame_id == frame_id || entry.ref_count >= 2 {
3951 panic!("used the same element state more than once in the same frame");
3952 }
3953 entry.ref_count += 1;
3954 entry.frame_id = frame_id;
3955 }
3956 Entry::Vacant(entry) => {
3957 entry.insert(ElementStateRefCount {
3958 ref_count: 1,
3959 frame_id,
3960 });
3961 self.dropped_element_states.remove(&id);
3962 }
3963 }
3964 }
3965
3966 fn dec_model(&mut self, model_id: usize) {
3967 let count = self.entity_counts.get_mut(&model_id).unwrap();
3968 *count -= 1;
3969 if *count == 0 {
3970 self.entity_counts.remove(&model_id);
3971 self.dropped_models.insert(model_id);
3972 }
3973 }
3974
3975 fn dec_view(&mut self, window_id: usize, view_id: usize) {
3976 let count = self.entity_counts.get_mut(&view_id).unwrap();
3977 *count -= 1;
3978 if *count == 0 {
3979 self.entity_counts.remove(&view_id);
3980 self.dropped_views.insert((window_id, view_id));
3981 }
3982 }
3983
3984 fn dec_element_state(&mut self, id: ElementStateId) {
3985 let entry = self.element_state_counts.get_mut(&id).unwrap();
3986 entry.ref_count -= 1;
3987 if entry.ref_count == 0 {
3988 self.element_state_counts.remove(&id);
3989 self.dropped_element_states.insert(id);
3990 }
3991 }
3992
3993 fn is_entity_alive(&self, entity_id: usize) -> bool {
3994 self.entity_counts.contains_key(&entity_id)
3995 }
3996
3997 fn take_dropped(
3998 &mut self,
3999 ) -> (
4000 HashSet<usize>,
4001 HashSet<(usize, usize)>,
4002 HashSet<ElementStateId>,
4003 ) {
4004 (
4005 std::mem::take(&mut self.dropped_models),
4006 std::mem::take(&mut self.dropped_views),
4007 std::mem::take(&mut self.dropped_element_states),
4008 )
4009 }
4010}
4011
4012#[cfg(test)]
4013mod tests {
4014 use super::*;
4015 use crate::elements::*;
4016 use smol::future::poll_once;
4017 use std::{
4018 cell::Cell,
4019 sync::atomic::{AtomicUsize, Ordering::SeqCst},
4020 };
4021
4022 #[crate::test(self)]
4023 fn test_model_handles(cx: &mut MutableAppContext) {
4024 struct Model {
4025 other: Option<ModelHandle<Model>>,
4026 events: Vec<String>,
4027 }
4028
4029 impl Entity for Model {
4030 type Event = usize;
4031 }
4032
4033 impl Model {
4034 fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4035 if let Some(other) = other.as_ref() {
4036 cx.observe(other, |me, _, _| {
4037 me.events.push("notified".into());
4038 })
4039 .detach();
4040 cx.subscribe(other, |me, _, event, _| {
4041 me.events.push(format!("observed event {}", event));
4042 })
4043 .detach();
4044 }
4045
4046 Self {
4047 other,
4048 events: Vec::new(),
4049 }
4050 }
4051 }
4052
4053 let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4054 let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4055 assert_eq!(cx.cx.models.len(), 2);
4056
4057 handle_1.update(cx, |model, cx| {
4058 model.events.push("updated".into());
4059 cx.emit(1);
4060 cx.notify();
4061 cx.emit(2);
4062 });
4063 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4064 assert_eq!(
4065 handle_2.read(cx).events,
4066 vec![
4067 "observed event 1".to_string(),
4068 "notified".to_string(),
4069 "observed event 2".to_string(),
4070 ]
4071 );
4072
4073 handle_2.update(cx, |model, _| {
4074 drop(handle_1);
4075 model.other.take();
4076 });
4077
4078 assert_eq!(cx.cx.models.len(), 1);
4079 assert!(cx.subscriptions.lock().is_empty());
4080 assert!(cx.observations.lock().is_empty());
4081 }
4082
4083 #[crate::test(self)]
4084 fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
4085 #[derive(Default)]
4086 struct Model {
4087 events: Vec<usize>,
4088 }
4089
4090 impl Entity for Model {
4091 type Event = usize;
4092 }
4093
4094 let handle_1 = cx.add_model(|_| Model::default());
4095 let handle_2 = cx.add_model(|_| Model::default());
4096 handle_1.update(cx, |_, c| {
4097 c.subscribe(&handle_2, move |model: &mut Model, emitter, event, c| {
4098 model.events.push(*event);
4099
4100 c.subscribe(&emitter, |model, _, event, _| {
4101 model.events.push(*event * 2);
4102 })
4103 .detach();
4104 })
4105 .detach();
4106 });
4107
4108 handle_2.update(cx, |_, c| c.emit(7));
4109 assert_eq!(handle_1.read(cx).events, vec![7]);
4110
4111 handle_2.update(cx, |_, c| c.emit(5));
4112 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4113 }
4114
4115 #[crate::test(self)]
4116 fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4117 #[derive(Default)]
4118 struct Model {
4119 count: usize,
4120 events: Vec<usize>,
4121 }
4122
4123 impl Entity for Model {
4124 type Event = ();
4125 }
4126
4127 let handle_1 = cx.add_model(|_| Model::default());
4128 let handle_2 = cx.add_model(|_| Model::default());
4129
4130 handle_1.update(cx, |_, c| {
4131 c.observe(&handle_2, move |model, observed, c| {
4132 model.events.push(observed.read(c).count);
4133 c.observe(&observed, |model, observed, c| {
4134 model.events.push(observed.read(c).count * 2);
4135 })
4136 .detach();
4137 })
4138 .detach();
4139 });
4140
4141 handle_2.update(cx, |model, c| {
4142 model.count = 7;
4143 c.notify()
4144 });
4145 assert_eq!(handle_1.read(cx).events, vec![7]);
4146
4147 handle_2.update(cx, |model, c| {
4148 model.count = 5;
4149 c.notify()
4150 });
4151 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4152 }
4153
4154 #[crate::test(self)]
4155 fn test_view_handles(cx: &mut MutableAppContext) {
4156 struct View {
4157 other: Option<ViewHandle<View>>,
4158 events: Vec<String>,
4159 }
4160
4161 impl Entity for View {
4162 type Event = usize;
4163 }
4164
4165 impl super::View for View {
4166 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4167 Empty::new().boxed()
4168 }
4169
4170 fn ui_name() -> &'static str {
4171 "View"
4172 }
4173 }
4174
4175 impl View {
4176 fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4177 if let Some(other) = other.as_ref() {
4178 cx.subscribe(other, |me, _, event, _| {
4179 me.events.push(format!("observed event {}", event));
4180 })
4181 .detach();
4182 }
4183 Self {
4184 other,
4185 events: Vec::new(),
4186 }
4187 }
4188 }
4189
4190 let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4191 let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4192 let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4193 assert_eq!(cx.cx.views.len(), 3);
4194
4195 handle_1.update(cx, |view, cx| {
4196 view.events.push("updated".into());
4197 cx.emit(1);
4198 cx.emit(2);
4199 });
4200 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4201 assert_eq!(
4202 handle_2.read(cx).events,
4203 vec![
4204 "observed event 1".to_string(),
4205 "observed event 2".to_string(),
4206 ]
4207 );
4208
4209 handle_2.update(cx, |view, _| {
4210 drop(handle_1);
4211 view.other.take();
4212 });
4213
4214 assert_eq!(cx.cx.views.len(), 2);
4215 assert!(cx.subscriptions.lock().is_empty());
4216 assert!(cx.observations.lock().is_empty());
4217 }
4218
4219 #[crate::test(self)]
4220 fn test_add_window(cx: &mut MutableAppContext) {
4221 struct View {
4222 mouse_down_count: Arc<AtomicUsize>,
4223 }
4224
4225 impl Entity for View {
4226 type Event = ();
4227 }
4228
4229 impl super::View for View {
4230 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4231 let mouse_down_count = self.mouse_down_count.clone();
4232 EventHandler::new(Empty::new().boxed())
4233 .on_mouse_down(move |_| {
4234 mouse_down_count.fetch_add(1, SeqCst);
4235 true
4236 })
4237 .boxed()
4238 }
4239
4240 fn ui_name() -> &'static str {
4241 "View"
4242 }
4243 }
4244
4245 let mouse_down_count = Arc::new(AtomicUsize::new(0));
4246 let (window_id, _) = cx.add_window(Default::default(), |_| View {
4247 mouse_down_count: mouse_down_count.clone(),
4248 });
4249 let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
4250 // Ensure window's root element is in a valid lifecycle state.
4251 presenter.borrow_mut().dispatch_event(
4252 Event::LeftMouseDown {
4253 position: Default::default(),
4254 ctrl: false,
4255 alt: false,
4256 shift: false,
4257 cmd: false,
4258 click_count: 1,
4259 },
4260 cx,
4261 );
4262 assert_eq!(mouse_down_count.load(SeqCst), 1);
4263 }
4264
4265 #[crate::test(self)]
4266 fn test_entity_release_hooks(cx: &mut MutableAppContext) {
4267 struct Model {
4268 released: Rc<Cell<bool>>,
4269 }
4270
4271 struct View {
4272 released: Rc<Cell<bool>>,
4273 }
4274
4275 impl Entity for Model {
4276 type Event = ();
4277
4278 fn release(&mut self, _: &mut MutableAppContext) {
4279 self.released.set(true);
4280 }
4281 }
4282
4283 impl Entity for View {
4284 type Event = ();
4285
4286 fn release(&mut self, _: &mut MutableAppContext) {
4287 self.released.set(true);
4288 }
4289 }
4290
4291 impl super::View for View {
4292 fn ui_name() -> &'static str {
4293 "View"
4294 }
4295
4296 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4297 Empty::new().boxed()
4298 }
4299 }
4300
4301 let model_released = Rc::new(Cell::new(false));
4302 let model_release_observed = Rc::new(Cell::new(false));
4303 let view_released = Rc::new(Cell::new(false));
4304 let view_release_observed = Rc::new(Cell::new(false));
4305
4306 let model = cx.add_model(|_| Model {
4307 released: model_released.clone(),
4308 });
4309 let (window_id, view) = cx.add_window(Default::default(), |_| View {
4310 released: view_released.clone(),
4311 });
4312 assert!(!model_released.get());
4313 assert!(!view_released.get());
4314
4315 cx.observe_release(&model, {
4316 let model_release_observed = model_release_observed.clone();
4317 move |_| model_release_observed.set(true)
4318 })
4319 .detach();
4320 cx.observe_release(&view, {
4321 let view_release_observed = view_release_observed.clone();
4322 move |_| view_release_observed.set(true)
4323 })
4324 .detach();
4325
4326 cx.update(move |_| {
4327 drop(model);
4328 });
4329 assert!(model_released.get());
4330 assert!(model_release_observed.get());
4331
4332 drop(view);
4333 cx.remove_window(window_id);
4334 assert!(view_released.get());
4335 assert!(view_release_observed.get());
4336 }
4337
4338 #[crate::test(self)]
4339 fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
4340 #[derive(Default)]
4341 struct View {
4342 events: Vec<usize>,
4343 }
4344
4345 impl Entity for View {
4346 type Event = usize;
4347 }
4348
4349 impl super::View for View {
4350 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4351 Empty::new().boxed()
4352 }
4353
4354 fn ui_name() -> &'static str {
4355 "View"
4356 }
4357 }
4358
4359 struct Model;
4360
4361 impl Entity for Model {
4362 type Event = usize;
4363 }
4364
4365 let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
4366 let handle_2 = cx.add_view(window_id, |_| View::default());
4367 let handle_3 = cx.add_model(|_| Model);
4368
4369 handle_1.update(cx, |_, c| {
4370 c.subscribe(&handle_2, move |me, emitter, event, c| {
4371 me.events.push(*event);
4372
4373 c.subscribe(&emitter, |me, _, event, _| {
4374 me.events.push(*event * 2);
4375 })
4376 .detach();
4377 })
4378 .detach();
4379
4380 c.subscribe(&handle_3, |me, _, event, _| {
4381 me.events.push(*event);
4382 })
4383 .detach();
4384 });
4385
4386 handle_2.update(cx, |_, c| c.emit(7));
4387 assert_eq!(handle_1.read(cx).events, vec![7]);
4388
4389 handle_2.update(cx, |_, c| c.emit(5));
4390 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4391
4392 handle_3.update(cx, |_, c| c.emit(9));
4393 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4394 }
4395
4396 #[crate::test(self)]
4397 fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4398 struct View;
4399
4400 impl Entity for View {
4401 type Event = ();
4402 }
4403
4404 impl super::View for View {
4405 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4406 Empty::new().boxed()
4407 }
4408
4409 fn ui_name() -> &'static str {
4410 "View"
4411 }
4412 }
4413
4414 struct Model;
4415
4416 impl Entity for Model {
4417 type Event = ();
4418 }
4419
4420 let (window_id, _) = cx.add_window(Default::default(), |_| View);
4421 let observing_view = cx.add_view(window_id, |_| View);
4422 let emitting_view = cx.add_view(window_id, |_| View);
4423 let observing_model = cx.add_model(|_| Model);
4424 let observed_model = cx.add_model(|_| Model);
4425
4426 observing_view.update(cx, |_, cx| {
4427 cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4428 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4429 });
4430 observing_model.update(cx, |_, cx| {
4431 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4432 });
4433
4434 cx.update(|_| {
4435 drop(observing_view);
4436 drop(observing_model);
4437 });
4438
4439 emitting_view.update(cx, |_, cx| cx.emit(()));
4440 observed_model.update(cx, |_, cx| cx.emit(()));
4441 }
4442
4443 #[crate::test(self)]
4444 fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
4445 #[derive(Default)]
4446 struct View {
4447 events: Vec<usize>,
4448 }
4449
4450 impl Entity for View {
4451 type Event = usize;
4452 }
4453
4454 impl super::View for View {
4455 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4456 Empty::new().boxed()
4457 }
4458
4459 fn ui_name() -> &'static str {
4460 "View"
4461 }
4462 }
4463
4464 #[derive(Default)]
4465 struct Model {
4466 count: usize,
4467 }
4468
4469 impl Entity for Model {
4470 type Event = ();
4471 }
4472
4473 let (_, view) = cx.add_window(Default::default(), |_| View::default());
4474 let model = cx.add_model(|_| Model::default());
4475
4476 view.update(cx, |_, c| {
4477 c.observe(&model, |me, observed, c| {
4478 me.events.push(observed.read(c).count)
4479 })
4480 .detach();
4481 });
4482
4483 model.update(cx, |model, c| {
4484 model.count = 11;
4485 c.notify();
4486 });
4487 assert_eq!(view.read(cx).events, vec![11]);
4488 }
4489
4490 #[crate::test(self)]
4491 fn test_dropping_observers(cx: &mut MutableAppContext) {
4492 struct View;
4493
4494 impl Entity for View {
4495 type Event = ();
4496 }
4497
4498 impl super::View for View {
4499 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4500 Empty::new().boxed()
4501 }
4502
4503 fn ui_name() -> &'static str {
4504 "View"
4505 }
4506 }
4507
4508 struct Model;
4509
4510 impl Entity for Model {
4511 type Event = ();
4512 }
4513
4514 let (window_id, _) = cx.add_window(Default::default(), |_| View);
4515 let observing_view = cx.add_view(window_id, |_| View);
4516 let observing_model = cx.add_model(|_| Model);
4517 let observed_model = cx.add_model(|_| Model);
4518
4519 observing_view.update(cx, |_, cx| {
4520 cx.observe(&observed_model, |_, _, _| {}).detach();
4521 });
4522 observing_model.update(cx, |_, cx| {
4523 cx.observe(&observed_model, |_, _, _| {}).detach();
4524 });
4525
4526 cx.update(|_| {
4527 drop(observing_view);
4528 drop(observing_model);
4529 });
4530
4531 observed_model.update(cx, |_, cx| cx.notify());
4532 }
4533
4534 #[crate::test(self)]
4535 fn test_focus(cx: &mut MutableAppContext) {
4536 struct View {
4537 name: String,
4538 events: Arc<Mutex<Vec<String>>>,
4539 }
4540
4541 impl Entity for View {
4542 type Event = ();
4543 }
4544
4545 impl super::View for View {
4546 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4547 Empty::new().boxed()
4548 }
4549
4550 fn ui_name() -> &'static str {
4551 "View"
4552 }
4553
4554 fn on_focus(&mut self, _: &mut ViewContext<Self>) {
4555 self.events.lock().push(format!("{} focused", &self.name));
4556 }
4557
4558 fn on_blur(&mut self, _: &mut ViewContext<Self>) {
4559 self.events.lock().push(format!("{} blurred", &self.name));
4560 }
4561 }
4562
4563 let events: Arc<Mutex<Vec<String>>> = Default::default();
4564 let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
4565 events: events.clone(),
4566 name: "view 1".to_string(),
4567 });
4568 let view_2 = cx.add_view(window_id, |_| View {
4569 events: events.clone(),
4570 name: "view 2".to_string(),
4571 });
4572
4573 view_1.update(cx, |_, cx| cx.focus(&view_2));
4574 view_1.update(cx, |_, cx| cx.focus(&view_1));
4575 view_1.update(cx, |_, cx| cx.focus(&view_2));
4576 view_1.update(cx, |_, _| drop(view_2));
4577
4578 assert_eq!(
4579 *events.lock(),
4580 [
4581 "view 1 focused".to_string(),
4582 "view 1 blurred".to_string(),
4583 "view 2 focused".to_string(),
4584 "view 2 blurred".to_string(),
4585 "view 1 focused".to_string(),
4586 "view 1 blurred".to_string(),
4587 "view 2 focused".to_string(),
4588 "view 1 focused".to_string(),
4589 ],
4590 );
4591 }
4592
4593 #[crate::test(self)]
4594 fn test_dispatch_action(cx: &mut MutableAppContext) {
4595 struct ViewA {
4596 id: usize,
4597 }
4598
4599 impl Entity for ViewA {
4600 type Event = ();
4601 }
4602
4603 impl View for ViewA {
4604 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4605 Empty::new().boxed()
4606 }
4607
4608 fn ui_name() -> &'static str {
4609 "View"
4610 }
4611 }
4612
4613 struct ViewB {
4614 id: usize,
4615 }
4616
4617 impl Entity for ViewB {
4618 type Event = ();
4619 }
4620
4621 impl View for ViewB {
4622 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4623 Empty::new().boxed()
4624 }
4625
4626 fn ui_name() -> &'static str {
4627 "View"
4628 }
4629 }
4630
4631 action!(Action, &'static str);
4632
4633 let actions = Rc::new(RefCell::new(Vec::new()));
4634
4635 {
4636 let actions = actions.clone();
4637 cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4638 actions.borrow_mut().push("global".to_string());
4639 });
4640 }
4641
4642 {
4643 let actions = actions.clone();
4644 cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4645 assert_eq!(action.0, "bar");
4646 cx.propagate_action();
4647 actions.borrow_mut().push(format!("{} a", view.id));
4648 });
4649 }
4650
4651 {
4652 let actions = actions.clone();
4653 cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4654 if view.id != 1 {
4655 cx.add_view(|cx| {
4656 cx.propagate_action(); // Still works on a nested ViewContext
4657 ViewB { id: 5 }
4658 });
4659 }
4660 actions.borrow_mut().push(format!("{} b", view.id));
4661 });
4662 }
4663
4664 {
4665 let actions = actions.clone();
4666 cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4667 cx.propagate_action();
4668 actions.borrow_mut().push(format!("{} c", view.id));
4669 });
4670 }
4671
4672 {
4673 let actions = actions.clone();
4674 cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4675 cx.propagate_action();
4676 actions.borrow_mut().push(format!("{} d", view.id));
4677 });
4678 }
4679
4680 {
4681 let actions = actions.clone();
4682 cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
4683 cx.propagate_action();
4684 actions.borrow_mut().push(format!("{} capture", view.id));
4685 });
4686 }
4687
4688 let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4689 let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4690 let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4691 let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4692
4693 cx.dispatch_action(
4694 window_id,
4695 vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4696 &Action("bar"),
4697 );
4698
4699 assert_eq!(
4700 *actions.borrow(),
4701 vec![
4702 "1 capture",
4703 "3 capture",
4704 "4 d",
4705 "4 c",
4706 "3 b",
4707 "3 a",
4708 "2 d",
4709 "2 c",
4710 "1 b"
4711 ]
4712 );
4713
4714 // Remove view_1, which doesn't propagate the action
4715 actions.borrow_mut().clear();
4716 cx.dispatch_action(
4717 window_id,
4718 vec![view_2.id(), view_3.id(), view_4.id()],
4719 &Action("bar"),
4720 );
4721
4722 assert_eq!(
4723 *actions.borrow(),
4724 vec![
4725 "3 capture",
4726 "4 d",
4727 "4 c",
4728 "3 b",
4729 "3 a",
4730 "2 d",
4731 "2 c",
4732 "global"
4733 ]
4734 );
4735 }
4736
4737 #[crate::test(self)]
4738 fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4739 use std::cell::Cell;
4740
4741 action!(Action, &'static str);
4742
4743 struct View {
4744 id: usize,
4745 keymap_context: keymap::Context,
4746 }
4747
4748 impl Entity for View {
4749 type Event = ();
4750 }
4751
4752 impl super::View for View {
4753 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4754 Empty::new().boxed()
4755 }
4756
4757 fn ui_name() -> &'static str {
4758 "View"
4759 }
4760
4761 fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4762 self.keymap_context.clone()
4763 }
4764 }
4765
4766 impl View {
4767 fn new(id: usize) -> Self {
4768 View {
4769 id,
4770 keymap_context: keymap::Context::default(),
4771 }
4772 }
4773 }
4774
4775 let mut view_1 = View::new(1);
4776 let mut view_2 = View::new(2);
4777 let mut view_3 = View::new(3);
4778 view_1.keymap_context.set.insert("a".into());
4779 view_2.keymap_context.set.insert("a".into());
4780 view_2.keymap_context.set.insert("b".into());
4781 view_3.keymap_context.set.insert("a".into());
4782 view_3.keymap_context.set.insert("b".into());
4783 view_3.keymap_context.set.insert("c".into());
4784
4785 let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4786 let view_2 = cx.add_view(window_id, |_| view_2);
4787 let view_3 = cx.add_view(window_id, |_| view_3);
4788
4789 // This keymap's only binding dispatches an action on view 2 because that view will have
4790 // "a" and "b" in its context, but not "c".
4791 cx.add_bindings(vec![keymap::Binding::new(
4792 "a",
4793 Action("a"),
4794 Some("a && b && !c"),
4795 )]);
4796
4797 let handled_action = Rc::new(Cell::new(false));
4798 let handled_action_clone = handled_action.clone();
4799 cx.add_action(move |view: &mut View, action: &Action, _| {
4800 handled_action_clone.set(true);
4801 assert_eq!(view.id, 2);
4802 assert_eq!(action.0, "a");
4803 });
4804
4805 cx.dispatch_keystroke(
4806 window_id,
4807 vec![view_1.id(), view_2.id(), view_3.id()],
4808 &Keystroke::parse("a").unwrap(),
4809 )
4810 .unwrap();
4811
4812 assert!(handled_action.get());
4813 }
4814
4815 #[crate::test(self)]
4816 async fn test_model_condition(cx: &mut TestAppContext) {
4817 struct Counter(usize);
4818
4819 impl super::Entity for Counter {
4820 type Event = ();
4821 }
4822
4823 impl Counter {
4824 fn inc(&mut self, cx: &mut ModelContext<Self>) {
4825 self.0 += 1;
4826 cx.notify();
4827 }
4828 }
4829
4830 let model = cx.add_model(|_| Counter(0));
4831
4832 let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4833 let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4834 smol::pin!(condition1, condition2);
4835
4836 model.update(cx, |model, cx| model.inc(cx));
4837 assert_eq!(poll_once(&mut condition1).await, None);
4838 assert_eq!(poll_once(&mut condition2).await, None);
4839
4840 model.update(cx, |model, cx| model.inc(cx));
4841 assert_eq!(poll_once(&mut condition1).await, Some(()));
4842 assert_eq!(poll_once(&mut condition2).await, None);
4843
4844 model.update(cx, |model, cx| model.inc(cx));
4845 assert_eq!(poll_once(&mut condition2).await, Some(()));
4846
4847 model.update(cx, |_, cx| cx.notify());
4848 }
4849
4850 #[crate::test(self)]
4851 #[should_panic]
4852 async fn test_model_condition_timeout(cx: &mut TestAppContext) {
4853 struct Model;
4854
4855 impl super::Entity for Model {
4856 type Event = ();
4857 }
4858
4859 let model = cx.add_model(|_| Model);
4860 model.condition(&cx, |_, _| false).await;
4861 }
4862
4863 #[crate::test(self)]
4864 #[should_panic(expected = "model dropped with pending condition")]
4865 async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
4866 struct Model;
4867
4868 impl super::Entity for Model {
4869 type Event = ();
4870 }
4871
4872 let model = cx.add_model(|_| Model);
4873 let condition = model.condition(&cx, |_, _| false);
4874 cx.update(|_| drop(model));
4875 condition.await;
4876 }
4877
4878 #[crate::test(self)]
4879 async fn test_view_condition(cx: &mut TestAppContext) {
4880 struct Counter(usize);
4881
4882 impl super::Entity for Counter {
4883 type Event = ();
4884 }
4885
4886 impl super::View for Counter {
4887 fn ui_name() -> &'static str {
4888 "test view"
4889 }
4890
4891 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4892 Empty::new().boxed()
4893 }
4894 }
4895
4896 impl Counter {
4897 fn inc(&mut self, cx: &mut ViewContext<Self>) {
4898 self.0 += 1;
4899 cx.notify();
4900 }
4901 }
4902
4903 let (_, view) = cx.add_window(|_| Counter(0));
4904
4905 let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4906 let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4907 smol::pin!(condition1, condition2);
4908
4909 view.update(cx, |view, cx| view.inc(cx));
4910 assert_eq!(poll_once(&mut condition1).await, None);
4911 assert_eq!(poll_once(&mut condition2).await, None);
4912
4913 view.update(cx, |view, cx| view.inc(cx));
4914 assert_eq!(poll_once(&mut condition1).await, Some(()));
4915 assert_eq!(poll_once(&mut condition2).await, None);
4916
4917 view.update(cx, |view, cx| view.inc(cx));
4918 assert_eq!(poll_once(&mut condition2).await, Some(()));
4919 view.update(cx, |_, cx| cx.notify());
4920 }
4921
4922 #[crate::test(self)]
4923 #[should_panic]
4924 async fn test_view_condition_timeout(cx: &mut TestAppContext) {
4925 struct View;
4926
4927 impl super::Entity for View {
4928 type Event = ();
4929 }
4930
4931 impl super::View for View {
4932 fn ui_name() -> &'static str {
4933 "test view"
4934 }
4935
4936 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4937 Empty::new().boxed()
4938 }
4939 }
4940
4941 let (_, view) = cx.add_window(|_| View);
4942 view.condition(&cx, |_, _| false).await;
4943 }
4944
4945 #[crate::test(self)]
4946 #[should_panic(expected = "view dropped with pending condition")]
4947 async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
4948 struct View;
4949
4950 impl super::Entity for View {
4951 type Event = ();
4952 }
4953
4954 impl super::View for View {
4955 fn ui_name() -> &'static str {
4956 "test view"
4957 }
4958
4959 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4960 Empty::new().boxed()
4961 }
4962 }
4963
4964 let window_id = cx.add_window(|_| View).0;
4965 let view = cx.add_view(window_id, |_| View);
4966
4967 let condition = view.condition(&cx, |_, _| false);
4968 cx.update(|_| drop(view));
4969 condition.await;
4970 }
4971}