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