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