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