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
1853pub struct ViewContext<'a, T: ?Sized> {
1854 app: &'a mut MutableAppContext,
1855 window_id: usize,
1856 view_id: usize,
1857 view_type: PhantomData<T>,
1858 halt_action_dispatch: bool,
1859}
1860
1861impl<'a, T: View> ViewContext<'a, T> {
1862 fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
1863 Self {
1864 app,
1865 window_id,
1866 view_id,
1867 view_type: PhantomData,
1868 halt_action_dispatch: true,
1869 }
1870 }
1871
1872 pub fn handle(&self) -> ViewHandle<T> {
1873 ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
1874 }
1875
1876 pub fn window_id(&self) -> usize {
1877 self.window_id
1878 }
1879
1880 pub fn view_id(&self) -> usize {
1881 self.view_id
1882 }
1883
1884 pub fn foreground(&self) -> &Rc<executor::Foreground> {
1885 self.app.foreground()
1886 }
1887
1888 pub fn background_executor(&self) -> &Arc<executor::Background> {
1889 &self.app.cx.background
1890 }
1891
1892 pub fn platform(&self) -> Arc<dyn Platform> {
1893 self.app.platform()
1894 }
1895
1896 pub fn prompt<F>(&self, level: PromptLevel, msg: &str, answers: &[&str], done_fn: F)
1897 where
1898 F: 'static + FnOnce(usize, &mut MutableAppContext),
1899 {
1900 self.app
1901 .prompt(self.window_id, level, msg, answers, done_fn)
1902 }
1903
1904 pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
1905 where
1906 F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
1907 {
1908 self.app.prompt_for_paths(options, done_fn)
1909 }
1910
1911 pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
1912 where
1913 F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
1914 {
1915 self.app.prompt_for_new_path(directory, done_fn)
1916 }
1917
1918 pub fn debug_elements(&self) -> crate::json::Value {
1919 self.app.debug_elements(self.window_id).unwrap()
1920 }
1921
1922 pub fn focus<S>(&mut self, handle: S)
1923 where
1924 S: Into<AnyViewHandle>,
1925 {
1926 let handle = handle.into();
1927 self.app.pending_effects.push_back(Effect::Focus {
1928 window_id: handle.window_id,
1929 view_id: handle.view_id,
1930 });
1931 }
1932
1933 pub fn focus_self(&mut self) {
1934 self.app.pending_effects.push_back(Effect::Focus {
1935 window_id: self.window_id,
1936 view_id: self.view_id,
1937 });
1938 }
1939
1940 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1941 where
1942 S: Entity,
1943 F: FnOnce(&mut ModelContext<S>) -> S,
1944 {
1945 self.app.add_model(build_model)
1946 }
1947
1948 pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
1949 where
1950 S: View,
1951 F: FnOnce(&mut ViewContext<S>) -> S,
1952 {
1953 self.app.add_view(self.window_id, build_view)
1954 }
1955
1956 pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
1957 where
1958 S: View,
1959 F: FnOnce(&mut ViewContext<S>) -> Option<S>,
1960 {
1961 self.app.add_option_view(self.window_id, build_view)
1962 }
1963
1964 pub fn subscribe_to_model<E, F>(&mut self, handle: &ModelHandle<E>, mut callback: F)
1965 where
1966 E: Entity,
1967 E::Event: 'static,
1968 F: 'static + FnMut(&mut T, ModelHandle<E>, &E::Event, &mut ViewContext<T>),
1969 {
1970 let emitter_handle = handle.downgrade();
1971 self.subscribe(handle, move |model, payload, cx| {
1972 if let Some(emitter_handle) = emitter_handle.upgrade(cx.as_ref()) {
1973 callback(model, emitter_handle, payload, cx);
1974 }
1975 });
1976 }
1977
1978 pub fn subscribe_to_view<V, F>(&mut self, handle: &ViewHandle<V>, mut callback: F)
1979 where
1980 V: View,
1981 V::Event: 'static,
1982 F: 'static + FnMut(&mut T, ViewHandle<V>, &V::Event, &mut ViewContext<T>),
1983 {
1984 let emitter_handle = handle.downgrade();
1985 self.subscribe(handle, move |view, payload, cx| {
1986 if let Some(emitter_handle) = emitter_handle.upgrade(cx.as_ref()) {
1987 callback(view, emitter_handle, payload, cx);
1988 }
1989 });
1990 }
1991
1992 pub fn subscribe<E, F>(&mut self, handle: &impl Handle<E>, mut callback: F)
1993 where
1994 E: Entity,
1995 E::Event: 'static,
1996 F: 'static + FnMut(&mut T, &E::Event, &mut ViewContext<T>),
1997 {
1998 self.app
1999 .subscriptions
2000 .entry(handle.id())
2001 .or_default()
2002 .push(Subscription::FromView {
2003 window_id: self.window_id,
2004 view_id: self.view_id,
2005 callback: Box::new(move |entity, payload, app, window_id, view_id| {
2006 let entity = entity.downcast_mut().expect("downcast is type safe");
2007 let payload = payload.downcast_ref().expect("downcast is type safe");
2008 let mut cx = ViewContext::new(app, window_id, view_id);
2009 callback(entity, payload, &mut cx);
2010 }),
2011 });
2012 }
2013
2014 pub fn emit(&mut self, payload: T::Event) {
2015 self.app.pending_effects.push_back(Effect::Event {
2016 entity_id: self.view_id,
2017 payload: Box::new(payload),
2018 });
2019 }
2020
2021 pub fn observe_model<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
2022 where
2023 S: Entity,
2024 F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ViewContext<T>),
2025 {
2026 self.app
2027 .model_observations
2028 .entry(handle.id())
2029 .or_default()
2030 .push(ModelObservation::FromView {
2031 window_id: self.window_id,
2032 view_id: self.view_id,
2033 callback: Box::new(move |view, observed_id, app, window_id, view_id| {
2034 let view = view.downcast_mut().expect("downcast is type safe");
2035 let observed = ModelHandle::new(observed_id, &app.cx.ref_counts);
2036 let mut cx = ViewContext::new(app, window_id, view_id);
2037 callback(view, observed, &mut cx);
2038 }),
2039 });
2040 }
2041
2042 pub fn observe_view<S, F>(&mut self, handle: &ViewHandle<S>, mut callback: F)
2043 where
2044 S: View,
2045 F: 'static + FnMut(&mut T, ViewHandle<S>, &mut ViewContext<T>),
2046 {
2047 self.app
2048 .view_observations
2049 .entry(handle.id())
2050 .or_default()
2051 .push(ViewObservation {
2052 window_id: self.window_id,
2053 view_id: self.view_id,
2054 callback: Box::new(
2055 move |view,
2056 observed_view_id,
2057 observed_window_id,
2058 app,
2059 observing_window_id,
2060 observing_view_id| {
2061 let view = view.downcast_mut().expect("downcast is type safe");
2062 let observed_handle = ViewHandle::new(
2063 observed_view_id,
2064 observed_window_id,
2065 &app.cx.ref_counts,
2066 );
2067 let mut cx = ViewContext::new(app, observing_window_id, observing_view_id);
2068 callback(view, observed_handle, &mut cx);
2069 },
2070 ),
2071 });
2072 }
2073
2074 pub fn notify(&mut self) {
2075 self.app.notify_view(self.window_id, self.view_id);
2076 }
2077
2078 pub fn propagate_action(&mut self) {
2079 self.halt_action_dispatch = false;
2080 }
2081
2082 pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2083 where
2084 F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2085 Fut: 'static + Future<Output = S>,
2086 S: 'static,
2087 {
2088 let handle = self.handle();
2089 self.app.spawn(|cx| f(handle, cx))
2090 }
2091}
2092
2093impl AsRef<AppContext> for &AppContext {
2094 fn as_ref(&self) -> &AppContext {
2095 self
2096 }
2097}
2098
2099impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2100 fn as_ref(&self) -> &AppContext {
2101 &self.app.cx
2102 }
2103}
2104
2105impl<M> Deref for ViewContext<'_, M> {
2106 type Target = MutableAppContext;
2107
2108 fn deref(&self) -> &Self::Target {
2109 &self.app
2110 }
2111}
2112
2113impl<M> DerefMut for ViewContext<'_, M> {
2114 fn deref_mut(&mut self) -> &mut Self::Target {
2115 &mut self.app
2116 }
2117}
2118
2119impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2120 fn as_mut(&mut self) -> &mut MutableAppContext {
2121 self.app
2122 }
2123}
2124
2125impl<V> ReadModel for ViewContext<'_, V> {
2126 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2127 self.app.read_model(handle)
2128 }
2129}
2130
2131impl<V: View> UpdateModel for ViewContext<'_, V> {
2132 fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2133 where
2134 T: Entity,
2135 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2136 {
2137 self.app.update_model(handle, update)
2138 }
2139}
2140
2141impl<V: View> ReadView for ViewContext<'_, V> {
2142 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2143 self.app.read_view(handle)
2144 }
2145}
2146
2147impl<V: View> UpdateView for ViewContext<'_, V> {
2148 fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
2149 where
2150 T: View,
2151 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2152 {
2153 self.app.update_view(handle, update)
2154 }
2155}
2156
2157pub trait Handle<T> {
2158 fn id(&self) -> usize;
2159 fn location(&self) -> EntityLocation;
2160}
2161
2162#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2163pub enum EntityLocation {
2164 Model(usize),
2165 View(usize, usize),
2166}
2167
2168pub struct ModelHandle<T> {
2169 model_id: usize,
2170 model_type: PhantomData<T>,
2171 ref_counts: Arc<Mutex<RefCounts>>,
2172}
2173
2174impl<T: Entity> ModelHandle<T> {
2175 fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2176 ref_counts.lock().inc_model(model_id);
2177 Self {
2178 model_id,
2179 model_type: PhantomData,
2180 ref_counts: ref_counts.clone(),
2181 }
2182 }
2183
2184 pub fn downgrade(&self) -> WeakModelHandle<T> {
2185 WeakModelHandle::new(self.model_id)
2186 }
2187
2188 pub fn id(&self) -> usize {
2189 self.model_id
2190 }
2191
2192 pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2193 cx.read_model(self)
2194 }
2195
2196 pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2197 where
2198 C: ReadModelWith,
2199 F: FnOnce(&T, &AppContext) -> S,
2200 {
2201 cx.read_model_with(self, read)
2202 }
2203
2204 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2205 where
2206 C: UpdateModel,
2207 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2208 {
2209 cx.update_model(self, update)
2210 }
2211
2212 pub fn condition(
2213 &self,
2214 cx: &TestAppContext,
2215 mut predicate: impl FnMut(&T, &AppContext) -> bool,
2216 ) -> impl Future<Output = ()> {
2217 let (tx, mut rx) = mpsc::channel(1024);
2218
2219 let mut cx = cx.cx.borrow_mut();
2220 self.update(&mut *cx, |_, cx| {
2221 cx.observe(self, {
2222 let mut tx = tx.clone();
2223 move |_, _, _| {
2224 tx.blocking_send(()).ok();
2225 }
2226 });
2227 cx.subscribe(self, {
2228 let mut tx = tx.clone();
2229 move |_, _, _| {
2230 tx.blocking_send(()).ok();
2231 }
2232 })
2233 });
2234
2235 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2236 let handle = self.downgrade();
2237 let duration = if std::env::var("CI").is_ok() {
2238 Duration::from_secs(5)
2239 } else {
2240 Duration::from_secs(1)
2241 };
2242
2243 async move {
2244 timeout(duration, async move {
2245 loop {
2246 {
2247 let cx = cx.borrow();
2248 let cx = cx.as_ref();
2249 if predicate(
2250 handle
2251 .upgrade(cx)
2252 .expect("model dropped with pending condition")
2253 .read(cx),
2254 cx,
2255 ) {
2256 break;
2257 }
2258 }
2259
2260 rx.recv()
2261 .await
2262 .expect("model dropped with pending condition");
2263 }
2264 })
2265 .await
2266 .expect("condition timed out");
2267 }
2268 }
2269}
2270
2271impl<T> Clone for ModelHandle<T> {
2272 fn clone(&self) -> Self {
2273 self.ref_counts.lock().inc_model(self.model_id);
2274 Self {
2275 model_id: self.model_id,
2276 model_type: PhantomData,
2277 ref_counts: self.ref_counts.clone(),
2278 }
2279 }
2280}
2281
2282impl<T> PartialEq for ModelHandle<T> {
2283 fn eq(&self, other: &Self) -> bool {
2284 self.model_id == other.model_id
2285 }
2286}
2287
2288impl<T> Eq for ModelHandle<T> {}
2289
2290impl<T> Hash for ModelHandle<T> {
2291 fn hash<H: Hasher>(&self, state: &mut H) {
2292 self.model_id.hash(state);
2293 }
2294}
2295
2296impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2297 fn borrow(&self) -> &usize {
2298 &self.model_id
2299 }
2300}
2301
2302impl<T> Debug for ModelHandle<T> {
2303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2304 f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2305 .field(&self.model_id)
2306 .finish()
2307 }
2308}
2309
2310unsafe impl<T> Send for ModelHandle<T> {}
2311unsafe impl<T> Sync for ModelHandle<T> {}
2312
2313impl<T> Drop for ModelHandle<T> {
2314 fn drop(&mut self) {
2315 self.ref_counts.lock().dec_model(self.model_id);
2316 }
2317}
2318
2319impl<T> Handle<T> for ModelHandle<T> {
2320 fn id(&self) -> usize {
2321 self.model_id
2322 }
2323
2324 fn location(&self) -> EntityLocation {
2325 EntityLocation::Model(self.model_id)
2326 }
2327}
2328
2329pub struct WeakModelHandle<T> {
2330 model_id: usize,
2331 model_type: PhantomData<T>,
2332}
2333
2334impl<T: Entity> WeakModelHandle<T> {
2335 fn new(model_id: usize) -> Self {
2336 Self {
2337 model_id,
2338 model_type: PhantomData,
2339 }
2340 }
2341
2342 pub fn upgrade(&self, cx: impl AsRef<AppContext>) -> Option<ModelHandle<T>> {
2343 let cx = cx.as_ref();
2344 if cx.models.contains_key(&self.model_id) {
2345 Some(ModelHandle::new(self.model_id, &cx.ref_counts))
2346 } else {
2347 None
2348 }
2349 }
2350}
2351
2352impl<T> Hash for WeakModelHandle<T> {
2353 fn hash<H: Hasher>(&self, state: &mut H) {
2354 self.model_id.hash(state)
2355 }
2356}
2357
2358impl<T> PartialEq for WeakModelHandle<T> {
2359 fn eq(&self, other: &Self) -> bool {
2360 self.model_id == other.model_id
2361 }
2362}
2363
2364impl<T> Eq for WeakModelHandle<T> {}
2365
2366impl<T> Clone for WeakModelHandle<T> {
2367 fn clone(&self) -> Self {
2368 Self {
2369 model_id: self.model_id,
2370 model_type: PhantomData,
2371 }
2372 }
2373}
2374
2375pub struct ViewHandle<T> {
2376 window_id: usize,
2377 view_id: usize,
2378 view_type: PhantomData<T>,
2379 ref_counts: Arc<Mutex<RefCounts>>,
2380}
2381
2382impl<T: View> ViewHandle<T> {
2383 fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2384 ref_counts.lock().inc_view(window_id, view_id);
2385 Self {
2386 window_id,
2387 view_id,
2388 view_type: PhantomData,
2389 ref_counts: ref_counts.clone(),
2390 }
2391 }
2392
2393 pub fn downgrade(&self) -> WeakViewHandle<T> {
2394 WeakViewHandle::new(self.window_id, self.view_id)
2395 }
2396
2397 pub fn window_id(&self) -> usize {
2398 self.window_id
2399 }
2400
2401 pub fn id(&self) -> usize {
2402 self.view_id
2403 }
2404
2405 pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2406 cx.read_view(self)
2407 }
2408
2409 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2410 where
2411 C: ReadViewWith,
2412 F: FnOnce(&T, &AppContext) -> S,
2413 {
2414 cx.read_view_with(self, read)
2415 }
2416
2417 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2418 where
2419 C: UpdateView,
2420 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2421 {
2422 cx.update_view(self, update)
2423 }
2424
2425 pub fn is_focused(&self, cx: &AppContext) -> bool {
2426 cx.focused_view_id(self.window_id)
2427 .map_or(false, |focused_id| focused_id == self.view_id)
2428 }
2429
2430 pub fn condition(
2431 &self,
2432 cx: &TestAppContext,
2433 mut predicate: impl FnMut(&T, &AppContext) -> bool,
2434 ) -> impl Future<Output = ()> {
2435 let (tx, mut rx) = mpsc::channel(1024);
2436
2437 let mut cx = cx.cx.borrow_mut();
2438 self.update(&mut *cx, |_, cx| {
2439 cx.observe_view(self, {
2440 let mut tx = tx.clone();
2441 move |_, _, _| {
2442 tx.blocking_send(()).ok();
2443 }
2444 });
2445
2446 cx.subscribe(self, {
2447 let mut tx = tx.clone();
2448 move |_, _, _| {
2449 tx.blocking_send(()).ok();
2450 }
2451 })
2452 });
2453
2454 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2455 let handle = self.downgrade();
2456 let duration = if std::env::var("CI").is_ok() {
2457 Duration::from_secs(2)
2458 } else {
2459 Duration::from_millis(500)
2460 };
2461
2462 async move {
2463 timeout(duration, async move {
2464 loop {
2465 {
2466 let cx = cx.borrow();
2467 let cx = cx.as_ref();
2468 if predicate(
2469 handle
2470 .upgrade(cx)
2471 .expect("view dropped with pending condition")
2472 .read(cx),
2473 cx,
2474 ) {
2475 break;
2476 }
2477 }
2478
2479 rx.recv()
2480 .await
2481 .expect("view dropped with pending condition");
2482 }
2483 })
2484 .await
2485 .expect("condition timed out");
2486 }
2487 }
2488}
2489
2490impl<T> Clone for ViewHandle<T> {
2491 fn clone(&self) -> Self {
2492 self.ref_counts
2493 .lock()
2494 .inc_view(self.window_id, self.view_id);
2495 Self {
2496 window_id: self.window_id,
2497 view_id: self.view_id,
2498 view_type: PhantomData,
2499 ref_counts: self.ref_counts.clone(),
2500 }
2501 }
2502}
2503
2504impl<T> PartialEq for ViewHandle<T> {
2505 fn eq(&self, other: &Self) -> bool {
2506 self.window_id == other.window_id && self.view_id == other.view_id
2507 }
2508}
2509
2510impl<T> Eq for ViewHandle<T> {}
2511
2512impl<T> Debug for ViewHandle<T> {
2513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2514 f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2515 .field("window_id", &self.window_id)
2516 .field("view_id", &self.view_id)
2517 .finish()
2518 }
2519}
2520
2521impl<T> Drop for ViewHandle<T> {
2522 fn drop(&mut self) {
2523 self.ref_counts
2524 .lock()
2525 .dec_view(self.window_id, self.view_id);
2526 }
2527}
2528
2529impl<T> Handle<T> for ViewHandle<T> {
2530 fn id(&self) -> usize {
2531 self.view_id
2532 }
2533
2534 fn location(&self) -> EntityLocation {
2535 EntityLocation::View(self.window_id, self.view_id)
2536 }
2537}
2538
2539pub struct AnyViewHandle {
2540 window_id: usize,
2541 view_id: usize,
2542 view_type: TypeId,
2543 ref_counts: Arc<Mutex<RefCounts>>,
2544}
2545
2546impl AnyViewHandle {
2547 pub fn id(&self) -> usize {
2548 self.view_id
2549 }
2550
2551 pub fn is<T: 'static>(&self) -> bool {
2552 TypeId::of::<T>() == self.view_type
2553 }
2554
2555 pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2556 if self.is::<T>() {
2557 let result = Some(ViewHandle {
2558 window_id: self.window_id,
2559 view_id: self.view_id,
2560 ref_counts: self.ref_counts.clone(),
2561 view_type: PhantomData,
2562 });
2563 unsafe {
2564 Arc::decrement_strong_count(&self.ref_counts);
2565 }
2566 std::mem::forget(self);
2567 result
2568 } else {
2569 None
2570 }
2571 }
2572}
2573
2574impl Clone for AnyViewHandle {
2575 fn clone(&self) -> Self {
2576 self.ref_counts
2577 .lock()
2578 .inc_view(self.window_id, self.view_id);
2579 Self {
2580 window_id: self.window_id,
2581 view_id: self.view_id,
2582 view_type: self.view_type,
2583 ref_counts: self.ref_counts.clone(),
2584 }
2585 }
2586}
2587
2588impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2589 fn from(handle: &ViewHandle<T>) -> Self {
2590 handle
2591 .ref_counts
2592 .lock()
2593 .inc_view(handle.window_id, handle.view_id);
2594 AnyViewHandle {
2595 window_id: handle.window_id,
2596 view_id: handle.view_id,
2597 view_type: TypeId::of::<T>(),
2598 ref_counts: handle.ref_counts.clone(),
2599 }
2600 }
2601}
2602
2603impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2604 fn from(handle: ViewHandle<T>) -> Self {
2605 let any_handle = AnyViewHandle {
2606 window_id: handle.window_id,
2607 view_id: handle.view_id,
2608 view_type: TypeId::of::<T>(),
2609 ref_counts: handle.ref_counts.clone(),
2610 };
2611 unsafe {
2612 Arc::decrement_strong_count(&handle.ref_counts);
2613 }
2614 std::mem::forget(handle);
2615 any_handle
2616 }
2617}
2618
2619impl Drop for AnyViewHandle {
2620 fn drop(&mut self) {
2621 self.ref_counts
2622 .lock()
2623 .dec_view(self.window_id, self.view_id);
2624 }
2625}
2626
2627pub struct AnyModelHandle {
2628 model_id: usize,
2629 ref_counts: Arc<Mutex<RefCounts>>,
2630}
2631
2632impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2633 fn from(handle: ModelHandle<T>) -> Self {
2634 handle.ref_counts.lock().inc_model(handle.model_id);
2635 Self {
2636 model_id: handle.model_id,
2637 ref_counts: handle.ref_counts.clone(),
2638 }
2639 }
2640}
2641
2642impl Drop for AnyModelHandle {
2643 fn drop(&mut self) {
2644 self.ref_counts.lock().dec_model(self.model_id);
2645 }
2646}
2647pub struct WeakViewHandle<T> {
2648 window_id: usize,
2649 view_id: usize,
2650 view_type: PhantomData<T>,
2651}
2652
2653impl<T: View> WeakViewHandle<T> {
2654 fn new(window_id: usize, view_id: usize) -> Self {
2655 Self {
2656 window_id,
2657 view_id,
2658 view_type: PhantomData,
2659 }
2660 }
2661
2662 pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
2663 if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2664 Some(ViewHandle::new(
2665 self.window_id,
2666 self.view_id,
2667 &cx.ref_counts,
2668 ))
2669 } else {
2670 None
2671 }
2672 }
2673}
2674
2675impl<T> Clone for WeakViewHandle<T> {
2676 fn clone(&self) -> Self {
2677 Self {
2678 window_id: self.window_id,
2679 view_id: self.view_id,
2680 view_type: PhantomData,
2681 }
2682 }
2683}
2684
2685pub struct ValueHandle<T> {
2686 value_type: PhantomData<T>,
2687 tag_type_id: TypeId,
2688 id: usize,
2689 ref_counts: Weak<Mutex<RefCounts>>,
2690}
2691
2692impl<T: 'static> ValueHandle<T> {
2693 fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2694 ref_counts.lock().inc_value(tag_type_id, id);
2695 Self {
2696 value_type: PhantomData,
2697 tag_type_id,
2698 id,
2699 ref_counts: Arc::downgrade(ref_counts),
2700 }
2701 }
2702
2703 pub fn read<R>(&self, cx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2704 f(cx.values
2705 .read()
2706 .get(&(self.tag_type_id, self.id))
2707 .unwrap()
2708 .downcast_ref()
2709 .unwrap())
2710 }
2711
2712 pub fn update<R>(
2713 &self,
2714 cx: &mut EventContext,
2715 f: impl FnOnce(&mut T, &mut EventContext) -> R,
2716 ) -> R {
2717 let mut value = cx
2718 .app
2719 .cx
2720 .values
2721 .write()
2722 .remove(&(self.tag_type_id, self.id))
2723 .unwrap();
2724 let result = f(value.downcast_mut().unwrap(), cx);
2725 cx.app
2726 .cx
2727 .values
2728 .write()
2729 .insert((self.tag_type_id, self.id), value);
2730 result
2731 }
2732}
2733
2734impl<T> Drop for ValueHandle<T> {
2735 fn drop(&mut self) {
2736 if let Some(ref_counts) = self.ref_counts.upgrade() {
2737 ref_counts.lock().dec_value(self.tag_type_id, self.id);
2738 }
2739 }
2740}
2741
2742#[derive(Default)]
2743struct RefCounts {
2744 entity_counts: HashMap<usize, usize>,
2745 value_counts: HashMap<(TypeId, usize), usize>,
2746 dropped_models: HashSet<usize>,
2747 dropped_views: HashSet<(usize, usize)>,
2748 dropped_values: HashSet<(TypeId, usize)>,
2749}
2750
2751impl RefCounts {
2752 fn inc_model(&mut self, model_id: usize) {
2753 match self.entity_counts.entry(model_id) {
2754 Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2755 Entry::Vacant(entry) => {
2756 entry.insert(1);
2757 self.dropped_models.remove(&model_id);
2758 }
2759 }
2760 }
2761
2762 fn inc_view(&mut self, window_id: usize, view_id: usize) {
2763 match self.entity_counts.entry(view_id) {
2764 Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2765 Entry::Vacant(entry) => {
2766 entry.insert(1);
2767 self.dropped_views.remove(&(window_id, view_id));
2768 }
2769 }
2770 }
2771
2772 fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
2773 *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
2774 }
2775
2776 fn dec_model(&mut self, model_id: usize) {
2777 let count = self.entity_counts.get_mut(&model_id).unwrap();
2778 *count -= 1;
2779 if *count == 0 {
2780 self.entity_counts.remove(&model_id);
2781 self.dropped_models.insert(model_id);
2782 }
2783 }
2784
2785 fn dec_view(&mut self, window_id: usize, view_id: usize) {
2786 let count = self.entity_counts.get_mut(&view_id).unwrap();
2787 *count -= 1;
2788 if *count == 0 {
2789 self.entity_counts.remove(&view_id);
2790 self.dropped_views.insert((window_id, view_id));
2791 }
2792 }
2793
2794 fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
2795 let key = (tag_type_id, id);
2796 let count = self.value_counts.get_mut(&key).unwrap();
2797 *count -= 1;
2798 if *count == 0 {
2799 self.value_counts.remove(&key);
2800 self.dropped_values.insert(key);
2801 }
2802 }
2803
2804 fn is_entity_alive(&self, entity_id: usize) -> bool {
2805 self.entity_counts.contains_key(&entity_id)
2806 }
2807
2808 fn take_dropped(
2809 &mut self,
2810 ) -> (
2811 HashSet<usize>,
2812 HashSet<(usize, usize)>,
2813 HashSet<(TypeId, usize)>,
2814 ) {
2815 let mut dropped_models = HashSet::new();
2816 let mut dropped_views = HashSet::new();
2817 let mut dropped_values = HashSet::new();
2818 std::mem::swap(&mut self.dropped_models, &mut dropped_models);
2819 std::mem::swap(&mut self.dropped_views, &mut dropped_views);
2820 std::mem::swap(&mut self.dropped_values, &mut dropped_values);
2821 (dropped_models, dropped_views, dropped_values)
2822 }
2823}
2824
2825enum Subscription {
2826 FromModel {
2827 model_id: usize,
2828 callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize)>,
2829 },
2830 FromView {
2831 window_id: usize,
2832 view_id: usize,
2833 callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize, usize)>,
2834 },
2835}
2836
2837enum ModelObservation {
2838 FromModel {
2839 model_id: usize,
2840 callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize)>,
2841 },
2842 FromView {
2843 window_id: usize,
2844 view_id: usize,
2845 callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize, usize)>,
2846 },
2847}
2848
2849struct ViewObservation {
2850 window_id: usize,
2851 view_id: usize,
2852 callback: Box<dyn FnMut(&mut dyn Any, usize, usize, &mut MutableAppContext, usize, usize)>,
2853}
2854
2855#[cfg(test)]
2856mod tests {
2857 use super::*;
2858 use crate::elements::*;
2859 use smol::future::poll_once;
2860 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
2861
2862 #[crate::test(self)]
2863 fn test_model_handles(cx: &mut MutableAppContext) {
2864 struct Model {
2865 other: Option<ModelHandle<Model>>,
2866 events: Vec<String>,
2867 }
2868
2869 impl Entity for Model {
2870 type Event = usize;
2871 }
2872
2873 impl Model {
2874 fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
2875 if let Some(other) = other.as_ref() {
2876 cx.observe(other, |me, _, _| {
2877 me.events.push("notified".into());
2878 });
2879 cx.subscribe(other, |me, event, _| {
2880 me.events.push(format!("observed event {}", event));
2881 });
2882 }
2883
2884 Self {
2885 other,
2886 events: Vec::new(),
2887 }
2888 }
2889 }
2890
2891 let handle_1 = cx.add_model(|cx| Model::new(None, cx));
2892 let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
2893 assert_eq!(cx.cx.models.len(), 2);
2894
2895 handle_1.update(cx, |model, cx| {
2896 model.events.push("updated".into());
2897 cx.emit(1);
2898 cx.notify();
2899 cx.emit(2);
2900 });
2901 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
2902 assert_eq!(
2903 handle_2.read(cx).events,
2904 vec![
2905 "observed event 1".to_string(),
2906 "notified".to_string(),
2907 "observed event 2".to_string(),
2908 ]
2909 );
2910
2911 handle_2.update(cx, |model, _| {
2912 drop(handle_1);
2913 model.other.take();
2914 });
2915
2916 assert_eq!(cx.cx.models.len(), 1);
2917 assert!(cx.subscriptions.is_empty());
2918 assert!(cx.model_observations.is_empty());
2919 }
2920
2921 #[crate::test(self)]
2922 fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
2923 #[derive(Default)]
2924 struct Model {
2925 events: Vec<usize>,
2926 }
2927
2928 impl Entity for Model {
2929 type Event = usize;
2930 }
2931
2932 let handle_1 = cx.add_model(|_| Model::default());
2933 let handle_2 = cx.add_model(|_| Model::default());
2934 let handle_2b = handle_2.clone();
2935
2936 handle_1.update(cx, |_, c| {
2937 c.subscribe(&handle_2, move |model: &mut Model, event, c| {
2938 model.events.push(*event);
2939
2940 c.subscribe(&handle_2b, |model, event, _| {
2941 model.events.push(*event * 2);
2942 });
2943 });
2944 });
2945
2946 handle_2.update(cx, |_, c| c.emit(7));
2947 assert_eq!(handle_1.read(cx).events, vec![7]);
2948
2949 handle_2.update(cx, |_, c| c.emit(5));
2950 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
2951 }
2952
2953 #[crate::test(self)]
2954 fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
2955 #[derive(Default)]
2956 struct Model {
2957 count: usize,
2958 events: Vec<usize>,
2959 }
2960
2961 impl Entity for Model {
2962 type Event = ();
2963 }
2964
2965 let handle_1 = cx.add_model(|_| Model::default());
2966 let handle_2 = cx.add_model(|_| Model::default());
2967 let handle_2b = handle_2.clone();
2968
2969 handle_1.update(cx, |_, c| {
2970 c.observe(&handle_2, move |model, observed, c| {
2971 model.events.push(observed.read(c).count);
2972 c.observe(&handle_2b, |model, observed, c| {
2973 model.events.push(observed.read(c).count * 2);
2974 });
2975 });
2976 });
2977
2978 handle_2.update(cx, |model, c| {
2979 model.count = 7;
2980 c.notify()
2981 });
2982 assert_eq!(handle_1.read(cx).events, vec![7]);
2983
2984 handle_2.update(cx, |model, c| {
2985 model.count = 5;
2986 c.notify()
2987 });
2988 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5])
2989 }
2990
2991 #[crate::test(self)]
2992 fn test_view_handles(cx: &mut MutableAppContext) {
2993 struct View {
2994 other: Option<ViewHandle<View>>,
2995 events: Vec<String>,
2996 }
2997
2998 impl Entity for View {
2999 type Event = usize;
3000 }
3001
3002 impl super::View for View {
3003 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3004 Empty::new().boxed()
3005 }
3006
3007 fn ui_name() -> &'static str {
3008 "View"
3009 }
3010 }
3011
3012 impl View {
3013 fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3014 if let Some(other) = other.as_ref() {
3015 cx.subscribe_to_view(other, |me, _, event, _| {
3016 me.events.push(format!("observed event {}", event));
3017 });
3018 }
3019 Self {
3020 other,
3021 events: Vec::new(),
3022 }
3023 }
3024 }
3025
3026 let (window_id, _) = cx.add_window(|cx| View::new(None, cx));
3027 let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3028 let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3029 assert_eq!(cx.cx.views.len(), 3);
3030
3031 handle_1.update(cx, |view, cx| {
3032 view.events.push("updated".into());
3033 cx.emit(1);
3034 cx.emit(2);
3035 });
3036 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3037 assert_eq!(
3038 handle_2.read(cx).events,
3039 vec![
3040 "observed event 1".to_string(),
3041 "observed event 2".to_string(),
3042 ]
3043 );
3044
3045 handle_2.update(cx, |view, _| {
3046 drop(handle_1);
3047 view.other.take();
3048 });
3049
3050 assert_eq!(cx.cx.views.len(), 2);
3051 assert!(cx.subscriptions.is_empty());
3052 assert!(cx.model_observations.is_empty());
3053 }
3054
3055 #[crate::test(self)]
3056 fn test_add_window(cx: &mut MutableAppContext) {
3057 struct View {
3058 mouse_down_count: Arc<AtomicUsize>,
3059 }
3060
3061 impl Entity for View {
3062 type Event = ();
3063 }
3064
3065 impl super::View for View {
3066 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3067 let mouse_down_count = self.mouse_down_count.clone();
3068 EventHandler::new(Empty::new().boxed())
3069 .on_mouse_down(move |_| {
3070 mouse_down_count.fetch_add(1, SeqCst);
3071 true
3072 })
3073 .boxed()
3074 }
3075
3076 fn ui_name() -> &'static str {
3077 "View"
3078 }
3079 }
3080
3081 let mouse_down_count = Arc::new(AtomicUsize::new(0));
3082 let (window_id, _) = cx.add_window(|_| View {
3083 mouse_down_count: mouse_down_count.clone(),
3084 });
3085 let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3086 // Ensure window's root element is in a valid lifecycle state.
3087 presenter.borrow_mut().dispatch_event(
3088 Event::LeftMouseDown {
3089 position: Default::default(),
3090 cmd: false,
3091 },
3092 cx,
3093 );
3094 assert_eq!(mouse_down_count.load(SeqCst), 1);
3095 }
3096
3097 #[crate::test(self)]
3098 fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3099 struct Model {
3100 released: Arc<Mutex<bool>>,
3101 }
3102
3103 struct View {
3104 released: Arc<Mutex<bool>>,
3105 }
3106
3107 impl Entity for Model {
3108 type Event = ();
3109
3110 fn release(&mut self, _: &mut MutableAppContext) {
3111 *self.released.lock() = true;
3112 }
3113 }
3114
3115 impl Entity for View {
3116 type Event = ();
3117
3118 fn release(&mut self, _: &mut MutableAppContext) {
3119 *self.released.lock() = true;
3120 }
3121 }
3122
3123 impl super::View for View {
3124 fn ui_name() -> &'static str {
3125 "View"
3126 }
3127
3128 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3129 Empty::new().boxed()
3130 }
3131 }
3132
3133 let model_released = Arc::new(Mutex::new(false));
3134 let view_released = Arc::new(Mutex::new(false));
3135
3136 let model = cx.add_model(|_| Model {
3137 released: model_released.clone(),
3138 });
3139
3140 let (window_id, _) = cx.add_window(|_| View {
3141 released: view_released.clone(),
3142 });
3143
3144 assert!(!*model_released.lock());
3145 assert!(!*view_released.lock());
3146
3147 cx.update(move || {
3148 drop(model);
3149 });
3150 assert!(*model_released.lock());
3151
3152 drop(cx.remove_window(window_id));
3153 assert!(*view_released.lock());
3154 }
3155
3156 #[crate::test(self)]
3157 fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3158 #[derive(Default)]
3159 struct View {
3160 events: Vec<usize>,
3161 }
3162
3163 impl Entity for View {
3164 type Event = usize;
3165 }
3166
3167 impl super::View for View {
3168 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3169 Empty::new().boxed()
3170 }
3171
3172 fn ui_name() -> &'static str {
3173 "View"
3174 }
3175 }
3176
3177 struct Model;
3178
3179 impl Entity for Model {
3180 type Event = usize;
3181 }
3182
3183 let (window_id, handle_1) = cx.add_window(|_| View::default());
3184 let handle_2 = cx.add_view(window_id, |_| View::default());
3185 let handle_2b = handle_2.clone();
3186 let handle_3 = cx.add_model(|_| Model);
3187
3188 handle_1.update(cx, |_, c| {
3189 c.subscribe_to_view(&handle_2, move |me, _, event, c| {
3190 me.events.push(*event);
3191
3192 c.subscribe_to_view(&handle_2b, |me, _, event, _| {
3193 me.events.push(*event * 2);
3194 });
3195 });
3196
3197 c.subscribe_to_model(&handle_3, |me, _, event, _| {
3198 me.events.push(*event);
3199 })
3200 });
3201
3202 handle_2.update(cx, |_, c| c.emit(7));
3203 assert_eq!(handle_1.read(cx).events, vec![7]);
3204
3205 handle_2.update(cx, |_, c| c.emit(5));
3206 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
3207
3208 handle_3.update(cx, |_, c| c.emit(9));
3209 assert_eq!(handle_1.read(cx).events, vec![7, 10, 5, 9]);
3210 }
3211
3212 #[crate::test(self)]
3213 fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3214 struct View;
3215
3216 impl Entity for View {
3217 type Event = ();
3218 }
3219
3220 impl super::View for View {
3221 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3222 Empty::new().boxed()
3223 }
3224
3225 fn ui_name() -> &'static str {
3226 "View"
3227 }
3228 }
3229
3230 struct Model;
3231
3232 impl Entity for Model {
3233 type Event = ();
3234 }
3235
3236 let (window_id, _) = cx.add_window(|_| View);
3237 let observing_view = cx.add_view(window_id, |_| View);
3238 let emitting_view = cx.add_view(window_id, |_| View);
3239 let observing_model = cx.add_model(|_| Model);
3240 let observed_model = cx.add_model(|_| Model);
3241
3242 observing_view.update(cx, |_, cx| {
3243 cx.subscribe_to_view(&emitting_view, |_, _, _, _| {});
3244 cx.subscribe_to_model(&observed_model, |_, _, _, _| {});
3245 });
3246 observing_model.update(cx, |_, cx| {
3247 cx.subscribe(&observed_model, |_, _, _| {});
3248 });
3249
3250 cx.update(|| {
3251 drop(observing_view);
3252 drop(observing_model);
3253 });
3254
3255 emitting_view.update(cx, |_, cx| cx.emit(()));
3256 observed_model.update(cx, |_, cx| cx.emit(()));
3257 }
3258
3259 #[crate::test(self)]
3260 fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3261 #[derive(Default)]
3262 struct View {
3263 events: Vec<usize>,
3264 }
3265
3266 impl Entity for View {
3267 type Event = usize;
3268 }
3269
3270 impl super::View for View {
3271 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3272 Empty::new().boxed()
3273 }
3274
3275 fn ui_name() -> &'static str {
3276 "View"
3277 }
3278 }
3279
3280 #[derive(Default)]
3281 struct Model {
3282 count: usize,
3283 }
3284
3285 impl Entity for Model {
3286 type Event = ();
3287 }
3288
3289 let (_, view) = cx.add_window(|_| View::default());
3290 let model = cx.add_model(|_| Model::default());
3291
3292 view.update(cx, |_, c| {
3293 c.observe_model(&model, |me, observed, c| {
3294 me.events.push(observed.read(c).count)
3295 });
3296 });
3297
3298 model.update(cx, |model, c| {
3299 model.count = 11;
3300 c.notify();
3301 });
3302 assert_eq!(view.read(cx).events, vec![11]);
3303 }
3304
3305 #[crate::test(self)]
3306 fn test_dropping_observers(cx: &mut MutableAppContext) {
3307 struct View;
3308
3309 impl Entity for View {
3310 type Event = ();
3311 }
3312
3313 impl super::View for View {
3314 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3315 Empty::new().boxed()
3316 }
3317
3318 fn ui_name() -> &'static str {
3319 "View"
3320 }
3321 }
3322
3323 struct Model;
3324
3325 impl Entity for Model {
3326 type Event = ();
3327 }
3328
3329 let (window_id, _) = cx.add_window(|_| View);
3330 let observing_view = cx.add_view(window_id, |_| View);
3331 let observing_model = cx.add_model(|_| Model);
3332 let observed_model = cx.add_model(|_| Model);
3333
3334 observing_view.update(cx, |_, cx| {
3335 cx.observe_model(&observed_model, |_, _, _| {});
3336 });
3337 observing_model.update(cx, |_, cx| {
3338 cx.observe(&observed_model, |_, _, _| {});
3339 });
3340
3341 cx.update(|| {
3342 drop(observing_view);
3343 drop(observing_model);
3344 });
3345
3346 observed_model.update(cx, |_, cx| cx.notify());
3347 }
3348
3349 #[crate::test(self)]
3350 fn test_focus(cx: &mut MutableAppContext) {
3351 struct View {
3352 name: String,
3353 events: Arc<Mutex<Vec<String>>>,
3354 }
3355
3356 impl Entity for View {
3357 type Event = ();
3358 }
3359
3360 impl super::View for View {
3361 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3362 Empty::new().boxed()
3363 }
3364
3365 fn ui_name() -> &'static str {
3366 "View"
3367 }
3368
3369 fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3370 self.events.lock().push(format!("{} focused", &self.name));
3371 }
3372
3373 fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3374 self.events.lock().push(format!("{} blurred", &self.name));
3375 }
3376 }
3377
3378 let events: Arc<Mutex<Vec<String>>> = Default::default();
3379 let (window_id, view_1) = cx.add_window(|_| View {
3380 events: events.clone(),
3381 name: "view 1".to_string(),
3382 });
3383 let view_2 = cx.add_view(window_id, |_| View {
3384 events: events.clone(),
3385 name: "view 2".to_string(),
3386 });
3387
3388 view_1.update(cx, |_, cx| cx.focus(&view_2));
3389 view_1.update(cx, |_, cx| cx.focus(&view_1));
3390 view_1.update(cx, |_, cx| cx.focus(&view_2));
3391 view_1.update(cx, |_, _| drop(view_2));
3392
3393 assert_eq!(
3394 *events.lock(),
3395 [
3396 "view 1 focused".to_string(),
3397 "view 1 blurred".to_string(),
3398 "view 2 focused".to_string(),
3399 "view 2 blurred".to_string(),
3400 "view 1 focused".to_string(),
3401 "view 1 blurred".to_string(),
3402 "view 2 focused".to_string(),
3403 "view 1 focused".to_string(),
3404 ],
3405 );
3406 }
3407
3408 #[crate::test(self)]
3409 fn test_dispatch_action(cx: &mut MutableAppContext) {
3410 struct ViewA {
3411 id: usize,
3412 }
3413
3414 impl Entity for ViewA {
3415 type Event = ();
3416 }
3417
3418 impl View for ViewA {
3419 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3420 Empty::new().boxed()
3421 }
3422
3423 fn ui_name() -> &'static str {
3424 "View"
3425 }
3426 }
3427
3428 struct ViewB {
3429 id: usize,
3430 }
3431
3432 impl Entity for ViewB {
3433 type Event = ();
3434 }
3435
3436 impl View for ViewB {
3437 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3438 Empty::new().boxed()
3439 }
3440
3441 fn ui_name() -> &'static str {
3442 "View"
3443 }
3444 }
3445
3446 struct ActionArg {
3447 foo: String,
3448 }
3449
3450 let actions = Rc::new(RefCell::new(Vec::new()));
3451
3452 let actions_clone = actions.clone();
3453 cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3454 actions_clone.borrow_mut().push("global a".to_string());
3455 });
3456
3457 let actions_clone = actions.clone();
3458 cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3459 actions_clone.borrow_mut().push("global b".to_string());
3460 });
3461
3462 let actions_clone = actions.clone();
3463 cx.add_action("action", move |view: &mut ViewA, arg: &ActionArg, cx| {
3464 assert_eq!(arg.foo, "bar");
3465 cx.propagate_action();
3466 actions_clone.borrow_mut().push(format!("{} a", view.id));
3467 });
3468
3469 let actions_clone = actions.clone();
3470 cx.add_action("action", move |view: &mut ViewA, _: &ActionArg, cx| {
3471 if view.id != 1 {
3472 cx.propagate_action();
3473 }
3474 actions_clone.borrow_mut().push(format!("{} b", view.id));
3475 });
3476
3477 let actions_clone = actions.clone();
3478 cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3479 cx.propagate_action();
3480 actions_clone.borrow_mut().push(format!("{} c", view.id));
3481 });
3482
3483 let actions_clone = actions.clone();
3484 cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3485 cx.propagate_action();
3486 actions_clone.borrow_mut().push(format!("{} d", view.id));
3487 });
3488
3489 let (window_id, view_1) = cx.add_window(|_| ViewA { id: 1 });
3490 let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3491 let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3492 let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3493
3494 cx.dispatch_action(
3495 window_id,
3496 vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3497 "action",
3498 ActionArg { foo: "bar".into() },
3499 );
3500
3501 assert_eq!(
3502 *actions.borrow(),
3503 vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3504 );
3505
3506 // Remove view_1, which doesn't propagate the action
3507 actions.borrow_mut().clear();
3508 cx.dispatch_action(
3509 window_id,
3510 vec![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", "global b", "global a"]
3518 );
3519 }
3520
3521 #[crate::test(self)]
3522 fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3523 use std::cell::Cell;
3524
3525 #[derive(Clone)]
3526 struct ActionArg {
3527 key: String,
3528 }
3529
3530 struct View {
3531 id: usize,
3532 keymap_context: keymap::Context,
3533 }
3534
3535 impl Entity for View {
3536 type Event = ();
3537 }
3538
3539 impl super::View for View {
3540 fn render<'a>(&self, _: &AppContext) -> ElementBox {
3541 Empty::new().boxed()
3542 }
3543
3544 fn ui_name() -> &'static str {
3545 "View"
3546 }
3547
3548 fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3549 self.keymap_context.clone()
3550 }
3551 }
3552
3553 impl View {
3554 fn new(id: usize) -> Self {
3555 View {
3556 id,
3557 keymap_context: keymap::Context::default(),
3558 }
3559 }
3560 }
3561
3562 let mut view_1 = View::new(1);
3563 let mut view_2 = View::new(2);
3564 let mut view_3 = View::new(3);
3565 view_1.keymap_context.set.insert("a".into());
3566 view_2.keymap_context.set.insert("b".into());
3567 view_3.keymap_context.set.insert("c".into());
3568
3569 let (window_id, view_1) = cx.add_window(|_| view_1);
3570 let view_2 = cx.add_view(window_id, |_| view_2);
3571 let view_3 = cx.add_view(window_id, |_| view_3);
3572
3573 // This keymap's only binding dispatches an action on view 2 because that view will have
3574 // "a" and "b" in its context, but not "c".
3575 let binding = keymap::Binding::new("a", "action", Some("a && b && !c"))
3576 .with_arg(ActionArg { key: "a".into() });
3577 cx.add_bindings(vec![binding]);
3578
3579 let handled_action = Rc::new(Cell::new(false));
3580 let handled_action_clone = handled_action.clone();
3581 cx.add_action("action", move |view: &mut View, arg: &ActionArg, _| {
3582 handled_action_clone.set(true);
3583 assert_eq!(view.id, 2);
3584 assert_eq!(arg.key, "a");
3585 });
3586
3587 cx.dispatch_keystroke(
3588 window_id,
3589 vec![view_1.id(), view_2.id(), view_3.id()],
3590 &Keystroke::parse("a").unwrap(),
3591 )
3592 .unwrap();
3593
3594 assert!(handled_action.get());
3595 }
3596
3597 #[crate::test(self)]
3598 async fn test_model_condition(mut cx: TestAppContext) {
3599 struct Counter(usize);
3600
3601 impl super::Entity for Counter {
3602 type Event = ();
3603 }
3604
3605 impl Counter {
3606 fn inc(&mut self, cx: &mut ModelContext<Self>) {
3607 self.0 += 1;
3608 cx.notify();
3609 }
3610 }
3611
3612 let model = cx.add_model(|_| Counter(0));
3613
3614 let condition1 = model.condition(&cx, |model, _| model.0 == 2);
3615 let condition2 = model.condition(&cx, |model, _| model.0 == 3);
3616 smol::pin!(condition1, condition2);
3617
3618 model.update(&mut cx, |model, cx| model.inc(cx));
3619 assert_eq!(poll_once(&mut condition1).await, None);
3620 assert_eq!(poll_once(&mut condition2).await, None);
3621
3622 model.update(&mut cx, |model, cx| model.inc(cx));
3623 assert_eq!(poll_once(&mut condition1).await, Some(()));
3624 assert_eq!(poll_once(&mut condition2).await, None);
3625
3626 model.update(&mut cx, |model, cx| model.inc(cx));
3627 assert_eq!(poll_once(&mut condition2).await, Some(()));
3628
3629 model.update(&mut cx, |_, cx| cx.notify());
3630 }
3631
3632 #[crate::test(self)]
3633 #[should_panic]
3634 async fn test_model_condition_timeout(mut cx: TestAppContext) {
3635 struct Model;
3636
3637 impl super::Entity for Model {
3638 type Event = ();
3639 }
3640
3641 let model = cx.add_model(|_| Model);
3642 model.condition(&cx, |_, _| false).await;
3643 }
3644
3645 #[crate::test(self)]
3646 #[should_panic(expected = "model dropped with pending condition")]
3647 async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
3648 struct Model;
3649
3650 impl super::Entity for Model {
3651 type Event = ();
3652 }
3653
3654 let model = cx.add_model(|_| Model);
3655 let condition = model.condition(&cx, |_, _| false);
3656 cx.update(|_| drop(model));
3657 condition.await;
3658 }
3659
3660 #[crate::test(self)]
3661 async fn test_view_condition(mut cx: TestAppContext) {
3662 struct Counter(usize);
3663
3664 impl super::Entity for Counter {
3665 type Event = ();
3666 }
3667
3668 impl super::View for Counter {
3669 fn ui_name() -> &'static str {
3670 "test view"
3671 }
3672
3673 fn render(&self, _: &AppContext) -> ElementBox {
3674 Empty::new().boxed()
3675 }
3676 }
3677
3678 impl Counter {
3679 fn inc(&mut self, cx: &mut ViewContext<Self>) {
3680 self.0 += 1;
3681 cx.notify();
3682 }
3683 }
3684
3685 let (_, view) = cx.add_window(|_| Counter(0));
3686
3687 let condition1 = view.condition(&cx, |view, _| view.0 == 2);
3688 let condition2 = view.condition(&cx, |view, _| view.0 == 3);
3689 smol::pin!(condition1, condition2);
3690
3691 view.update(&mut cx, |view, cx| view.inc(cx));
3692 assert_eq!(poll_once(&mut condition1).await, None);
3693 assert_eq!(poll_once(&mut condition2).await, None);
3694
3695 view.update(&mut cx, |view, cx| view.inc(cx));
3696 assert_eq!(poll_once(&mut condition1).await, Some(()));
3697 assert_eq!(poll_once(&mut condition2).await, None);
3698
3699 view.update(&mut cx, |view, cx| view.inc(cx));
3700 assert_eq!(poll_once(&mut condition2).await, Some(()));
3701 view.update(&mut cx, |_, cx| cx.notify());
3702 }
3703
3704 #[crate::test(self)]
3705 #[should_panic]
3706 async fn test_view_condition_timeout(mut cx: TestAppContext) {
3707 struct View;
3708
3709 impl super::Entity for View {
3710 type Event = ();
3711 }
3712
3713 impl super::View for View {
3714 fn ui_name() -> &'static str {
3715 "test view"
3716 }
3717
3718 fn render(&self, _: &AppContext) -> ElementBox {
3719 Empty::new().boxed()
3720 }
3721 }
3722
3723 let (_, view) = cx.add_window(|_| View);
3724 view.condition(&cx, |_, _| false).await;
3725 }
3726
3727 #[crate::test(self)]
3728 #[should_panic(expected = "view dropped with pending condition")]
3729 async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
3730 struct View;
3731
3732 impl super::Entity for View {
3733 type Event = ();
3734 }
3735
3736 impl super::View for View {
3737 fn ui_name() -> &'static str {
3738 "test view"
3739 }
3740
3741 fn render(&self, _: &AppContext) -> ElementBox {
3742 Empty::new().boxed()
3743 }
3744 }
3745
3746 let window_id = cx.add_window(|_| View).0;
3747 let view = cx.add_view(window_id, |_| View);
3748
3749 let condition = view.condition(&cx, |_, _| false);
3750 cx.update(|_| drop(view));
3751 condition.await;
3752 }
3753}