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