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