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