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