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