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