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