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