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