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