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