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