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