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