1use crate::{
2 elements::ElementBox,
3 executor,
4 keymap::{self, Keystroke},
5 platform::{self, Platform, PromptLevel, WindowOptions},
6 presenter::Presenter,
7 util::{post_inc, timeout},
8 AssetCache, AssetSource, ClipboardItem, EventContext, FontCache, PathPromptOptions,
9 TextLayoutCache,
10};
11use anyhow::{anyhow, Result};
12use async_task::Task;
13use keymap::MatchResult;
14use parking_lot::{Mutex, RwLock};
15use platform::Event;
16use postage::{mpsc, sink::Sink as _, stream::Stream as _};
17use smol::prelude::*;
18use std::{
19 any::{type_name, Any, TypeId},
20 cell::RefCell,
21 collections::{hash_map::Entry, HashMap, HashSet, VecDeque},
22 fmt::{self, Debug},
23 hash::{Hash, Hasher},
24 marker::PhantomData,
25 ops::{Deref, DerefMut},
26 path::{Path, PathBuf},
27 rc::{self, Rc},
28 sync::{Arc, Weak},
29 time::Duration,
30};
31
32pub trait Entity: 'static {
33 type Event;
34
35 fn release(&mut self, _: &mut MutableAppContext) {}
36}
37
38pub trait View: Entity + Sized {
39 fn ui_name() -> &'static str;
40 fn render(&self, cx: &RenderContext<'_, Self>) -> ElementBox;
41 fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
42 fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
43 fn keymap_context(&self, _: &AppContext) -> keymap::Context {
44 Self::default_keymap_context()
45 }
46 fn default_keymap_context() -> keymap::Context {
47 let mut cx = keymap::Context::default();
48 cx.set.insert(Self::ui_name().into());
49 cx
50 }
51}
52
53pub trait ReadModel {
54 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
55}
56
57pub trait ReadModelWith {
58 fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
59 &self,
60 handle: &ModelHandle<E>,
61 read: F,
62 ) -> T;
63}
64
65pub trait UpdateModel {
66 fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
67 where
68 T: Entity,
69 F: FnOnce(&mut T, &mut ModelContext<T>) -> S;
70}
71
72pub trait UpgradeModelHandle {
73 fn upgrade_model_handle<T: Entity>(&self, handle: WeakModelHandle<T>)
74 -> Option<ModelHandle<T>>;
75}
76
77pub trait ReadView {
78 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
79}
80
81pub trait ReadViewWith {
82 fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
83 where
84 V: View,
85 F: FnOnce(&V, &AppContext) -> T;
86}
87
88pub trait UpdateView {
89 fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
90 where
91 T: View,
92 F: FnOnce(&mut T, &mut ViewContext<T>) -> S;
93}
94
95pub trait Action: 'static + AnyAction {
96 type Argument: 'static + Clone;
97}
98
99pub trait AnyAction {
100 fn id(&self) -> TypeId;
101 fn name(&self) -> &'static str;
102 fn as_any(&self) -> &dyn Any;
103 fn boxed_clone(&self) -> Box<dyn AnyAction>;
104 fn boxed_clone_as_any(&self) -> Box<dyn Any>;
105}
106
107#[macro_export]
108macro_rules! action {
109 ($name:ident, $arg:ty) => {
110 #[derive(Clone)]
111 pub struct $name(pub $arg);
112
113 impl $crate::Action for $name {
114 type Argument = $arg;
115 }
116
117 impl $crate::AnyAction for $name {
118 fn id(&self) -> std::any::TypeId {
119 std::any::TypeId::of::<$name>()
120 }
121
122 fn name(&self) -> &'static str {
123 stringify!($name)
124 }
125
126 fn as_any(&self) -> &dyn std::any::Any {
127 self
128 }
129
130 fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
131 Box::new(self.clone())
132 }
133
134 fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
135 Box::new(self.clone())
136 }
137 }
138 };
139
140 ($name:ident) => {
141 #[derive(Clone, Debug, Eq, PartialEq)]
142 pub struct $name;
143
144 impl $crate::Action for $name {
145 type Argument = ();
146 }
147
148 impl $crate::AnyAction for $name {
149 fn id(&self) -> std::any::TypeId {
150 std::any::TypeId::of::<$name>()
151 }
152
153 fn name(&self) -> &'static str {
154 stringify!($name)
155 }
156
157 fn as_any(&self) -> &dyn std::any::Any {
158 self
159 }
160
161 fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
162 Box::new(self.clone())
163 }
164
165 fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
166 Box::new(self.clone())
167 }
168 }
169 };
170}
171
172pub struct Menu<'a> {
173 pub name: &'a str,
174 pub items: Vec<MenuItem<'a>>,
175}
176
177pub enum MenuItem<'a> {
178 Action {
179 name: &'a str,
180 keystroke: Option<&'a str>,
181 action: Box<dyn AnyAction>,
182 },
183 Separator,
184}
185
186#[derive(Clone)]
187pub struct App(Rc<RefCell<MutableAppContext>>);
188
189#[derive(Clone)]
190pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
191
192pub struct BackgroundAppContext(*const RefCell<MutableAppContext>);
193
194#[derive(Clone)]
195pub struct TestAppContext {
196 cx: Rc<RefCell<MutableAppContext>>,
197 foreground_platform: Rc<platform::test::ForegroundPlatform>,
198}
199
200impl App {
201 pub fn new(asset_source: impl AssetSource) -> Result<Self> {
202 let platform = platform::current::platform();
203 let foreground_platform = platform::current::foreground_platform();
204 let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
205 let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
206 foreground,
207 Arc::new(executor::Background::new()),
208 platform.clone(),
209 foreground_platform.clone(),
210 Arc::new(FontCache::new(platform.fonts())),
211 asset_source,
212 ))));
213
214 let cx = app.0.clone();
215 foreground_platform.on_menu_command(Box::new(move |action| {
216 let mut cx = cx.borrow_mut();
217 if let Some(key_window_id) = cx.cx.platform.key_window_id() {
218 if let Some((presenter, _)) = cx.presenters_and_platform_windows.get(&key_window_id)
219 {
220 let presenter = presenter.clone();
221 let path = presenter.borrow().dispatch_path(cx.as_ref());
222 cx.dispatch_action_any(key_window_id, &path, action);
223 } else {
224 cx.dispatch_global_action_any(action);
225 }
226 } else {
227 cx.dispatch_global_action_any(action);
228 }
229 }));
230
231 app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
232 Ok(app)
233 }
234
235 pub fn on_become_active<F>(self, mut callback: F) -> Self
236 where
237 F: 'static + FnMut(&mut MutableAppContext),
238 {
239 let cx = self.0.clone();
240 self.0
241 .borrow_mut()
242 .foreground_platform
243 .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
244 self
245 }
246
247 pub fn on_resign_active<F>(self, mut callback: F) -> Self
248 where
249 F: 'static + FnMut(&mut MutableAppContext),
250 {
251 let cx = self.0.clone();
252 self.0
253 .borrow_mut()
254 .foreground_platform
255 .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
256 self
257 }
258
259 pub fn on_event<F>(self, mut callback: F) -> Self
260 where
261 F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
262 {
263 let cx = self.0.clone();
264 self.0
265 .borrow_mut()
266 .foreground_platform
267 .on_event(Box::new(move |event| {
268 callback(event, &mut *cx.borrow_mut())
269 }));
270 self
271 }
272
273 pub fn on_open_files<F>(self, mut callback: F) -> Self
274 where
275 F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
276 {
277 let cx = self.0.clone();
278 self.0
279 .borrow_mut()
280 .foreground_platform
281 .on_open_files(Box::new(move |paths| {
282 callback(paths, &mut *cx.borrow_mut())
283 }));
284 self
285 }
286
287 pub fn run<F>(self, on_finish_launching: F)
288 where
289 F: 'static + FnOnce(&mut MutableAppContext),
290 {
291 let platform = self.0.borrow().foreground_platform.clone();
292 platform.run(Box::new(move || {
293 let mut cx = self.0.borrow_mut();
294 on_finish_launching(&mut *cx);
295 }))
296 }
297
298 pub fn font_cache(&self) -> Arc<FontCache> {
299 self.0.borrow().cx.font_cache.clone()
300 }
301
302 fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
303 let mut state = self.0.borrow_mut();
304 state.pending_flushes += 1;
305 let result = callback(&mut *state);
306 state.flush_effects();
307 result
308 }
309}
310
311impl TestAppContext {
312 pub fn new(
313 foreground_platform: Rc<platform::test::ForegroundPlatform>,
314 platform: Arc<dyn Platform>,
315 foreground: Rc<executor::Foreground>,
316 background: Arc<executor::Background>,
317 font_cache: Arc<FontCache>,
318 first_entity_id: usize,
319 ) -> Self {
320 let mut cx = MutableAppContext::new(
321 foreground.clone(),
322 background,
323 platform,
324 foreground_platform.clone(),
325 font_cache,
326 (),
327 );
328 cx.next_entity_id = first_entity_id;
329 let cx = TestAppContext {
330 cx: Rc::new(RefCell::new(cx)),
331 foreground_platform,
332 };
333 cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
334 cx
335 }
336
337 pub fn dispatch_action<A: Action>(
338 &self,
339 window_id: usize,
340 responder_chain: Vec<usize>,
341 action: A,
342 ) {
343 self.cx
344 .borrow_mut()
345 .dispatch_action_any(window_id, &responder_chain, &action);
346 }
347
348 pub fn dispatch_global_action<A: Action>(&self, action: A) {
349 self.cx.borrow_mut().dispatch_global_action(action);
350 }
351
352 pub fn dispatch_keystroke(
353 &self,
354 window_id: usize,
355 responder_chain: Vec<usize>,
356 keystroke: &Keystroke,
357 ) -> Result<bool> {
358 let mut state = self.cx.borrow_mut();
359 state.dispatch_keystroke(window_id, responder_chain, keystroke)
360 }
361
362 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
363 where
364 T: Entity,
365 F: FnOnce(&mut ModelContext<T>) -> T,
366 {
367 let mut state = self.cx.borrow_mut();
368 state.pending_flushes += 1;
369 let handle = state.add_model(build_model);
370 state.flush_effects();
371 handle
372 }
373
374 pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
375 where
376 T: View,
377 F: FnOnce(&mut ViewContext<T>) -> T,
378 {
379 self.cx
380 .borrow_mut()
381 .add_window(Default::default(), build_root_view)
382 }
383
384 pub fn window_ids(&self) -> Vec<usize> {
385 self.cx.borrow().window_ids().collect()
386 }
387
388 pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
389 self.cx.borrow().root_view(window_id)
390 }
391
392 pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
393 where
394 T: View,
395 F: FnOnce(&mut ViewContext<T>) -> T,
396 {
397 let mut state = self.cx.borrow_mut();
398 state.pending_flushes += 1;
399 let handle = state.add_view(window_id, build_view);
400 state.flush_effects();
401 handle
402 }
403
404 pub fn add_option_view<T, F>(
405 &mut self,
406 window_id: usize,
407 build_view: F,
408 ) -> Option<ViewHandle<T>>
409 where
410 T: View,
411 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
412 {
413 let mut state = self.cx.borrow_mut();
414 state.pending_flushes += 1;
415 let handle = state.add_option_view(window_id, build_view);
416 state.flush_effects();
417 handle
418 }
419
420 pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
421 callback(self.cx.borrow().as_ref())
422 }
423
424 pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
425 let mut state = self.cx.borrow_mut();
426 // Don't increment pending flushes in order to effects to be flushed before the callback
427 // completes, which is helpful in tests.
428 let result = callback(&mut *state);
429 // Flush effects after the callback just in case there are any. This can happen in edge
430 // cases such as the closure dropping handles.
431 state.flush_effects();
432 result
433 }
434
435 pub fn to_async(&self) -> AsyncAppContext {
436 AsyncAppContext(self.cx.clone())
437 }
438
439 pub fn font_cache(&self) -> Arc<FontCache> {
440 self.cx.borrow().cx.font_cache.clone()
441 }
442
443 pub fn platform(&self) -> Arc<dyn platform::Platform> {
444 self.cx.borrow().cx.platform.clone()
445 }
446
447 pub fn foreground(&self) -> Rc<executor::Foreground> {
448 self.cx.borrow().foreground().clone()
449 }
450
451 pub fn background(&self) -> Arc<executor::Background> {
452 self.cx.borrow().background().clone()
453 }
454
455 pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
456 self.foreground_platform.simulate_new_path_selection(result);
457 }
458
459 pub fn did_prompt_for_new_path(&self) -> bool {
460 self.foreground_platform.as_ref().did_prompt_for_new_path()
461 }
462
463 pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
464 let mut state = self.cx.borrow_mut();
465 let (_, window) = state
466 .presenters_and_platform_windows
467 .get_mut(&window_id)
468 .unwrap();
469 let test_window = window
470 .as_any_mut()
471 .downcast_mut::<platform::test::Window>()
472 .unwrap();
473 let callback = test_window
474 .last_prompt
475 .take()
476 .expect("prompt was not called");
477 (callback)(answer);
478 }
479}
480
481impl AsyncAppContext {
482 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
483 where
484 F: FnOnce(AsyncAppContext) -> Fut,
485 Fut: 'static + Future<Output = T>,
486 T: 'static,
487 {
488 self.0.borrow().foreground.spawn(f(self.clone()))
489 }
490
491 pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
492 callback(self.0.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.0.borrow_mut();
497 state.pending_flushes += 1;
498 let result = callback(&mut *state);
499 state.flush_effects();
500 result
501 }
502
503 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
504 where
505 T: Entity,
506 F: FnOnce(&mut ModelContext<T>) -> T,
507 {
508 self.update(|cx| cx.add_model(build_model))
509 }
510
511 pub fn platform(&self) -> Arc<dyn Platform> {
512 self.0.borrow().platform()
513 }
514
515 pub fn foreground(&self) -> Rc<executor::Foreground> {
516 self.0.borrow().foreground.clone()
517 }
518
519 pub fn background(&self) -> Arc<executor::Background> {
520 self.0.borrow().cx.background.clone()
521 }
522}
523
524impl UpdateModel for AsyncAppContext {
525 fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
526 where
527 T: Entity,
528 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
529 {
530 let mut state = self.0.borrow_mut();
531 state.pending_flushes += 1;
532 let result = state.update_model(handle, update);
533 state.flush_effects();
534 result
535 }
536}
537
538impl UpgradeModelHandle for AsyncAppContext {
539 fn upgrade_model_handle<T: Entity>(
540 &self,
541 handle: WeakModelHandle<T>,
542 ) -> Option<ModelHandle<T>> {
543 self.0.borrow_mut().upgrade_model_handle(handle)
544 }
545}
546
547impl ReadModelWith for AsyncAppContext {
548 fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
549 &self,
550 handle: &ModelHandle<E>,
551 read: F,
552 ) -> T {
553 let cx = self.0.borrow();
554 let cx = cx.as_ref();
555 read(handle.read(cx), cx)
556 }
557}
558
559impl UpdateView for AsyncAppContext {
560 fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
561 where
562 T: View,
563 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
564 {
565 let mut state = self.0.borrow_mut();
566 state.pending_flushes += 1;
567 let result = state.update_view(handle, update);
568 state.flush_effects();
569 result
570 }
571}
572
573impl ReadViewWith for AsyncAppContext {
574 fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
575 where
576 V: View,
577 F: FnOnce(&V, &AppContext) -> T,
578 {
579 let cx = self.0.borrow();
580 let cx = cx.as_ref();
581 read(handle.read(cx), cx)
582 }
583}
584
585impl UpdateModel for TestAppContext {
586 fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
587 where
588 T: Entity,
589 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
590 {
591 let mut state = self.cx.borrow_mut();
592 state.pending_flushes += 1;
593 let result = state.update_model(handle, update);
594 state.flush_effects();
595 result
596 }
597}
598
599impl ReadModelWith for TestAppContext {
600 fn read_model_with<E: Entity, F: FnOnce(&E, &AppContext) -> T, T>(
601 &self,
602 handle: &ModelHandle<E>,
603 read: F,
604 ) -> T {
605 let cx = self.cx.borrow();
606 let cx = cx.as_ref();
607 read(handle.read(cx), cx)
608 }
609}
610
611impl UpdateView for TestAppContext {
612 fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
613 where
614 T: View,
615 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
616 {
617 let mut state = self.cx.borrow_mut();
618 state.pending_flushes += 1;
619 let result = state.update_view(handle, update);
620 state.flush_effects();
621 result
622 }
623}
624
625impl ReadViewWith for TestAppContext {
626 fn read_view_with<V, F, T>(&self, handle: &ViewHandle<V>, read: F) -> T
627 where
628 V: View,
629 F: FnOnce(&V, &AppContext) -> T,
630 {
631 let cx = self.cx.borrow();
632 let cx = cx.as_ref();
633 read(handle.read(cx), cx)
634 }
635}
636
637type ActionCallback =
638 dyn FnMut(&mut dyn AnyView, &dyn AnyAction, &mut MutableAppContext, usize, usize) -> bool;
639
640type GlobalActionCallback = dyn FnMut(&dyn AnyAction, &mut MutableAppContext);
641
642pub struct MutableAppContext {
643 weak_self: Option<rc::Weak<RefCell<Self>>>,
644 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
645 assets: Arc<AssetCache>,
646 cx: AppContext,
647 actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
648 global_actions: HashMap<TypeId, Vec<Box<GlobalActionCallback>>>,
649 keystroke_matcher: keymap::Matcher,
650 next_entity_id: usize,
651 next_window_id: usize,
652 subscriptions: HashMap<usize, Vec<Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>>>,
653 observations: HashMap<usize, Vec<Box<dyn FnMut(&mut MutableAppContext) -> bool>>>,
654 presenters_and_platform_windows:
655 HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
656 debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
657 foreground: Rc<executor::Foreground>,
658 pending_effects: VecDeque<Effect>,
659 pending_flushes: usize,
660 flushing_effects: bool,
661}
662
663impl MutableAppContext {
664 fn new(
665 foreground: Rc<executor::Foreground>,
666 background: Arc<executor::Background>,
667 platform: Arc<dyn platform::Platform>,
668 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
669 font_cache: Arc<FontCache>,
670 asset_source: impl AssetSource,
671 ) -> Self {
672 Self {
673 weak_self: None,
674 foreground_platform,
675 assets: Arc::new(AssetCache::new(asset_source)),
676 cx: AppContext {
677 models: Default::default(),
678 views: Default::default(),
679 windows: Default::default(),
680 values: Default::default(),
681 ref_counts: Arc::new(Mutex::new(RefCounts::default())),
682 background,
683 font_cache,
684 platform,
685 },
686 actions: HashMap::new(),
687 global_actions: HashMap::new(),
688 keystroke_matcher: keymap::Matcher::default(),
689 next_entity_id: 0,
690 next_window_id: 0,
691 subscriptions: HashMap::new(),
692 observations: HashMap::new(),
693 presenters_and_platform_windows: HashMap::new(),
694 debug_elements_callbacks: HashMap::new(),
695 foreground,
696 pending_effects: VecDeque::new(),
697 pending_flushes: 0,
698 flushing_effects: false,
699 }
700 }
701
702 pub fn upgrade(&self) -> App {
703 App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
704 }
705
706 pub fn platform(&self) -> Arc<dyn platform::Platform> {
707 self.cx.platform.clone()
708 }
709
710 pub fn font_cache(&self) -> &Arc<FontCache> {
711 &self.cx.font_cache
712 }
713
714 pub fn foreground(&self) -> &Rc<executor::Foreground> {
715 &self.foreground
716 }
717
718 pub fn background(&self) -> &Arc<executor::Background> {
719 &self.cx.background
720 }
721
722 pub fn on_debug_elements<F>(&mut self, window_id: usize, callback: F)
723 where
724 F: 'static + Fn(&AppContext) -> crate::json::Value,
725 {
726 self.debug_elements_callbacks
727 .insert(window_id, Box::new(callback));
728 }
729
730 pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
731 self.debug_elements_callbacks
732 .get(&window_id)
733 .map(|debug_elements| debug_elements(&self.cx))
734 }
735
736 pub fn add_action<A, V, F>(&mut self, mut handler: F)
737 where
738 A: Action,
739 V: View,
740 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
741 {
742 let handler = Box::new(
743 move |view: &mut dyn AnyView,
744 action: &dyn AnyAction,
745 cx: &mut MutableAppContext,
746 window_id: usize,
747 view_id: usize| {
748 let action = action.as_any().downcast_ref().unwrap();
749 let mut cx = ViewContext::new(cx, window_id, view_id);
750 handler(
751 view.as_any_mut()
752 .downcast_mut()
753 .expect("downcast is type safe"),
754 action,
755 &mut cx,
756 );
757 cx.halt_action_dispatch
758 },
759 );
760
761 self.actions
762 .entry(TypeId::of::<V>())
763 .or_default()
764 .entry(TypeId::of::<A>())
765 .or_default()
766 .push(handler);
767 }
768
769 pub fn add_global_action<A, F>(&mut self, mut handler: F)
770 where
771 A: Action,
772 F: 'static + FnMut(&A, &mut MutableAppContext),
773 {
774 let handler = Box::new(move |action: &dyn AnyAction, cx: &mut MutableAppContext| {
775 let action = action.as_any().downcast_ref().unwrap();
776 handler(action, cx);
777 });
778
779 self.global_actions
780 .entry(TypeId::of::<A>())
781 .or_default()
782 .push(handler);
783 }
784
785 pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
786 self.cx.windows.keys().cloned()
787 }
788
789 pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
790 self.cx
791 .windows
792 .get(&window_id)
793 .and_then(|window| window.root_view.clone().downcast::<T>())
794 }
795
796 pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
797 self.cx.root_view_id(window_id)
798 }
799
800 pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
801 self.cx.focused_view_id(window_id)
802 }
803
804 pub fn render_views(
805 &self,
806 window_id: usize,
807 titlebar_height: f32,
808 ) -> HashMap<usize, ElementBox> {
809 self.cx.render_views(window_id, titlebar_height)
810 }
811
812 pub fn update<T, F: FnOnce() -> T>(&mut self, callback: F) -> T {
813 self.pending_flushes += 1;
814 let result = callback();
815 self.flush_effects();
816 result
817 }
818
819 pub fn set_menus(&mut self, menus: Vec<Menu>) {
820 self.foreground_platform.set_menus(menus);
821 }
822
823 fn prompt<F>(
824 &self,
825 window_id: usize,
826 level: PromptLevel,
827 msg: &str,
828 answers: &[&str],
829 done_fn: F,
830 ) where
831 F: 'static + FnOnce(usize, &mut MutableAppContext),
832 {
833 let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
834 let foreground = self.foreground.clone();
835 let (_, window) = &self.presenters_and_platform_windows[&window_id];
836 window.prompt(
837 level,
838 msg,
839 answers,
840 Box::new(move |answer| {
841 foreground
842 .spawn(async move { (done_fn)(answer, &mut *app.borrow_mut()) })
843 .detach();
844 }),
845 );
846 }
847
848 pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
849 where
850 F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
851 {
852 let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
853 let foreground = self.foreground.clone();
854 self.foreground_platform.prompt_for_paths(
855 options,
856 Box::new(move |paths| {
857 foreground
858 .spawn(async move { (done_fn)(paths, &mut *app.borrow_mut()) })
859 .detach();
860 }),
861 );
862 }
863
864 pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
865 where
866 F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
867 {
868 let app = self.weak_self.as_ref().unwrap().upgrade().unwrap();
869 let foreground = self.foreground.clone();
870 self.foreground_platform.prompt_for_new_path(
871 directory,
872 Box::new(move |path| {
873 foreground
874 .spawn(async move { (done_fn)(path, &mut *app.borrow_mut()) })
875 .detach();
876 }),
877 );
878 }
879
880 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F)
881 where
882 E: Entity,
883 E::Event: 'static,
884 H: Handle<E>,
885 F: 'static + FnMut(H, &E::Event, &mut Self),
886 {
887 self.subscribe_internal(handle, move |handle, event, cx| {
888 callback(handle, event, cx);
889 true
890 })
891 }
892
893 fn observe<E, H, F>(&mut self, handle: &H, mut callback: F)
894 where
895 E: Entity,
896 E::Event: 'static,
897 H: Handle<E>,
898 F: 'static + FnMut(H, &mut Self),
899 {
900 self.observe_internal(handle, move |handle, cx| {
901 callback(handle, cx);
902 true
903 })
904 }
905
906 pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F)
907 where
908 E: Entity,
909 E::Event: 'static,
910 H: Handle<E>,
911 F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
912 {
913 let emitter = handle.downgrade();
914 self.subscriptions
915 .entry(handle.id())
916 .or_default()
917 .push(Box::new(move |payload, cx| {
918 if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
919 let payload = payload.downcast_ref().expect("downcast is type safe");
920 callback(emitter, payload, cx)
921 } else {
922 false
923 }
924 }))
925 }
926
927 fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F)
928 where
929 E: Entity,
930 E::Event: 'static,
931 H: Handle<E>,
932 F: 'static + FnMut(H, &mut Self) -> bool,
933 {
934 let observed = handle.downgrade();
935 self.observations
936 .entry(handle.id())
937 .or_default()
938 .push(Box::new(move |cx| {
939 if let Some(observed) = H::upgrade_from(&observed, cx) {
940 callback(observed, cx)
941 } else {
942 false
943 }
944 }))
945 }
946
947 pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
948 self.pending_effects
949 .push_back(Effect::ViewNotification { window_id, view_id });
950 }
951
952 pub(crate) fn notify_all_views(&mut self) {
953 let notifications = self
954 .views
955 .keys()
956 .copied()
957 .map(|(window_id, view_id)| Effect::ViewNotification { window_id, view_id })
958 .collect::<Vec<_>>();
959 self.pending_effects.extend(notifications);
960 }
961
962 pub fn dispatch_action<A: Action>(
963 &mut self,
964 window_id: usize,
965 responder_chain: Vec<usize>,
966 action: &A,
967 ) {
968 self.dispatch_action_any(window_id, &responder_chain, action);
969 }
970
971 pub(crate) fn dispatch_action_any(
972 &mut self,
973 window_id: usize,
974 path: &[usize],
975 action: &dyn AnyAction,
976 ) -> bool {
977 self.pending_flushes += 1;
978 let mut halted_dispatch = false;
979
980 for view_id in path.iter().rev() {
981 if let Some(mut view) = self.cx.views.remove(&(window_id, *view_id)) {
982 let type_id = view.as_any().type_id();
983
984 if let Some((name, mut handlers)) = self
985 .actions
986 .get_mut(&type_id)
987 .and_then(|h| h.remove_entry(&action.id()))
988 {
989 for handler in handlers.iter_mut().rev() {
990 let halt_dispatch =
991 handler(view.as_mut(), action, self, window_id, *view_id);
992 if halt_dispatch {
993 halted_dispatch = true;
994 break;
995 }
996 }
997 self.actions
998 .get_mut(&type_id)
999 .unwrap()
1000 .insert(name, handlers);
1001 }
1002
1003 self.cx.views.insert((window_id, *view_id), view);
1004
1005 if halted_dispatch {
1006 break;
1007 }
1008 }
1009 }
1010
1011 if !halted_dispatch {
1012 self.dispatch_global_action_any(action);
1013 }
1014
1015 self.flush_effects();
1016 halted_dispatch
1017 }
1018
1019 pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1020 self.dispatch_global_action_any(&action);
1021 }
1022
1023 fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) {
1024 if let Some((name, mut handlers)) = self.global_actions.remove_entry(&action.id()) {
1025 self.pending_flushes += 1;
1026 for handler in handlers.iter_mut().rev() {
1027 handler(action, self);
1028 }
1029 self.global_actions.insert(name, handlers);
1030 self.flush_effects();
1031 }
1032 }
1033
1034 pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1035 self.keystroke_matcher.add_bindings(bindings);
1036 }
1037
1038 pub fn dispatch_keystroke(
1039 &mut self,
1040 window_id: usize,
1041 responder_chain: Vec<usize>,
1042 keystroke: &Keystroke,
1043 ) -> Result<bool> {
1044 let mut context_chain = Vec::new();
1045 let mut context = keymap::Context::default();
1046 for view_id in &responder_chain {
1047 if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1048 context.extend(view.keymap_context(self.as_ref()));
1049 context_chain.push(context.clone());
1050 } else {
1051 return Err(anyhow!(
1052 "View {} in responder chain does not exist",
1053 view_id
1054 ));
1055 }
1056 }
1057
1058 let mut pending = false;
1059 for (i, cx) in context_chain.iter().enumerate().rev() {
1060 match self
1061 .keystroke_matcher
1062 .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1063 {
1064 MatchResult::None => {}
1065 MatchResult::Pending => pending = true,
1066 MatchResult::Action(action) => {
1067 if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1068 {
1069 return Ok(true);
1070 }
1071 }
1072 }
1073 }
1074
1075 Ok(pending)
1076 }
1077
1078 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1079 where
1080 T: Entity,
1081 F: FnOnce(&mut ModelContext<T>) -> T,
1082 {
1083 self.pending_flushes += 1;
1084 let model_id = post_inc(&mut self.next_entity_id);
1085 let handle = ModelHandle::new(model_id, &self.cx.ref_counts);
1086 let mut cx = ModelContext::new(self, model_id);
1087 let model = build_model(&mut cx);
1088 self.cx.models.insert(model_id, Box::new(model));
1089 self.flush_effects();
1090 handle
1091 }
1092
1093 pub fn add_window<T, F>(
1094 &mut self,
1095 window_options: WindowOptions,
1096 build_root_view: F,
1097 ) -> (usize, ViewHandle<T>)
1098 where
1099 T: View,
1100 F: FnOnce(&mut ViewContext<T>) -> T,
1101 {
1102 self.pending_flushes += 1;
1103 let window_id = post_inc(&mut self.next_window_id);
1104 let root_view = self.add_view(window_id, build_root_view);
1105
1106 self.cx.windows.insert(
1107 window_id,
1108 Window {
1109 root_view: root_view.clone().into(),
1110 focused_view_id: root_view.id(),
1111 invalidation: None,
1112 },
1113 );
1114 self.open_platform_window(window_id, window_options);
1115 root_view.update(self, |view, cx| {
1116 view.on_focus(cx);
1117 cx.notify();
1118 });
1119 self.flush_effects();
1120
1121 (window_id, root_view)
1122 }
1123
1124 pub fn remove_window(&mut self, window_id: usize) {
1125 self.cx.windows.remove(&window_id);
1126 self.presenters_and_platform_windows.remove(&window_id);
1127 self.remove_dropped_entities();
1128 }
1129
1130 fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1131 let mut window =
1132 self.cx
1133 .platform
1134 .open_window(window_id, window_options, self.foreground.clone());
1135 let presenter = Rc::new(RefCell::new(
1136 self.build_presenter(window_id, window.titlebar_height()),
1137 ));
1138
1139 {
1140 let mut app = self.upgrade();
1141 let presenter = presenter.clone();
1142 window.on_event(Box::new(move |event| {
1143 app.update(|cx| {
1144 if let Event::KeyDown { keystroke, .. } = &event {
1145 if cx
1146 .dispatch_keystroke(
1147 window_id,
1148 presenter.borrow().dispatch_path(cx.as_ref()),
1149 keystroke,
1150 )
1151 .unwrap()
1152 {
1153 return;
1154 }
1155 }
1156
1157 presenter.borrow_mut().dispatch_event(event, cx);
1158 })
1159 }));
1160 }
1161
1162 {
1163 let mut app = self.upgrade();
1164 let presenter = presenter.clone();
1165 window.on_resize(Box::new(move |window| {
1166 app.update(|cx| {
1167 let scene = presenter.borrow_mut().build_scene(
1168 window.size(),
1169 window.scale_factor(),
1170 cx,
1171 );
1172 window.present_scene(scene);
1173 })
1174 }));
1175 }
1176
1177 {
1178 let mut app = self.upgrade();
1179 window.on_close(Box::new(move || {
1180 app.update(|cx| cx.remove_window(window_id));
1181 }));
1182 }
1183
1184 self.presenters_and_platform_windows
1185 .insert(window_id, (presenter.clone(), window));
1186
1187 self.on_debug_elements(window_id, move |cx| {
1188 presenter.borrow().debug_elements(cx).unwrap()
1189 });
1190 }
1191
1192 pub fn build_presenter(&self, window_id: usize, titlebar_height: f32) -> Presenter {
1193 Presenter::new(
1194 window_id,
1195 titlebar_height,
1196 self.cx.font_cache.clone(),
1197 TextLayoutCache::new(self.cx.platform.fonts()),
1198 self.assets.clone(),
1199 self,
1200 )
1201 }
1202
1203 pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1204 where
1205 T: View,
1206 F: FnOnce(&mut ViewContext<T>) -> T,
1207 {
1208 self.add_option_view(window_id, |cx| Some(build_view(cx)))
1209 .unwrap()
1210 }
1211
1212 pub fn add_option_view<T, F>(
1213 &mut self,
1214 window_id: usize,
1215 build_view: F,
1216 ) -> Option<ViewHandle<T>>
1217 where
1218 T: View,
1219 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1220 {
1221 let view_id = post_inc(&mut self.next_entity_id);
1222 self.pending_flushes += 1;
1223 let handle = ViewHandle::new(window_id, view_id, &self.cx.ref_counts);
1224 let mut cx = ViewContext::new(self, window_id, view_id);
1225 let handle = if let Some(view) = build_view(&mut cx) {
1226 self.cx.views.insert((window_id, view_id), Box::new(view));
1227 if let Some(window) = self.cx.windows.get_mut(&window_id) {
1228 window
1229 .invalidation
1230 .get_or_insert_with(Default::default)
1231 .updated
1232 .insert(view_id);
1233 }
1234 Some(handle)
1235 } else {
1236 None
1237 };
1238 self.flush_effects();
1239 handle
1240 }
1241
1242 fn remove_dropped_entities(&mut self) {
1243 loop {
1244 let (dropped_models, dropped_views, dropped_values) =
1245 self.cx.ref_counts.lock().take_dropped();
1246 if dropped_models.is_empty() && dropped_views.is_empty() && dropped_values.is_empty() {
1247 break;
1248 }
1249
1250 for model_id in dropped_models {
1251 self.subscriptions.remove(&model_id);
1252 self.observations.remove(&model_id);
1253 let mut model = self.cx.models.remove(&model_id).unwrap();
1254 model.release(self);
1255 }
1256
1257 for (window_id, view_id) in dropped_views {
1258 self.subscriptions.remove(&view_id);
1259 self.observations.remove(&view_id);
1260 let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1261 view.release(self);
1262 let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1263 window
1264 .invalidation
1265 .get_or_insert_with(Default::default)
1266 .removed
1267 .push(view_id);
1268 if window.focused_view_id == view_id {
1269 Some(window.root_view.id())
1270 } else {
1271 None
1272 }
1273 });
1274
1275 if let Some(view_id) = change_focus_to {
1276 self.focus(window_id, view_id);
1277 }
1278 }
1279
1280 let mut values = self.cx.values.write();
1281 for key in dropped_values {
1282 values.remove(&key);
1283 }
1284 }
1285 }
1286
1287 fn flush_effects(&mut self) {
1288 self.pending_flushes = self.pending_flushes.saturating_sub(1);
1289
1290 if !self.flushing_effects && self.pending_flushes == 0 {
1291 self.flushing_effects = true;
1292
1293 loop {
1294 if let Some(effect) = self.pending_effects.pop_front() {
1295 match effect {
1296 Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1297 Effect::ModelNotification { model_id } => {
1298 self.notify_model_observers(model_id)
1299 }
1300 Effect::ViewNotification { window_id, view_id } => {
1301 self.notify_view_observers(window_id, view_id)
1302 }
1303 Effect::Focus { window_id, view_id } => {
1304 self.focus(window_id, view_id);
1305 }
1306 }
1307 self.remove_dropped_entities();
1308 } else {
1309 self.remove_dropped_entities();
1310 self.update_windows();
1311
1312 if self.pending_effects.is_empty() {
1313 self.flushing_effects = false;
1314 break;
1315 }
1316 }
1317 }
1318 }
1319 }
1320
1321 fn update_windows(&mut self) {
1322 let mut invalidations = HashMap::new();
1323 for (window_id, window) in &mut self.cx.windows {
1324 if let Some(invalidation) = window.invalidation.take() {
1325 invalidations.insert(*window_id, invalidation);
1326 }
1327 }
1328
1329 for (window_id, invalidation) in invalidations {
1330 if let Some((presenter, mut window)) =
1331 self.presenters_and_platform_windows.remove(&window_id)
1332 {
1333 {
1334 let mut presenter = presenter.borrow_mut();
1335 presenter.invalidate(invalidation, self.as_ref());
1336 let scene = presenter.build_scene(window.size(), window.scale_factor(), self);
1337 window.present_scene(scene);
1338 }
1339 self.presenters_and_platform_windows
1340 .insert(window_id, (presenter, window));
1341 }
1342 }
1343 }
1344
1345 fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1346 if let Some(callbacks) = self.subscriptions.remove(&entity_id) {
1347 for mut callback in callbacks {
1348 let alive = callback(payload.as_ref(), self);
1349 if alive {
1350 self.subscriptions
1351 .entry(entity_id)
1352 .or_default()
1353 .push(callback);
1354 }
1355 }
1356 }
1357 }
1358
1359 fn notify_model_observers(&mut self, observed_id: usize) {
1360 if let Some(callbacks) = self.observations.remove(&observed_id) {
1361 if self.cx.models.contains_key(&observed_id) {
1362 for mut callback in callbacks {
1363 let alive = callback(self);
1364 if alive {
1365 self.observations
1366 .entry(observed_id)
1367 .or_default()
1368 .push(callback);
1369 }
1370 }
1371 }
1372 }
1373 }
1374
1375 fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1376 if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1377 window
1378 .invalidation
1379 .get_or_insert_with(Default::default)
1380 .updated
1381 .insert(observed_view_id);
1382 }
1383
1384 if let Some(callbacks) = self.observations.remove(&observed_view_id) {
1385 if self
1386 .cx
1387 .views
1388 .contains_key(&(observed_window_id, observed_view_id))
1389 {
1390 for mut callback in callbacks {
1391 let alive = callback(self);
1392 if alive {
1393 self.observations
1394 .entry(observed_view_id)
1395 .or_default()
1396 .push(callback);
1397 }
1398 }
1399 }
1400 }
1401 }
1402
1403 fn focus(&mut self, window_id: usize, focused_id: usize) {
1404 if self
1405 .cx
1406 .windows
1407 .get(&window_id)
1408 .map(|w| w.focused_view_id)
1409 .map_or(false, |cur_focused| cur_focused == focused_id)
1410 {
1411 return;
1412 }
1413
1414 self.pending_flushes += 1;
1415
1416 let blurred_id = self.cx.windows.get_mut(&window_id).map(|window| {
1417 let blurred_id = window.focused_view_id;
1418 window.focused_view_id = focused_id;
1419 blurred_id
1420 });
1421
1422 if let Some(blurred_id) = blurred_id {
1423 if let Some(mut blurred_view) = self.cx.views.remove(&(window_id, blurred_id)) {
1424 blurred_view.on_blur(self, window_id, blurred_id);
1425 self.cx.views.insert((window_id, blurred_id), blurred_view);
1426 }
1427 }
1428
1429 if let Some(mut focused_view) = self.cx.views.remove(&(window_id, focused_id)) {
1430 focused_view.on_focus(self, window_id, focused_id);
1431 self.cx.views.insert((window_id, focused_id), focused_view);
1432 }
1433
1434 self.flush_effects();
1435 }
1436
1437 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1438 where
1439 F: FnOnce(AsyncAppContext) -> Fut,
1440 Fut: 'static + Future<Output = T>,
1441 T: 'static,
1442 {
1443 let cx = self.to_async();
1444 self.foreground.spawn(f(cx))
1445 }
1446
1447 pub fn to_async(&self) -> AsyncAppContext {
1448 AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1449 }
1450
1451 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1452 self.cx.platform.write_to_clipboard(item);
1453 }
1454
1455 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1456 self.cx.platform.read_from_clipboard()
1457 }
1458}
1459
1460impl ReadModel for MutableAppContext {
1461 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1462 if let Some(model) = self.cx.models.get(&handle.model_id) {
1463 model
1464 .as_any()
1465 .downcast_ref()
1466 .expect("downcast is type safe")
1467 } else {
1468 panic!("circular model reference");
1469 }
1470 }
1471}
1472
1473impl UpdateModel for MutableAppContext {
1474 fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1475 where
1476 T: Entity,
1477 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1478 {
1479 if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1480 self.pending_flushes += 1;
1481 let mut cx = ModelContext::new(self, handle.model_id);
1482 let result = update(
1483 model
1484 .as_any_mut()
1485 .downcast_mut()
1486 .expect("downcast is type safe"),
1487 &mut cx,
1488 );
1489 self.cx.models.insert(handle.model_id, model);
1490 self.flush_effects();
1491 result
1492 } else {
1493 panic!("circular model update");
1494 }
1495 }
1496}
1497
1498impl UpgradeModelHandle for MutableAppContext {
1499 fn upgrade_model_handle<T: Entity>(
1500 &self,
1501 handle: WeakModelHandle<T>,
1502 ) -> Option<ModelHandle<T>> {
1503 self.cx.upgrade_model_handle(handle)
1504 }
1505}
1506
1507impl ReadView for MutableAppContext {
1508 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1509 if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1510 view.as_any().downcast_ref().expect("downcast is type safe")
1511 } else {
1512 panic!("circular view reference");
1513 }
1514 }
1515}
1516
1517impl UpdateView for MutableAppContext {
1518 fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
1519 where
1520 T: View,
1521 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
1522 {
1523 self.pending_flushes += 1;
1524 let mut view = self
1525 .cx
1526 .views
1527 .remove(&(handle.window_id, handle.view_id))
1528 .expect("circular view update");
1529
1530 let mut cx = ViewContext::new(self, handle.window_id, handle.view_id);
1531 let result = update(
1532 view.as_any_mut()
1533 .downcast_mut()
1534 .expect("downcast is type safe"),
1535 &mut cx,
1536 );
1537 self.cx
1538 .views
1539 .insert((handle.window_id, handle.view_id), view);
1540 self.flush_effects();
1541 result
1542 }
1543}
1544
1545impl AsRef<AppContext> for MutableAppContext {
1546 fn as_ref(&self) -> &AppContext {
1547 &self.cx
1548 }
1549}
1550
1551impl Deref for MutableAppContext {
1552 type Target = AppContext;
1553
1554 fn deref(&self) -> &Self::Target {
1555 &self.cx
1556 }
1557}
1558
1559pub struct AppContext {
1560 models: HashMap<usize, Box<dyn AnyModel>>,
1561 views: HashMap<(usize, usize), Box<dyn AnyView>>,
1562 windows: HashMap<usize, Window>,
1563 values: RwLock<HashMap<(TypeId, usize), Box<dyn Any>>>,
1564 background: Arc<executor::Background>,
1565 ref_counts: Arc<Mutex<RefCounts>>,
1566 font_cache: Arc<FontCache>,
1567 platform: Arc<dyn Platform>,
1568}
1569
1570impl AppContext {
1571 pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1572 self.windows
1573 .get(&window_id)
1574 .map(|window| window.root_view.id())
1575 }
1576
1577 pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1578 self.windows
1579 .get(&window_id)
1580 .map(|window| window.focused_view_id)
1581 }
1582
1583 pub fn render_view(
1584 &self,
1585 window_id: usize,
1586 view_id: usize,
1587 titlebar_height: f32,
1588 ) -> Result<ElementBox> {
1589 self.views
1590 .get(&(window_id, view_id))
1591 .map(|v| v.render(window_id, view_id, titlebar_height, self))
1592 .ok_or(anyhow!("view not found"))
1593 }
1594
1595 pub fn render_views(
1596 &self,
1597 window_id: usize,
1598 titlebar_height: f32,
1599 ) -> HashMap<usize, ElementBox> {
1600 self.views
1601 .iter()
1602 .filter_map(|((win_id, view_id), view)| {
1603 if *win_id == window_id {
1604 Some((
1605 *view_id,
1606 view.render(*win_id, *view_id, titlebar_height, self),
1607 ))
1608 } else {
1609 None
1610 }
1611 })
1612 .collect::<HashMap<_, ElementBox>>()
1613 }
1614
1615 pub fn background(&self) -> &Arc<executor::Background> {
1616 &self.background
1617 }
1618
1619 pub fn font_cache(&self) -> &Arc<FontCache> {
1620 &self.font_cache
1621 }
1622
1623 pub fn platform(&self) -> &Arc<dyn Platform> {
1624 &self.platform
1625 }
1626
1627 pub fn value<Tag: 'static, T: 'static + Default>(&self, id: usize) -> ValueHandle<T> {
1628 let key = (TypeId::of::<Tag>(), id);
1629 self.values
1630 .write()
1631 .entry(key)
1632 .or_insert_with(|| Box::new(T::default()));
1633 ValueHandle::new(TypeId::of::<Tag>(), id, &self.ref_counts)
1634 }
1635}
1636
1637impl ReadModel for AppContext {
1638 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1639 if let Some(model) = self.models.get(&handle.model_id) {
1640 model
1641 .as_any()
1642 .downcast_ref()
1643 .expect("downcast should be type safe")
1644 } else {
1645 panic!("circular model reference");
1646 }
1647 }
1648}
1649
1650impl UpgradeModelHandle for AppContext {
1651 fn upgrade_model_handle<T: Entity>(
1652 &self,
1653 handle: WeakModelHandle<T>,
1654 ) -> Option<ModelHandle<T>> {
1655 if self.models.contains_key(&handle.model_id) {
1656 Some(ModelHandle::new(handle.model_id, &self.ref_counts))
1657 } else {
1658 None
1659 }
1660 }
1661}
1662
1663impl ReadView for AppContext {
1664 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1665 if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1666 view.as_any()
1667 .downcast_ref()
1668 .expect("downcast should be type safe")
1669 } else {
1670 panic!("circular view reference");
1671 }
1672 }
1673}
1674
1675struct Window {
1676 root_view: AnyViewHandle,
1677 focused_view_id: usize,
1678 invalidation: Option<WindowInvalidation>,
1679}
1680
1681#[derive(Default, Clone)]
1682pub struct WindowInvalidation {
1683 pub updated: HashSet<usize>,
1684 pub removed: Vec<usize>,
1685}
1686
1687pub enum Effect {
1688 Event {
1689 entity_id: usize,
1690 payload: Box<dyn Any>,
1691 },
1692 ModelNotification {
1693 model_id: usize,
1694 },
1695 ViewNotification {
1696 window_id: usize,
1697 view_id: usize,
1698 },
1699 Focus {
1700 window_id: usize,
1701 view_id: usize,
1702 },
1703}
1704
1705impl Debug for Effect {
1706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1707 match self {
1708 Effect::Event { entity_id, .. } => f
1709 .debug_struct("Effect::Event")
1710 .field("entity_id", entity_id)
1711 .finish(),
1712 Effect::ModelNotification { model_id } => f
1713 .debug_struct("Effect::ModelNotification")
1714 .field("model_id", model_id)
1715 .finish(),
1716 Effect::ViewNotification { window_id, view_id } => f
1717 .debug_struct("Effect::ViewNotification")
1718 .field("window_id", window_id)
1719 .field("view_id", view_id)
1720 .finish(),
1721 Effect::Focus { window_id, view_id } => f
1722 .debug_struct("Effect::Focus")
1723 .field("window_id", window_id)
1724 .field("view_id", view_id)
1725 .finish(),
1726 }
1727 }
1728}
1729
1730pub trait AnyModel {
1731 fn as_any(&self) -> &dyn Any;
1732 fn as_any_mut(&mut self) -> &mut dyn Any;
1733 fn release(&mut self, cx: &mut MutableAppContext);
1734}
1735
1736impl<T> AnyModel for T
1737where
1738 T: Entity,
1739{
1740 fn as_any(&self) -> &dyn Any {
1741 self
1742 }
1743
1744 fn as_any_mut(&mut self) -> &mut dyn Any {
1745 self
1746 }
1747
1748 fn release(&mut self, cx: &mut MutableAppContext) {
1749 self.release(cx);
1750 }
1751}
1752
1753pub trait AnyView {
1754 fn as_any(&self) -> &dyn Any;
1755 fn as_any_mut(&mut self) -> &mut dyn Any;
1756 fn release(&mut self, cx: &mut MutableAppContext);
1757 fn ui_name(&self) -> &'static str;
1758 fn render<'a>(
1759 &self,
1760 window_id: usize,
1761 view_id: usize,
1762 titlebar_height: f32,
1763 cx: &AppContext,
1764 ) -> ElementBox;
1765 fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1766 fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1767 fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
1768}
1769
1770impl<T> AnyView for T
1771where
1772 T: View,
1773{
1774 fn as_any(&self) -> &dyn Any {
1775 self
1776 }
1777
1778 fn as_any_mut(&mut self) -> &mut dyn Any {
1779 self
1780 }
1781
1782 fn release(&mut self, cx: &mut MutableAppContext) {
1783 self.release(cx);
1784 }
1785
1786 fn ui_name(&self) -> &'static str {
1787 T::ui_name()
1788 }
1789
1790 fn render<'a>(
1791 &self,
1792 window_id: usize,
1793 view_id: usize,
1794 titlebar_height: f32,
1795 cx: &AppContext,
1796 ) -> ElementBox {
1797 View::render(
1798 self,
1799 &RenderContext {
1800 window_id,
1801 view_id,
1802 app: cx,
1803 view_type: PhantomData::<T>,
1804 titlebar_height,
1805 },
1806 )
1807 }
1808
1809 fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1810 let mut cx = ViewContext::new(cx, window_id, view_id);
1811 View::on_focus(self, &mut cx);
1812 }
1813
1814 fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1815 let mut cx = ViewContext::new(cx, window_id, view_id);
1816 View::on_blur(self, &mut cx);
1817 }
1818
1819 fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
1820 View::keymap_context(self, cx)
1821 }
1822}
1823
1824pub struct ModelContext<'a, T: ?Sized> {
1825 app: &'a mut MutableAppContext,
1826 model_id: usize,
1827 model_type: PhantomData<T>,
1828 halt_stream: bool,
1829}
1830
1831impl<'a, T: Entity> ModelContext<'a, T> {
1832 fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
1833 Self {
1834 app,
1835 model_id,
1836 model_type: PhantomData,
1837 halt_stream: false,
1838 }
1839 }
1840
1841 pub fn background(&self) -> &Arc<executor::Background> {
1842 &self.app.cx.background
1843 }
1844
1845 pub fn halt_stream(&mut self) {
1846 self.halt_stream = true;
1847 }
1848
1849 pub fn model_id(&self) -> usize {
1850 self.model_id
1851 }
1852
1853 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1854 where
1855 S: Entity,
1856 F: FnOnce(&mut ModelContext<S>) -> S,
1857 {
1858 self.app.add_model(build_model)
1859 }
1860
1861 pub fn emit(&mut self, payload: T::Event) {
1862 self.app.pending_effects.push_back(Effect::Event {
1863 entity_id: self.model_id,
1864 payload: Box::new(payload),
1865 });
1866 }
1867
1868 pub fn notify(&mut self) {
1869 self.app
1870 .pending_effects
1871 .push_back(Effect::ModelNotification {
1872 model_id: self.model_id,
1873 });
1874 }
1875
1876 pub fn subscribe<S: Entity, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1877 where
1878 S::Event: 'static,
1879 F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
1880 {
1881 let subscriber = self.handle().downgrade();
1882 self.app
1883 .subscribe_internal(handle, move |emitter, event, cx| {
1884 if let Some(subscriber) = subscriber.upgrade(cx) {
1885 subscriber.update(cx, |subscriber, cx| {
1886 callback(subscriber, emitter, event, cx);
1887 });
1888 true
1889 } else {
1890 false
1891 }
1892 });
1893 }
1894
1895 pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1896 where
1897 S: Entity,
1898 F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
1899 {
1900 let observer = self.handle().downgrade();
1901 self.app.observe_internal(handle, move |observed, cx| {
1902 if let Some(observer) = observer.upgrade(cx) {
1903 observer.update(cx, |observer, cx| {
1904 callback(observer, observed, cx);
1905 });
1906 true
1907 } else {
1908 false
1909 }
1910 });
1911 }
1912
1913 pub fn handle(&self) -> ModelHandle<T> {
1914 ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
1915 }
1916
1917 pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
1918 where
1919 F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
1920 Fut: 'static + Future<Output = S>,
1921 S: 'static,
1922 {
1923 let handle = self.handle();
1924 self.app.spawn(|cx| f(handle, cx))
1925 }
1926
1927 pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
1928 where
1929 F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
1930 Fut: 'static + Future<Output = S>,
1931 S: 'static,
1932 {
1933 let handle = self.handle().downgrade();
1934 self.app.spawn(|cx| f(handle, cx))
1935 }
1936}
1937
1938impl<M> AsRef<AppContext> for ModelContext<'_, M> {
1939 fn as_ref(&self) -> &AppContext {
1940 &self.app.cx
1941 }
1942}
1943
1944impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
1945 fn as_mut(&mut self) -> &mut MutableAppContext {
1946 self.app
1947 }
1948}
1949
1950impl<M> ReadModel for ModelContext<'_, M> {
1951 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1952 self.app.read_model(handle)
1953 }
1954}
1955
1956impl<M> UpdateModel for ModelContext<'_, M> {
1957 fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1958 where
1959 T: Entity,
1960 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1961 {
1962 self.app.update_model(handle, update)
1963 }
1964}
1965
1966impl<M> UpgradeModelHandle for ModelContext<'_, M> {
1967 fn upgrade_model_handle<T: Entity>(
1968 &self,
1969 handle: WeakModelHandle<T>,
1970 ) -> Option<ModelHandle<T>> {
1971 self.cx.upgrade_model_handle(handle)
1972 }
1973}
1974
1975impl<M> Deref for ModelContext<'_, M> {
1976 type Target = MutableAppContext;
1977
1978 fn deref(&self) -> &Self::Target {
1979 &self.app
1980 }
1981}
1982
1983impl<M> DerefMut for ModelContext<'_, M> {
1984 fn deref_mut(&mut self) -> &mut Self::Target {
1985 &mut self.app
1986 }
1987}
1988
1989pub struct ViewContext<'a, T: ?Sized> {
1990 app: &'a mut MutableAppContext,
1991 window_id: usize,
1992 view_id: usize,
1993 view_type: PhantomData<T>,
1994 halt_action_dispatch: bool,
1995}
1996
1997impl<'a, T: View> ViewContext<'a, T> {
1998 fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
1999 Self {
2000 app,
2001 window_id,
2002 view_id,
2003 view_type: PhantomData,
2004 halt_action_dispatch: true,
2005 }
2006 }
2007
2008 pub fn handle(&self) -> ViewHandle<T> {
2009 ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2010 }
2011
2012 pub fn window_id(&self) -> usize {
2013 self.window_id
2014 }
2015
2016 pub fn view_id(&self) -> usize {
2017 self.view_id
2018 }
2019
2020 pub fn foreground(&self) -> &Rc<executor::Foreground> {
2021 self.app.foreground()
2022 }
2023
2024 pub fn background_executor(&self) -> &Arc<executor::Background> {
2025 &self.app.cx.background
2026 }
2027
2028 pub fn platform(&self) -> Arc<dyn Platform> {
2029 self.app.platform()
2030 }
2031
2032 pub fn prompt<F>(&self, level: PromptLevel, msg: &str, answers: &[&str], done_fn: F)
2033 where
2034 F: 'static + FnOnce(usize, &mut MutableAppContext),
2035 {
2036 self.app
2037 .prompt(self.window_id, level, msg, answers, done_fn)
2038 }
2039
2040 pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
2041 where
2042 F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
2043 {
2044 self.app.prompt_for_paths(options, done_fn)
2045 }
2046
2047 pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
2048 where
2049 F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
2050 {
2051 self.app.prompt_for_new_path(directory, done_fn)
2052 }
2053
2054 pub fn debug_elements(&self) -> crate::json::Value {
2055 self.app.debug_elements(self.window_id).unwrap()
2056 }
2057
2058 pub fn focus<S>(&mut self, handle: S)
2059 where
2060 S: Into<AnyViewHandle>,
2061 {
2062 let handle = handle.into();
2063 self.app.pending_effects.push_back(Effect::Focus {
2064 window_id: handle.window_id,
2065 view_id: handle.view_id,
2066 });
2067 }
2068
2069 pub fn focus_self(&mut self) {
2070 self.app.pending_effects.push_back(Effect::Focus {
2071 window_id: self.window_id,
2072 view_id: self.view_id,
2073 });
2074 }
2075
2076 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2077 where
2078 S: Entity,
2079 F: FnOnce(&mut ModelContext<S>) -> S,
2080 {
2081 self.app.add_model(build_model)
2082 }
2083
2084 pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2085 where
2086 S: View,
2087 F: FnOnce(&mut ViewContext<S>) -> S,
2088 {
2089 self.app.add_view(self.window_id, build_view)
2090 }
2091
2092 pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2093 where
2094 S: View,
2095 F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2096 {
2097 self.app.add_option_view(self.window_id, build_view)
2098 }
2099
2100 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F)
2101 where
2102 E: Entity,
2103 E::Event: 'static,
2104 H: Handle<E>,
2105 F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2106 {
2107 let subscriber = self.handle().downgrade();
2108 self.app
2109 .subscribe_internal(handle, move |emitter, event, cx| {
2110 if let Some(subscriber) = subscriber.upgrade(cx) {
2111 subscriber.update(cx, |subscriber, cx| {
2112 callback(subscriber, emitter, event, cx);
2113 });
2114 true
2115 } else {
2116 false
2117 }
2118 });
2119 }
2120
2121 pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F)
2122 where
2123 E: Entity,
2124 H: Handle<E>,
2125 F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2126 {
2127 let observer = self.handle().downgrade();
2128 self.app.observe_internal(handle, move |observed, cx| {
2129 if let Some(observer) = observer.upgrade(cx) {
2130 observer.update(cx, |observer, cx| {
2131 callback(observer, observed, cx);
2132 });
2133 true
2134 } else {
2135 false
2136 }
2137 });
2138 }
2139
2140 pub fn emit(&mut self, payload: T::Event) {
2141 self.app.pending_effects.push_back(Effect::Event {
2142 entity_id: self.view_id,
2143 payload: Box::new(payload),
2144 });
2145 }
2146
2147 pub fn notify(&mut self) {
2148 self.app.notify_view(self.window_id, self.view_id);
2149 }
2150
2151 pub fn notify_all(&mut self) {
2152 self.app.notify_all_views();
2153 }
2154
2155 pub fn propagate_action(&mut self) {
2156 self.halt_action_dispatch = false;
2157 }
2158
2159 pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2160 where
2161 F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2162 Fut: 'static + Future<Output = S>,
2163 S: 'static,
2164 {
2165 let handle = self.handle();
2166 self.app.spawn(|cx| f(handle, cx))
2167 }
2168}
2169
2170pub struct RenderContext<'a, T: View> {
2171 pub app: &'a AppContext,
2172 pub titlebar_height: f32,
2173 window_id: usize,
2174 view_id: usize,
2175 view_type: PhantomData<T>,
2176}
2177
2178impl<'a, T: View> RenderContext<'a, T> {
2179 pub fn handle(&self) -> WeakViewHandle<T> {
2180 WeakViewHandle::new(self.window_id, self.view_id)
2181 }
2182}
2183
2184impl AsRef<AppContext> for &AppContext {
2185 fn as_ref(&self) -> &AppContext {
2186 self
2187 }
2188}
2189
2190impl<V: View> Deref for RenderContext<'_, V> {
2191 type Target = AppContext;
2192
2193 fn deref(&self) -> &Self::Target {
2194 &self.app
2195 }
2196}
2197
2198impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2199 fn as_ref(&self) -> &AppContext {
2200 &self.app.cx
2201 }
2202}
2203
2204impl<M> Deref for ViewContext<'_, M> {
2205 type Target = MutableAppContext;
2206
2207 fn deref(&self) -> &Self::Target {
2208 &self.app
2209 }
2210}
2211
2212impl<M> DerefMut for ViewContext<'_, M> {
2213 fn deref_mut(&mut self) -> &mut Self::Target {
2214 &mut self.app
2215 }
2216}
2217
2218impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2219 fn as_mut(&mut self) -> &mut MutableAppContext {
2220 self.app
2221 }
2222}
2223
2224impl<V> ReadModel for ViewContext<'_, V> {
2225 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2226 self.app.read_model(handle)
2227 }
2228}
2229
2230impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2231 fn upgrade_model_handle<T: Entity>(
2232 &self,
2233 handle: WeakModelHandle<T>,
2234 ) -> Option<ModelHandle<T>> {
2235 self.cx.upgrade_model_handle(handle)
2236 }
2237}
2238
2239impl<V: View> UpdateModel for ViewContext<'_, V> {
2240 fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2241 where
2242 T: Entity,
2243 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2244 {
2245 self.app.update_model(handle, update)
2246 }
2247}
2248
2249impl<V: View> ReadView for ViewContext<'_, V> {
2250 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2251 self.app.read_view(handle)
2252 }
2253}
2254
2255impl<V: View> UpdateView for ViewContext<'_, V> {
2256 fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
2257 where
2258 T: View,
2259 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2260 {
2261 self.app.update_view(handle, update)
2262 }
2263}
2264
2265pub trait Handle<T> {
2266 type Weak: 'static;
2267 fn id(&self) -> usize;
2268 fn location(&self) -> EntityLocation;
2269 fn downgrade(&self) -> Self::Weak;
2270 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2271 where
2272 Self: Sized;
2273}
2274
2275#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2276pub enum EntityLocation {
2277 Model(usize),
2278 View(usize, usize),
2279}
2280
2281pub struct ModelHandle<T> {
2282 model_id: usize,
2283 model_type: PhantomData<T>,
2284 ref_counts: Arc<Mutex<RefCounts>>,
2285}
2286
2287impl<T: Entity> ModelHandle<T> {
2288 fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2289 ref_counts.lock().inc_model(model_id);
2290 Self {
2291 model_id,
2292 model_type: PhantomData,
2293 ref_counts: ref_counts.clone(),
2294 }
2295 }
2296
2297 pub fn downgrade(&self) -> WeakModelHandle<T> {
2298 WeakModelHandle::new(self.model_id)
2299 }
2300
2301 pub fn id(&self) -> usize {
2302 self.model_id
2303 }
2304
2305 pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2306 cx.read_model(self)
2307 }
2308
2309 pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2310 where
2311 C: ReadModelWith,
2312 F: FnOnce(&T, &AppContext) -> S,
2313 {
2314 cx.read_model_with(self, read)
2315 }
2316
2317 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2318 where
2319 C: UpdateModel,
2320 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2321 {
2322 cx.update_model(self, update)
2323 }
2324
2325 pub fn condition(
2326 &self,
2327 cx: &TestAppContext,
2328 mut predicate: impl FnMut(&T, &AppContext) -> bool,
2329 ) -> impl Future<Output = ()> {
2330 let (tx, mut rx) = mpsc::channel(1024);
2331
2332 let mut cx = cx.cx.borrow_mut();
2333 cx.observe(self, {
2334 let mut tx = tx.clone();
2335 move |_, _| {
2336 tx.blocking_send(()).ok();
2337 }
2338 });
2339 cx.subscribe(self, {
2340 let mut tx = tx.clone();
2341 move |_, _, _| {
2342 tx.blocking_send(()).ok();
2343 }
2344 });
2345
2346 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2347 let handle = self.downgrade();
2348 let duration = if std::env::var("CI").is_ok() {
2349 Duration::from_secs(5)
2350 } else {
2351 Duration::from_secs(1)
2352 };
2353
2354 async move {
2355 timeout(duration, async move {
2356 loop {
2357 {
2358 let cx = cx.borrow();
2359 let cx = cx.as_ref();
2360 if predicate(
2361 handle
2362 .upgrade(cx)
2363 .expect("model dropped with pending condition")
2364 .read(cx),
2365 cx,
2366 ) {
2367 break;
2368 }
2369 }
2370
2371 rx.recv()
2372 .await
2373 .expect("model dropped with pending condition");
2374 }
2375 })
2376 .await
2377 .expect("condition timed out");
2378 }
2379 }
2380}
2381
2382impl<T> Clone for ModelHandle<T> {
2383 fn clone(&self) -> Self {
2384 self.ref_counts.lock().inc_model(self.model_id);
2385 Self {
2386 model_id: self.model_id,
2387 model_type: PhantomData,
2388 ref_counts: self.ref_counts.clone(),
2389 }
2390 }
2391}
2392
2393impl<T> PartialEq for ModelHandle<T> {
2394 fn eq(&self, other: &Self) -> bool {
2395 self.model_id == other.model_id
2396 }
2397}
2398
2399impl<T> Eq for ModelHandle<T> {}
2400
2401impl<T> Hash for ModelHandle<T> {
2402 fn hash<H: Hasher>(&self, state: &mut H) {
2403 self.model_id.hash(state);
2404 }
2405}
2406
2407impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2408 fn borrow(&self) -> &usize {
2409 &self.model_id
2410 }
2411}
2412
2413impl<T> Debug for ModelHandle<T> {
2414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2415 f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2416 .field(&self.model_id)
2417 .finish()
2418 }
2419}
2420
2421unsafe impl<T> Send for ModelHandle<T> {}
2422unsafe impl<T> Sync for ModelHandle<T> {}
2423
2424impl<T> Drop for ModelHandle<T> {
2425 fn drop(&mut self) {
2426 self.ref_counts.lock().dec_model(self.model_id);
2427 }
2428}
2429
2430impl<T: Entity> Handle<T> for ModelHandle<T> {
2431 type Weak = WeakModelHandle<T>;
2432
2433 fn id(&self) -> usize {
2434 self.model_id
2435 }
2436
2437 fn location(&self) -> EntityLocation {
2438 EntityLocation::Model(self.model_id)
2439 }
2440
2441 fn downgrade(&self) -> Self::Weak {
2442 self.downgrade()
2443 }
2444
2445 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2446 where
2447 Self: Sized,
2448 {
2449 weak.upgrade(cx)
2450 }
2451}
2452
2453pub struct WeakModelHandle<T> {
2454 model_id: usize,
2455 model_type: PhantomData<T>,
2456}
2457
2458unsafe impl<T> Send for WeakModelHandle<T> {}
2459unsafe impl<T> Sync for WeakModelHandle<T> {}
2460
2461impl<T: Entity> WeakModelHandle<T> {
2462 fn new(model_id: usize) -> Self {
2463 Self {
2464 model_id,
2465 model_type: PhantomData,
2466 }
2467 }
2468
2469 pub fn upgrade(self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2470 cx.upgrade_model_handle(self)
2471 }
2472}
2473
2474impl<T> Hash for WeakModelHandle<T> {
2475 fn hash<H: Hasher>(&self, state: &mut H) {
2476 self.model_id.hash(state)
2477 }
2478}
2479
2480impl<T> PartialEq for WeakModelHandle<T> {
2481 fn eq(&self, other: &Self) -> bool {
2482 self.model_id == other.model_id
2483 }
2484}
2485
2486impl<T> Eq for WeakModelHandle<T> {}
2487
2488impl<T> Clone for WeakModelHandle<T> {
2489 fn clone(&self) -> Self {
2490 Self {
2491 model_id: self.model_id,
2492 model_type: PhantomData,
2493 }
2494 }
2495}
2496
2497impl<T> Copy for WeakModelHandle<T> {}
2498
2499pub struct ViewHandle<T> {
2500 window_id: usize,
2501 view_id: usize,
2502 view_type: PhantomData<T>,
2503 ref_counts: Arc<Mutex<RefCounts>>,
2504}
2505
2506impl<T: View> ViewHandle<T> {
2507 fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2508 ref_counts.lock().inc_view(window_id, view_id);
2509 Self {
2510 window_id,
2511 view_id,
2512 view_type: PhantomData,
2513 ref_counts: ref_counts.clone(),
2514 }
2515 }
2516
2517 pub fn downgrade(&self) -> WeakViewHandle<T> {
2518 WeakViewHandle::new(self.window_id, self.view_id)
2519 }
2520
2521 pub fn window_id(&self) -> usize {
2522 self.window_id
2523 }
2524
2525 pub fn id(&self) -> usize {
2526 self.view_id
2527 }
2528
2529 pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2530 cx.read_view(self)
2531 }
2532
2533 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2534 where
2535 C: ReadViewWith,
2536 F: FnOnce(&T, &AppContext) -> S,
2537 {
2538 cx.read_view_with(self, read)
2539 }
2540
2541 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2542 where
2543 C: UpdateView,
2544 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2545 {
2546 cx.update_view(self, update)
2547 }
2548
2549 pub fn is_focused(&self, cx: &AppContext) -> bool {
2550 cx.focused_view_id(self.window_id)
2551 .map_or(false, |focused_id| focused_id == self.view_id)
2552 }
2553
2554 pub fn condition(
2555 &self,
2556 cx: &TestAppContext,
2557 mut predicate: impl FnMut(&T, &AppContext) -> bool,
2558 ) -> impl Future<Output = ()> {
2559 let (tx, mut rx) = mpsc::channel(1024);
2560
2561 let mut cx = cx.cx.borrow_mut();
2562 self.update(&mut *cx, |_, cx| {
2563 cx.observe(self, {
2564 let mut tx = tx.clone();
2565 move |_, _, _| {
2566 tx.blocking_send(()).ok();
2567 }
2568 });
2569
2570 cx.subscribe(self, {
2571 let mut tx = tx.clone();
2572 move |_, _, _, _| {
2573 tx.blocking_send(()).ok();
2574 }
2575 })
2576 });
2577
2578 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2579 let handle = self.downgrade();
2580 let duration = if std::env::var("CI").is_ok() {
2581 Duration::from_secs(2)
2582 } else {
2583 Duration::from_millis(500)
2584 };
2585
2586 async move {
2587 timeout(duration, async move {
2588 loop {
2589 {
2590 let cx = cx.borrow();
2591 let cx = cx.as_ref();
2592 if predicate(
2593 handle
2594 .upgrade(cx)
2595 .expect("view dropped with pending condition")
2596 .read(cx),
2597 cx,
2598 ) {
2599 break;
2600 }
2601 }
2602
2603 rx.recv()
2604 .await
2605 .expect("view dropped with pending condition");
2606 }
2607 })
2608 .await
2609 .expect("condition timed out");
2610 }
2611 }
2612}
2613
2614impl<T> Clone for ViewHandle<T> {
2615 fn clone(&self) -> Self {
2616 self.ref_counts
2617 .lock()
2618 .inc_view(self.window_id, self.view_id);
2619 Self {
2620 window_id: self.window_id,
2621 view_id: self.view_id,
2622 view_type: PhantomData,
2623 ref_counts: self.ref_counts.clone(),
2624 }
2625 }
2626}
2627
2628impl<T> PartialEq for ViewHandle<T> {
2629 fn eq(&self, other: &Self) -> bool {
2630 self.window_id == other.window_id && self.view_id == other.view_id
2631 }
2632}
2633
2634impl<T> Eq for ViewHandle<T> {}
2635
2636impl<T> Debug for ViewHandle<T> {
2637 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2638 f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2639 .field("window_id", &self.window_id)
2640 .field("view_id", &self.view_id)
2641 .finish()
2642 }
2643}
2644
2645impl<T> Drop for ViewHandle<T> {
2646 fn drop(&mut self) {
2647 self.ref_counts
2648 .lock()
2649 .dec_view(self.window_id, self.view_id);
2650 }
2651}
2652
2653impl<T: View> Handle<T> for ViewHandle<T> {
2654 type Weak = WeakViewHandle<T>;
2655
2656 fn id(&self) -> usize {
2657 self.view_id
2658 }
2659
2660 fn location(&self) -> EntityLocation {
2661 EntityLocation::View(self.window_id, self.view_id)
2662 }
2663
2664 fn downgrade(&self) -> Self::Weak {
2665 self.downgrade()
2666 }
2667
2668 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2669 where
2670 Self: Sized,
2671 {
2672 weak.upgrade(cx)
2673 }
2674}
2675
2676pub struct AnyViewHandle {
2677 window_id: usize,
2678 view_id: usize,
2679 view_type: TypeId,
2680 ref_counts: Arc<Mutex<RefCounts>>,
2681}
2682
2683impl AnyViewHandle {
2684 pub fn id(&self) -> usize {
2685 self.view_id
2686 }
2687
2688 pub fn is<T: 'static>(&self) -> bool {
2689 TypeId::of::<T>() == self.view_type
2690 }
2691
2692 pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2693 if self.is::<T>() {
2694 let result = Some(ViewHandle {
2695 window_id: self.window_id,
2696 view_id: self.view_id,
2697 ref_counts: self.ref_counts.clone(),
2698 view_type: PhantomData,
2699 });
2700 unsafe {
2701 Arc::decrement_strong_count(&self.ref_counts);
2702 }
2703 std::mem::forget(self);
2704 result
2705 } else {
2706 None
2707 }
2708 }
2709}
2710
2711impl Clone for AnyViewHandle {
2712 fn clone(&self) -> Self {
2713 self.ref_counts
2714 .lock()
2715 .inc_view(self.window_id, self.view_id);
2716 Self {
2717 window_id: self.window_id,
2718 view_id: self.view_id,
2719 view_type: self.view_type,
2720 ref_counts: self.ref_counts.clone(),
2721 }
2722 }
2723}
2724
2725impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2726 fn from(handle: &ViewHandle<T>) -> Self {
2727 handle
2728 .ref_counts
2729 .lock()
2730 .inc_view(handle.window_id, handle.view_id);
2731 AnyViewHandle {
2732 window_id: handle.window_id,
2733 view_id: handle.view_id,
2734 view_type: TypeId::of::<T>(),
2735 ref_counts: handle.ref_counts.clone(),
2736 }
2737 }
2738}
2739
2740impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2741 fn from(handle: ViewHandle<T>) -> Self {
2742 let any_handle = AnyViewHandle {
2743 window_id: handle.window_id,
2744 view_id: handle.view_id,
2745 view_type: TypeId::of::<T>(),
2746 ref_counts: handle.ref_counts.clone(),
2747 };
2748 unsafe {
2749 Arc::decrement_strong_count(&handle.ref_counts);
2750 }
2751 std::mem::forget(handle);
2752 any_handle
2753 }
2754}
2755
2756impl Drop for AnyViewHandle {
2757 fn drop(&mut self) {
2758 self.ref_counts
2759 .lock()
2760 .dec_view(self.window_id, self.view_id);
2761 }
2762}
2763
2764pub struct AnyModelHandle {
2765 model_id: usize,
2766 ref_counts: Arc<Mutex<RefCounts>>,
2767}
2768
2769impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2770 fn from(handle: ModelHandle<T>) -> Self {
2771 handle.ref_counts.lock().inc_model(handle.model_id);
2772 Self {
2773 model_id: handle.model_id,
2774 ref_counts: handle.ref_counts.clone(),
2775 }
2776 }
2777}
2778
2779impl Drop for AnyModelHandle {
2780 fn drop(&mut self) {
2781 self.ref_counts.lock().dec_model(self.model_id);
2782 }
2783}
2784pub struct WeakViewHandle<T> {
2785 window_id: usize,
2786 view_id: usize,
2787 view_type: PhantomData<T>,
2788}
2789
2790impl<T: View> WeakViewHandle<T> {
2791 fn new(window_id: usize, view_id: usize) -> Self {
2792 Self {
2793 window_id,
2794 view_id,
2795 view_type: PhantomData,
2796 }
2797 }
2798
2799 pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
2800 if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2801 Some(ViewHandle::new(
2802 self.window_id,
2803 self.view_id,
2804 &cx.ref_counts,
2805 ))
2806 } else {
2807 None
2808 }
2809 }
2810}
2811
2812impl<T> Clone for WeakViewHandle<T> {
2813 fn clone(&self) -> Self {
2814 Self {
2815 window_id: self.window_id,
2816 view_id: self.view_id,
2817 view_type: PhantomData,
2818 }
2819 }
2820}
2821
2822pub struct ValueHandle<T> {
2823 value_type: PhantomData<T>,
2824 tag_type_id: TypeId,
2825 id: usize,
2826 ref_counts: Weak<Mutex<RefCounts>>,
2827}
2828
2829impl<T: 'static> ValueHandle<T> {
2830 fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2831 ref_counts.lock().inc_value(tag_type_id, id);
2832 Self {
2833 value_type: PhantomData,
2834 tag_type_id,
2835 id,
2836 ref_counts: Arc::downgrade(ref_counts),
2837 }
2838 }
2839
2840 pub fn read<R>(&self, cx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2841 f(cx.values
2842 .read()
2843 .get(&(self.tag_type_id, self.id))
2844 .unwrap()
2845 .downcast_ref()
2846 .unwrap())
2847 }
2848
2849 pub fn update<R>(
2850 &self,
2851 cx: &mut EventContext,
2852 f: impl FnOnce(&mut T, &mut EventContext) -> R,
2853 ) -> R {
2854 let mut value = cx
2855 .app
2856 .cx
2857 .values
2858 .write()
2859 .remove(&(self.tag_type_id, self.id))
2860 .unwrap();
2861 let result = f(value.downcast_mut().unwrap(), cx);
2862 cx.app
2863 .cx
2864 .values
2865 .write()
2866 .insert((self.tag_type_id, self.id), value);
2867 result
2868 }
2869}
2870
2871impl<T> Drop for ValueHandle<T> {
2872 fn drop(&mut self) {
2873 if let Some(ref_counts) = self.ref_counts.upgrade() {
2874 ref_counts.lock().dec_value(self.tag_type_id, self.id);
2875 }
2876 }
2877}
2878
2879#[derive(Default)]
2880struct RefCounts {
2881 entity_counts: HashMap<usize, usize>,
2882 value_counts: HashMap<(TypeId, usize), usize>,
2883 dropped_models: HashSet<usize>,
2884 dropped_views: HashSet<(usize, usize)>,
2885 dropped_values: HashSet<(TypeId, usize)>,
2886}
2887
2888impl RefCounts {
2889 fn inc_model(&mut self, model_id: usize) {
2890 match self.entity_counts.entry(model_id) {
2891 Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2892 Entry::Vacant(entry) => {
2893 entry.insert(1);
2894 self.dropped_models.remove(&model_id);
2895 }
2896 }
2897 }
2898
2899 fn inc_view(&mut self, window_id: usize, view_id: usize) {
2900 match self.entity_counts.entry(view_id) {
2901 Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2902 Entry::Vacant(entry) => {
2903 entry.insert(1);
2904 self.dropped_views.remove(&(window_id, view_id));
2905 }
2906 }
2907 }
2908
2909 fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
2910 *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
2911 }
2912
2913 fn dec_model(&mut self, model_id: usize) {
2914 let count = self.entity_counts.get_mut(&model_id).unwrap();
2915 *count -= 1;
2916 if *count == 0 {
2917 self.entity_counts.remove(&model_id);
2918 self.dropped_models.insert(model_id);
2919 }
2920 }
2921
2922 fn dec_view(&mut self, window_id: usize, view_id: usize) {
2923 let count = self.entity_counts.get_mut(&view_id).unwrap();
2924 *count -= 1;
2925 if *count == 0 {
2926 self.entity_counts.remove(&view_id);
2927 self.dropped_views.insert((window_id, view_id));
2928 }
2929 }
2930
2931 fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
2932 let key = (tag_type_id, id);
2933 let count = self.value_counts.get_mut(&key).unwrap();
2934 *count -= 1;
2935 if *count == 0 {
2936 self.value_counts.remove(&key);
2937 self.dropped_values.insert(key);
2938 }
2939 }
2940
2941 fn is_entity_alive(&self, entity_id: usize) -> bool {
2942 self.entity_counts.contains_key(&entity_id)
2943 }
2944
2945 fn take_dropped(
2946 &mut self,
2947 ) -> (
2948 HashSet<usize>,
2949 HashSet<(usize, usize)>,
2950 HashSet<(TypeId, usize)>,
2951 ) {
2952 let mut dropped_models = HashSet::new();
2953 let mut dropped_views = HashSet::new();
2954 let mut dropped_values = HashSet::new();
2955 std::mem::swap(&mut self.dropped_models, &mut dropped_models);
2956 std::mem::swap(&mut self.dropped_views, &mut dropped_views);
2957 std::mem::swap(&mut self.dropped_values, &mut dropped_values);
2958 (dropped_models, dropped_views, dropped_values)
2959 }
2960}
2961
2962#[cfg(test)]
2963mod tests {
2964 use super::*;
2965 use crate::elements::*;
2966 use smol::future::poll_once;
2967 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
2968
2969 #[crate::test(self)]
2970 fn test_model_handles(cx: &mut MutableAppContext) {
2971 struct Model {
2972 other: Option<ModelHandle<Model>>,
2973 events: Vec<String>,
2974 }
2975
2976 impl Entity for Model {
2977 type Event = usize;
2978 }
2979
2980 impl Model {
2981 fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
2982 if let Some(other) = other.as_ref() {
2983 cx.observe(other, |me, _, _| {
2984 me.events.push("notified".into());
2985 });
2986 cx.subscribe(other, |me, _, event, _| {
2987 me.events.push(format!("observed event {}", event));
2988 });
2989 }
2990
2991 Self {
2992 other,
2993 events: Vec::new(),
2994 }
2995 }
2996 }
2997
2998 let handle_1 = cx.add_model(|cx| Model::new(None, cx));
2999 let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3000 assert_eq!(cx.cx.models.len(), 2);
3001
3002 handle_1.update(cx, |model, cx| {
3003 model.events.push("updated".into());
3004 cx.emit(1);
3005 cx.notify();
3006 cx.emit(2);
3007 });
3008 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3009 assert_eq!(
3010 handle_2.read(cx).events,
3011 vec![
3012 "observed event 1".to_string(),
3013 "notified".to_string(),
3014 "observed event 2".to_string(),
3015 ]
3016 );
3017
3018 handle_2.update(cx, |model, _| {
3019 drop(handle_1);
3020 model.other.take();
3021 });
3022
3023 assert_eq!(cx.cx.models.len(), 1);
3024 assert!(cx.subscriptions.is_empty());
3025 assert!(cx.observations.is_empty());
3026 }
3027
3028 #[crate::test(self)]
3029 fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3030 #[derive(Default)]
3031 struct Model {
3032 events: Vec<usize>,
3033 }
3034
3035 impl Entity for Model {
3036 type Event = usize;
3037 }
3038
3039 let handle_1 = cx.add_model(|_| Model::default());
3040 let handle_2 = cx.add_model(|_| Model::default());
3041 let handle_2b = handle_2.clone();
3042
3043 handle_1.update(cx, |_, c| {
3044 c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
3045 model.events.push(*event);
3046
3047 c.subscribe(&handle_2b, |model, _, event, _| {
3048 model.events.push(*event * 2);
3049 });
3050 });
3051 });
3052
3053 handle_2.update(cx, |_, c| c.emit(7));
3054 assert_eq!(handle_1.read(cx).events, vec![7]);
3055
3056 handle_2.update(cx, |_, c| c.emit(5));
3057 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
3058 }
3059
3060 #[crate::test(self)]
3061 fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3062 #[derive(Default)]
3063 struct Model {
3064 count: usize,
3065 events: Vec<usize>,
3066 }
3067
3068 impl Entity for Model {
3069 type Event = ();
3070 }
3071
3072 let handle_1 = cx.add_model(|_| Model::default());
3073 let handle_2 = cx.add_model(|_| Model::default());
3074 let handle_2b = handle_2.clone();
3075
3076 handle_1.update(cx, |_, c| {
3077 c.observe(&handle_2, move |model, observed, c| {
3078 model.events.push(observed.read(c).count);
3079 c.observe(&handle_2b, |model, observed, c| {
3080 model.events.push(observed.read(c).count * 2);
3081 });
3082 });
3083 });
3084
3085 handle_2.update(cx, |model, c| {
3086 model.count = 7;
3087 c.notify()
3088 });
3089 assert_eq!(handle_1.read(cx).events, vec![7]);
3090
3091 handle_2.update(cx, |model, c| {
3092 model.count = 5;
3093 c.notify()
3094 });
3095 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5])
3096 }
3097
3098 #[crate::test(self)]
3099 fn test_view_handles(cx: &mut MutableAppContext) {
3100 struct View {
3101 other: Option<ViewHandle<View>>,
3102 events: Vec<String>,
3103 }
3104
3105 impl Entity for View {
3106 type Event = usize;
3107 }
3108
3109 impl super::View for View {
3110 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3111 Empty::new().boxed()
3112 }
3113
3114 fn ui_name() -> &'static str {
3115 "View"
3116 }
3117 }
3118
3119 impl View {
3120 fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3121 if let Some(other) = other.as_ref() {
3122 cx.subscribe(other, |me, _, event, _| {
3123 me.events.push(format!("observed event {}", event));
3124 });
3125 }
3126 Self {
3127 other,
3128 events: Vec::new(),
3129 }
3130 }
3131 }
3132
3133 let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3134 let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3135 let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3136 assert_eq!(cx.cx.views.len(), 3);
3137
3138 handle_1.update(cx, |view, cx| {
3139 view.events.push("updated".into());
3140 cx.emit(1);
3141 cx.emit(2);
3142 });
3143 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3144 assert_eq!(
3145 handle_2.read(cx).events,
3146 vec![
3147 "observed event 1".to_string(),
3148 "observed event 2".to_string(),
3149 ]
3150 );
3151
3152 handle_2.update(cx, |view, _| {
3153 drop(handle_1);
3154 view.other.take();
3155 });
3156
3157 assert_eq!(cx.cx.views.len(), 2);
3158 assert!(cx.subscriptions.is_empty());
3159 assert!(cx.observations.is_empty());
3160 }
3161
3162 #[crate::test(self)]
3163 fn test_add_window(cx: &mut MutableAppContext) {
3164 struct View {
3165 mouse_down_count: Arc<AtomicUsize>,
3166 }
3167
3168 impl Entity for View {
3169 type Event = ();
3170 }
3171
3172 impl super::View for View {
3173 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3174 let mouse_down_count = self.mouse_down_count.clone();
3175 EventHandler::new(Empty::new().boxed())
3176 .on_mouse_down(move |_| {
3177 mouse_down_count.fetch_add(1, SeqCst);
3178 true
3179 })
3180 .boxed()
3181 }
3182
3183 fn ui_name() -> &'static str {
3184 "View"
3185 }
3186 }
3187
3188 let mouse_down_count = Arc::new(AtomicUsize::new(0));
3189 let (window_id, _) = cx.add_window(Default::default(), |_| View {
3190 mouse_down_count: mouse_down_count.clone(),
3191 });
3192 let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3193 // Ensure window's root element is in a valid lifecycle state.
3194 presenter.borrow_mut().dispatch_event(
3195 Event::LeftMouseDown {
3196 position: Default::default(),
3197 cmd: false,
3198 },
3199 cx,
3200 );
3201 assert_eq!(mouse_down_count.load(SeqCst), 1);
3202 }
3203
3204 #[crate::test(self)]
3205 fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3206 struct Model {
3207 released: Arc<Mutex<bool>>,
3208 }
3209
3210 struct View {
3211 released: Arc<Mutex<bool>>,
3212 }
3213
3214 impl Entity for Model {
3215 type Event = ();
3216
3217 fn release(&mut self, _: &mut MutableAppContext) {
3218 *self.released.lock() = true;
3219 }
3220 }
3221
3222 impl Entity for View {
3223 type Event = ();
3224
3225 fn release(&mut self, _: &mut MutableAppContext) {
3226 *self.released.lock() = true;
3227 }
3228 }
3229
3230 impl super::View for View {
3231 fn ui_name() -> &'static str {
3232 "View"
3233 }
3234
3235 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3236 Empty::new().boxed()
3237 }
3238 }
3239
3240 let model_released = Arc::new(Mutex::new(false));
3241 let view_released = Arc::new(Mutex::new(false));
3242
3243 let model = cx.add_model(|_| Model {
3244 released: model_released.clone(),
3245 });
3246
3247 let (window_id, _) = cx.add_window(Default::default(), |_| View {
3248 released: view_released.clone(),
3249 });
3250
3251 assert!(!*model_released.lock());
3252 assert!(!*view_released.lock());
3253
3254 cx.update(move || {
3255 drop(model);
3256 });
3257 assert!(*model_released.lock());
3258
3259 drop(cx.remove_window(window_id));
3260 assert!(*view_released.lock());
3261 }
3262
3263 #[crate::test(self)]
3264 fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3265 #[derive(Default)]
3266 struct View {
3267 events: Vec<usize>,
3268 }
3269
3270 impl Entity for View {
3271 type Event = usize;
3272 }
3273
3274 impl super::View for View {
3275 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3276 Empty::new().boxed()
3277 }
3278
3279 fn ui_name() -> &'static str {
3280 "View"
3281 }
3282 }
3283
3284 struct Model;
3285
3286 impl Entity for Model {
3287 type Event = usize;
3288 }
3289
3290 let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3291 let handle_2 = cx.add_view(window_id, |_| View::default());
3292 let handle_2b = handle_2.clone();
3293 let handle_3 = cx.add_model(|_| Model);
3294
3295 handle_1.update(cx, |_, c| {
3296 c.subscribe(&handle_2, move |me, _, event, c| {
3297 me.events.push(*event);
3298
3299 c.subscribe(&handle_2b, |me, _, event, _| {
3300 me.events.push(*event * 2);
3301 });
3302 });
3303
3304 c.subscribe(&handle_3, |me, _, event, _| {
3305 me.events.push(*event);
3306 })
3307 });
3308
3309 handle_2.update(cx, |_, c| c.emit(7));
3310 assert_eq!(handle_1.read(cx).events, vec![7]);
3311
3312 handle_2.update(cx, |_, c| c.emit(5));
3313 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
3314
3315 handle_3.update(cx, |_, c| c.emit(9));
3316 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5, 9]);
3317 }
3318
3319 #[crate::test(self)]
3320 fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3321 struct View;
3322
3323 impl Entity for View {
3324 type Event = ();
3325 }
3326
3327 impl super::View for View {
3328 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3329 Empty::new().boxed()
3330 }
3331
3332 fn ui_name() -> &'static str {
3333 "View"
3334 }
3335 }
3336
3337 struct Model;
3338
3339 impl Entity for Model {
3340 type Event = ();
3341 }
3342
3343 let (window_id, _) = cx.add_window(Default::default(), |_| View);
3344 let observing_view = cx.add_view(window_id, |_| View);
3345 let emitting_view = cx.add_view(window_id, |_| View);
3346 let observing_model = cx.add_model(|_| Model);
3347 let observed_model = cx.add_model(|_| Model);
3348
3349 observing_view.update(cx, |_, cx| {
3350 cx.subscribe(&emitting_view, |_, _, _, _| {});
3351 cx.subscribe(&observed_model, |_, _, _, _| {});
3352 });
3353 observing_model.update(cx, |_, cx| {
3354 cx.subscribe(&observed_model, |_, _, _, _| {});
3355 });
3356
3357 cx.update(|| {
3358 drop(observing_view);
3359 drop(observing_model);
3360 });
3361
3362 emitting_view.update(cx, |_, cx| cx.emit(()));
3363 observed_model.update(cx, |_, cx| cx.emit(()));
3364 }
3365
3366 #[crate::test(self)]
3367 fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3368 #[derive(Default)]
3369 struct View {
3370 events: Vec<usize>,
3371 }
3372
3373 impl Entity for View {
3374 type Event = usize;
3375 }
3376
3377 impl super::View for View {
3378 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3379 Empty::new().boxed()
3380 }
3381
3382 fn ui_name() -> &'static str {
3383 "View"
3384 }
3385 }
3386
3387 #[derive(Default)]
3388 struct Model {
3389 count: usize,
3390 }
3391
3392 impl Entity for Model {
3393 type Event = ();
3394 }
3395
3396 let (_, view) = cx.add_window(Default::default(), |_| View::default());
3397 let model = cx.add_model(|_| Model::default());
3398
3399 view.update(cx, |_, c| {
3400 c.observe(&model, |me, observed, c| {
3401 me.events.push(observed.read(c).count)
3402 });
3403 });
3404
3405 model.update(cx, |model, c| {
3406 model.count = 11;
3407 c.notify();
3408 });
3409 assert_eq!(view.read(cx).events, vec![11]);
3410 }
3411
3412 #[crate::test(self)]
3413 fn test_dropping_observers(cx: &mut MutableAppContext) {
3414 struct View;
3415
3416 impl Entity for View {
3417 type Event = ();
3418 }
3419
3420 impl super::View for View {
3421 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3422 Empty::new().boxed()
3423 }
3424
3425 fn ui_name() -> &'static str {
3426 "View"
3427 }
3428 }
3429
3430 struct Model;
3431
3432 impl Entity for Model {
3433 type Event = ();
3434 }
3435
3436 let (window_id, _) = cx.add_window(Default::default(), |_| View);
3437 let observing_view = cx.add_view(window_id, |_| View);
3438 let observing_model = cx.add_model(|_| Model);
3439 let observed_model = cx.add_model(|_| Model);
3440
3441 observing_view.update(cx, |_, cx| {
3442 cx.observe(&observed_model, |_, _, _| {});
3443 });
3444 observing_model.update(cx, |_, cx| {
3445 cx.observe(&observed_model, |_, _, _| {});
3446 });
3447
3448 cx.update(|| {
3449 drop(observing_view);
3450 drop(observing_model);
3451 });
3452
3453 observed_model.update(cx, |_, cx| cx.notify());
3454 }
3455
3456 #[crate::test(self)]
3457 fn test_focus(cx: &mut MutableAppContext) {
3458 struct View {
3459 name: String,
3460 events: Arc<Mutex<Vec<String>>>,
3461 }
3462
3463 impl Entity for View {
3464 type Event = ();
3465 }
3466
3467 impl super::View for View {
3468 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3469 Empty::new().boxed()
3470 }
3471
3472 fn ui_name() -> &'static str {
3473 "View"
3474 }
3475
3476 fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3477 self.events.lock().push(format!("{} focused", &self.name));
3478 }
3479
3480 fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3481 self.events.lock().push(format!("{} blurred", &self.name));
3482 }
3483 }
3484
3485 let events: Arc<Mutex<Vec<String>>> = Default::default();
3486 let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
3487 events: events.clone(),
3488 name: "view 1".to_string(),
3489 });
3490 let view_2 = cx.add_view(window_id, |_| View {
3491 events: events.clone(),
3492 name: "view 2".to_string(),
3493 });
3494
3495 view_1.update(cx, |_, cx| cx.focus(&view_2));
3496 view_1.update(cx, |_, cx| cx.focus(&view_1));
3497 view_1.update(cx, |_, cx| cx.focus(&view_2));
3498 view_1.update(cx, |_, _| drop(view_2));
3499
3500 assert_eq!(
3501 *events.lock(),
3502 [
3503 "view 1 focused".to_string(),
3504 "view 1 blurred".to_string(),
3505 "view 2 focused".to_string(),
3506 "view 2 blurred".to_string(),
3507 "view 1 focused".to_string(),
3508 "view 1 blurred".to_string(),
3509 "view 2 focused".to_string(),
3510 "view 1 focused".to_string(),
3511 ],
3512 );
3513 }
3514
3515 #[crate::test(self)]
3516 fn test_dispatch_action(cx: &mut MutableAppContext) {
3517 struct ViewA {
3518 id: usize,
3519 }
3520
3521 impl Entity for ViewA {
3522 type Event = ();
3523 }
3524
3525 impl View for ViewA {
3526 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3527 Empty::new().boxed()
3528 }
3529
3530 fn ui_name() -> &'static str {
3531 "View"
3532 }
3533 }
3534
3535 struct ViewB {
3536 id: usize,
3537 }
3538
3539 impl Entity for ViewB {
3540 type Event = ();
3541 }
3542
3543 impl View for ViewB {
3544 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3545 Empty::new().boxed()
3546 }
3547
3548 fn ui_name() -> &'static str {
3549 "View"
3550 }
3551 }
3552
3553 action!(Action, &'static str);
3554
3555 let actions = Rc::new(RefCell::new(Vec::new()));
3556
3557 let actions_clone = actions.clone();
3558 cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3559 actions_clone.borrow_mut().push("global a".to_string());
3560 });
3561
3562 let actions_clone = actions.clone();
3563 cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3564 actions_clone.borrow_mut().push("global b".to_string());
3565 });
3566
3567 let actions_clone = actions.clone();
3568 cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
3569 assert_eq!(action.0, "bar");
3570 cx.propagate_action();
3571 actions_clone.borrow_mut().push(format!("{} a", view.id));
3572 });
3573
3574 let actions_clone = actions.clone();
3575 cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
3576 if view.id != 1 {
3577 cx.propagate_action();
3578 }
3579 actions_clone.borrow_mut().push(format!("{} b", view.id));
3580 });
3581
3582 let actions_clone = actions.clone();
3583 cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3584 cx.propagate_action();
3585 actions_clone.borrow_mut().push(format!("{} c", view.id));
3586 });
3587
3588 let actions_clone = actions.clone();
3589 cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3590 cx.propagate_action();
3591 actions_clone.borrow_mut().push(format!("{} d", view.id));
3592 });
3593
3594 let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
3595 let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3596 let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3597 let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3598
3599 cx.dispatch_action(
3600 window_id,
3601 vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3602 &Action("bar"),
3603 );
3604
3605 assert_eq!(
3606 *actions.borrow(),
3607 vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3608 );
3609
3610 // Remove view_1, which doesn't propagate the action
3611 actions.borrow_mut().clear();
3612 cx.dispatch_action(
3613 window_id,
3614 vec![view_2.id(), view_3.id(), view_4.id()],
3615 &Action("bar"),
3616 );
3617
3618 assert_eq!(
3619 *actions.borrow(),
3620 vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3621 );
3622 }
3623
3624 #[crate::test(self)]
3625 fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3626 use std::cell::Cell;
3627
3628 action!(Action, &'static str);
3629
3630 struct View {
3631 id: usize,
3632 keymap_context: keymap::Context,
3633 }
3634
3635 impl Entity for View {
3636 type Event = ();
3637 }
3638
3639 impl super::View for View {
3640 fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3641 Empty::new().boxed()
3642 }
3643
3644 fn ui_name() -> &'static str {
3645 "View"
3646 }
3647
3648 fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3649 self.keymap_context.clone()
3650 }
3651 }
3652
3653 impl View {
3654 fn new(id: usize) -> Self {
3655 View {
3656 id,
3657 keymap_context: keymap::Context::default(),
3658 }
3659 }
3660 }
3661
3662 let mut view_1 = View::new(1);
3663 let mut view_2 = View::new(2);
3664 let mut view_3 = View::new(3);
3665 view_1.keymap_context.set.insert("a".into());
3666 view_2.keymap_context.set.insert("b".into());
3667 view_3.keymap_context.set.insert("c".into());
3668
3669 let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
3670 let view_2 = cx.add_view(window_id, |_| view_2);
3671 let view_3 = cx.add_view(window_id, |_| view_3);
3672
3673 // This keymap's only binding dispatches an action on view 2 because that view will have
3674 // "a" and "b" in its context, but not "c".
3675 cx.add_bindings(vec![keymap::Binding::new(
3676 "a",
3677 Action("a"),
3678 Some("a && b && !c"),
3679 )]);
3680
3681 let handled_action = Rc::new(Cell::new(false));
3682 let handled_action_clone = handled_action.clone();
3683 cx.add_action(move |view: &mut View, action: &Action, _| {
3684 handled_action_clone.set(true);
3685 assert_eq!(view.id, 2);
3686 assert_eq!(action.0, "a");
3687 });
3688
3689 cx.dispatch_keystroke(
3690 window_id,
3691 vec![view_1.id(), view_2.id(), view_3.id()],
3692 &Keystroke::parse("a").unwrap(),
3693 )
3694 .unwrap();
3695
3696 assert!(handled_action.get());
3697 }
3698
3699 #[crate::test(self)]
3700 async fn test_model_condition(mut cx: TestAppContext) {
3701 struct Counter(usize);
3702
3703 impl super::Entity for Counter {
3704 type Event = ();
3705 }
3706
3707 impl Counter {
3708 fn inc(&mut self, cx: &mut ModelContext<Self>) {
3709 self.0 += 1;
3710 cx.notify();
3711 }
3712 }
3713
3714 let model = cx.add_model(|_| Counter(0));
3715
3716 let condition1 = model.condition(&cx, |model, _| model.0 == 2);
3717 let condition2 = model.condition(&cx, |model, _| model.0 == 3);
3718 smol::pin!(condition1, condition2);
3719
3720 model.update(&mut cx, |model, cx| model.inc(cx));
3721 assert_eq!(poll_once(&mut condition1).await, None);
3722 assert_eq!(poll_once(&mut condition2).await, None);
3723
3724 model.update(&mut cx, |model, cx| model.inc(cx));
3725 assert_eq!(poll_once(&mut condition1).await, Some(()));
3726 assert_eq!(poll_once(&mut condition2).await, None);
3727
3728 model.update(&mut cx, |model, cx| model.inc(cx));
3729 assert_eq!(poll_once(&mut condition2).await, Some(()));
3730
3731 model.update(&mut cx, |_, cx| cx.notify());
3732 }
3733
3734 #[crate::test(self)]
3735 #[should_panic]
3736 async fn test_model_condition_timeout(mut cx: TestAppContext) {
3737 struct Model;
3738
3739 impl super::Entity for Model {
3740 type Event = ();
3741 }
3742
3743 let model = cx.add_model(|_| Model);
3744 model.condition(&cx, |_, _| false).await;
3745 }
3746
3747 #[crate::test(self)]
3748 #[should_panic(expected = "model dropped with pending condition")]
3749 async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
3750 struct Model;
3751
3752 impl super::Entity for Model {
3753 type Event = ();
3754 }
3755
3756 let model = cx.add_model(|_| Model);
3757 let condition = model.condition(&cx, |_, _| false);
3758 cx.update(|_| drop(model));
3759 condition.await;
3760 }
3761
3762 #[crate::test(self)]
3763 async fn test_view_condition(mut cx: TestAppContext) {
3764 struct Counter(usize);
3765
3766 impl super::Entity for Counter {
3767 type Event = ();
3768 }
3769
3770 impl super::View for Counter {
3771 fn ui_name() -> &'static str {
3772 "test view"
3773 }
3774
3775 fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3776 Empty::new().boxed()
3777 }
3778 }
3779
3780 impl Counter {
3781 fn inc(&mut self, cx: &mut ViewContext<Self>) {
3782 self.0 += 1;
3783 cx.notify();
3784 }
3785 }
3786
3787 let (_, view) = cx.add_window(|_| Counter(0));
3788
3789 let condition1 = view.condition(&cx, |view, _| view.0 == 2);
3790 let condition2 = view.condition(&cx, |view, _| view.0 == 3);
3791 smol::pin!(condition1, condition2);
3792
3793 view.update(&mut cx, |view, cx| view.inc(cx));
3794 assert_eq!(poll_once(&mut condition1).await, None);
3795 assert_eq!(poll_once(&mut condition2).await, None);
3796
3797 view.update(&mut cx, |view, cx| view.inc(cx));
3798 assert_eq!(poll_once(&mut condition1).await, Some(()));
3799 assert_eq!(poll_once(&mut condition2).await, None);
3800
3801 view.update(&mut cx, |view, cx| view.inc(cx));
3802 assert_eq!(poll_once(&mut condition2).await, Some(()));
3803 view.update(&mut cx, |_, cx| cx.notify());
3804 }
3805
3806 #[crate::test(self)]
3807 #[should_panic]
3808 async fn test_view_condition_timeout(mut cx: TestAppContext) {
3809 struct View;
3810
3811 impl super::Entity for View {
3812 type Event = ();
3813 }
3814
3815 impl super::View for View {
3816 fn ui_name() -> &'static str {
3817 "test view"
3818 }
3819
3820 fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3821 Empty::new().boxed()
3822 }
3823 }
3824
3825 let (_, view) = cx.add_window(|_| View);
3826 view.condition(&cx, |_, _| false).await;
3827 }
3828
3829 #[crate::test(self)]
3830 #[should_panic(expected = "view dropped with pending condition")]
3831 async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
3832 struct View;
3833
3834 impl super::Entity for View {
3835 type Event = ();
3836 }
3837
3838 impl super::View for View {
3839 fn ui_name() -> &'static str {
3840 "test view"
3841 }
3842
3843 fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3844 Empty::new().boxed()
3845 }
3846 }
3847
3848 let window_id = cx.add_window(|_| View).0;
3849 let view = cx.add_view(window_id, |_| View);
3850
3851 let condition = view.condition(&cx, |_, _| false);
3852 cx.update(|_| drop(view));
3853 condition.await;
3854 }
3855}