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