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