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