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