1pub mod action;
2
3use crate::{
4 elements::ElementBox,
5 executor::{self, Task},
6 geometry::rect::RectF,
7 keymap::{self, Binding, Keystroke},
8 platform::{self, KeyDownEvent, Platform, PromptLevel, WindowOptions},
9 presenter::Presenter,
10 util::post_inc,
11 AssetCache, AssetSource, ClipboardItem, FontCache, InputHandler, MouseRegionId,
12 PathPromptOptions, TextLayoutCache,
13};
14pub use action::*;
15use anyhow::{anyhow, Context, Result};
16use collections::btree_map;
17use keymap::MatchResult;
18use lazy_static::lazy_static;
19use parking_lot::Mutex;
20use platform::Event;
21use postage::oneshot;
22use smallvec::SmallVec;
23use smol::prelude::*;
24use std::{
25 any::{type_name, Any, TypeId},
26 cell::RefCell,
27 collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque},
28 fmt::{self, Debug},
29 hash::{Hash, Hasher},
30 marker::PhantomData,
31 mem,
32 ops::{Deref, DerefMut, Range},
33 path::{Path, PathBuf},
34 pin::Pin,
35 rc::{self, Rc},
36 sync::{Arc, Weak},
37 time::Duration,
38};
39
40pub trait Entity: 'static {
41 type Event;
42
43 fn release(&mut self, _: &mut MutableAppContext) {}
44 fn app_will_quit(
45 &mut self,
46 _: &mut MutableAppContext,
47 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
48 None
49 }
50}
51
52pub trait View: Entity + Sized {
53 fn ui_name() -> &'static str;
54 fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
55 fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
56 fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
57 fn keymap_context(&self, _: &AppContext) -> keymap::Context {
58 Self::default_keymap_context()
59 }
60 fn default_keymap_context() -> keymap::Context {
61 let mut cx = keymap::Context::default();
62 cx.set.insert(Self::ui_name().into());
63 cx
64 }
65 fn debug_json(&self, _: &AppContext) -> serde_json::Value {
66 serde_json::Value::Null
67 }
68
69 fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
70 None
71 }
72 fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
73 None
74 }
75 fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
76 None
77 }
78 fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
79 fn replace_text_in_range(
80 &mut self,
81 _: Option<Range<usize>>,
82 _: &str,
83 _: &mut ViewContext<Self>,
84 ) {
85 }
86 fn replace_and_mark_text_in_range(
87 &mut self,
88 _: Option<Range<usize>>,
89 _: &str,
90 _: Option<Range<usize>>,
91 _: &mut ViewContext<Self>,
92 ) {
93 }
94}
95
96pub trait ReadModel {
97 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
98}
99
100pub trait ReadModelWith {
101 fn read_model_with<E: Entity, T>(
102 &self,
103 handle: &ModelHandle<E>,
104 read: &mut dyn FnMut(&E, &AppContext) -> T,
105 ) -> T;
106}
107
108pub trait UpdateModel {
109 fn update_model<T: Entity, O>(
110 &mut self,
111 handle: &ModelHandle<T>,
112 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
113 ) -> O;
114}
115
116pub trait UpgradeModelHandle {
117 fn upgrade_model_handle<T: Entity>(
118 &self,
119 handle: &WeakModelHandle<T>,
120 ) -> Option<ModelHandle<T>>;
121
122 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
123
124 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
125}
126
127pub trait UpgradeViewHandle {
128 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
129
130 fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle>;
131}
132
133pub trait ReadView {
134 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
135}
136
137pub trait ReadViewWith {
138 fn read_view_with<V, T>(
139 &self,
140 handle: &ViewHandle<V>,
141 read: &mut dyn FnMut(&V, &AppContext) -> T,
142 ) -> T
143 where
144 V: View;
145}
146
147pub trait UpdateView {
148 fn update_view<T, S>(
149 &mut self,
150 handle: &ViewHandle<T>,
151 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
152 ) -> S
153 where
154 T: View;
155}
156
157pub struct Menu<'a> {
158 pub name: &'a str,
159 pub items: Vec<MenuItem<'a>>,
160}
161
162pub enum MenuItem<'a> {
163 Separator,
164 Submenu(Menu<'a>),
165 Action {
166 name: &'a str,
167 action: Box<dyn Action>,
168 },
169}
170
171#[derive(Clone)]
172pub struct App(Rc<RefCell<MutableAppContext>>);
173
174#[derive(Clone)]
175pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
176
177#[cfg(any(test, feature = "test-support"))]
178pub struct TestAppContext {
179 cx: Rc<RefCell<MutableAppContext>>,
180 foreground_platform: Rc<platform::test::ForegroundPlatform>,
181 condition_duration: Option<Duration>,
182}
183
184pub struct WindowInputHandler {
185 app: Rc<RefCell<MutableAppContext>>,
186 window_id: usize,
187}
188
189impl App {
190 pub fn new(asset_source: impl AssetSource) -> Result<Self> {
191 let platform = platform::current::platform();
192 let foreground_platform = platform::current::foreground_platform();
193 let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
194 let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
195 foreground,
196 Arc::new(executor::Background::new()),
197 platform.clone(),
198 foreground_platform.clone(),
199 Arc::new(FontCache::new(platform.fonts())),
200 Default::default(),
201 asset_source,
202 ))));
203
204 foreground_platform.on_quit(Box::new({
205 let cx = app.0.clone();
206 move || {
207 cx.borrow_mut().quit();
208 }
209 }));
210 foreground_platform.on_will_open_menu(Box::new({
211 let cx = app.0.clone();
212 move || {
213 let mut cx = cx.borrow_mut();
214 cx.keystroke_matcher.clear_pending();
215 }
216 }));
217 foreground_platform.on_validate_menu_command(Box::new({
218 let cx = app.0.clone();
219 move |action| {
220 let cx = cx.borrow_mut();
221 !cx.keystroke_matcher.has_pending_keystrokes() && cx.is_action_available(action)
222 }
223 }));
224 foreground_platform.on_menu_command(Box::new({
225 let cx = app.0.clone();
226 move |action| {
227 let mut cx = cx.borrow_mut();
228 if let Some(key_window_id) = cx.cx.platform.key_window_id() {
229 if let Some((presenter, _)) =
230 cx.presenters_and_platform_windows.get(&key_window_id)
231 {
232 let presenter = presenter.clone();
233 let path = presenter.borrow().dispatch_path(cx.as_ref());
234 cx.dispatch_action_any(key_window_id, &path, action);
235 } else {
236 cx.dispatch_global_action_any(action);
237 }
238 } else {
239 cx.dispatch_global_action_any(action);
240 }
241 }
242 }));
243
244 app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
245 Ok(app)
246 }
247
248 pub fn background(&self) -> Arc<executor::Background> {
249 self.0.borrow().background().clone()
250 }
251
252 pub fn on_become_active<F>(self, mut callback: F) -> Self
253 where
254 F: 'static + FnMut(&mut MutableAppContext),
255 {
256 let cx = self.0.clone();
257 self.0
258 .borrow_mut()
259 .foreground_platform
260 .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
261 self
262 }
263
264 pub fn on_resign_active<F>(self, mut callback: F) -> Self
265 where
266 F: 'static + FnMut(&mut MutableAppContext),
267 {
268 let cx = self.0.clone();
269 self.0
270 .borrow_mut()
271 .foreground_platform
272 .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
273 self
274 }
275
276 pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
277 where
278 F: 'static + FnMut(&mut MutableAppContext),
279 {
280 let cx = self.0.clone();
281 self.0
282 .borrow_mut()
283 .foreground_platform
284 .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
285 self
286 }
287
288 pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
289 where
290 F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
291 {
292 let cx = self.0.clone();
293 self.0
294 .borrow_mut()
295 .foreground_platform
296 .on_event(Box::new(move |event| {
297 callback(event, &mut *cx.borrow_mut())
298 }));
299 self
300 }
301
302 pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
303 where
304 F: 'static + FnMut(Vec<String>, &mut MutableAppContext),
305 {
306 let cx = self.0.clone();
307 self.0
308 .borrow_mut()
309 .foreground_platform
310 .on_open_urls(Box::new(move |paths| {
311 callback(paths, &mut *cx.borrow_mut())
312 }));
313 self
314 }
315
316 pub fn run<F>(self, on_finish_launching: F)
317 where
318 F: 'static + FnOnce(&mut MutableAppContext),
319 {
320 let platform = self.0.borrow().foreground_platform.clone();
321 platform.run(Box::new(move || {
322 let mut cx = self.0.borrow_mut();
323 let cx = &mut *cx;
324 crate::views::init(cx);
325 on_finish_launching(cx);
326 }))
327 }
328
329 pub fn platform(&self) -> Arc<dyn Platform> {
330 self.0.borrow().platform()
331 }
332
333 pub fn font_cache(&self) -> Arc<FontCache> {
334 self.0.borrow().cx.font_cache.clone()
335 }
336
337 fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
338 let mut state = self.0.borrow_mut();
339 let result = state.update(callback);
340 state.pending_notifications.clear();
341 result
342 }
343}
344
345impl WindowInputHandler {
346 fn read_focused_view<T, F>(&self, f: F) -> Option<T>
347 where
348 F: FnOnce(&dyn AnyView, &AppContext) -> T,
349 {
350 let app = self.app.borrow();
351 let view_id = app.focused_view_id(self.window_id)?;
352 let view = app.cx.views.get(&(self.window_id, view_id))?;
353 let result = f(view.as_ref(), &app);
354 Some(result)
355 }
356
357 fn update_focused_view<T, F>(&mut self, f: F) -> Option<T>
358 where
359 F: FnOnce(usize, usize, &mut dyn AnyView, &mut MutableAppContext) -> T,
360 {
361 let mut app = self.app.borrow_mut();
362 app.update(|app| {
363 let view_id = app.focused_view_id(self.window_id)?;
364 let mut view = app.cx.views.remove(&(self.window_id, view_id))?;
365 let result = f(self.window_id, view_id, view.as_mut(), &mut *app);
366 app.cx.views.insert((self.window_id, view_id), view);
367 Some(result)
368 })
369 }
370}
371
372impl InputHandler for WindowInputHandler {
373 fn text_for_range(&self, range: Range<usize>) -> Option<String> {
374 self.read_focused_view(|view, cx| view.text_for_range(range.clone(), cx))
375 .flatten()
376 }
377
378 fn selected_text_range(&self) -> Option<Range<usize>> {
379 self.read_focused_view(|view, cx| view.selected_text_range(cx))
380 .flatten()
381 }
382
383 fn replace_text_in_range(&mut self, range: Option<Range<usize>>, text: &str) {
384 self.update_focused_view(|window_id, view_id, view, cx| {
385 view.replace_text_in_range(range, text, cx, window_id, view_id);
386 });
387 }
388
389 fn marked_text_range(&self) -> Option<Range<usize>> {
390 self.read_focused_view(|view, cx| view.marked_text_range(cx))
391 .flatten()
392 }
393
394 fn unmark_text(&mut self) {
395 self.update_focused_view(|window_id, view_id, view, cx| {
396 view.unmark_text(cx, window_id, view_id);
397 });
398 }
399
400 fn replace_and_mark_text_in_range(
401 &mut self,
402 range: Option<Range<usize>>,
403 new_text: &str,
404 new_selected_range: Option<Range<usize>>,
405 ) {
406 self.update_focused_view(|window_id, view_id, view, cx| {
407 view.replace_and_mark_text_in_range(
408 range,
409 new_text,
410 new_selected_range,
411 cx,
412 window_id,
413 view_id,
414 );
415 });
416 }
417
418 fn rect_for_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
419 let app = self.app.borrow();
420 let (presenter, _) = app.presenters_and_platform_windows.get(&self.window_id)?;
421 let presenter = presenter.borrow();
422 presenter.rect_for_text_range(range_utf16, &app)
423 }
424}
425
426#[cfg(any(test, feature = "test-support"))]
427impl TestAppContext {
428 pub fn new(
429 foreground_platform: Rc<platform::test::ForegroundPlatform>,
430 platform: Arc<dyn Platform>,
431 foreground: Rc<executor::Foreground>,
432 background: Arc<executor::Background>,
433 font_cache: Arc<FontCache>,
434 leak_detector: Arc<Mutex<LeakDetector>>,
435 first_entity_id: usize,
436 ) -> Self {
437 let mut cx = MutableAppContext::new(
438 foreground.clone(),
439 background,
440 platform,
441 foreground_platform.clone(),
442 font_cache,
443 RefCounts {
444 #[cfg(any(test, feature = "test-support"))]
445 leak_detector,
446 ..Default::default()
447 },
448 (),
449 );
450 cx.next_entity_id = first_entity_id;
451 let cx = TestAppContext {
452 cx: Rc::new(RefCell::new(cx)),
453 foreground_platform,
454 condition_duration: None,
455 };
456 cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
457 cx
458 }
459
460 pub fn dispatch_action<A: Action>(&self, window_id: usize, action: A) {
461 let mut cx = self.cx.borrow_mut();
462 let dispatch_path = cx
463 .presenters_and_platform_windows
464 .get(&window_id)
465 .unwrap()
466 .0
467 .borrow()
468 .dispatch_path(cx.as_ref());
469
470 cx.dispatch_action_any(window_id, &dispatch_path, &action);
471 }
472
473 pub fn dispatch_global_action<A: Action>(&self, action: A) {
474 self.cx.borrow_mut().dispatch_global_action(action);
475 }
476
477 pub fn dispatch_keystroke(&mut self, window_id: usize, keystroke: Keystroke, is_held: bool) {
478 let handled = self.cx.borrow_mut().update(|cx| {
479 let presenter = cx
480 .presenters_and_platform_windows
481 .get(&window_id)
482 .unwrap()
483 .0
484 .clone();
485 let dispatch_path = presenter.borrow().dispatch_path(cx.as_ref());
486
487 if cx.dispatch_keystroke(window_id, dispatch_path, &keystroke) {
488 return true;
489 }
490 if presenter.borrow_mut().dispatch_event(
491 Event::KeyDown(KeyDownEvent {
492 keystroke: keystroke.clone(),
493 is_held,
494 }),
495 cx,
496 ) {
497 return true;
498 }
499
500 false
501 });
502
503 if !handled && !keystroke.cmd && !keystroke.ctrl {
504 WindowInputHandler {
505 app: self.cx.clone(),
506 window_id,
507 }
508 .replace_text_in_range(None, &keystroke.key)
509 }
510 }
511
512 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
513 where
514 T: Entity,
515 F: FnOnce(&mut ModelContext<T>) -> T,
516 {
517 self.cx.borrow_mut().add_model(build_model)
518 }
519
520 pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
521 where
522 T: View,
523 F: FnOnce(&mut ViewContext<T>) -> T,
524 {
525 let (window_id, view) = self
526 .cx
527 .borrow_mut()
528 .add_window(Default::default(), build_root_view);
529 self.simulate_window_activation(Some(window_id));
530 (window_id, view)
531 }
532
533 pub fn window_ids(&self) -> Vec<usize> {
534 self.cx.borrow().window_ids().collect()
535 }
536
537 pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
538 self.cx.borrow().root_view(window_id)
539 }
540
541 pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
542 where
543 T: View,
544 F: FnOnce(&mut ViewContext<T>) -> T,
545 {
546 self.cx.borrow_mut().add_view(window_id, build_view)
547 }
548
549 pub fn add_option_view<T, F>(
550 &mut self,
551 window_id: usize,
552 build_view: F,
553 ) -> Option<ViewHandle<T>>
554 where
555 T: View,
556 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
557 {
558 self.cx.borrow_mut().add_option_view(window_id, build_view)
559 }
560
561 pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
562 callback(self.cx.borrow().as_ref())
563 }
564
565 pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
566 let mut state = self.cx.borrow_mut();
567 // Don't increment pending flushes in order for effects to be flushed before the callback
568 // completes, which is helpful in tests.
569 let result = callback(&mut *state);
570 // Flush effects after the callback just in case there are any. This can happen in edge
571 // cases such as the closure dropping handles.
572 state.flush_effects();
573 result
574 }
575
576 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
577 where
578 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
579 V: View,
580 {
581 handle.update(&mut *self.cx.borrow_mut(), |view, cx| {
582 let mut render_cx = RenderContext {
583 app: cx,
584 window_id: handle.window_id(),
585 view_id: handle.id(),
586 view_type: PhantomData,
587 titlebar_height: 0.,
588 hovered_region_ids: Default::default(),
589 clicked_region_id: None,
590 right_clicked_region_id: None,
591 refreshing: false,
592 };
593 f(view, &mut render_cx)
594 })
595 }
596
597 pub fn to_async(&self) -> AsyncAppContext {
598 AsyncAppContext(self.cx.clone())
599 }
600
601 pub fn font_cache(&self) -> Arc<FontCache> {
602 self.cx.borrow().cx.font_cache.clone()
603 }
604
605 pub fn foreground_platform(&self) -> Rc<platform::test::ForegroundPlatform> {
606 self.foreground_platform.clone()
607 }
608
609 pub fn platform(&self) -> Arc<dyn platform::Platform> {
610 self.cx.borrow().cx.platform.clone()
611 }
612
613 pub fn foreground(&self) -> Rc<executor::Foreground> {
614 self.cx.borrow().foreground().clone()
615 }
616
617 pub fn background(&self) -> Arc<executor::Background> {
618 self.cx.borrow().background().clone()
619 }
620
621 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
622 where
623 F: FnOnce(AsyncAppContext) -> Fut,
624 Fut: 'static + Future<Output = T>,
625 T: 'static,
626 {
627 let foreground = self.foreground();
628 let future = f(self.to_async());
629 let cx = self.to_async();
630 foreground.spawn(async move {
631 let result = future.await;
632 cx.0.borrow_mut().flush_effects();
633 result
634 })
635 }
636
637 pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
638 self.foreground_platform.simulate_new_path_selection(result);
639 }
640
641 pub fn did_prompt_for_new_path(&self) -> bool {
642 self.foreground_platform.as_ref().did_prompt_for_new_path()
643 }
644
645 pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
646 use postage::prelude::Sink as _;
647
648 let mut done_tx = self
649 .window_mut(window_id)
650 .pending_prompts
651 .borrow_mut()
652 .pop_front()
653 .expect("prompt was not called");
654 let _ = done_tx.try_send(answer);
655 }
656
657 pub fn has_pending_prompt(&self, window_id: usize) -> bool {
658 let window = self.window_mut(window_id);
659 let prompts = window.pending_prompts.borrow_mut();
660 !prompts.is_empty()
661 }
662
663 pub fn current_window_title(&self, window_id: usize) -> Option<String> {
664 self.window_mut(window_id).title.clone()
665 }
666
667 pub fn simulate_window_close(&self, window_id: usize) -> bool {
668 let handler = self.window_mut(window_id).should_close_handler.take();
669 if let Some(mut handler) = handler {
670 let should_close = handler();
671 self.window_mut(window_id).should_close_handler = Some(handler);
672 should_close
673 } else {
674 false
675 }
676 }
677
678 pub fn simulate_window_activation(&self, to_activate: Option<usize>) {
679 let mut handlers = BTreeMap::new();
680 {
681 let mut cx = self.cx.borrow_mut();
682 for (window_id, (_, window)) in &mut cx.presenters_and_platform_windows {
683 let window = window
684 .as_any_mut()
685 .downcast_mut::<platform::test::Window>()
686 .unwrap();
687 handlers.insert(
688 *window_id,
689 mem::take(&mut window.active_status_change_handlers),
690 );
691 }
692 };
693 let mut handlers = handlers.into_iter().collect::<Vec<_>>();
694 handlers.sort_unstable_by_key(|(window_id, _)| Some(*window_id) == to_activate);
695
696 for (window_id, mut window_handlers) in handlers {
697 for window_handler in &mut window_handlers {
698 window_handler(Some(window_id) == to_activate);
699 }
700
701 self.window_mut(window_id)
702 .active_status_change_handlers
703 .extend(window_handlers);
704 }
705 }
706
707 pub fn is_window_edited(&self, window_id: usize) -> bool {
708 self.window_mut(window_id).edited
709 }
710
711 pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
712 self.cx.borrow().leak_detector()
713 }
714
715 pub fn assert_dropped(&self, handle: impl WeakHandle) {
716 self.cx
717 .borrow()
718 .leak_detector()
719 .lock()
720 .assert_dropped(handle.id())
721 }
722
723 fn window_mut(&self, window_id: usize) -> std::cell::RefMut<platform::test::Window> {
724 std::cell::RefMut::map(self.cx.borrow_mut(), |state| {
725 let (_, window) = state
726 .presenters_and_platform_windows
727 .get_mut(&window_id)
728 .unwrap();
729 let test_window = window
730 .as_any_mut()
731 .downcast_mut::<platform::test::Window>()
732 .unwrap();
733 test_window
734 })
735 }
736
737 pub fn set_condition_duration(&mut self, duration: Option<Duration>) {
738 self.condition_duration = duration;
739 }
740
741 pub fn condition_duration(&self) -> Duration {
742 self.condition_duration.unwrap_or_else(|| {
743 if std::env::var("CI").is_ok() {
744 Duration::from_secs(2)
745 } else {
746 Duration::from_millis(500)
747 }
748 })
749 }
750
751 pub fn assert_clipboard_content(&mut self, expected_content: Option<&str>) {
752 self.update(|cx| {
753 let actual_content = cx.read_from_clipboard().map(|item| item.text().to_owned());
754 let expected_content = expected_content.map(|content| content.to_owned());
755 assert_eq!(actual_content, expected_content);
756 })
757 }
758}
759
760impl AsyncAppContext {
761 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
762 where
763 F: FnOnce(AsyncAppContext) -> Fut,
764 Fut: 'static + Future<Output = T>,
765 T: 'static,
766 {
767 self.0.borrow().foreground.spawn(f(self.clone()))
768 }
769
770 pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
771 callback(self.0.borrow().as_ref())
772 }
773
774 pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
775 self.0.borrow_mut().update(callback)
776 }
777
778 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
779 where
780 T: Entity,
781 F: FnOnce(&mut ModelContext<T>) -> T,
782 {
783 self.update(|cx| cx.add_model(build_model))
784 }
785
786 pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
787 where
788 T: View,
789 F: FnOnce(&mut ViewContext<T>) -> T,
790 {
791 self.update(|cx| cx.add_view(window_id, build_view))
792 }
793
794 pub fn add_window<T, F>(
795 &mut self,
796 window_options: WindowOptions,
797 build_root_view: F,
798 ) -> (usize, ViewHandle<T>)
799 where
800 T: View,
801 F: FnOnce(&mut ViewContext<T>) -> T,
802 {
803 self.update(|cx| cx.add_window(window_options, build_root_view))
804 }
805
806 pub fn platform(&self) -> Arc<dyn Platform> {
807 self.0.borrow().platform()
808 }
809
810 pub fn foreground(&self) -> Rc<executor::Foreground> {
811 self.0.borrow().foreground.clone()
812 }
813
814 pub fn background(&self) -> Arc<executor::Background> {
815 self.0.borrow().cx.background.clone()
816 }
817}
818
819impl UpdateModel for AsyncAppContext {
820 fn update_model<E: Entity, O>(
821 &mut self,
822 handle: &ModelHandle<E>,
823 update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
824 ) -> O {
825 self.0.borrow_mut().update_model(handle, update)
826 }
827}
828
829impl UpgradeModelHandle for AsyncAppContext {
830 fn upgrade_model_handle<T: Entity>(
831 &self,
832 handle: &WeakModelHandle<T>,
833 ) -> Option<ModelHandle<T>> {
834 self.0.borrow().upgrade_model_handle(handle)
835 }
836
837 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
838 self.0.borrow().model_handle_is_upgradable(handle)
839 }
840
841 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
842 self.0.borrow().upgrade_any_model_handle(handle)
843 }
844}
845
846impl UpgradeViewHandle for AsyncAppContext {
847 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
848 self.0.borrow_mut().upgrade_view_handle(handle)
849 }
850
851 fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
852 self.0.borrow_mut().upgrade_any_view_handle(handle)
853 }
854}
855
856impl ReadModelWith for AsyncAppContext {
857 fn read_model_with<E: Entity, T>(
858 &self,
859 handle: &ModelHandle<E>,
860 read: &mut dyn FnMut(&E, &AppContext) -> T,
861 ) -> T {
862 let cx = self.0.borrow();
863 let cx = cx.as_ref();
864 read(handle.read(cx), cx)
865 }
866}
867
868impl UpdateView for AsyncAppContext {
869 fn update_view<T, S>(
870 &mut self,
871 handle: &ViewHandle<T>,
872 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
873 ) -> S
874 where
875 T: View,
876 {
877 self.0.borrow_mut().update_view(handle, update)
878 }
879}
880
881impl ReadViewWith for AsyncAppContext {
882 fn read_view_with<V, T>(
883 &self,
884 handle: &ViewHandle<V>,
885 read: &mut dyn FnMut(&V, &AppContext) -> T,
886 ) -> T
887 where
888 V: View,
889 {
890 let cx = self.0.borrow();
891 let cx = cx.as_ref();
892 read(handle.read(cx), cx)
893 }
894}
895
896#[cfg(any(test, feature = "test-support"))]
897impl UpdateModel for TestAppContext {
898 fn update_model<T: Entity, O>(
899 &mut self,
900 handle: &ModelHandle<T>,
901 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
902 ) -> O {
903 self.cx.borrow_mut().update_model(handle, update)
904 }
905}
906
907#[cfg(any(test, feature = "test-support"))]
908impl ReadModelWith for TestAppContext {
909 fn read_model_with<E: Entity, T>(
910 &self,
911 handle: &ModelHandle<E>,
912 read: &mut dyn FnMut(&E, &AppContext) -> T,
913 ) -> T {
914 let cx = self.cx.borrow();
915 let cx = cx.as_ref();
916 read(handle.read(cx), cx)
917 }
918}
919
920#[cfg(any(test, feature = "test-support"))]
921impl UpdateView for TestAppContext {
922 fn update_view<T, S>(
923 &mut self,
924 handle: &ViewHandle<T>,
925 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
926 ) -> S
927 where
928 T: View,
929 {
930 self.cx.borrow_mut().update_view(handle, update)
931 }
932}
933
934#[cfg(any(test, feature = "test-support"))]
935impl ReadViewWith for TestAppContext {
936 fn read_view_with<V, T>(
937 &self,
938 handle: &ViewHandle<V>,
939 read: &mut dyn FnMut(&V, &AppContext) -> T,
940 ) -> T
941 where
942 V: View,
943 {
944 let cx = self.cx.borrow();
945 let cx = cx.as_ref();
946 read(handle.read(cx), cx)
947 }
948}
949
950type ActionCallback =
951 dyn FnMut(&mut dyn AnyView, &dyn Action, &mut MutableAppContext, usize, usize);
952type GlobalActionCallback = dyn FnMut(&dyn Action, &mut MutableAppContext);
953
954type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
955type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext)>;
956type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
957type FocusObservationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
958type GlobalObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
959type ReleaseObservationCallback = Box<dyn FnOnce(&dyn Any, &mut MutableAppContext)>;
960type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut MutableAppContext)>;
961type WindowActivationCallback = Box<dyn FnMut(bool, &mut MutableAppContext) -> bool>;
962type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
963type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
964
965pub struct MutableAppContext {
966 weak_self: Option<rc::Weak<RefCell<Self>>>,
967 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
968 assets: Arc<AssetCache>,
969 cx: AppContext,
970 action_deserializers: HashMap<&'static str, (TypeId, DeserializeActionCallback)>,
971 capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
972 actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
973 global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
974 keystroke_matcher: keymap::Matcher,
975 next_entity_id: usize,
976 next_window_id: usize,
977 next_subscription_id: usize,
978 frame_count: usize,
979 subscriptions: Arc<Mutex<HashMap<usize, BTreeMap<usize, Option<SubscriptionCallback>>>>>,
980 global_subscriptions:
981 Arc<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalSubscriptionCallback>>>>>,
982 observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, Option<ObservationCallback>>>>>,
983 focus_observations:
984 Arc<Mutex<HashMap<usize, BTreeMap<usize, Option<FocusObservationCallback>>>>>,
985 global_observations:
986 Arc<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalObservationCallback>>>>>,
987 release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
988 window_activation_observations:
989 Arc<Mutex<HashMap<usize, BTreeMap<usize, Option<WindowActivationCallback>>>>>,
990 action_dispatch_observations: Arc<Mutex<BTreeMap<usize, ActionObservationCallback>>>,
991 presenters_and_platform_windows:
992 HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
993 foreground: Rc<executor::Foreground>,
994 pending_effects: VecDeque<Effect>,
995 pending_focus_index: Option<usize>,
996 pending_notifications: HashSet<usize>,
997 pending_global_notifications: HashSet<TypeId>,
998 pending_flushes: usize,
999 flushing_effects: bool,
1000 halt_action_dispatch: bool,
1001}
1002
1003impl MutableAppContext {
1004 fn new(
1005 foreground: Rc<executor::Foreground>,
1006 background: Arc<executor::Background>,
1007 platform: Arc<dyn platform::Platform>,
1008 foreground_platform: Rc<dyn platform::ForegroundPlatform>,
1009 font_cache: Arc<FontCache>,
1010 ref_counts: RefCounts,
1011 asset_source: impl AssetSource,
1012 ) -> Self {
1013 Self {
1014 weak_self: None,
1015 foreground_platform,
1016 assets: Arc::new(AssetCache::new(asset_source)),
1017 cx: AppContext {
1018 models: Default::default(),
1019 views: Default::default(),
1020 windows: Default::default(),
1021 globals: Default::default(),
1022 element_states: Default::default(),
1023 ref_counts: Arc::new(Mutex::new(ref_counts)),
1024 background,
1025 font_cache,
1026 platform,
1027 },
1028 action_deserializers: HashMap::new(),
1029 capture_actions: HashMap::new(),
1030 actions: HashMap::new(),
1031 global_actions: HashMap::new(),
1032 keystroke_matcher: keymap::Matcher::default(),
1033 next_entity_id: 0,
1034 next_window_id: 0,
1035 next_subscription_id: 0,
1036 frame_count: 0,
1037 subscriptions: Default::default(),
1038 global_subscriptions: Default::default(),
1039 observations: Default::default(),
1040 focus_observations: Default::default(),
1041 release_observations: Default::default(),
1042 global_observations: Default::default(),
1043 window_activation_observations: Default::default(),
1044 action_dispatch_observations: Default::default(),
1045 presenters_and_platform_windows: HashMap::new(),
1046 foreground,
1047 pending_effects: VecDeque::new(),
1048 pending_focus_index: None,
1049 pending_notifications: HashSet::new(),
1050 pending_global_notifications: HashSet::new(),
1051 pending_flushes: 0,
1052 flushing_effects: false,
1053 halt_action_dispatch: false,
1054 }
1055 }
1056
1057 pub fn upgrade(&self) -> App {
1058 App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1059 }
1060
1061 pub fn quit(&mut self) {
1062 let mut futures = Vec::new();
1063 for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
1064 let mut model = self.cx.models.remove(&model_id).unwrap();
1065 futures.extend(model.app_will_quit(self));
1066 self.cx.models.insert(model_id, model);
1067 }
1068
1069 for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
1070 let mut view = self.cx.views.remove(&view_id).unwrap();
1071 futures.extend(view.app_will_quit(self));
1072 self.cx.views.insert(view_id, view);
1073 }
1074
1075 self.remove_all_windows();
1076
1077 let futures = futures::future::join_all(futures);
1078 if self
1079 .background
1080 .block_with_timeout(Duration::from_millis(100), futures)
1081 .is_err()
1082 {
1083 log::error!("timed out waiting on app_will_quit");
1084 }
1085 }
1086
1087 pub fn remove_all_windows(&mut self) {
1088 for (window_id, _) in self.cx.windows.drain() {
1089 self.presenters_and_platform_windows.remove(&window_id);
1090 }
1091 self.flush_effects();
1092 }
1093
1094 pub fn platform(&self) -> Arc<dyn platform::Platform> {
1095 self.cx.platform.clone()
1096 }
1097
1098 pub fn font_cache(&self) -> &Arc<FontCache> {
1099 &self.cx.font_cache
1100 }
1101
1102 pub fn foreground(&self) -> &Rc<executor::Foreground> {
1103 &self.foreground
1104 }
1105
1106 pub fn background(&self) -> &Arc<executor::Background> {
1107 &self.cx.background
1108 }
1109
1110 pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
1111 self.presenters_and_platform_windows
1112 .get(&window_id)
1113 .and_then(|(presenter, _)| presenter.borrow().debug_elements(self))
1114 }
1115
1116 pub fn deserialize_action(
1117 &self,
1118 name: &str,
1119 argument: Option<&str>,
1120 ) -> Result<Box<dyn Action>> {
1121 let callback = self
1122 .action_deserializers
1123 .get(name)
1124 .ok_or_else(|| anyhow!("unknown action {}", name))?
1125 .1;
1126 callback(argument.unwrap_or("{}"))
1127 .with_context(|| format!("invalid data for action {}", name))
1128 }
1129
1130 pub fn add_action<A, V, F>(&mut self, handler: F)
1131 where
1132 A: Action,
1133 V: View,
1134 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
1135 {
1136 self.add_action_internal(handler, false)
1137 }
1138
1139 pub fn capture_action<A, V, F>(&mut self, handler: F)
1140 where
1141 A: Action,
1142 V: View,
1143 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
1144 {
1145 self.add_action_internal(handler, true)
1146 }
1147
1148 fn add_action_internal<A, V, F>(&mut self, mut handler: F, capture: bool)
1149 where
1150 A: Action,
1151 V: View,
1152 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
1153 {
1154 let handler = Box::new(
1155 move |view: &mut dyn AnyView,
1156 action: &dyn Action,
1157 cx: &mut MutableAppContext,
1158 window_id: usize,
1159 view_id: usize| {
1160 let action = action.as_any().downcast_ref().unwrap();
1161 let mut cx = ViewContext::new(cx, window_id, view_id);
1162 handler(
1163 view.as_any_mut()
1164 .downcast_mut()
1165 .expect("downcast is type safe"),
1166 action,
1167 &mut cx,
1168 );
1169 },
1170 );
1171
1172 self.action_deserializers
1173 .entry(A::qualified_name())
1174 .or_insert((TypeId::of::<A>(), A::from_json_str));
1175
1176 let actions = if capture {
1177 &mut self.capture_actions
1178 } else {
1179 &mut self.actions
1180 };
1181
1182 actions
1183 .entry(TypeId::of::<V>())
1184 .or_default()
1185 .entry(TypeId::of::<A>())
1186 .or_default()
1187 .push(handler);
1188 }
1189
1190 pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
1191 where
1192 A: Action,
1193 V: View,
1194 F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
1195 {
1196 self.add_action(move |view, action, cx| {
1197 handler(view, action, cx).map(|task| task.detach_and_log_err(cx));
1198 })
1199 }
1200
1201 pub fn add_global_action<A, F>(&mut self, mut handler: F)
1202 where
1203 A: Action,
1204 F: 'static + FnMut(&A, &mut MutableAppContext),
1205 {
1206 let handler = Box::new(move |action: &dyn Action, cx: &mut MutableAppContext| {
1207 let action = action.as_any().downcast_ref().unwrap();
1208 handler(action, cx);
1209 });
1210
1211 self.action_deserializers
1212 .entry(A::qualified_name())
1213 .or_insert((TypeId::of::<A>(), A::from_json_str));
1214
1215 if self
1216 .global_actions
1217 .insert(TypeId::of::<A>(), handler)
1218 .is_some()
1219 {
1220 panic!(
1221 "registered multiple global handlers for {}",
1222 type_name::<A>()
1223 );
1224 }
1225 }
1226
1227 pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
1228 self.cx.windows.keys().cloned()
1229 }
1230
1231 pub fn activate_window(&self, window_id: usize) {
1232 if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
1233 window.activate()
1234 }
1235 }
1236
1237 pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
1238 self.cx
1239 .windows
1240 .get(&window_id)
1241 .and_then(|window| window.root_view.clone().downcast::<T>())
1242 }
1243
1244 pub fn window_is_active(&self, window_id: usize) -> bool {
1245 self.cx
1246 .windows
1247 .get(&window_id)
1248 .map_or(false, |window| window.is_active)
1249 }
1250
1251 pub fn render_view(&mut self, params: RenderParams) -> Result<ElementBox> {
1252 let window_id = params.window_id;
1253 let view_id = params.view_id;
1254 let mut view = self
1255 .cx
1256 .views
1257 .remove(&(params.window_id, params.view_id))
1258 .ok_or(anyhow!("view not found"))?;
1259 let element = view.render(params, self);
1260 self.cx.views.insert((window_id, view_id), view);
1261 Ok(element)
1262 }
1263
1264 pub fn render_views(
1265 &mut self,
1266 window_id: usize,
1267 titlebar_height: f32,
1268 ) -> HashMap<usize, ElementBox> {
1269 self.start_frame();
1270 let view_ids = self
1271 .views
1272 .keys()
1273 .filter_map(|(win_id, view_id)| {
1274 if *win_id == window_id {
1275 Some(*view_id)
1276 } else {
1277 None
1278 }
1279 })
1280 .collect::<Vec<_>>();
1281 view_ids
1282 .into_iter()
1283 .map(|view_id| {
1284 (
1285 view_id,
1286 self.render_view(RenderParams {
1287 window_id,
1288 view_id,
1289 titlebar_height,
1290 hovered_region_ids: Default::default(),
1291 clicked_region_id: None,
1292 right_clicked_region_id: None,
1293 refreshing: false,
1294 })
1295 .unwrap(),
1296 )
1297 })
1298 .collect()
1299 }
1300
1301 pub(crate) fn start_frame(&mut self) {
1302 self.frame_count += 1;
1303 }
1304
1305 pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
1306 self.pending_flushes += 1;
1307 let result = callback(self);
1308 self.flush_effects();
1309 result
1310 }
1311
1312 pub fn set_menus(&mut self, menus: Vec<Menu>) {
1313 self.foreground_platform
1314 .set_menus(menus, &self.keystroke_matcher);
1315 }
1316
1317 fn show_character_palette(&self, window_id: usize) {
1318 let (_, window) = &self.presenters_and_platform_windows[&window_id];
1319 window.show_character_palette();
1320 }
1321
1322 pub fn minimize_window(&self, window_id: usize) {
1323 let (_, window) = &self.presenters_and_platform_windows[&window_id];
1324 window.minimize();
1325 }
1326
1327 pub fn zoom_window(&self, window_id: usize) {
1328 let (_, window) = &self.presenters_and_platform_windows[&window_id];
1329 window.zoom();
1330 }
1331
1332 fn prompt(
1333 &self,
1334 window_id: usize,
1335 level: PromptLevel,
1336 msg: &str,
1337 answers: &[&str],
1338 ) -> oneshot::Receiver<usize> {
1339 let (_, window) = &self.presenters_and_platform_windows[&window_id];
1340 window.prompt(level, msg, answers)
1341 }
1342
1343 pub fn prompt_for_paths(
1344 &self,
1345 options: PathPromptOptions,
1346 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1347 self.foreground_platform.prompt_for_paths(options)
1348 }
1349
1350 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1351 self.foreground_platform.prompt_for_new_path(directory)
1352 }
1353
1354 pub fn emit_global<E: Any>(&mut self, payload: E) {
1355 self.pending_effects.push_back(Effect::GlobalEvent {
1356 payload: Box::new(payload),
1357 });
1358 }
1359
1360 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1361 where
1362 E: Entity,
1363 E::Event: 'static,
1364 H: Handle<E>,
1365 F: 'static + FnMut(H, &E::Event, &mut Self),
1366 {
1367 self.subscribe_internal(handle, move |handle, event, cx| {
1368 callback(handle, event, cx);
1369 true
1370 })
1371 }
1372
1373 pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
1374 where
1375 E: Any,
1376 F: 'static + FnMut(&E, &mut Self),
1377 {
1378 let subscription_id = post_inc(&mut self.next_subscription_id);
1379 let type_id = TypeId::of::<E>();
1380 self.pending_effects.push_back(Effect::GlobalSubscription {
1381 type_id,
1382 subscription_id,
1383 callback: Box::new(move |payload, cx| {
1384 let payload = payload.downcast_ref().expect("downcast is type safe");
1385 callback(payload, cx)
1386 }),
1387 });
1388 Subscription::GlobalSubscription {
1389 id: subscription_id,
1390 type_id,
1391 subscriptions: Some(Arc::downgrade(&self.global_subscriptions)),
1392 }
1393 }
1394
1395 pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1396 where
1397 E: Entity,
1398 E::Event: 'static,
1399 H: Handle<E>,
1400 F: 'static + FnMut(H, &mut Self),
1401 {
1402 self.observe_internal(handle, move |handle, cx| {
1403 callback(handle, cx);
1404 true
1405 })
1406 }
1407
1408 pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1409 where
1410 E: Entity,
1411 E::Event: 'static,
1412 H: Handle<E>,
1413 F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1414 {
1415 let subscription_id = post_inc(&mut self.next_subscription_id);
1416 let emitter = handle.downgrade();
1417 self.pending_effects.push_back(Effect::Subscription {
1418 entity_id: handle.id(),
1419 subscription_id,
1420 callback: Box::new(move |payload, cx| {
1421 if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1422 let payload = payload.downcast_ref().expect("downcast is type safe");
1423 callback(emitter, payload, cx)
1424 } else {
1425 false
1426 }
1427 }),
1428 });
1429 Subscription::Subscription {
1430 id: subscription_id,
1431 entity_id: handle.id(),
1432 subscriptions: Some(Arc::downgrade(&self.subscriptions)),
1433 }
1434 }
1435
1436 fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1437 where
1438 E: Entity,
1439 E::Event: 'static,
1440 H: Handle<E>,
1441 F: 'static + FnMut(H, &mut Self) -> bool,
1442 {
1443 let subscription_id = post_inc(&mut self.next_subscription_id);
1444 let observed = handle.downgrade();
1445 let entity_id = handle.id();
1446 self.pending_effects.push_back(Effect::Observation {
1447 entity_id,
1448 subscription_id,
1449 callback: Box::new(move |cx| {
1450 if let Some(observed) = H::upgrade_from(&observed, cx) {
1451 callback(observed, cx)
1452 } else {
1453 false
1454 }
1455 }),
1456 });
1457 Subscription::Observation {
1458 id: subscription_id,
1459 entity_id,
1460 observations: Some(Arc::downgrade(&self.observations)),
1461 }
1462 }
1463
1464 fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
1465 where
1466 F: 'static + FnMut(ViewHandle<V>, bool, &mut MutableAppContext) -> bool,
1467 V: View,
1468 {
1469 let subscription_id = post_inc(&mut self.next_subscription_id);
1470 let observed = handle.downgrade();
1471 let view_id = handle.id();
1472 self.pending_effects.push_back(Effect::FocusObservation {
1473 view_id,
1474 subscription_id,
1475 callback: Box::new(move |focused, cx| {
1476 if let Some(observed) = observed.upgrade(cx) {
1477 callback(observed, focused, cx)
1478 } else {
1479 false
1480 }
1481 }),
1482 });
1483 Subscription::FocusObservation {
1484 id: subscription_id,
1485 view_id,
1486 observations: Some(Arc::downgrade(&self.focus_observations)),
1487 }
1488 }
1489
1490 pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
1491 where
1492 G: Any,
1493 F: 'static + FnMut(&mut MutableAppContext),
1494 {
1495 let type_id = TypeId::of::<G>();
1496 let id = post_inc(&mut self.next_subscription_id);
1497
1498 self.global_observations
1499 .lock()
1500 .entry(type_id)
1501 .or_default()
1502 .insert(
1503 id,
1504 Some(Box::new(move |cx: &mut MutableAppContext| observe(cx))
1505 as GlobalObservationCallback),
1506 );
1507
1508 Subscription::GlobalObservation {
1509 id,
1510 type_id,
1511 observations: Some(Arc::downgrade(&self.global_observations)),
1512 }
1513 }
1514
1515 pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
1516 where
1517 E: Entity,
1518 E::Event: 'static,
1519 H: Handle<E>,
1520 F: 'static + FnOnce(&E, &mut Self),
1521 {
1522 let id = post_inc(&mut self.next_subscription_id);
1523 self.release_observations
1524 .lock()
1525 .entry(handle.id())
1526 .or_default()
1527 .insert(
1528 id,
1529 Box::new(move |released, cx| {
1530 let released = released.downcast_ref().unwrap();
1531 callback(released, cx)
1532 }),
1533 );
1534 Subscription::ReleaseObservation {
1535 id,
1536 entity_id: handle.id(),
1537 observations: Some(Arc::downgrade(&self.release_observations)),
1538 }
1539 }
1540
1541 pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
1542 where
1543 F: 'static + FnMut(TypeId, &mut MutableAppContext),
1544 {
1545 let id = post_inc(&mut self.next_subscription_id);
1546 self.action_dispatch_observations
1547 .lock()
1548 .insert(id, Box::new(callback));
1549 Subscription::ActionObservation {
1550 id,
1551 observations: Some(Arc::downgrade(&self.action_dispatch_observations)),
1552 }
1553 }
1554
1555 fn observe_window_activation<F>(&mut self, window_id: usize, callback: F) -> Subscription
1556 where
1557 F: 'static + FnMut(bool, &mut MutableAppContext) -> bool,
1558 {
1559 let subscription_id = post_inc(&mut self.next_subscription_id);
1560 self.pending_effects
1561 .push_back(Effect::WindowActivationObservation {
1562 window_id,
1563 subscription_id,
1564 callback: Box::new(callback),
1565 });
1566 Subscription::WindowActivationObservation {
1567 id: subscription_id,
1568 window_id,
1569 observations: Some(Arc::downgrade(&self.window_activation_observations)),
1570 }
1571 }
1572
1573 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1574 self.pending_effects.push_back(Effect::Deferred {
1575 callback: Box::new(callback),
1576 after_window_update: false,
1577 })
1578 }
1579
1580 pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut MutableAppContext)) {
1581 self.pending_effects.push_back(Effect::Deferred {
1582 callback: Box::new(callback),
1583 after_window_update: true,
1584 })
1585 }
1586
1587 pub(crate) fn notify_model(&mut self, model_id: usize) {
1588 if self.pending_notifications.insert(model_id) {
1589 self.pending_effects
1590 .push_back(Effect::ModelNotification { model_id });
1591 }
1592 }
1593
1594 pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1595 if self.pending_notifications.insert(view_id) {
1596 self.pending_effects
1597 .push_back(Effect::ViewNotification { window_id, view_id });
1598 }
1599 }
1600
1601 pub(crate) fn notify_global(&mut self, type_id: TypeId) {
1602 if self.pending_global_notifications.insert(type_id) {
1603 self.pending_effects
1604 .push_back(Effect::GlobalNotification { type_id });
1605 }
1606 }
1607
1608 pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1609 self.action_deserializers.keys().copied()
1610 }
1611
1612 pub fn available_actions(
1613 &self,
1614 window_id: usize,
1615 view_id: usize,
1616 ) -> impl Iterator<Item = (&'static str, Box<dyn Action>, SmallVec<[&Binding; 1]>)> {
1617 let mut action_types: HashSet<_> = self.global_actions.keys().copied().collect();
1618
1619 let presenter = self
1620 .presenters_and_platform_windows
1621 .get(&window_id)
1622 .unwrap()
1623 .0
1624 .clone();
1625 let mut dispatch_path = Vec::new();
1626 presenter
1627 .borrow()
1628 .compute_dispatch_path_from(view_id, &mut dispatch_path);
1629 for view_id in dispatch_path {
1630 if let Some(view) = self.views.get(&(window_id, view_id)) {
1631 let view_type = view.as_any().type_id();
1632 if let Some(actions) = self.actions.get(&view_type) {
1633 action_types.extend(actions.keys().copied());
1634 }
1635 }
1636 }
1637
1638 self.action_deserializers
1639 .iter()
1640 .filter_map(move |(name, (type_id, deserialize))| {
1641 if action_types.contains(type_id) {
1642 Some((
1643 *name,
1644 deserialize("{}").ok()?,
1645 self.keystroke_matcher
1646 .bindings_for_action_type(*type_id)
1647 .collect(),
1648 ))
1649 } else {
1650 None
1651 }
1652 })
1653 }
1654
1655 pub fn is_action_available(&self, action: &dyn Action) -> bool {
1656 let action_type = action.as_any().type_id();
1657 if let Some(window_id) = self.cx.platform.key_window_id() {
1658 if let Some((presenter, _)) = self.presenters_and_platform_windows.get(&window_id) {
1659 let dispatch_path = presenter.borrow().dispatch_path(&self.cx);
1660 for view_id in dispatch_path {
1661 if let Some(view) = self.views.get(&(window_id, view_id)) {
1662 let view_type = view.as_any().type_id();
1663 if let Some(actions) = self.actions.get(&view_type) {
1664 if actions.contains_key(&action_type) {
1665 return true;
1666 }
1667 }
1668 }
1669 }
1670 }
1671 }
1672 self.global_actions.contains_key(&action_type)
1673 }
1674
1675 /// Return keystrokes that would dispatch the given action closest to the focused view, if there are any.
1676 pub(crate) fn keystrokes_for_action(
1677 &self,
1678 window_id: usize,
1679 dispatch_path: &[usize],
1680 action: &dyn Action,
1681 ) -> Option<SmallVec<[Keystroke; 2]>> {
1682 for view_id in dispatch_path.iter().rev() {
1683 let view = self
1684 .cx
1685 .views
1686 .get(&(window_id, *view_id))
1687 .expect("view in responder chain does not exist");
1688 let cx = view.keymap_context(self.as_ref());
1689 let keystrokes = self.keystroke_matcher.keystrokes_for_action(action, &cx);
1690 if keystrokes.is_some() {
1691 return keystrokes;
1692 }
1693 }
1694
1695 None
1696 }
1697
1698 pub fn dispatch_action_at(&mut self, window_id: usize, view_id: usize, action: &dyn Action) {
1699 let presenter = self
1700 .presenters_and_platform_windows
1701 .get(&window_id)
1702 .unwrap()
1703 .0
1704 .clone();
1705 let mut dispatch_path = Vec::new();
1706 presenter
1707 .borrow()
1708 .compute_dispatch_path_from(view_id, &mut dispatch_path);
1709 self.dispatch_action_any(window_id, &dispatch_path, action);
1710 }
1711
1712 pub fn dispatch_action<A: Action>(
1713 &mut self,
1714 window_id: usize,
1715 dispatch_path: Vec<usize>,
1716 action: &A,
1717 ) {
1718 self.dispatch_action_any(window_id, &dispatch_path, action);
1719 }
1720
1721 pub(crate) fn dispatch_action_any(
1722 &mut self,
1723 window_id: usize,
1724 path: &[usize],
1725 action: &dyn Action,
1726 ) -> bool {
1727 self.update(|this| {
1728 this.halt_action_dispatch = false;
1729 for (capture_phase, view_id) in path
1730 .iter()
1731 .map(|view_id| (true, *view_id))
1732 .chain(path.iter().rev().map(|view_id| (false, *view_id)))
1733 {
1734 if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
1735 let type_id = view.as_any().type_id();
1736
1737 if let Some((name, mut handlers)) = this
1738 .actions_mut(capture_phase)
1739 .get_mut(&type_id)
1740 .and_then(|h| h.remove_entry(&action.id()))
1741 {
1742 for handler in handlers.iter_mut().rev() {
1743 this.halt_action_dispatch = true;
1744 handler(view.as_mut(), action, this, window_id, view_id);
1745 if this.halt_action_dispatch {
1746 break;
1747 }
1748 }
1749 this.actions_mut(capture_phase)
1750 .get_mut(&type_id)
1751 .unwrap()
1752 .insert(name, handlers);
1753 }
1754
1755 this.cx.views.insert((window_id, view_id), view);
1756
1757 if this.halt_action_dispatch {
1758 break;
1759 }
1760 }
1761 }
1762
1763 if !this.halt_action_dispatch {
1764 this.halt_action_dispatch = this.dispatch_global_action_any(action);
1765 }
1766
1767 this.pending_effects
1768 .push_back(Effect::ActionDispatchNotification {
1769 action_id: action.id(),
1770 });
1771 this.halt_action_dispatch
1772 })
1773 }
1774
1775 fn actions_mut(
1776 &mut self,
1777 capture_phase: bool,
1778 ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1779 if capture_phase {
1780 &mut self.capture_actions
1781 } else {
1782 &mut self.actions
1783 }
1784 }
1785
1786 pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1787 self.dispatch_global_action_any(&action);
1788 }
1789
1790 fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1791 self.update(|this| {
1792 if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1793 handler(action, this);
1794 this.global_actions.insert(name, handler);
1795 true
1796 } else {
1797 false
1798 }
1799 })
1800 }
1801
1802 pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1803 self.keystroke_matcher.add_bindings(bindings);
1804 }
1805
1806 pub fn clear_bindings(&mut self) {
1807 self.keystroke_matcher.clear_bindings();
1808 }
1809
1810 pub fn dispatch_keystroke(
1811 &mut self,
1812 window_id: usize,
1813 dispatch_path: Vec<usize>,
1814 keystroke: &Keystroke,
1815 ) -> bool {
1816 let mut context_chain = Vec::new();
1817 for view_id in &dispatch_path {
1818 let view = self
1819 .cx
1820 .views
1821 .get(&(window_id, *view_id))
1822 .expect("view in responder chain does not exist");
1823 context_chain.push(view.keymap_context(self.as_ref()));
1824 }
1825
1826 let mut pending = false;
1827 for (i, cx) in context_chain.iter().enumerate().rev() {
1828 match self
1829 .keystroke_matcher
1830 .push_keystroke(keystroke.clone(), dispatch_path[i], cx)
1831 {
1832 MatchResult::None => {}
1833 MatchResult::Pending => pending = true,
1834 MatchResult::Action(action) => {
1835 if self.dispatch_action_any(window_id, &dispatch_path[0..=i], action.as_ref()) {
1836 self.keystroke_matcher.clear_pending();
1837 return true;
1838 }
1839 }
1840 }
1841 }
1842
1843 pending
1844 }
1845
1846 pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1847 let type_id = TypeId::of::<T>();
1848 self.update(|this| {
1849 if let Entry::Vacant(entry) = this.cx.globals.entry(type_id) {
1850 entry.insert(Box::new(T::default()));
1851 this.notify_global(type_id);
1852 }
1853 });
1854 self.globals.get(&type_id).unwrap().downcast_ref().unwrap()
1855 }
1856
1857 pub fn set_global<T: 'static>(&mut self, state: T) {
1858 self.update(|this| {
1859 let type_id = TypeId::of::<T>();
1860 this.cx.globals.insert(type_id, Box::new(state));
1861 this.notify_global(type_id);
1862 });
1863 }
1864
1865 pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1866 where
1867 T: 'static + Default,
1868 F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1869 {
1870 self.update(|this| {
1871 let type_id = TypeId::of::<T>();
1872 let mut state = this
1873 .cx
1874 .globals
1875 .remove(&type_id)
1876 .unwrap_or_else(|| Box::new(T::default()));
1877 let result = update(state.downcast_mut().unwrap(), this);
1878 this.cx.globals.insert(type_id, state);
1879 this.notify_global(type_id);
1880 result
1881 })
1882 }
1883
1884 pub fn update_global<T, F, U>(&mut self, update: F) -> U
1885 where
1886 T: 'static,
1887 F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1888 {
1889 self.update(|this| {
1890 let type_id = TypeId::of::<T>();
1891 let mut state = this
1892 .cx
1893 .globals
1894 .remove(&type_id)
1895 .expect("no global has been added for this type");
1896 let result = update(state.downcast_mut().unwrap(), this);
1897 this.cx.globals.insert(type_id, state);
1898 this.notify_global(type_id);
1899 result
1900 })
1901 }
1902
1903 pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1904 where
1905 T: Entity,
1906 F: FnOnce(&mut ModelContext<T>) -> T,
1907 {
1908 self.update(|this| {
1909 let model_id = post_inc(&mut this.next_entity_id);
1910 let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1911 let mut cx = ModelContext::new(this, model_id);
1912 let model = build_model(&mut cx);
1913 this.cx.models.insert(model_id, Box::new(model));
1914 handle
1915 })
1916 }
1917
1918 pub fn add_window<T, F>(
1919 &mut self,
1920 window_options: WindowOptions,
1921 build_root_view: F,
1922 ) -> (usize, ViewHandle<T>)
1923 where
1924 T: View,
1925 F: FnOnce(&mut ViewContext<T>) -> T,
1926 {
1927 self.update(|this| {
1928 let window_id = post_inc(&mut this.next_window_id);
1929 let root_view = this.add_view(window_id, build_root_view);
1930 this.cx.windows.insert(
1931 window_id,
1932 Window {
1933 root_view: root_view.clone().into(),
1934 focused_view_id: Some(root_view.id()),
1935 is_active: false,
1936 invalidation: None,
1937 },
1938 );
1939 root_view.update(this, |view, cx| view.on_focus(cx));
1940 this.open_platform_window(window_id, window_options);
1941
1942 (window_id, root_view)
1943 })
1944 }
1945
1946 pub fn replace_root_view<T, F>(&mut self, window_id: usize, build_root_view: F) -> ViewHandle<T>
1947 where
1948 T: View,
1949 F: FnOnce(&mut ViewContext<T>) -> T,
1950 {
1951 self.update(|this| {
1952 let root_view = this.add_view(window_id, build_root_view);
1953 let window = this.cx.windows.get_mut(&window_id).unwrap();
1954 window.root_view = root_view.clone().into();
1955 window.focused_view_id = Some(root_view.id());
1956 root_view
1957 })
1958 }
1959
1960 pub fn remove_window(&mut self, window_id: usize) {
1961 self.cx.windows.remove(&window_id);
1962 self.presenters_and_platform_windows.remove(&window_id);
1963 self.flush_effects();
1964 }
1965
1966 fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1967 let mut window =
1968 self.cx
1969 .platform
1970 .open_window(window_id, window_options, self.foreground.clone());
1971 let presenter = Rc::new(RefCell::new(
1972 self.build_presenter(window_id, window.titlebar_height()),
1973 ));
1974
1975 {
1976 let mut app = self.upgrade();
1977 let presenter = Rc::downgrade(&presenter);
1978 window.on_event(Box::new(move |event| {
1979 app.update(|cx| {
1980 if let Some(presenter) = presenter.upgrade() {
1981 if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
1982 if cx.dispatch_keystroke(
1983 window_id,
1984 presenter.borrow().dispatch_path(cx.as_ref()),
1985 keystroke,
1986 ) {
1987 return true;
1988 }
1989 }
1990
1991 presenter.borrow_mut().dispatch_event(event, cx)
1992 } else {
1993 false
1994 }
1995 })
1996 }));
1997 }
1998
1999 {
2000 let mut app = self.upgrade();
2001 window.on_active_status_change(Box::new(move |is_active| {
2002 app.update(|cx| cx.window_changed_active_status(window_id, is_active))
2003 }));
2004 }
2005
2006 {
2007 let mut app = self.upgrade();
2008 window.on_resize(Box::new(move || {
2009 app.update(|cx| cx.window_was_resized(window_id))
2010 }));
2011 }
2012
2013 {
2014 let mut app = self.upgrade();
2015 window.on_close(Box::new(move || {
2016 app.update(|cx| cx.remove_window(window_id));
2017 }));
2018 }
2019
2020 window.set_input_handler(Box::new(WindowInputHandler {
2021 app: self.upgrade().0,
2022 window_id,
2023 }));
2024
2025 let scene =
2026 presenter
2027 .borrow_mut()
2028 .build_scene(window.size(), window.scale_factor(), false, self);
2029 window.present_scene(scene);
2030 self.presenters_and_platform_windows
2031 .insert(window_id, (presenter.clone(), window));
2032 }
2033
2034 pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
2035 Presenter::new(
2036 window_id,
2037 titlebar_height,
2038 self.cx.font_cache.clone(),
2039 TextLayoutCache::new(self.cx.platform.fonts()),
2040 self.assets.clone(),
2041 self,
2042 )
2043 }
2044
2045 pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
2046 where
2047 T: View,
2048 F: FnOnce(&mut ViewContext<T>) -> T,
2049 {
2050 self.add_option_view(window_id, |cx| Some(build_view(cx)))
2051 .unwrap()
2052 }
2053
2054 pub fn add_option_view<T, F>(
2055 &mut self,
2056 window_id: usize,
2057 build_view: F,
2058 ) -> Option<ViewHandle<T>>
2059 where
2060 T: View,
2061 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
2062 {
2063 self.update(|this| {
2064 let view_id = post_inc(&mut this.next_entity_id);
2065 let mut cx = ViewContext::new(this, window_id, view_id);
2066 let handle = if let Some(view) = build_view(&mut cx) {
2067 this.cx.views.insert((window_id, view_id), Box::new(view));
2068 if let Some(window) = this.cx.windows.get_mut(&window_id) {
2069 window
2070 .invalidation
2071 .get_or_insert_with(Default::default)
2072 .updated
2073 .insert(view_id);
2074 }
2075 Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
2076 } else {
2077 None
2078 };
2079 handle
2080 })
2081 }
2082
2083 fn remove_dropped_entities(&mut self) {
2084 loop {
2085 let (dropped_models, dropped_views, dropped_element_states) =
2086 self.cx.ref_counts.lock().take_dropped();
2087 if dropped_models.is_empty()
2088 && dropped_views.is_empty()
2089 && dropped_element_states.is_empty()
2090 {
2091 break;
2092 }
2093
2094 for model_id in dropped_models {
2095 self.subscriptions.lock().remove(&model_id);
2096 self.observations.lock().remove(&model_id);
2097 let mut model = self.cx.models.remove(&model_id).unwrap();
2098 model.release(self);
2099 self.pending_effects
2100 .push_back(Effect::ModelRelease { model_id, model });
2101 }
2102
2103 for (window_id, view_id) in dropped_views {
2104 self.subscriptions.lock().remove(&view_id);
2105 self.observations.lock().remove(&view_id);
2106 let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
2107 view.release(self);
2108 let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
2109 window
2110 .invalidation
2111 .get_or_insert_with(Default::default)
2112 .removed
2113 .push(view_id);
2114 if window.focused_view_id == Some(view_id) {
2115 Some(window.root_view.id())
2116 } else {
2117 None
2118 }
2119 });
2120
2121 if let Some(view_id) = change_focus_to {
2122 self.handle_focus_effect(window_id, Some(view_id));
2123 }
2124
2125 self.pending_effects
2126 .push_back(Effect::ViewRelease { view_id, view });
2127 }
2128
2129 for key in dropped_element_states {
2130 self.cx.element_states.remove(&key);
2131 }
2132 }
2133 }
2134
2135 fn flush_effects(&mut self) {
2136 self.pending_flushes = self.pending_flushes.saturating_sub(1);
2137 let mut after_window_update_callbacks = Vec::new();
2138
2139 if !self.flushing_effects && self.pending_flushes == 0 {
2140 self.flushing_effects = true;
2141
2142 let mut refreshing = false;
2143 loop {
2144 if let Some(effect) = self.pending_effects.pop_front() {
2145 if let Some(pending_focus_index) = self.pending_focus_index.as_mut() {
2146 *pending_focus_index = pending_focus_index.saturating_sub(1);
2147 }
2148 match effect {
2149 Effect::Subscription {
2150 entity_id,
2151 subscription_id,
2152 callback,
2153 } => self.handle_subscription_effect(entity_id, subscription_id, callback),
2154 Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
2155 Effect::GlobalSubscription {
2156 type_id,
2157 subscription_id,
2158 callback,
2159 } => self.handle_global_subscription_effect(
2160 type_id,
2161 subscription_id,
2162 callback,
2163 ),
2164 Effect::GlobalEvent { payload } => self.emit_global_event(payload),
2165 Effect::Observation {
2166 entity_id,
2167 subscription_id,
2168 callback,
2169 } => self.handle_observation_effect(entity_id, subscription_id, callback),
2170 Effect::ModelNotification { model_id } => {
2171 self.handle_model_notification_effect(model_id)
2172 }
2173 Effect::ViewNotification { window_id, view_id } => {
2174 self.handle_view_notification_effect(window_id, view_id)
2175 }
2176 Effect::GlobalNotification { type_id } => {
2177 self.handle_global_notification_effect(type_id)
2178 }
2179 Effect::Deferred {
2180 callback,
2181 after_window_update,
2182 } => {
2183 if after_window_update {
2184 after_window_update_callbacks.push(callback);
2185 } else {
2186 callback(self)
2187 }
2188 }
2189 Effect::ModelRelease { model_id, model } => {
2190 self.handle_entity_release_effect(model_id, model.as_any())
2191 }
2192 Effect::ViewRelease { view_id, view } => {
2193 self.handle_entity_release_effect(view_id, view.as_any())
2194 }
2195 Effect::Focus { window_id, view_id } => {
2196 self.handle_focus_effect(window_id, view_id);
2197 }
2198 Effect::FocusObservation {
2199 view_id,
2200 subscription_id,
2201 callback,
2202 } => {
2203 self.handle_focus_observation_effect(view_id, subscription_id, callback)
2204 }
2205 Effect::ResizeWindow { window_id } => {
2206 if let Some(window) = self.cx.windows.get_mut(&window_id) {
2207 window
2208 .invalidation
2209 .get_or_insert(WindowInvalidation::default());
2210 }
2211 }
2212 Effect::WindowActivationObservation {
2213 window_id,
2214 subscription_id,
2215 callback,
2216 } => self.handle_window_activation_observation_effect(
2217 window_id,
2218 subscription_id,
2219 callback,
2220 ),
2221 Effect::ActivateWindow {
2222 window_id,
2223 is_active,
2224 } => self.handle_window_activation_effect(window_id, is_active),
2225 Effect::RefreshWindows => {
2226 refreshing = true;
2227 }
2228 Effect::ActionDispatchNotification { action_id } => {
2229 self.handle_action_dispatch_notification_effect(action_id)
2230 }
2231 Effect::WindowShouldCloseSubscription {
2232 window_id,
2233 callback,
2234 } => {
2235 self.handle_window_should_close_subscription_effect(window_id, callback)
2236 }
2237 }
2238 self.pending_notifications.clear();
2239 self.remove_dropped_entities();
2240 } else {
2241 self.remove_dropped_entities();
2242 if refreshing {
2243 self.perform_window_refresh();
2244 } else {
2245 self.update_windows();
2246 }
2247
2248 if self.pending_effects.is_empty() {
2249 for callback in after_window_update_callbacks.drain(..) {
2250 callback(self);
2251 }
2252
2253 if self.pending_effects.is_empty() {
2254 self.flushing_effects = false;
2255 self.pending_notifications.clear();
2256 self.pending_global_notifications.clear();
2257 break;
2258 }
2259 }
2260
2261 refreshing = false;
2262 }
2263 }
2264 }
2265 }
2266
2267 fn update_windows(&mut self) {
2268 let mut invalidations = HashMap::new();
2269 for (window_id, window) in &mut self.cx.windows {
2270 if let Some(invalidation) = window.invalidation.take() {
2271 invalidations.insert(*window_id, invalidation);
2272 }
2273 }
2274
2275 for (window_id, mut invalidation) in invalidations {
2276 if let Some((presenter, mut window)) =
2277 self.presenters_and_platform_windows.remove(&window_id)
2278 {
2279 {
2280 let mut presenter = presenter.borrow_mut();
2281 presenter.invalidate(&mut invalidation, self);
2282 let scene =
2283 presenter.build_scene(window.size(), window.scale_factor(), false, self);
2284 window.present_scene(scene);
2285 }
2286 self.presenters_and_platform_windows
2287 .insert(window_id, (presenter, window));
2288 }
2289 }
2290 }
2291
2292 fn window_was_resized(&mut self, window_id: usize) {
2293 self.pending_effects
2294 .push_back(Effect::ResizeWindow { window_id });
2295 }
2296
2297 fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
2298 self.pending_effects.push_back(Effect::ActivateWindow {
2299 window_id,
2300 is_active,
2301 });
2302 }
2303
2304 pub fn refresh_windows(&mut self) {
2305 self.pending_effects.push_back(Effect::RefreshWindows);
2306 }
2307
2308 fn perform_window_refresh(&mut self) {
2309 let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
2310 for (window_id, (presenter, window)) in &mut presenters {
2311 let mut invalidation = self
2312 .cx
2313 .windows
2314 .get_mut(&window_id)
2315 .unwrap()
2316 .invalidation
2317 .take();
2318 let mut presenter = presenter.borrow_mut();
2319 presenter.refresh(
2320 invalidation.as_mut().unwrap_or(&mut Default::default()),
2321 self,
2322 );
2323 let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
2324 window.present_scene(scene);
2325 }
2326 self.presenters_and_platform_windows = presenters;
2327 }
2328
2329 fn handle_subscription_effect(
2330 &mut self,
2331 entity_id: usize,
2332 subscription_id: usize,
2333 callback: SubscriptionCallback,
2334 ) {
2335 match self
2336 .subscriptions
2337 .lock()
2338 .entry(entity_id)
2339 .or_default()
2340 .entry(subscription_id)
2341 {
2342 btree_map::Entry::Vacant(entry) => {
2343 entry.insert(Some(callback));
2344 }
2345 // Subscription was dropped before effect was processed
2346 btree_map::Entry::Occupied(entry) => {
2347 debug_assert!(entry.get().is_none());
2348 entry.remove();
2349 }
2350 }
2351 }
2352
2353 fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
2354 let callbacks = self.subscriptions.lock().remove(&entity_id);
2355 if let Some(callbacks) = callbacks {
2356 for (id, callback) in callbacks {
2357 if let Some(mut callback) = callback {
2358 let alive = callback(payload.as_ref(), self);
2359 if alive {
2360 match self
2361 .subscriptions
2362 .lock()
2363 .entry(entity_id)
2364 .or_default()
2365 .entry(id)
2366 {
2367 btree_map::Entry::Vacant(entry) => {
2368 entry.insert(Some(callback));
2369 }
2370 btree_map::Entry::Occupied(entry) => {
2371 entry.remove();
2372 }
2373 }
2374 }
2375 }
2376 }
2377 }
2378 }
2379
2380 fn handle_global_subscription_effect(
2381 &mut self,
2382 type_id: TypeId,
2383 subscription_id: usize,
2384 callback: GlobalSubscriptionCallback,
2385 ) {
2386 match self
2387 .global_subscriptions
2388 .lock()
2389 .entry(type_id)
2390 .or_default()
2391 .entry(subscription_id)
2392 {
2393 btree_map::Entry::Vacant(entry) => {
2394 entry.insert(Some(callback));
2395 }
2396 // Subscription was dropped before effect was processed
2397 btree_map::Entry::Occupied(entry) => {
2398 debug_assert!(entry.get().is_none());
2399 entry.remove();
2400 }
2401 }
2402 }
2403
2404 fn emit_global_event(&mut self, payload: Box<dyn Any>) {
2405 let type_id = (&*payload).type_id();
2406 let callbacks = self.global_subscriptions.lock().remove(&type_id);
2407 if let Some(callbacks) = callbacks {
2408 for (id, callback) in callbacks {
2409 if let Some(mut callback) = callback {
2410 callback(payload.as_ref(), self);
2411 match self
2412 .global_subscriptions
2413 .lock()
2414 .entry(type_id)
2415 .or_default()
2416 .entry(id)
2417 {
2418 btree_map::Entry::Vacant(entry) => {
2419 entry.insert(Some(callback));
2420 }
2421 btree_map::Entry::Occupied(entry) => {
2422 entry.remove();
2423 }
2424 }
2425 }
2426 }
2427 }
2428 }
2429
2430 fn handle_observation_effect(
2431 &mut self,
2432 entity_id: usize,
2433 subscription_id: usize,
2434 callback: ObservationCallback,
2435 ) {
2436 match self
2437 .observations
2438 .lock()
2439 .entry(entity_id)
2440 .or_default()
2441 .entry(subscription_id)
2442 {
2443 btree_map::Entry::Vacant(entry) => {
2444 entry.insert(Some(callback));
2445 }
2446 // Observation was dropped before effect was processed
2447 btree_map::Entry::Occupied(entry) => {
2448 debug_assert!(entry.get().is_none());
2449 entry.remove();
2450 }
2451 }
2452 }
2453
2454 fn handle_focus_observation_effect(
2455 &mut self,
2456 view_id: usize,
2457 subscription_id: usize,
2458 callback: FocusObservationCallback,
2459 ) {
2460 match self
2461 .focus_observations
2462 .lock()
2463 .entry(view_id)
2464 .or_default()
2465 .entry(subscription_id)
2466 {
2467 btree_map::Entry::Vacant(entry) => {
2468 entry.insert(Some(callback));
2469 }
2470 // Observation was dropped before effect was processed
2471 btree_map::Entry::Occupied(entry) => {
2472 debug_assert!(entry.get().is_none());
2473 entry.remove();
2474 }
2475 }
2476 }
2477
2478 fn handle_model_notification_effect(&mut self, observed_id: usize) {
2479 let callbacks = self.observations.lock().remove(&observed_id);
2480 if let Some(callbacks) = callbacks {
2481 if self.cx.models.contains_key(&observed_id) {
2482 for (id, callback) in callbacks {
2483 if let Some(mut callback) = callback {
2484 let alive = callback(self);
2485 if alive {
2486 match self
2487 .observations
2488 .lock()
2489 .entry(observed_id)
2490 .or_default()
2491 .entry(id)
2492 {
2493 btree_map::Entry::Vacant(entry) => {
2494 entry.insert(Some(callback));
2495 }
2496 btree_map::Entry::Occupied(entry) => {
2497 entry.remove();
2498 }
2499 }
2500 }
2501 }
2502 }
2503 }
2504 }
2505 }
2506
2507 fn handle_view_notification_effect(
2508 &mut self,
2509 observed_window_id: usize,
2510 observed_view_id: usize,
2511 ) {
2512 let callbacks = self.observations.lock().remove(&observed_view_id);
2513
2514 if self
2515 .cx
2516 .views
2517 .contains_key(&(observed_window_id, observed_view_id))
2518 {
2519 if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
2520 window
2521 .invalidation
2522 .get_or_insert_with(Default::default)
2523 .updated
2524 .insert(observed_view_id);
2525 }
2526
2527 if let Some(callbacks) = callbacks {
2528 for (id, callback) in callbacks {
2529 if let Some(mut callback) = callback {
2530 let alive = callback(self);
2531 if alive {
2532 match self
2533 .observations
2534 .lock()
2535 .entry(observed_view_id)
2536 .or_default()
2537 .entry(id)
2538 {
2539 btree_map::Entry::Vacant(entry) => {
2540 entry.insert(Some(callback));
2541 }
2542 btree_map::Entry::Occupied(entry) => {
2543 entry.remove();
2544 }
2545 }
2546 }
2547 }
2548 }
2549 }
2550 }
2551 }
2552
2553 fn handle_global_notification_effect(&mut self, observed_type_id: TypeId) {
2554 let callbacks = self.global_observations.lock().remove(&observed_type_id);
2555 if let Some(callbacks) = callbacks {
2556 for (id, callback) in callbacks {
2557 if let Some(mut callback) = callback {
2558 callback(self);
2559 match self
2560 .global_observations
2561 .lock()
2562 .entry(observed_type_id)
2563 .or_default()
2564 .entry(id)
2565 {
2566 collections::btree_map::Entry::Vacant(entry) => {
2567 entry.insert(Some(callback));
2568 }
2569 collections::btree_map::Entry::Occupied(entry) => {
2570 entry.remove();
2571 }
2572 }
2573 }
2574 }
2575 }
2576 }
2577
2578 fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
2579 let callbacks = self.release_observations.lock().remove(&entity_id);
2580 if let Some(callbacks) = callbacks {
2581 for (_, callback) in callbacks {
2582 callback(entity, self);
2583 }
2584 }
2585 }
2586
2587 fn handle_window_activation_observation_effect(
2588 &mut self,
2589 window_id: usize,
2590 subscription_id: usize,
2591 callback: WindowActivationCallback,
2592 ) {
2593 match self
2594 .window_activation_observations
2595 .lock()
2596 .entry(window_id)
2597 .or_default()
2598 .entry(subscription_id)
2599 {
2600 btree_map::Entry::Vacant(entry) => {
2601 entry.insert(Some(callback));
2602 }
2603 // Observation was dropped before effect was processed
2604 btree_map::Entry::Occupied(entry) => {
2605 debug_assert!(entry.get().is_none());
2606 entry.remove();
2607 }
2608 }
2609 }
2610
2611 fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
2612 if self
2613 .cx
2614 .windows
2615 .get(&window_id)
2616 .map(|w| w.is_active)
2617 .map_or(false, |cur_active| cur_active == active)
2618 {
2619 return;
2620 }
2621
2622 self.update(|this| {
2623 let window = this.cx.windows.get_mut(&window_id)?;
2624 window.is_active = active;
2625 let view_id = window.focused_view_id?;
2626 if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
2627 if active {
2628 view.on_focus(this, window_id, view_id);
2629 } else {
2630 view.on_blur(this, window_id, view_id);
2631 }
2632 this.cx.views.insert((window_id, view_id), view);
2633 }
2634
2635 let callbacks = this
2636 .window_activation_observations
2637 .lock()
2638 .remove(&window_id);
2639 if let Some(callbacks) = callbacks {
2640 for (id, callback) in callbacks {
2641 if let Some(mut callback) = callback {
2642 let alive = callback(active, this);
2643 if alive {
2644 match this
2645 .window_activation_observations
2646 .lock()
2647 .entry(window_id)
2648 .or_default()
2649 .entry(id)
2650 {
2651 btree_map::Entry::Vacant(entry) => {
2652 entry.insert(Some(callback));
2653 }
2654 btree_map::Entry::Occupied(entry) => {
2655 entry.remove();
2656 }
2657 }
2658 }
2659 }
2660 }
2661 }
2662
2663 Some(())
2664 });
2665 }
2666
2667 fn handle_focus_effect(&mut self, window_id: usize, focused_id: Option<usize>) {
2668 self.pending_focus_index.take();
2669
2670 if self
2671 .cx
2672 .windows
2673 .get(&window_id)
2674 .map(|w| w.focused_view_id)
2675 .map_or(false, |cur_focused| cur_focused == focused_id)
2676 {
2677 return;
2678 }
2679
2680 self.update(|this| {
2681 let blurred_id = this.cx.windows.get_mut(&window_id).and_then(|window| {
2682 let blurred_id = window.focused_view_id;
2683 window.focused_view_id = focused_id;
2684 blurred_id
2685 });
2686
2687 if let Some(blurred_id) = blurred_id {
2688 if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
2689 blurred_view.on_blur(this, window_id, blurred_id);
2690 this.cx.views.insert((window_id, blurred_id), blurred_view);
2691
2692 let callbacks = this.focus_observations.lock().remove(&blurred_id);
2693 if let Some(callbacks) = callbacks {
2694 for (id, callback) in callbacks {
2695 if let Some(mut callback) = callback {
2696 let alive = callback(false, this);
2697 if alive {
2698 match this
2699 .focus_observations
2700 .lock()
2701 .entry(blurred_id)
2702 .or_default()
2703 .entry(id)
2704 {
2705 btree_map::Entry::Vacant(entry) => {
2706 entry.insert(Some(callback));
2707 }
2708 btree_map::Entry::Occupied(entry) => {
2709 entry.remove();
2710 }
2711 }
2712 }
2713 }
2714 }
2715 }
2716 }
2717 }
2718
2719 if let Some(focused_id) = focused_id {
2720 if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
2721 focused_view.on_focus(this, window_id, focused_id);
2722 this.cx.views.insert((window_id, focused_id), focused_view);
2723
2724 let callbacks = this.focus_observations.lock().remove(&focused_id);
2725 if let Some(callbacks) = callbacks {
2726 for (id, callback) in callbacks {
2727 if let Some(mut callback) = callback {
2728 let alive = callback(true, this);
2729 if alive {
2730 match this
2731 .focus_observations
2732 .lock()
2733 .entry(focused_id)
2734 .or_default()
2735 .entry(id)
2736 {
2737 btree_map::Entry::Vacant(entry) => {
2738 entry.insert(Some(callback));
2739 }
2740 btree_map::Entry::Occupied(entry) => {
2741 entry.remove();
2742 }
2743 }
2744 }
2745 }
2746 }
2747 }
2748 }
2749 }
2750 })
2751 }
2752
2753 fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
2754 let mut callbacks = mem::take(&mut *self.action_dispatch_observations.lock());
2755 for (_, callback) in &mut callbacks {
2756 callback(action_id, self);
2757 }
2758 self.action_dispatch_observations.lock().extend(callbacks);
2759 }
2760
2761 fn handle_window_should_close_subscription_effect(
2762 &mut self,
2763 window_id: usize,
2764 mut callback: WindowShouldCloseSubscriptionCallback,
2765 ) {
2766 let mut app = self.upgrade();
2767 if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
2768 window.on_should_close(Box::new(move || app.update(|cx| callback(cx))))
2769 }
2770 }
2771
2772 pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2773 if let Some(pending_focus_index) = self.pending_focus_index {
2774 self.pending_effects.remove(pending_focus_index);
2775 }
2776 self.pending_focus_index = Some(self.pending_effects.len());
2777 self.pending_effects
2778 .push_back(Effect::Focus { window_id, view_id });
2779 }
2780
2781 pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
2782 where
2783 F: FnOnce(AsyncAppContext) -> Fut,
2784 Fut: 'static + Future<Output = T>,
2785 T: 'static,
2786 {
2787 let future = f(self.to_async());
2788 let cx = self.to_async();
2789 self.foreground.spawn(async move {
2790 let result = future.await;
2791 cx.0.borrow_mut().flush_effects();
2792 result
2793 })
2794 }
2795
2796 pub fn to_async(&self) -> AsyncAppContext {
2797 AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2798 }
2799
2800 pub fn write_to_clipboard(&self, item: ClipboardItem) {
2801 self.cx.platform.write_to_clipboard(item);
2802 }
2803
2804 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2805 self.cx.platform.read_from_clipboard()
2806 }
2807
2808 #[cfg(any(test, feature = "test-support"))]
2809 pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2810 self.cx.ref_counts.lock().leak_detector.clone()
2811 }
2812}
2813
2814impl ReadModel for MutableAppContext {
2815 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2816 if let Some(model) = self.cx.models.get(&handle.model_id) {
2817 model
2818 .as_any()
2819 .downcast_ref()
2820 .expect("downcast is type safe")
2821 } else {
2822 panic!("circular model reference");
2823 }
2824 }
2825}
2826
2827impl UpdateModel for MutableAppContext {
2828 fn update_model<T: Entity, V>(
2829 &mut self,
2830 handle: &ModelHandle<T>,
2831 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2832 ) -> V {
2833 if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
2834 self.update(|this| {
2835 let mut cx = ModelContext::new(this, handle.model_id);
2836 let result = update(
2837 model
2838 .as_any_mut()
2839 .downcast_mut()
2840 .expect("downcast is type safe"),
2841 &mut cx,
2842 );
2843 this.cx.models.insert(handle.model_id, model);
2844 result
2845 })
2846 } else {
2847 panic!("circular model update");
2848 }
2849 }
2850}
2851
2852impl UpgradeModelHandle for MutableAppContext {
2853 fn upgrade_model_handle<T: Entity>(
2854 &self,
2855 handle: &WeakModelHandle<T>,
2856 ) -> Option<ModelHandle<T>> {
2857 self.cx.upgrade_model_handle(handle)
2858 }
2859
2860 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2861 self.cx.model_handle_is_upgradable(handle)
2862 }
2863
2864 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2865 self.cx.upgrade_any_model_handle(handle)
2866 }
2867}
2868
2869impl UpgradeViewHandle for MutableAppContext {
2870 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2871 self.cx.upgrade_view_handle(handle)
2872 }
2873
2874 fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
2875 self.cx.upgrade_any_view_handle(handle)
2876 }
2877}
2878
2879impl ReadView for MutableAppContext {
2880 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2881 if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
2882 view.as_any().downcast_ref().expect("downcast is type safe")
2883 } else {
2884 panic!("circular view reference");
2885 }
2886 }
2887}
2888
2889impl UpdateView for MutableAppContext {
2890 fn update_view<T, S>(
2891 &mut self,
2892 handle: &ViewHandle<T>,
2893 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2894 ) -> S
2895 where
2896 T: View,
2897 {
2898 self.update(|this| {
2899 let mut view = this
2900 .cx
2901 .views
2902 .remove(&(handle.window_id, handle.view_id))
2903 .expect("circular view update");
2904
2905 let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
2906 let result = update(
2907 view.as_any_mut()
2908 .downcast_mut()
2909 .expect("downcast is type safe"),
2910 &mut cx,
2911 );
2912 this.cx
2913 .views
2914 .insert((handle.window_id, handle.view_id), view);
2915 result
2916 })
2917 }
2918}
2919
2920impl AsRef<AppContext> for MutableAppContext {
2921 fn as_ref(&self) -> &AppContext {
2922 &self.cx
2923 }
2924}
2925
2926impl Deref for MutableAppContext {
2927 type Target = AppContext;
2928
2929 fn deref(&self) -> &Self::Target {
2930 &self.cx
2931 }
2932}
2933
2934pub struct AppContext {
2935 models: HashMap<usize, Box<dyn AnyModel>>,
2936 views: HashMap<(usize, usize), Box<dyn AnyView>>,
2937 windows: HashMap<usize, Window>,
2938 globals: HashMap<TypeId, Box<dyn Any>>,
2939 element_states: HashMap<ElementStateId, Box<dyn Any>>,
2940 background: Arc<executor::Background>,
2941 ref_counts: Arc<Mutex<RefCounts>>,
2942 font_cache: Arc<FontCache>,
2943 platform: Arc<dyn Platform>,
2944}
2945
2946impl AppContext {
2947 pub(crate) fn root_view(&self, window_id: usize) -> Option<AnyViewHandle> {
2948 self.windows
2949 .get(&window_id)
2950 .map(|window| window.root_view.clone())
2951 }
2952
2953 pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
2954 self.windows
2955 .get(&window_id)
2956 .map(|window| window.root_view.id())
2957 }
2958
2959 pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
2960 self.windows
2961 .get(&window_id)
2962 .and_then(|window| window.focused_view_id)
2963 }
2964
2965 pub fn background(&self) -> &Arc<executor::Background> {
2966 &self.background
2967 }
2968
2969 pub fn font_cache(&self) -> &Arc<FontCache> {
2970 &self.font_cache
2971 }
2972
2973 pub fn platform(&self) -> &Arc<dyn Platform> {
2974 &self.platform
2975 }
2976
2977 pub fn has_global<T: 'static>(&self) -> bool {
2978 self.globals.contains_key(&TypeId::of::<T>())
2979 }
2980
2981 pub fn global<T: 'static>(&self) -> &T {
2982 if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
2983 global.downcast_ref().unwrap()
2984 } else {
2985 panic!("no global has been added for {}", type_name::<T>());
2986 }
2987 }
2988}
2989
2990impl ReadModel for AppContext {
2991 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2992 if let Some(model) = self.models.get(&handle.model_id) {
2993 model
2994 .as_any()
2995 .downcast_ref()
2996 .expect("downcast should be type safe")
2997 } else {
2998 panic!("circular model reference");
2999 }
3000 }
3001}
3002
3003impl UpgradeModelHandle for AppContext {
3004 fn upgrade_model_handle<T: Entity>(
3005 &self,
3006 handle: &WeakModelHandle<T>,
3007 ) -> Option<ModelHandle<T>> {
3008 if self.models.contains_key(&handle.model_id) {
3009 Some(ModelHandle::new(handle.model_id, &self.ref_counts))
3010 } else {
3011 None
3012 }
3013 }
3014
3015 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3016 self.models.contains_key(&handle.model_id)
3017 }
3018
3019 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3020 if self.models.contains_key(&handle.model_id) {
3021 Some(AnyModelHandle::new(
3022 handle.model_id,
3023 handle.model_type,
3024 self.ref_counts.clone(),
3025 ))
3026 } else {
3027 None
3028 }
3029 }
3030}
3031
3032impl UpgradeViewHandle for AppContext {
3033 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
3034 if self.ref_counts.lock().is_entity_alive(handle.view_id) {
3035 Some(ViewHandle::new(
3036 handle.window_id,
3037 handle.view_id,
3038 &self.ref_counts,
3039 ))
3040 } else {
3041 None
3042 }
3043 }
3044
3045 fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
3046 if self.ref_counts.lock().is_entity_alive(handle.view_id) {
3047 Some(AnyViewHandle::new(
3048 handle.window_id,
3049 handle.view_id,
3050 handle.view_type,
3051 self.ref_counts.clone(),
3052 ))
3053 } else {
3054 None
3055 }
3056 }
3057}
3058
3059impl ReadView for AppContext {
3060 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
3061 if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
3062 view.as_any()
3063 .downcast_ref()
3064 .expect("downcast should be type safe")
3065 } else {
3066 panic!("circular view reference");
3067 }
3068 }
3069}
3070
3071struct Window {
3072 root_view: AnyViewHandle,
3073 focused_view_id: Option<usize>,
3074 is_active: bool,
3075 invalidation: Option<WindowInvalidation>,
3076}
3077
3078#[derive(Default, Clone)]
3079pub struct WindowInvalidation {
3080 pub updated: HashSet<usize>,
3081 pub removed: Vec<usize>,
3082}
3083
3084pub enum Effect {
3085 Subscription {
3086 entity_id: usize,
3087 subscription_id: usize,
3088 callback: SubscriptionCallback,
3089 },
3090 Event {
3091 entity_id: usize,
3092 payload: Box<dyn Any>,
3093 },
3094 GlobalSubscription {
3095 type_id: TypeId,
3096 subscription_id: usize,
3097 callback: GlobalSubscriptionCallback,
3098 },
3099 GlobalEvent {
3100 payload: Box<dyn Any>,
3101 },
3102 Observation {
3103 entity_id: usize,
3104 subscription_id: usize,
3105 callback: ObservationCallback,
3106 },
3107 ModelNotification {
3108 model_id: usize,
3109 },
3110 ViewNotification {
3111 window_id: usize,
3112 view_id: usize,
3113 },
3114 Deferred {
3115 callback: Box<dyn FnOnce(&mut MutableAppContext)>,
3116 after_window_update: bool,
3117 },
3118 GlobalNotification {
3119 type_id: TypeId,
3120 },
3121 ModelRelease {
3122 model_id: usize,
3123 model: Box<dyn AnyModel>,
3124 },
3125 ViewRelease {
3126 view_id: usize,
3127 view: Box<dyn AnyView>,
3128 },
3129 Focus {
3130 window_id: usize,
3131 view_id: Option<usize>,
3132 },
3133 FocusObservation {
3134 view_id: usize,
3135 subscription_id: usize,
3136 callback: FocusObservationCallback,
3137 },
3138 ResizeWindow {
3139 window_id: usize,
3140 },
3141 ActivateWindow {
3142 window_id: usize,
3143 is_active: bool,
3144 },
3145 WindowActivationObservation {
3146 window_id: usize,
3147 subscription_id: usize,
3148 callback: WindowActivationCallback,
3149 },
3150 RefreshWindows,
3151 ActionDispatchNotification {
3152 action_id: TypeId,
3153 },
3154 WindowShouldCloseSubscription {
3155 window_id: usize,
3156 callback: WindowShouldCloseSubscriptionCallback,
3157 },
3158}
3159
3160impl Debug for Effect {
3161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3162 match self {
3163 Effect::Subscription {
3164 entity_id,
3165 subscription_id,
3166 ..
3167 } => f
3168 .debug_struct("Effect::Subscribe")
3169 .field("entity_id", entity_id)
3170 .field("subscription_id", subscription_id)
3171 .finish(),
3172 Effect::Event { entity_id, .. } => f
3173 .debug_struct("Effect::Event")
3174 .field("entity_id", entity_id)
3175 .finish(),
3176 Effect::GlobalSubscription {
3177 type_id,
3178 subscription_id,
3179 ..
3180 } => f
3181 .debug_struct("Effect::Subscribe")
3182 .field("type_id", type_id)
3183 .field("subscription_id", subscription_id)
3184 .finish(),
3185 Effect::GlobalEvent { payload, .. } => f
3186 .debug_struct("Effect::GlobalEvent")
3187 .field("type_id", &(&*payload).type_id())
3188 .finish(),
3189 Effect::Observation {
3190 entity_id,
3191 subscription_id,
3192 ..
3193 } => f
3194 .debug_struct("Effect::Observation")
3195 .field("entity_id", entity_id)
3196 .field("subscription_id", subscription_id)
3197 .finish(),
3198 Effect::ModelNotification { model_id } => f
3199 .debug_struct("Effect::ModelNotification")
3200 .field("model_id", model_id)
3201 .finish(),
3202 Effect::ViewNotification { window_id, view_id } => f
3203 .debug_struct("Effect::ViewNotification")
3204 .field("window_id", window_id)
3205 .field("view_id", view_id)
3206 .finish(),
3207 Effect::GlobalNotification { type_id } => f
3208 .debug_struct("Effect::GlobalNotification")
3209 .field("type_id", type_id)
3210 .finish(),
3211 Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
3212 Effect::ModelRelease { model_id, .. } => f
3213 .debug_struct("Effect::ModelRelease")
3214 .field("model_id", model_id)
3215 .finish(),
3216 Effect::ViewRelease { view_id, .. } => f
3217 .debug_struct("Effect::ViewRelease")
3218 .field("view_id", view_id)
3219 .finish(),
3220 Effect::Focus { window_id, view_id } => f
3221 .debug_struct("Effect::Focus")
3222 .field("window_id", window_id)
3223 .field("view_id", view_id)
3224 .finish(),
3225 Effect::FocusObservation {
3226 view_id,
3227 subscription_id,
3228 ..
3229 } => f
3230 .debug_struct("Effect::FocusObservation")
3231 .field("view_id", view_id)
3232 .field("subscription_id", subscription_id)
3233 .finish(),
3234 Effect::ActionDispatchNotification { action_id, .. } => f
3235 .debug_struct("Effect::ActionDispatchNotification")
3236 .field("action_id", action_id)
3237 .finish(),
3238 Effect::ResizeWindow { window_id } => f
3239 .debug_struct("Effect::RefreshWindow")
3240 .field("window_id", window_id)
3241 .finish(),
3242 Effect::WindowActivationObservation {
3243 window_id,
3244 subscription_id,
3245 ..
3246 } => f
3247 .debug_struct("Effect::WindowActivationObservation")
3248 .field("window_id", window_id)
3249 .field("subscription_id", subscription_id)
3250 .finish(),
3251 Effect::ActivateWindow {
3252 window_id,
3253 is_active,
3254 } => f
3255 .debug_struct("Effect::ActivateWindow")
3256 .field("window_id", window_id)
3257 .field("is_active", is_active)
3258 .finish(),
3259 Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
3260 Effect::WindowShouldCloseSubscription { window_id, .. } => f
3261 .debug_struct("Effect::WindowShouldCloseSubscription")
3262 .field("window_id", window_id)
3263 .finish(),
3264 }
3265 }
3266}
3267
3268pub trait AnyModel {
3269 fn as_any(&self) -> &dyn Any;
3270 fn as_any_mut(&mut self) -> &mut dyn Any;
3271 fn release(&mut self, cx: &mut MutableAppContext);
3272 fn app_will_quit(
3273 &mut self,
3274 cx: &mut MutableAppContext,
3275 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3276}
3277
3278impl<T> AnyModel for T
3279where
3280 T: Entity,
3281{
3282 fn as_any(&self) -> &dyn Any {
3283 self
3284 }
3285
3286 fn as_any_mut(&mut self) -> &mut dyn Any {
3287 self
3288 }
3289
3290 fn release(&mut self, cx: &mut MutableAppContext) {
3291 self.release(cx);
3292 }
3293
3294 fn app_will_quit(
3295 &mut self,
3296 cx: &mut MutableAppContext,
3297 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3298 self.app_will_quit(cx)
3299 }
3300}
3301
3302pub trait AnyView {
3303 fn as_any(&self) -> &dyn Any;
3304 fn as_any_mut(&mut self) -> &mut dyn Any;
3305 fn release(&mut self, cx: &mut MutableAppContext);
3306 fn app_will_quit(
3307 &mut self,
3308 cx: &mut MutableAppContext,
3309 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
3310 fn ui_name(&self) -> &'static str;
3311 fn render<'a>(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox;
3312 fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3313 fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3314 fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
3315 fn debug_json(&self, cx: &AppContext) -> serde_json::Value;
3316
3317 fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String>;
3318 fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3319 fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>>;
3320 fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
3321 fn replace_text_in_range(
3322 &mut self,
3323 range: Option<Range<usize>>,
3324 text: &str,
3325 cx: &mut MutableAppContext,
3326 window_id: usize,
3327 view_id: usize,
3328 );
3329 fn replace_and_mark_text_in_range(
3330 &mut self,
3331 range: Option<Range<usize>>,
3332 new_text: &str,
3333 new_selected_range: Option<Range<usize>>,
3334 cx: &mut MutableAppContext,
3335 window_id: usize,
3336 view_id: usize,
3337 );
3338}
3339
3340impl<T> AnyView for T
3341where
3342 T: View,
3343{
3344 fn as_any(&self) -> &dyn Any {
3345 self
3346 }
3347
3348 fn as_any_mut(&mut self) -> &mut dyn Any {
3349 self
3350 }
3351
3352 fn release(&mut self, cx: &mut MutableAppContext) {
3353 self.release(cx);
3354 }
3355
3356 fn app_will_quit(
3357 &mut self,
3358 cx: &mut MutableAppContext,
3359 ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
3360 self.app_will_quit(cx)
3361 }
3362
3363 fn ui_name(&self) -> &'static str {
3364 T::ui_name()
3365 }
3366
3367 fn render<'a>(&mut self, params: RenderParams, cx: &mut MutableAppContext) -> ElementBox {
3368 View::render(self, &mut RenderContext::new(params, cx))
3369 }
3370
3371 fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3372 let mut cx = ViewContext::new(cx, window_id, view_id);
3373 View::on_focus(self, &mut cx);
3374 }
3375
3376 fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3377 let mut cx = ViewContext::new(cx, window_id, view_id);
3378 View::on_blur(self, &mut cx);
3379 }
3380
3381 fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
3382 View::keymap_context(self, cx)
3383 }
3384
3385 fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
3386 View::debug_json(self, cx)
3387 }
3388
3389 fn text_for_range(&self, range: Range<usize>, cx: &AppContext) -> Option<String> {
3390 View::text_for_range(self, range, cx)
3391 }
3392
3393 fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3394 View::selected_text_range(self, cx)
3395 }
3396
3397 fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
3398 View::marked_text_range(self, cx)
3399 }
3400
3401 fn unmark_text(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
3402 let mut cx = ViewContext::new(cx, window_id, view_id);
3403 View::unmark_text(self, &mut cx)
3404 }
3405
3406 fn replace_text_in_range(
3407 &mut self,
3408 range: Option<Range<usize>>,
3409 text: &str,
3410 cx: &mut MutableAppContext,
3411 window_id: usize,
3412 view_id: usize,
3413 ) {
3414 let mut cx = ViewContext::new(cx, window_id, view_id);
3415 View::replace_text_in_range(self, range, text, &mut cx)
3416 }
3417
3418 fn replace_and_mark_text_in_range(
3419 &mut self,
3420 range: Option<Range<usize>>,
3421 new_text: &str,
3422 new_selected_range: Option<Range<usize>>,
3423 cx: &mut MutableAppContext,
3424 window_id: usize,
3425 view_id: usize,
3426 ) {
3427 let mut cx = ViewContext::new(cx, window_id, view_id);
3428 View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
3429 }
3430}
3431
3432pub struct ModelContext<'a, T: ?Sized> {
3433 app: &'a mut MutableAppContext,
3434 model_id: usize,
3435 model_type: PhantomData<T>,
3436 halt_stream: bool,
3437}
3438
3439impl<'a, T: Entity> ModelContext<'a, T> {
3440 fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
3441 Self {
3442 app,
3443 model_id,
3444 model_type: PhantomData,
3445 halt_stream: false,
3446 }
3447 }
3448
3449 pub fn background(&self) -> &Arc<executor::Background> {
3450 &self.app.cx.background
3451 }
3452
3453 pub fn halt_stream(&mut self) {
3454 self.halt_stream = true;
3455 }
3456
3457 pub fn model_id(&self) -> usize {
3458 self.model_id
3459 }
3460
3461 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3462 where
3463 S: Entity,
3464 F: FnOnce(&mut ModelContext<S>) -> S,
3465 {
3466 self.app.add_model(build_model)
3467 }
3468
3469 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ModelContext<T>)) {
3470 let handle = self.handle();
3471 self.app.defer(move |cx| {
3472 handle.update(cx, |model, cx| {
3473 callback(model, cx);
3474 })
3475 })
3476 }
3477
3478 pub fn emit(&mut self, payload: T::Event) {
3479 self.app.pending_effects.push_back(Effect::Event {
3480 entity_id: self.model_id,
3481 payload: Box::new(payload),
3482 });
3483 }
3484
3485 pub fn notify(&mut self) {
3486 self.app.notify_model(self.model_id);
3487 }
3488
3489 pub fn subscribe<S: Entity, F>(
3490 &mut self,
3491 handle: &ModelHandle<S>,
3492 mut callback: F,
3493 ) -> Subscription
3494 where
3495 S::Event: 'static,
3496 F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
3497 {
3498 let subscriber = self.weak_handle();
3499 self.app
3500 .subscribe_internal(handle, move |emitter, event, cx| {
3501 if let Some(subscriber) = subscriber.upgrade(cx) {
3502 subscriber.update(cx, |subscriber, cx| {
3503 callback(subscriber, emitter, event, cx);
3504 });
3505 true
3506 } else {
3507 false
3508 }
3509 })
3510 }
3511
3512 pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
3513 where
3514 S: Entity,
3515 F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
3516 {
3517 let observer = self.weak_handle();
3518 self.app.observe_internal(handle, move |observed, cx| {
3519 if let Some(observer) = observer.upgrade(cx) {
3520 observer.update(cx, |observer, cx| {
3521 callback(observer, observed, cx);
3522 });
3523 true
3524 } else {
3525 false
3526 }
3527 })
3528 }
3529
3530 pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3531 where
3532 G: Any,
3533 F: 'static + FnMut(&mut T, &mut ModelContext<T>),
3534 {
3535 let observer = self.weak_handle();
3536 self.app.observe_global::<G, _>(move |cx| {
3537 if let Some(observer) = observer.upgrade(cx) {
3538 observer.update(cx, |observer, cx| callback(observer, cx));
3539 }
3540 })
3541 }
3542
3543 pub fn observe_release<S, F>(
3544 &mut self,
3545 handle: &ModelHandle<S>,
3546 mut callback: F,
3547 ) -> Subscription
3548 where
3549 S: Entity,
3550 F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
3551 {
3552 let observer = self.weak_handle();
3553 self.app.observe_release(handle, move |released, cx| {
3554 if let Some(observer) = observer.upgrade(cx) {
3555 observer.update(cx, |observer, cx| {
3556 callback(observer, released, cx);
3557 });
3558 }
3559 })
3560 }
3561
3562 pub fn handle(&self) -> ModelHandle<T> {
3563 ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
3564 }
3565
3566 pub fn weak_handle(&self) -> WeakModelHandle<T> {
3567 WeakModelHandle::new(self.model_id)
3568 }
3569
3570 pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3571 where
3572 F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
3573 Fut: 'static + Future<Output = S>,
3574 S: 'static,
3575 {
3576 let handle = self.handle();
3577 self.app.spawn(|cx| f(handle, cx))
3578 }
3579
3580 pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3581 where
3582 F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
3583 Fut: 'static + Future<Output = S>,
3584 S: 'static,
3585 {
3586 let handle = self.weak_handle();
3587 self.app.spawn(|cx| f(handle, cx))
3588 }
3589}
3590
3591impl<M> AsRef<AppContext> for ModelContext<'_, M> {
3592 fn as_ref(&self) -> &AppContext {
3593 &self.app.cx
3594 }
3595}
3596
3597impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
3598 fn as_mut(&mut self) -> &mut MutableAppContext {
3599 self.app
3600 }
3601}
3602
3603impl<M> ReadModel for ModelContext<'_, M> {
3604 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
3605 self.app.read_model(handle)
3606 }
3607}
3608
3609impl<M> UpdateModel for ModelContext<'_, M> {
3610 fn update_model<T: Entity, V>(
3611 &mut self,
3612 handle: &ModelHandle<T>,
3613 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
3614 ) -> V {
3615 self.app.update_model(handle, update)
3616 }
3617}
3618
3619impl<M> UpgradeModelHandle for ModelContext<'_, M> {
3620 fn upgrade_model_handle<T: Entity>(
3621 &self,
3622 handle: &WeakModelHandle<T>,
3623 ) -> Option<ModelHandle<T>> {
3624 self.cx.upgrade_model_handle(handle)
3625 }
3626
3627 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
3628 self.cx.model_handle_is_upgradable(handle)
3629 }
3630
3631 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
3632 self.cx.upgrade_any_model_handle(handle)
3633 }
3634}
3635
3636impl<M> Deref for ModelContext<'_, M> {
3637 type Target = MutableAppContext;
3638
3639 fn deref(&self) -> &Self::Target {
3640 &self.app
3641 }
3642}
3643
3644impl<M> DerefMut for ModelContext<'_, M> {
3645 fn deref_mut(&mut self) -> &mut Self::Target {
3646 &mut self.app
3647 }
3648}
3649
3650pub struct ViewContext<'a, T: ?Sized> {
3651 app: &'a mut MutableAppContext,
3652 window_id: usize,
3653 view_id: usize,
3654 view_type: PhantomData<T>,
3655}
3656
3657impl<'a, T: View> ViewContext<'a, T> {
3658 fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
3659 Self {
3660 app,
3661 window_id,
3662 view_id,
3663 view_type: PhantomData,
3664 }
3665 }
3666
3667 pub fn handle(&self) -> ViewHandle<T> {
3668 ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
3669 }
3670
3671 pub fn weak_handle(&self) -> WeakViewHandle<T> {
3672 WeakViewHandle::new(self.window_id, self.view_id)
3673 }
3674
3675 pub fn window_id(&self) -> usize {
3676 self.window_id
3677 }
3678
3679 pub fn view_id(&self) -> usize {
3680 self.view_id
3681 }
3682
3683 pub fn foreground(&self) -> &Rc<executor::Foreground> {
3684 self.app.foreground()
3685 }
3686
3687 pub fn background_executor(&self) -> &Arc<executor::Background> {
3688 &self.app.cx.background
3689 }
3690
3691 pub fn platform(&self) -> Arc<dyn Platform> {
3692 self.app.platform()
3693 }
3694
3695 pub fn show_character_palette(&self) {
3696 self.app.show_character_palette(self.window_id);
3697 }
3698
3699 pub fn minimize_window(&self) {
3700 self.app.minimize_window(self.window_id)
3701 }
3702
3703 pub fn zoom_window(&self) {
3704 self.app.zoom_window(self.window_id)
3705 }
3706
3707 pub fn prompt(
3708 &self,
3709 level: PromptLevel,
3710 msg: &str,
3711 answers: &[&str],
3712 ) -> oneshot::Receiver<usize> {
3713 self.app.prompt(self.window_id, level, msg, answers)
3714 }
3715
3716 pub fn prompt_for_paths(
3717 &self,
3718 options: PathPromptOptions,
3719 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
3720 self.app.prompt_for_paths(options)
3721 }
3722
3723 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
3724 self.app.prompt_for_new_path(directory)
3725 }
3726
3727 pub fn debug_elements(&self) -> crate::json::Value {
3728 self.app.debug_elements(self.window_id).unwrap()
3729 }
3730
3731 pub fn focus<S>(&mut self, handle: S)
3732 where
3733 S: Into<AnyViewHandle>,
3734 {
3735 let handle = handle.into();
3736 self.app.focus(handle.window_id, Some(handle.view_id));
3737 }
3738
3739 pub fn focus_self(&mut self) {
3740 self.app.focus(self.window_id, Some(self.view_id));
3741 }
3742
3743 pub fn is_self_focused(&self) -> bool {
3744 self.app.focused_view_id(self.window_id) == Some(self.view_id)
3745 }
3746
3747 pub fn blur(&mut self) {
3748 self.app.focus(self.window_id, None);
3749 }
3750
3751 pub fn set_window_title(&mut self, title: &str) {
3752 let window_id = self.window_id();
3753 if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3754 window.set_title(title);
3755 }
3756 }
3757
3758 pub fn set_window_edited(&mut self, edited: bool) {
3759 let window_id = self.window_id();
3760 if let Some((_, window)) = self.presenters_and_platform_windows.get_mut(&window_id) {
3761 window.set_edited(edited);
3762 }
3763 }
3764
3765 pub fn on_window_should_close<F>(&mut self, mut callback: F)
3766 where
3767 F: 'static + FnMut(&mut T, &mut ViewContext<T>) -> bool,
3768 {
3769 let window_id = self.window_id();
3770 let view = self.weak_handle();
3771 self.pending_effects
3772 .push_back(Effect::WindowShouldCloseSubscription {
3773 window_id,
3774 callback: Box::new(move |cx| {
3775 if let Some(view) = view.upgrade(cx) {
3776 view.update(cx, |view, cx| callback(view, cx))
3777 } else {
3778 true
3779 }
3780 }),
3781 });
3782 }
3783
3784 pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
3785 where
3786 S: Entity,
3787 F: FnOnce(&mut ModelContext<S>) -> S,
3788 {
3789 self.app.add_model(build_model)
3790 }
3791
3792 pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
3793 where
3794 S: View,
3795 F: FnOnce(&mut ViewContext<S>) -> S,
3796 {
3797 self.app.add_view(self.window_id, build_view)
3798 }
3799
3800 pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
3801 where
3802 S: View,
3803 F: FnOnce(&mut ViewContext<S>) -> Option<S>,
3804 {
3805 self.app.add_option_view(self.window_id, build_view)
3806 }
3807
3808 pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
3809 where
3810 V: View,
3811 F: FnOnce(&mut ViewContext<V>) -> V,
3812 {
3813 let window_id = self.window_id;
3814 self.update(|this| {
3815 let root_view = this.add_view(window_id, build_root_view);
3816 let window = this.cx.windows.get_mut(&window_id).unwrap();
3817 window.root_view = root_view.clone().into();
3818 window.focused_view_id = Some(root_view.id());
3819 root_view
3820 })
3821 }
3822
3823 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
3824 where
3825 E: Entity,
3826 E::Event: 'static,
3827 H: Handle<E>,
3828 F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
3829 {
3830 let subscriber = self.weak_handle();
3831 self.app
3832 .subscribe_internal(handle, move |emitter, event, cx| {
3833 if let Some(subscriber) = subscriber.upgrade(cx) {
3834 subscriber.update(cx, |subscriber, cx| {
3835 callback(subscriber, emitter, event, cx);
3836 });
3837 true
3838 } else {
3839 false
3840 }
3841 })
3842 }
3843
3844 pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3845 where
3846 E: Entity,
3847 H: Handle<E>,
3848 F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
3849 {
3850 let observer = self.weak_handle();
3851 self.app.observe_internal(handle, move |observed, cx| {
3852 if let Some(observer) = observer.upgrade(cx) {
3853 observer.update(cx, |observer, cx| {
3854 callback(observer, observed, cx);
3855 });
3856 true
3857 } else {
3858 false
3859 }
3860 })
3861 }
3862
3863 pub fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
3864 where
3865 F: 'static + FnMut(&mut T, ViewHandle<V>, bool, &mut ViewContext<T>),
3866 V: View,
3867 {
3868 let observer = self.weak_handle();
3869 self.app
3870 .observe_focus(handle, move |observed, focused, cx| {
3871 if let Some(observer) = observer.upgrade(cx) {
3872 observer.update(cx, |observer, cx| {
3873 callback(observer, observed, focused, cx);
3874 });
3875 true
3876 } else {
3877 false
3878 }
3879 })
3880 }
3881
3882 pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3883 where
3884 E: Entity,
3885 H: Handle<E>,
3886 F: 'static + FnMut(&mut T, &E, &mut ViewContext<T>),
3887 {
3888 let observer = self.weak_handle();
3889 self.app.observe_release(handle, move |released, cx| {
3890 if let Some(observer) = observer.upgrade(cx) {
3891 observer.update(cx, |observer, cx| {
3892 callback(observer, released, cx);
3893 });
3894 }
3895 })
3896 }
3897
3898 pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3899 where
3900 F: 'static + FnMut(&mut T, TypeId, &mut ViewContext<T>),
3901 {
3902 let observer = self.weak_handle();
3903 self.app.observe_actions(move |action_id, cx| {
3904 if let Some(observer) = observer.upgrade(cx) {
3905 observer.update(cx, |observer, cx| {
3906 callback(observer, action_id, cx);
3907 });
3908 }
3909 })
3910 }
3911
3912 pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3913 where
3914 F: 'static + FnMut(&mut T, bool, &mut ViewContext<T>),
3915 {
3916 let observer = self.weak_handle();
3917 self.app
3918 .observe_window_activation(self.window_id(), move |active, cx| {
3919 if let Some(observer) = observer.upgrade(cx) {
3920 observer.update(cx, |observer, cx| {
3921 callback(observer, active, cx);
3922 });
3923 true
3924 } else {
3925 false
3926 }
3927 })
3928 }
3929
3930 pub fn emit(&mut self, payload: T::Event) {
3931 self.app.pending_effects.push_back(Effect::Event {
3932 entity_id: self.view_id,
3933 payload: Box::new(payload),
3934 });
3935 }
3936
3937 pub fn notify(&mut self) {
3938 self.app.notify_view(self.window_id, self.view_id);
3939 }
3940
3941 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
3942 let handle = self.handle();
3943 self.app.defer(move |cx| {
3944 handle.update(cx, |view, cx| {
3945 callback(view, cx);
3946 })
3947 })
3948 }
3949
3950 pub fn after_window_update(
3951 &mut self,
3952 callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>),
3953 ) {
3954 let handle = self.handle();
3955 self.app.after_window_update(move |cx| {
3956 handle.update(cx, |view, cx| {
3957 callback(view, cx);
3958 })
3959 })
3960 }
3961
3962 pub fn propagate_action(&mut self) {
3963 self.app.halt_action_dispatch = false;
3964 }
3965
3966 pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
3967 where
3968 F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
3969 Fut: 'static + Future<Output = S>,
3970 S: 'static,
3971 {
3972 let handle = self.handle();
3973 self.app.spawn(|cx| f(handle, cx))
3974 }
3975
3976 pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
3977 where
3978 F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
3979 Fut: 'static + Future<Output = S>,
3980 S: 'static,
3981 {
3982 let handle = self.weak_handle();
3983 self.app.spawn(|cx| f(handle, cx))
3984 }
3985}
3986
3987pub struct RenderParams {
3988 pub window_id: usize,
3989 pub view_id: usize,
3990 pub titlebar_height: f32,
3991 pub hovered_region_ids: HashSet<MouseRegionId>,
3992 pub clicked_region_id: Option<MouseRegionId>,
3993 pub right_clicked_region_id: Option<MouseRegionId>,
3994 pub refreshing: bool,
3995}
3996
3997pub struct RenderContext<'a, T: View> {
3998 pub(crate) window_id: usize,
3999 pub(crate) view_id: usize,
4000 pub(crate) view_type: PhantomData<T>,
4001 pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
4002 pub(crate) clicked_region_id: Option<MouseRegionId>,
4003 pub(crate) right_clicked_region_id: Option<MouseRegionId>,
4004 pub app: &'a mut MutableAppContext,
4005 pub titlebar_height: f32,
4006 pub refreshing: bool,
4007}
4008
4009#[derive(Clone, Copy, Default)]
4010pub struct MouseState {
4011 pub hovered: bool,
4012 pub clicked: bool,
4013 pub right_clicked: bool,
4014}
4015
4016impl<'a, V: View> RenderContext<'a, V> {
4017 fn new(params: RenderParams, app: &'a mut MutableAppContext) -> Self {
4018 Self {
4019 app,
4020 window_id: params.window_id,
4021 view_id: params.view_id,
4022 view_type: PhantomData,
4023 titlebar_height: params.titlebar_height,
4024 hovered_region_ids: params.hovered_region_ids.clone(),
4025 clicked_region_id: params.clicked_region_id,
4026 right_clicked_region_id: params.right_clicked_region_id,
4027 refreshing: params.refreshing,
4028 }
4029 }
4030
4031 pub fn handle(&self) -> WeakViewHandle<V> {
4032 WeakViewHandle::new(self.window_id, self.view_id)
4033 }
4034
4035 pub fn view_id(&self) -> usize {
4036 self.view_id
4037 }
4038
4039 pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
4040 let region_id = MouseRegionId {
4041 view_id: self.view_id,
4042 discriminant: (TypeId::of::<Tag>(), region_id),
4043 };
4044 MouseState {
4045 hovered: self.hovered_region_ids.contains(®ion_id),
4046 clicked: self.clicked_region_id == Some(region_id),
4047 right_clicked: self.right_clicked_region_id == Some(region_id),
4048 }
4049 }
4050
4051 pub fn element_state<Tag: 'static, T: 'static + Default>(
4052 &mut self,
4053 element_id: usize,
4054 ) -> ElementStateHandle<T> {
4055 let id = ElementStateId {
4056 view_id: self.view_id(),
4057 element_id,
4058 tag: TypeId::of::<Tag>(),
4059 };
4060 self.cx
4061 .element_states
4062 .entry(id)
4063 .or_insert_with(|| Box::new(T::default()));
4064 ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
4065 }
4066}
4067
4068impl AsRef<AppContext> for &AppContext {
4069 fn as_ref(&self) -> &AppContext {
4070 self
4071 }
4072}
4073
4074impl<V: View> Deref for RenderContext<'_, V> {
4075 type Target = MutableAppContext;
4076
4077 fn deref(&self) -> &Self::Target {
4078 self.app
4079 }
4080}
4081
4082impl<V: View> DerefMut for RenderContext<'_, V> {
4083 fn deref_mut(&mut self) -> &mut Self::Target {
4084 self.app
4085 }
4086}
4087
4088impl<V: View> ReadModel for RenderContext<'_, V> {
4089 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4090 self.app.read_model(handle)
4091 }
4092}
4093
4094impl<V: View> UpdateModel for RenderContext<'_, V> {
4095 fn update_model<T: Entity, O>(
4096 &mut self,
4097 handle: &ModelHandle<T>,
4098 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4099 ) -> O {
4100 self.app.update_model(handle, update)
4101 }
4102}
4103
4104impl<V: View> ReadView for RenderContext<'_, V> {
4105 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4106 self.app.read_view(handle)
4107 }
4108}
4109
4110impl<M> AsRef<AppContext> for ViewContext<'_, M> {
4111 fn as_ref(&self) -> &AppContext {
4112 &self.app.cx
4113 }
4114}
4115
4116impl<M> Deref for ViewContext<'_, M> {
4117 type Target = MutableAppContext;
4118
4119 fn deref(&self) -> &Self::Target {
4120 &self.app
4121 }
4122}
4123
4124impl<M> DerefMut for ViewContext<'_, M> {
4125 fn deref_mut(&mut self) -> &mut Self::Target {
4126 &mut self.app
4127 }
4128}
4129
4130impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
4131 fn as_mut(&mut self) -> &mut MutableAppContext {
4132 self.app
4133 }
4134}
4135
4136impl<V> ReadModel for ViewContext<'_, V> {
4137 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
4138 self.app.read_model(handle)
4139 }
4140}
4141
4142impl<V> UpgradeModelHandle for ViewContext<'_, V> {
4143 fn upgrade_model_handle<T: Entity>(
4144 &self,
4145 handle: &WeakModelHandle<T>,
4146 ) -> Option<ModelHandle<T>> {
4147 self.cx.upgrade_model_handle(handle)
4148 }
4149
4150 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
4151 self.cx.model_handle_is_upgradable(handle)
4152 }
4153
4154 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
4155 self.cx.upgrade_any_model_handle(handle)
4156 }
4157}
4158
4159impl<V> UpgradeViewHandle for ViewContext<'_, V> {
4160 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4161 self.cx.upgrade_view_handle(handle)
4162 }
4163
4164 fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4165 self.cx.upgrade_any_view_handle(handle)
4166 }
4167}
4168
4169impl<V: View> UpgradeViewHandle for RenderContext<'_, V> {
4170 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
4171 self.cx.upgrade_view_handle(handle)
4172 }
4173
4174 fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
4175 self.cx.upgrade_any_view_handle(handle)
4176 }
4177}
4178
4179impl<V: View> UpdateModel for ViewContext<'_, V> {
4180 fn update_model<T: Entity, O>(
4181 &mut self,
4182 handle: &ModelHandle<T>,
4183 update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
4184 ) -> O {
4185 self.app.update_model(handle, update)
4186 }
4187}
4188
4189impl<V: View> ReadView for ViewContext<'_, V> {
4190 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
4191 self.app.read_view(handle)
4192 }
4193}
4194
4195impl<V: View> UpdateView for ViewContext<'_, V> {
4196 fn update_view<T, S>(
4197 &mut self,
4198 handle: &ViewHandle<T>,
4199 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
4200 ) -> S
4201 where
4202 T: View,
4203 {
4204 self.app.update_view(handle, update)
4205 }
4206}
4207
4208pub trait Handle<T> {
4209 type Weak: 'static;
4210 fn id(&self) -> usize;
4211 fn location(&self) -> EntityLocation;
4212 fn downgrade(&self) -> Self::Weak;
4213 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4214 where
4215 Self: Sized;
4216}
4217
4218pub trait WeakHandle {
4219 fn id(&self) -> usize;
4220}
4221
4222#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4223pub enum EntityLocation {
4224 Model(usize),
4225 View(usize, usize),
4226}
4227
4228pub struct ModelHandle<T: Entity> {
4229 model_id: usize,
4230 model_type: PhantomData<T>,
4231 ref_counts: Arc<Mutex<RefCounts>>,
4232
4233 #[cfg(any(test, feature = "test-support"))]
4234 handle_id: usize,
4235}
4236
4237impl<T: Entity> ModelHandle<T> {
4238 fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4239 ref_counts.lock().inc_model(model_id);
4240
4241 #[cfg(any(test, feature = "test-support"))]
4242 let handle_id = ref_counts
4243 .lock()
4244 .leak_detector
4245 .lock()
4246 .handle_created(Some(type_name::<T>()), model_id);
4247
4248 Self {
4249 model_id,
4250 model_type: PhantomData,
4251 ref_counts: ref_counts.clone(),
4252
4253 #[cfg(any(test, feature = "test-support"))]
4254 handle_id,
4255 }
4256 }
4257
4258 pub fn downgrade(&self) -> WeakModelHandle<T> {
4259 WeakModelHandle::new(self.model_id)
4260 }
4261
4262 pub fn id(&self) -> usize {
4263 self.model_id
4264 }
4265
4266 pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
4267 cx.read_model(self)
4268 }
4269
4270 pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
4271 where
4272 C: ReadModelWith,
4273 F: FnOnce(&T, &AppContext) -> S,
4274 {
4275 let mut read = Some(read);
4276 cx.read_model_with(self, &mut |model, cx| {
4277 let read = read.take().unwrap();
4278 read(model, cx)
4279 })
4280 }
4281
4282 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4283 where
4284 C: UpdateModel,
4285 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
4286 {
4287 let mut update = Some(update);
4288 cx.update_model(self, &mut |model, cx| {
4289 let update = update.take().unwrap();
4290 update(model, cx)
4291 })
4292 }
4293
4294 #[cfg(any(test, feature = "test-support"))]
4295 pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
4296 let (tx, mut rx) = futures::channel::mpsc::unbounded();
4297 let mut cx = cx.cx.borrow_mut();
4298 let subscription = cx.observe(self, move |_, _| {
4299 tx.unbounded_send(()).ok();
4300 });
4301
4302 let duration = if std::env::var("CI").is_ok() {
4303 Duration::from_secs(5)
4304 } else {
4305 Duration::from_secs(1)
4306 };
4307
4308 async move {
4309 let notification = crate::util::timeout(duration, rx.next())
4310 .await
4311 .expect("next notification timed out");
4312 drop(subscription);
4313 notification.expect("model dropped while test was waiting for its next notification")
4314 }
4315 }
4316
4317 #[cfg(any(test, feature = "test-support"))]
4318 pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
4319 where
4320 T::Event: Clone,
4321 {
4322 let (tx, mut rx) = futures::channel::mpsc::unbounded();
4323 let mut cx = cx.cx.borrow_mut();
4324 let subscription = cx.subscribe(self, move |_, event, _| {
4325 tx.unbounded_send(event.clone()).ok();
4326 });
4327
4328 let duration = if std::env::var("CI").is_ok() {
4329 Duration::from_secs(5)
4330 } else {
4331 Duration::from_secs(1)
4332 };
4333
4334 cx.foreground.start_waiting();
4335 async move {
4336 let event = crate::util::timeout(duration, rx.next())
4337 .await
4338 .expect("next event timed out");
4339 drop(subscription);
4340 event.expect("model dropped while test was waiting for its next event")
4341 }
4342 }
4343
4344 #[cfg(any(test, feature = "test-support"))]
4345 pub fn condition(
4346 &self,
4347 cx: &TestAppContext,
4348 mut predicate: impl FnMut(&T, &AppContext) -> bool,
4349 ) -> impl Future<Output = ()> {
4350 let (tx, mut rx) = futures::channel::mpsc::unbounded();
4351
4352 let mut cx = cx.cx.borrow_mut();
4353 let subscriptions = (
4354 cx.observe(self, {
4355 let tx = tx.clone();
4356 move |_, _| {
4357 tx.unbounded_send(()).ok();
4358 }
4359 }),
4360 cx.subscribe(self, {
4361 let tx = tx.clone();
4362 move |_, _, _| {
4363 tx.unbounded_send(()).ok();
4364 }
4365 }),
4366 );
4367
4368 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
4369 let handle = self.downgrade();
4370 let duration = if std::env::var("CI").is_ok() {
4371 Duration::from_secs(5)
4372 } else {
4373 Duration::from_secs(1)
4374 };
4375
4376 async move {
4377 crate::util::timeout(duration, async move {
4378 loop {
4379 {
4380 let cx = cx.borrow();
4381 let cx = cx.as_ref();
4382 if predicate(
4383 handle
4384 .upgrade(cx)
4385 .expect("model dropped with pending condition")
4386 .read(cx),
4387 cx,
4388 ) {
4389 break;
4390 }
4391 }
4392
4393 cx.borrow().foreground().start_waiting();
4394 rx.next()
4395 .await
4396 .expect("model dropped with pending condition");
4397 cx.borrow().foreground().finish_waiting();
4398 }
4399 })
4400 .await
4401 .expect("condition timed out");
4402 drop(subscriptions);
4403 }
4404 }
4405}
4406
4407impl<T: Entity> Clone for ModelHandle<T> {
4408 fn clone(&self) -> Self {
4409 Self::new(self.model_id, &self.ref_counts)
4410 }
4411}
4412
4413impl<T: Entity> PartialEq for ModelHandle<T> {
4414 fn eq(&self, other: &Self) -> bool {
4415 self.model_id == other.model_id
4416 }
4417}
4418
4419impl<T: Entity> Eq for ModelHandle<T> {}
4420
4421impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
4422 fn eq(&self, other: &WeakModelHandle<T>) -> bool {
4423 self.model_id == other.model_id
4424 }
4425}
4426
4427impl<T: Entity> Hash for ModelHandle<T> {
4428 fn hash<H: Hasher>(&self, state: &mut H) {
4429 self.model_id.hash(state);
4430 }
4431}
4432
4433impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
4434 fn borrow(&self) -> &usize {
4435 &self.model_id
4436 }
4437}
4438
4439impl<T: Entity> Debug for ModelHandle<T> {
4440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4441 f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
4442 .field(&self.model_id)
4443 .finish()
4444 }
4445}
4446
4447unsafe impl<T: Entity> Send for ModelHandle<T> {}
4448unsafe impl<T: Entity> Sync for ModelHandle<T> {}
4449
4450impl<T: Entity> Drop for ModelHandle<T> {
4451 fn drop(&mut self) {
4452 let mut ref_counts = self.ref_counts.lock();
4453 ref_counts.dec_model(self.model_id);
4454
4455 #[cfg(any(test, feature = "test-support"))]
4456 ref_counts
4457 .leak_detector
4458 .lock()
4459 .handle_dropped(self.model_id, self.handle_id);
4460 }
4461}
4462
4463impl<T: Entity> Handle<T> for ModelHandle<T> {
4464 type Weak = WeakModelHandle<T>;
4465
4466 fn id(&self) -> usize {
4467 self.model_id
4468 }
4469
4470 fn location(&self) -> EntityLocation {
4471 EntityLocation::Model(self.model_id)
4472 }
4473
4474 fn downgrade(&self) -> Self::Weak {
4475 self.downgrade()
4476 }
4477
4478 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4479 where
4480 Self: Sized,
4481 {
4482 weak.upgrade(cx)
4483 }
4484}
4485
4486pub struct WeakModelHandle<T> {
4487 model_id: usize,
4488 model_type: PhantomData<T>,
4489}
4490
4491impl<T> WeakHandle for WeakModelHandle<T> {
4492 fn id(&self) -> usize {
4493 self.model_id
4494 }
4495}
4496
4497unsafe impl<T> Send for WeakModelHandle<T> {}
4498unsafe impl<T> Sync for WeakModelHandle<T> {}
4499
4500impl<T: Entity> WeakModelHandle<T> {
4501 fn new(model_id: usize) -> Self {
4502 Self {
4503 model_id,
4504 model_type: PhantomData,
4505 }
4506 }
4507
4508 pub fn id(&self) -> usize {
4509 self.model_id
4510 }
4511
4512 pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
4513 cx.model_handle_is_upgradable(self)
4514 }
4515
4516 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
4517 cx.upgrade_model_handle(self)
4518 }
4519}
4520
4521impl<T> Hash for WeakModelHandle<T> {
4522 fn hash<H: Hasher>(&self, state: &mut H) {
4523 self.model_id.hash(state)
4524 }
4525}
4526
4527impl<T> PartialEq for WeakModelHandle<T> {
4528 fn eq(&self, other: &Self) -> bool {
4529 self.model_id == other.model_id
4530 }
4531}
4532
4533impl<T> Eq for WeakModelHandle<T> {}
4534
4535impl<T> Clone for WeakModelHandle<T> {
4536 fn clone(&self) -> Self {
4537 Self {
4538 model_id: self.model_id,
4539 model_type: PhantomData,
4540 }
4541 }
4542}
4543
4544impl<T> Copy for WeakModelHandle<T> {}
4545
4546pub struct ViewHandle<T> {
4547 window_id: usize,
4548 view_id: usize,
4549 view_type: PhantomData<T>,
4550 ref_counts: Arc<Mutex<RefCounts>>,
4551 #[cfg(any(test, feature = "test-support"))]
4552 handle_id: usize,
4553}
4554
4555impl<T: View> ViewHandle<T> {
4556 fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4557 ref_counts.lock().inc_view(window_id, view_id);
4558 #[cfg(any(test, feature = "test-support"))]
4559 let handle_id = ref_counts
4560 .lock()
4561 .leak_detector
4562 .lock()
4563 .handle_created(Some(type_name::<T>()), view_id);
4564
4565 Self {
4566 window_id,
4567 view_id,
4568 view_type: PhantomData,
4569 ref_counts: ref_counts.clone(),
4570
4571 #[cfg(any(test, feature = "test-support"))]
4572 handle_id,
4573 }
4574 }
4575
4576 pub fn downgrade(&self) -> WeakViewHandle<T> {
4577 WeakViewHandle::new(self.window_id, self.view_id)
4578 }
4579
4580 pub fn window_id(&self) -> usize {
4581 self.window_id
4582 }
4583
4584 pub fn id(&self) -> usize {
4585 self.view_id
4586 }
4587
4588 pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
4589 cx.read_view(self)
4590 }
4591
4592 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
4593 where
4594 C: ReadViewWith,
4595 F: FnOnce(&T, &AppContext) -> S,
4596 {
4597 let mut read = Some(read);
4598 cx.read_view_with(self, &mut |view, cx| {
4599 let read = read.take().unwrap();
4600 read(view, cx)
4601 })
4602 }
4603
4604 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
4605 where
4606 C: UpdateView,
4607 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
4608 {
4609 let mut update = Some(update);
4610 cx.update_view(self, &mut |view, cx| {
4611 let update = update.take().unwrap();
4612 update(view, cx)
4613 })
4614 }
4615
4616 pub fn defer<C, F>(&self, cx: &mut C, update: F)
4617 where
4618 C: AsMut<MutableAppContext>,
4619 F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
4620 {
4621 let this = self.clone();
4622 cx.as_mut().defer(move |cx| {
4623 this.update(cx, |view, cx| update(view, cx));
4624 });
4625 }
4626
4627 pub fn is_focused(&self, cx: &AppContext) -> bool {
4628 cx.focused_view_id(self.window_id)
4629 .map_or(false, |focused_id| focused_id == self.view_id)
4630 }
4631
4632 #[cfg(any(test, feature = "test-support"))]
4633 pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
4634 use postage::prelude::{Sink as _, Stream as _};
4635
4636 let (mut tx, mut rx) = postage::mpsc::channel(1);
4637 let mut cx = cx.cx.borrow_mut();
4638 let subscription = cx.observe(self, move |_, _| {
4639 tx.try_send(()).ok();
4640 });
4641
4642 let duration = if std::env::var("CI").is_ok() {
4643 Duration::from_secs(5)
4644 } else {
4645 Duration::from_secs(1)
4646 };
4647
4648 async move {
4649 let notification = crate::util::timeout(duration, rx.recv())
4650 .await
4651 .expect("next notification timed out");
4652 drop(subscription);
4653 notification.expect("model dropped while test was waiting for its next notification")
4654 }
4655 }
4656
4657 #[cfg(any(test, feature = "test-support"))]
4658 pub fn condition(
4659 &self,
4660 cx: &TestAppContext,
4661 mut predicate: impl FnMut(&T, &AppContext) -> bool,
4662 ) -> impl Future<Output = ()> {
4663 use postage::prelude::{Sink as _, Stream as _};
4664
4665 let (tx, mut rx) = postage::mpsc::channel(1024);
4666 let timeout_duration = cx.condition_duration();
4667
4668 let mut cx = cx.cx.borrow_mut();
4669 let subscriptions = self.update(&mut *cx, |_, cx| {
4670 (
4671 cx.observe(self, {
4672 let mut tx = tx.clone();
4673 move |_, _, _| {
4674 tx.blocking_send(()).ok();
4675 }
4676 }),
4677 cx.subscribe(self, {
4678 let mut tx = tx.clone();
4679 move |_, _, _, _| {
4680 tx.blocking_send(()).ok();
4681 }
4682 }),
4683 )
4684 });
4685
4686 let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
4687 let handle = self.downgrade();
4688
4689 async move {
4690 crate::util::timeout(timeout_duration, async move {
4691 loop {
4692 {
4693 let cx = cx.borrow();
4694 let cx = cx.as_ref();
4695 if predicate(
4696 handle
4697 .upgrade(cx)
4698 .expect("view dropped with pending condition")
4699 .read(cx),
4700 cx,
4701 ) {
4702 break;
4703 }
4704 }
4705
4706 cx.borrow().foreground().start_waiting();
4707 rx.recv()
4708 .await
4709 .expect("view dropped with pending condition");
4710 cx.borrow().foreground().finish_waiting();
4711 }
4712 })
4713 .await
4714 .expect("condition timed out");
4715 drop(subscriptions);
4716 }
4717 }
4718}
4719
4720impl<T: View> Clone for ViewHandle<T> {
4721 fn clone(&self) -> Self {
4722 ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
4723 }
4724}
4725
4726impl<T> PartialEq for ViewHandle<T> {
4727 fn eq(&self, other: &Self) -> bool {
4728 self.window_id == other.window_id && self.view_id == other.view_id
4729 }
4730}
4731
4732impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
4733 fn eq(&self, other: &WeakViewHandle<T>) -> bool {
4734 self.window_id == other.window_id && self.view_id == other.view_id
4735 }
4736}
4737
4738impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
4739 fn eq(&self, other: &ViewHandle<T>) -> bool {
4740 self.window_id == other.window_id && self.view_id == other.view_id
4741 }
4742}
4743
4744impl<T> Eq for ViewHandle<T> {}
4745
4746impl<T> Hash for ViewHandle<T> {
4747 fn hash<H: Hasher>(&self, state: &mut H) {
4748 self.window_id.hash(state);
4749 self.view_id.hash(state);
4750 }
4751}
4752
4753impl<T> Debug for ViewHandle<T> {
4754 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4755 f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
4756 .field("window_id", &self.window_id)
4757 .field("view_id", &self.view_id)
4758 .finish()
4759 }
4760}
4761
4762impl<T> Drop for ViewHandle<T> {
4763 fn drop(&mut self) {
4764 self.ref_counts
4765 .lock()
4766 .dec_view(self.window_id, self.view_id);
4767 #[cfg(any(test, feature = "test-support"))]
4768 self.ref_counts
4769 .lock()
4770 .leak_detector
4771 .lock()
4772 .handle_dropped(self.view_id, self.handle_id);
4773 }
4774}
4775
4776impl<T: View> Handle<T> for ViewHandle<T> {
4777 type Weak = WeakViewHandle<T>;
4778
4779 fn id(&self) -> usize {
4780 self.view_id
4781 }
4782
4783 fn location(&self) -> EntityLocation {
4784 EntityLocation::View(self.window_id, self.view_id)
4785 }
4786
4787 fn downgrade(&self) -> Self::Weak {
4788 self.downgrade()
4789 }
4790
4791 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
4792 where
4793 Self: Sized,
4794 {
4795 weak.upgrade(cx)
4796 }
4797}
4798
4799pub struct AnyViewHandle {
4800 window_id: usize,
4801 view_id: usize,
4802 view_type: TypeId,
4803 ref_counts: Arc<Mutex<RefCounts>>,
4804
4805 #[cfg(any(test, feature = "test-support"))]
4806 handle_id: usize,
4807}
4808
4809impl AnyViewHandle {
4810 fn new(
4811 window_id: usize,
4812 view_id: usize,
4813 view_type: TypeId,
4814 ref_counts: Arc<Mutex<RefCounts>>,
4815 ) -> Self {
4816 ref_counts.lock().inc_view(window_id, view_id);
4817
4818 #[cfg(any(test, feature = "test-support"))]
4819 let handle_id = ref_counts
4820 .lock()
4821 .leak_detector
4822 .lock()
4823 .handle_created(None, view_id);
4824
4825 Self {
4826 window_id,
4827 view_id,
4828 view_type,
4829 ref_counts,
4830 #[cfg(any(test, feature = "test-support"))]
4831 handle_id,
4832 }
4833 }
4834
4835 pub fn id(&self) -> usize {
4836 self.view_id
4837 }
4838
4839 pub fn is<T: 'static>(&self) -> bool {
4840 TypeId::of::<T>() == self.view_type
4841 }
4842
4843 pub fn is_focused(&self, cx: &AppContext) -> bool {
4844 cx.focused_view_id(self.window_id)
4845 .map_or(false, |focused_id| focused_id == self.view_id)
4846 }
4847
4848 pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
4849 if self.is::<T>() {
4850 let result = Some(ViewHandle {
4851 window_id: self.window_id,
4852 view_id: self.view_id,
4853 ref_counts: self.ref_counts.clone(),
4854 view_type: PhantomData,
4855 #[cfg(any(test, feature = "test-support"))]
4856 handle_id: self.handle_id,
4857 });
4858 unsafe {
4859 Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4860 }
4861 std::mem::forget(self);
4862 result
4863 } else {
4864 None
4865 }
4866 }
4867
4868 pub fn downgrade(&self) -> AnyWeakViewHandle {
4869 AnyWeakViewHandle {
4870 window_id: self.window_id,
4871 view_id: self.view_id,
4872 view_type: self.view_type,
4873 }
4874 }
4875
4876 pub fn view_type(&self) -> TypeId {
4877 self.view_type
4878 }
4879
4880 pub fn debug_json(&self, cx: &AppContext) -> serde_json::Value {
4881 cx.views
4882 .get(&(self.window_id, self.view_id))
4883 .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
4884 }
4885}
4886
4887impl Clone for AnyViewHandle {
4888 fn clone(&self) -> Self {
4889 Self::new(
4890 self.window_id,
4891 self.view_id,
4892 self.view_type,
4893 self.ref_counts.clone(),
4894 )
4895 }
4896}
4897
4898impl From<&AnyViewHandle> for AnyViewHandle {
4899 fn from(handle: &AnyViewHandle) -> Self {
4900 handle.clone()
4901 }
4902}
4903
4904impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
4905 fn from(handle: &ViewHandle<T>) -> Self {
4906 Self::new(
4907 handle.window_id,
4908 handle.view_id,
4909 TypeId::of::<T>(),
4910 handle.ref_counts.clone(),
4911 )
4912 }
4913}
4914
4915impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
4916 fn from(handle: ViewHandle<T>) -> Self {
4917 let any_handle = AnyViewHandle {
4918 window_id: handle.window_id,
4919 view_id: handle.view_id,
4920 view_type: TypeId::of::<T>(),
4921 ref_counts: handle.ref_counts.clone(),
4922 #[cfg(any(test, feature = "test-support"))]
4923 handle_id: handle.handle_id,
4924 };
4925
4926 unsafe {
4927 Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
4928 }
4929 std::mem::forget(handle);
4930 any_handle
4931 }
4932}
4933
4934impl Drop for AnyViewHandle {
4935 fn drop(&mut self) {
4936 self.ref_counts
4937 .lock()
4938 .dec_view(self.window_id, self.view_id);
4939 #[cfg(any(test, feature = "test-support"))]
4940 self.ref_counts
4941 .lock()
4942 .leak_detector
4943 .lock()
4944 .handle_dropped(self.view_id, self.handle_id);
4945 }
4946}
4947
4948pub struct AnyModelHandle {
4949 model_id: usize,
4950 model_type: TypeId,
4951 ref_counts: Arc<Mutex<RefCounts>>,
4952
4953 #[cfg(any(test, feature = "test-support"))]
4954 handle_id: usize,
4955}
4956
4957impl AnyModelHandle {
4958 fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
4959 ref_counts.lock().inc_model(model_id);
4960
4961 #[cfg(any(test, feature = "test-support"))]
4962 let handle_id = ref_counts
4963 .lock()
4964 .leak_detector
4965 .lock()
4966 .handle_created(None, model_id);
4967
4968 Self {
4969 model_id,
4970 model_type,
4971 ref_counts,
4972
4973 #[cfg(any(test, feature = "test-support"))]
4974 handle_id,
4975 }
4976 }
4977
4978 pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
4979 if self.is::<T>() {
4980 let result = Some(ModelHandle {
4981 model_id: self.model_id,
4982 model_type: PhantomData,
4983 ref_counts: self.ref_counts.clone(),
4984
4985 #[cfg(any(test, feature = "test-support"))]
4986 handle_id: self.handle_id,
4987 });
4988 unsafe {
4989 Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
4990 }
4991 std::mem::forget(self);
4992 result
4993 } else {
4994 None
4995 }
4996 }
4997
4998 pub fn downgrade(&self) -> AnyWeakModelHandle {
4999 AnyWeakModelHandle {
5000 model_id: self.model_id,
5001 model_type: self.model_type,
5002 }
5003 }
5004
5005 pub fn is<T: Entity>(&self) -> bool {
5006 self.model_type == TypeId::of::<T>()
5007 }
5008
5009 pub fn model_type(&self) -> TypeId {
5010 self.model_type
5011 }
5012}
5013
5014impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
5015 fn from(handle: ModelHandle<T>) -> Self {
5016 Self::new(
5017 handle.model_id,
5018 TypeId::of::<T>(),
5019 handle.ref_counts.clone(),
5020 )
5021 }
5022}
5023
5024impl Clone for AnyModelHandle {
5025 fn clone(&self) -> Self {
5026 Self::new(self.model_id, self.model_type, self.ref_counts.clone())
5027 }
5028}
5029
5030impl Drop for AnyModelHandle {
5031 fn drop(&mut self) {
5032 let mut ref_counts = self.ref_counts.lock();
5033 ref_counts.dec_model(self.model_id);
5034
5035 #[cfg(any(test, feature = "test-support"))]
5036 ref_counts
5037 .leak_detector
5038 .lock()
5039 .handle_dropped(self.model_id, self.handle_id);
5040 }
5041}
5042
5043pub struct AnyWeakModelHandle {
5044 model_id: usize,
5045 model_type: TypeId,
5046}
5047
5048impl AnyWeakModelHandle {
5049 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
5050 cx.upgrade_any_model_handle(self)
5051 }
5052}
5053
5054impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
5055 fn from(handle: WeakModelHandle<T>) -> Self {
5056 AnyWeakModelHandle {
5057 model_id: handle.model_id,
5058 model_type: TypeId::of::<T>(),
5059 }
5060 }
5061}
5062
5063pub struct WeakViewHandle<T> {
5064 window_id: usize,
5065 view_id: usize,
5066 view_type: PhantomData<T>,
5067}
5068
5069impl<T> WeakHandle for WeakViewHandle<T> {
5070 fn id(&self) -> usize {
5071 self.view_id
5072 }
5073}
5074
5075impl<T: View> WeakViewHandle<T> {
5076 fn new(window_id: usize, view_id: usize) -> Self {
5077 Self {
5078 window_id,
5079 view_id,
5080 view_type: PhantomData,
5081 }
5082 }
5083
5084 pub fn id(&self) -> usize {
5085 self.view_id
5086 }
5087
5088 pub fn window_id(&self) -> usize {
5089 self.window_id
5090 }
5091
5092 pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
5093 cx.upgrade_view_handle(self)
5094 }
5095}
5096
5097impl<T> Clone for WeakViewHandle<T> {
5098 fn clone(&self) -> Self {
5099 Self {
5100 window_id: self.window_id,
5101 view_id: self.view_id,
5102 view_type: PhantomData,
5103 }
5104 }
5105}
5106
5107impl<T> PartialEq for WeakViewHandle<T> {
5108 fn eq(&self, other: &Self) -> bool {
5109 self.window_id == other.window_id && self.view_id == other.view_id
5110 }
5111}
5112
5113impl<T> Eq for WeakViewHandle<T> {}
5114
5115impl<T> Hash for WeakViewHandle<T> {
5116 fn hash<H: Hasher>(&self, state: &mut H) {
5117 self.window_id.hash(state);
5118 self.view_id.hash(state);
5119 }
5120}
5121
5122pub struct AnyWeakViewHandle {
5123 window_id: usize,
5124 view_id: usize,
5125 view_type: TypeId,
5126}
5127
5128impl AnyWeakViewHandle {
5129 pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<AnyViewHandle> {
5130 cx.upgrade_any_view_handle(self)
5131 }
5132}
5133
5134impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
5135 fn from(handle: WeakViewHandle<T>) -> Self {
5136 AnyWeakViewHandle {
5137 window_id: handle.window_id,
5138 view_id: handle.view_id,
5139 view_type: TypeId::of::<T>(),
5140 }
5141 }
5142}
5143
5144#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5145pub struct ElementStateId {
5146 view_id: usize,
5147 element_id: usize,
5148 tag: TypeId,
5149}
5150
5151pub struct ElementStateHandle<T> {
5152 value_type: PhantomData<T>,
5153 id: ElementStateId,
5154 ref_counts: Weak<Mutex<RefCounts>>,
5155}
5156
5157impl<T: 'static> ElementStateHandle<T> {
5158 fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
5159 ref_counts.lock().inc_element_state(id, frame_id);
5160 Self {
5161 value_type: PhantomData,
5162 id,
5163 ref_counts: Arc::downgrade(ref_counts),
5164 }
5165 }
5166
5167 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
5168 cx.element_states
5169 .get(&self.id)
5170 .unwrap()
5171 .downcast_ref()
5172 .unwrap()
5173 }
5174
5175 pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
5176 where
5177 C: DerefMut<Target = MutableAppContext>,
5178 {
5179 let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
5180 let result = f(element_state.downcast_mut().unwrap(), cx);
5181 cx.deref_mut()
5182 .cx
5183 .element_states
5184 .insert(self.id, element_state);
5185 result
5186 }
5187}
5188
5189impl<T> Drop for ElementStateHandle<T> {
5190 fn drop(&mut self) {
5191 if let Some(ref_counts) = self.ref_counts.upgrade() {
5192 ref_counts.lock().dec_element_state(self.id);
5193 }
5194 }
5195}
5196
5197#[must_use]
5198pub enum Subscription {
5199 Subscription {
5200 id: usize,
5201 entity_id: usize,
5202 subscriptions:
5203 Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<SubscriptionCallback>>>>>>,
5204 },
5205 GlobalSubscription {
5206 id: usize,
5207 type_id: TypeId,
5208 subscriptions: Option<
5209 Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalSubscriptionCallback>>>>>,
5210 >,
5211 },
5212 Observation {
5213 id: usize,
5214 entity_id: usize,
5215 observations:
5216 Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<ObservationCallback>>>>>>,
5217 },
5218 GlobalObservation {
5219 id: usize,
5220 type_id: TypeId,
5221 observations: Option<
5222 Weak<Mutex<HashMap<TypeId, BTreeMap<usize, Option<GlobalObservationCallback>>>>>,
5223 >,
5224 },
5225 FocusObservation {
5226 id: usize,
5227 view_id: usize,
5228 observations:
5229 Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<FocusObservationCallback>>>>>>,
5230 },
5231 ReleaseObservation {
5232 id: usize,
5233 entity_id: usize,
5234 observations:
5235 Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
5236 },
5237 ActionObservation {
5238 id: usize,
5239 observations: Option<Weak<Mutex<BTreeMap<usize, ActionObservationCallback>>>>,
5240 },
5241 WindowActivationObservation {
5242 id: usize,
5243 window_id: usize,
5244 observations:
5245 Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, Option<WindowActivationCallback>>>>>>,
5246 },
5247}
5248
5249impl Subscription {
5250 pub fn detach(&mut self) {
5251 match self {
5252 Subscription::Subscription { subscriptions, .. } => {
5253 subscriptions.take();
5254 }
5255 Subscription::GlobalSubscription { subscriptions, .. } => {
5256 subscriptions.take();
5257 }
5258 Subscription::Observation { observations, .. } => {
5259 observations.take();
5260 }
5261 Subscription::GlobalObservation { observations, .. } => {
5262 observations.take();
5263 }
5264 Subscription::ReleaseObservation { observations, .. } => {
5265 observations.take();
5266 }
5267 Subscription::FocusObservation { observations, .. } => {
5268 observations.take();
5269 }
5270 Subscription::ActionObservation { observations, .. } => {
5271 observations.take();
5272 }
5273 Subscription::WindowActivationObservation { observations, .. } => {
5274 observations.take();
5275 }
5276 }
5277 }
5278}
5279
5280impl Drop for Subscription {
5281 fn drop(&mut self) {
5282 match self {
5283 Subscription::Subscription {
5284 id,
5285 entity_id,
5286 subscriptions,
5287 } => {
5288 if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5289 match subscriptions
5290 .lock()
5291 .entry(*entity_id)
5292 .or_default()
5293 .entry(*id)
5294 {
5295 btree_map::Entry::Vacant(entry) => {
5296 entry.insert(None);
5297 }
5298 btree_map::Entry::Occupied(entry) => {
5299 entry.remove();
5300 }
5301 }
5302 }
5303 }
5304 Subscription::GlobalSubscription {
5305 id,
5306 type_id,
5307 subscriptions,
5308 } => {
5309 if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
5310 match subscriptions.lock().entry(*type_id).or_default().entry(*id) {
5311 btree_map::Entry::Vacant(entry) => {
5312 entry.insert(None);
5313 }
5314 btree_map::Entry::Occupied(entry) => {
5315 entry.remove();
5316 }
5317 }
5318 }
5319 }
5320 Subscription::Observation {
5321 id,
5322 entity_id,
5323 observations,
5324 } => {
5325 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5326 match observations
5327 .lock()
5328 .entry(*entity_id)
5329 .or_default()
5330 .entry(*id)
5331 {
5332 btree_map::Entry::Vacant(entry) => {
5333 entry.insert(None);
5334 }
5335 btree_map::Entry::Occupied(entry) => {
5336 entry.remove();
5337 }
5338 }
5339 }
5340 }
5341 Subscription::GlobalObservation {
5342 id,
5343 type_id,
5344 observations,
5345 } => {
5346 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5347 match observations.lock().entry(*type_id).or_default().entry(*id) {
5348 collections::btree_map::Entry::Vacant(entry) => {
5349 entry.insert(None);
5350 }
5351 collections::btree_map::Entry::Occupied(entry) => {
5352 entry.remove();
5353 }
5354 }
5355 }
5356 }
5357 Subscription::ReleaseObservation {
5358 id,
5359 entity_id,
5360 observations,
5361 } => {
5362 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5363 if let Some(observations) = observations.lock().get_mut(entity_id) {
5364 observations.remove(id);
5365 }
5366 }
5367 }
5368 Subscription::FocusObservation {
5369 id,
5370 view_id,
5371 observations,
5372 } => {
5373 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5374 match observations.lock().entry(*view_id).or_default().entry(*id) {
5375 btree_map::Entry::Vacant(entry) => {
5376 entry.insert(None);
5377 }
5378 btree_map::Entry::Occupied(entry) => {
5379 entry.remove();
5380 }
5381 }
5382 }
5383 }
5384 Subscription::ActionObservation { id, observations } => {
5385 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5386 observations.lock().remove(&id);
5387 }
5388 }
5389 Subscription::WindowActivationObservation {
5390 id,
5391 window_id,
5392 observations,
5393 } => {
5394 if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
5395 match observations
5396 .lock()
5397 .entry(*window_id)
5398 .or_default()
5399 .entry(*id)
5400 {
5401 btree_map::Entry::Vacant(entry) => {
5402 entry.insert(None);
5403 }
5404 btree_map::Entry::Occupied(entry) => {
5405 entry.remove();
5406 }
5407 }
5408 }
5409 }
5410 }
5411 }
5412}
5413
5414lazy_static! {
5415 static ref LEAK_BACKTRACE: bool =
5416 std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
5417}
5418
5419#[cfg(any(test, feature = "test-support"))]
5420#[derive(Default)]
5421pub struct LeakDetector {
5422 next_handle_id: usize,
5423 handle_backtraces: HashMap<
5424 usize,
5425 (
5426 Option<&'static str>,
5427 HashMap<usize, Option<backtrace::Backtrace>>,
5428 ),
5429 >,
5430}
5431
5432#[cfg(any(test, feature = "test-support"))]
5433impl LeakDetector {
5434 fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
5435 let handle_id = post_inc(&mut self.next_handle_id);
5436 let entry = self.handle_backtraces.entry(entity_id).or_default();
5437 let backtrace = if *LEAK_BACKTRACE {
5438 Some(backtrace::Backtrace::new_unresolved())
5439 } else {
5440 None
5441 };
5442 if let Some(type_name) = type_name {
5443 entry.0.get_or_insert(type_name);
5444 }
5445 entry.1.insert(handle_id, backtrace);
5446 handle_id
5447 }
5448
5449 fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
5450 if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5451 assert!(backtraces.remove(&handle_id).is_some());
5452 if backtraces.is_empty() {
5453 self.handle_backtraces.remove(&entity_id);
5454 }
5455 }
5456 }
5457
5458 pub fn assert_dropped(&mut self, entity_id: usize) {
5459 if let Some((type_name, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
5460 for trace in backtraces.values_mut() {
5461 if let Some(trace) = trace {
5462 trace.resolve();
5463 eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5464 }
5465 }
5466
5467 let hint = if *LEAK_BACKTRACE {
5468 ""
5469 } else {
5470 " – set LEAK_BACKTRACE=1 for more information"
5471 };
5472
5473 panic!(
5474 "{} handles to {} {} still exist{}",
5475 backtraces.len(),
5476 type_name.unwrap_or("entity"),
5477 entity_id,
5478 hint
5479 );
5480 }
5481 }
5482
5483 pub fn detect(&mut self) {
5484 let mut found_leaks = false;
5485 for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
5486 eprintln!(
5487 "leaked {} handles to {} {}",
5488 backtraces.len(),
5489 type_name.unwrap_or("entity"),
5490 id
5491 );
5492 for trace in backtraces.values_mut() {
5493 if let Some(trace) = trace {
5494 trace.resolve();
5495 eprintln!("{:?}", crate::util::CwdBacktrace(trace));
5496 }
5497 }
5498 found_leaks = true;
5499 }
5500
5501 let hint = if *LEAK_BACKTRACE {
5502 ""
5503 } else {
5504 " – set LEAK_BACKTRACE=1 for more information"
5505 };
5506 assert!(!found_leaks, "detected leaked handles{}", hint);
5507 }
5508}
5509
5510#[derive(Default)]
5511struct RefCounts {
5512 entity_counts: HashMap<usize, usize>,
5513 element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
5514 dropped_models: HashSet<usize>,
5515 dropped_views: HashSet<(usize, usize)>,
5516 dropped_element_states: HashSet<ElementStateId>,
5517
5518 #[cfg(any(test, feature = "test-support"))]
5519 leak_detector: Arc<Mutex<LeakDetector>>,
5520}
5521
5522struct ElementStateRefCount {
5523 ref_count: usize,
5524 frame_id: usize,
5525}
5526
5527impl RefCounts {
5528 fn inc_model(&mut self, model_id: usize) {
5529 match self.entity_counts.entry(model_id) {
5530 Entry::Occupied(mut entry) => {
5531 *entry.get_mut() += 1;
5532 }
5533 Entry::Vacant(entry) => {
5534 entry.insert(1);
5535 self.dropped_models.remove(&model_id);
5536 }
5537 }
5538 }
5539
5540 fn inc_view(&mut self, window_id: usize, view_id: usize) {
5541 match self.entity_counts.entry(view_id) {
5542 Entry::Occupied(mut entry) => *entry.get_mut() += 1,
5543 Entry::Vacant(entry) => {
5544 entry.insert(1);
5545 self.dropped_views.remove(&(window_id, view_id));
5546 }
5547 }
5548 }
5549
5550 fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
5551 match self.element_state_counts.entry(id) {
5552 Entry::Occupied(mut entry) => {
5553 let entry = entry.get_mut();
5554 if entry.frame_id == frame_id || entry.ref_count >= 2 {
5555 panic!("used the same element state more than once in the same frame");
5556 }
5557 entry.ref_count += 1;
5558 entry.frame_id = frame_id;
5559 }
5560 Entry::Vacant(entry) => {
5561 entry.insert(ElementStateRefCount {
5562 ref_count: 1,
5563 frame_id,
5564 });
5565 self.dropped_element_states.remove(&id);
5566 }
5567 }
5568 }
5569
5570 fn dec_model(&mut self, model_id: usize) {
5571 let count = self.entity_counts.get_mut(&model_id).unwrap();
5572 *count -= 1;
5573 if *count == 0 {
5574 self.entity_counts.remove(&model_id);
5575 self.dropped_models.insert(model_id);
5576 }
5577 }
5578
5579 fn dec_view(&mut self, window_id: usize, view_id: usize) {
5580 let count = self.entity_counts.get_mut(&view_id).unwrap();
5581 *count -= 1;
5582 if *count == 0 {
5583 self.entity_counts.remove(&view_id);
5584 self.dropped_views.insert((window_id, view_id));
5585 }
5586 }
5587
5588 fn dec_element_state(&mut self, id: ElementStateId) {
5589 let entry = self.element_state_counts.get_mut(&id).unwrap();
5590 entry.ref_count -= 1;
5591 if entry.ref_count == 0 {
5592 self.element_state_counts.remove(&id);
5593 self.dropped_element_states.insert(id);
5594 }
5595 }
5596
5597 fn is_entity_alive(&self, entity_id: usize) -> bool {
5598 self.entity_counts.contains_key(&entity_id)
5599 }
5600
5601 fn take_dropped(
5602 &mut self,
5603 ) -> (
5604 HashSet<usize>,
5605 HashSet<(usize, usize)>,
5606 HashSet<ElementStateId>,
5607 ) {
5608 (
5609 std::mem::take(&mut self.dropped_models),
5610 std::mem::take(&mut self.dropped_views),
5611 std::mem::take(&mut self.dropped_element_states),
5612 )
5613 }
5614}
5615
5616#[cfg(test)]
5617mod tests {
5618 use super::*;
5619 use crate::{actions, elements::*, impl_actions, MouseButton, MouseButtonEvent};
5620 use serde::Deserialize;
5621 use smol::future::poll_once;
5622 use std::{
5623 cell::Cell,
5624 sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
5625 };
5626
5627 #[crate::test(self)]
5628 fn test_model_handles(cx: &mut MutableAppContext) {
5629 struct Model {
5630 other: Option<ModelHandle<Model>>,
5631 events: Vec<String>,
5632 }
5633
5634 impl Entity for Model {
5635 type Event = usize;
5636 }
5637
5638 impl Model {
5639 fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
5640 if let Some(other) = other.as_ref() {
5641 cx.observe(other, |me, _, _| {
5642 me.events.push("notified".into());
5643 })
5644 .detach();
5645 cx.subscribe(other, |me, _, event, _| {
5646 me.events.push(format!("observed event {}", event));
5647 })
5648 .detach();
5649 }
5650
5651 Self {
5652 other,
5653 events: Vec::new(),
5654 }
5655 }
5656 }
5657
5658 let handle_1 = cx.add_model(|cx| Model::new(None, cx));
5659 let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
5660 assert_eq!(cx.cx.models.len(), 2);
5661
5662 handle_1.update(cx, |model, cx| {
5663 model.events.push("updated".into());
5664 cx.emit(1);
5665 cx.notify();
5666 cx.emit(2);
5667 });
5668 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5669 assert_eq!(
5670 handle_2.read(cx).events,
5671 vec![
5672 "observed event 1".to_string(),
5673 "notified".to_string(),
5674 "observed event 2".to_string(),
5675 ]
5676 );
5677
5678 handle_2.update(cx, |model, _| {
5679 drop(handle_1);
5680 model.other.take();
5681 });
5682
5683 assert_eq!(cx.cx.models.len(), 1);
5684 assert!(cx.subscriptions.lock().is_empty());
5685 assert!(cx.observations.lock().is_empty());
5686 }
5687
5688 #[crate::test(self)]
5689 fn test_model_events(cx: &mut MutableAppContext) {
5690 #[derive(Default)]
5691 struct Model {
5692 events: Vec<usize>,
5693 }
5694
5695 impl Entity for Model {
5696 type Event = usize;
5697 }
5698
5699 let handle_1 = cx.add_model(|_| Model::default());
5700 let handle_2 = cx.add_model(|_| Model::default());
5701
5702 handle_1.update(cx, |_, cx| {
5703 cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
5704 model.events.push(*event);
5705
5706 cx.subscribe(&emitter, |model, _, event, _| {
5707 model.events.push(*event * 2);
5708 })
5709 .detach();
5710 })
5711 .detach();
5712 });
5713
5714 handle_2.update(cx, |_, c| c.emit(7));
5715 assert_eq!(handle_1.read(cx).events, vec![7]);
5716
5717 handle_2.update(cx, |_, c| c.emit(5));
5718 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
5719 }
5720
5721 #[crate::test(self)]
5722 fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
5723 #[derive(Default)]
5724 struct Model;
5725
5726 impl Entity for Model {
5727 type Event = ();
5728 }
5729
5730 let events = Rc::new(RefCell::new(Vec::new()));
5731 cx.add_model(|cx| {
5732 drop(cx.subscribe(&cx.handle(), {
5733 let events = events.clone();
5734 move |_, _, _, _| events.borrow_mut().push("dropped before flush")
5735 }));
5736 cx.subscribe(&cx.handle(), {
5737 let events = events.clone();
5738 move |_, _, _, _| events.borrow_mut().push("before emit")
5739 })
5740 .detach();
5741 cx.emit(());
5742 cx.subscribe(&cx.handle(), {
5743 let events = events.clone();
5744 move |_, _, _, _| events.borrow_mut().push("after emit")
5745 })
5746 .detach();
5747 Model
5748 });
5749 assert_eq!(*events.borrow(), ["before emit"]);
5750 }
5751
5752 #[crate::test(self)]
5753 fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
5754 #[derive(Default)]
5755 struct Model {
5756 count: usize,
5757 events: Vec<usize>,
5758 }
5759
5760 impl Entity for Model {
5761 type Event = ();
5762 }
5763
5764 let handle_1 = cx.add_model(|_| Model::default());
5765 let handle_2 = cx.add_model(|_| Model::default());
5766
5767 handle_1.update(cx, |_, c| {
5768 c.observe(&handle_2, move |model, observed, c| {
5769 model.events.push(observed.read(c).count);
5770 c.observe(&observed, |model, observed, c| {
5771 model.events.push(observed.read(c).count * 2);
5772 })
5773 .detach();
5774 })
5775 .detach();
5776 });
5777
5778 handle_2.update(cx, |model, c| {
5779 model.count = 7;
5780 c.notify()
5781 });
5782 assert_eq!(handle_1.read(cx).events, vec![7]);
5783
5784 handle_2.update(cx, |model, c| {
5785 model.count = 5;
5786 c.notify()
5787 });
5788 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
5789 }
5790
5791 #[crate::test(self)]
5792 fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
5793 #[derive(Default)]
5794 struct Model;
5795
5796 impl Entity for Model {
5797 type Event = ();
5798 }
5799
5800 let events = Rc::new(RefCell::new(Vec::new()));
5801 cx.add_model(|cx| {
5802 drop(cx.observe(&cx.handle(), {
5803 let events = events.clone();
5804 move |_, _, _| events.borrow_mut().push("dropped before flush")
5805 }));
5806 cx.observe(&cx.handle(), {
5807 let events = events.clone();
5808 move |_, _, _| events.borrow_mut().push("before notify")
5809 })
5810 .detach();
5811 cx.notify();
5812 cx.observe(&cx.handle(), {
5813 let events = events.clone();
5814 move |_, _, _| events.borrow_mut().push("after notify")
5815 })
5816 .detach();
5817 Model
5818 });
5819 assert_eq!(*events.borrow(), ["before notify"]);
5820 }
5821
5822 #[crate::test(self)]
5823 fn test_defer_and_after_window_update(cx: &mut MutableAppContext) {
5824 struct View {
5825 render_count: usize,
5826 }
5827
5828 impl Entity for View {
5829 type Event = usize;
5830 }
5831
5832 impl super::View for View {
5833 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5834 post_inc(&mut self.render_count);
5835 Empty::new().boxed()
5836 }
5837
5838 fn ui_name() -> &'static str {
5839 "View"
5840 }
5841 }
5842
5843 let (_, view) = cx.add_window(Default::default(), |_| View { render_count: 0 });
5844 let called_defer = Rc::new(AtomicBool::new(false));
5845 let called_after_window_update = Rc::new(AtomicBool::new(false));
5846
5847 view.update(cx, |this, cx| {
5848 assert_eq!(this.render_count, 1);
5849 cx.defer({
5850 let called_defer = called_defer.clone();
5851 move |this, _| {
5852 assert_eq!(this.render_count, 1);
5853 called_defer.store(true, SeqCst);
5854 }
5855 });
5856 cx.after_window_update({
5857 let called_after_window_update = called_after_window_update.clone();
5858 move |this, cx| {
5859 assert_eq!(this.render_count, 2);
5860 called_after_window_update.store(true, SeqCst);
5861 cx.notify();
5862 }
5863 });
5864 assert!(!called_defer.load(SeqCst));
5865 assert!(!called_after_window_update.load(SeqCst));
5866 cx.notify();
5867 });
5868
5869 assert!(called_defer.load(SeqCst));
5870 assert!(called_after_window_update.load(SeqCst));
5871 assert_eq!(view.read(cx).render_count, 3);
5872 }
5873
5874 #[crate::test(self)]
5875 fn test_view_handles(cx: &mut MutableAppContext) {
5876 struct View {
5877 other: Option<ViewHandle<View>>,
5878 events: Vec<String>,
5879 }
5880
5881 impl Entity for View {
5882 type Event = usize;
5883 }
5884
5885 impl super::View for View {
5886 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5887 Empty::new().boxed()
5888 }
5889
5890 fn ui_name() -> &'static str {
5891 "View"
5892 }
5893 }
5894
5895 impl View {
5896 fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
5897 if let Some(other) = other.as_ref() {
5898 cx.subscribe(other, |me, _, event, _| {
5899 me.events.push(format!("observed event {}", event));
5900 })
5901 .detach();
5902 }
5903 Self {
5904 other,
5905 events: Vec::new(),
5906 }
5907 }
5908 }
5909
5910 let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
5911 let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
5912 let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
5913 assert_eq!(cx.cx.views.len(), 3);
5914
5915 handle_1.update(cx, |view, cx| {
5916 view.events.push("updated".into());
5917 cx.emit(1);
5918 cx.emit(2);
5919 });
5920 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
5921 assert_eq!(
5922 handle_2.read(cx).events,
5923 vec![
5924 "observed event 1".to_string(),
5925 "observed event 2".to_string(),
5926 ]
5927 );
5928
5929 handle_2.update(cx, |view, _| {
5930 drop(handle_1);
5931 view.other.take();
5932 });
5933
5934 assert_eq!(cx.cx.views.len(), 2);
5935 assert!(cx.subscriptions.lock().is_empty());
5936 assert!(cx.observations.lock().is_empty());
5937 }
5938
5939 #[crate::test(self)]
5940 fn test_add_window(cx: &mut MutableAppContext) {
5941 struct View {
5942 mouse_down_count: Arc<AtomicUsize>,
5943 }
5944
5945 impl Entity for View {
5946 type Event = ();
5947 }
5948
5949 impl super::View for View {
5950 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
5951 let mouse_down_count = self.mouse_down_count.clone();
5952 EventHandler::new(Empty::new().boxed())
5953 .on_mouse_down(move |_| {
5954 mouse_down_count.fetch_add(1, SeqCst);
5955 true
5956 })
5957 .boxed()
5958 }
5959
5960 fn ui_name() -> &'static str {
5961 "View"
5962 }
5963 }
5964
5965 let mouse_down_count = Arc::new(AtomicUsize::new(0));
5966 let (window_id, _) = cx.add_window(Default::default(), |_| View {
5967 mouse_down_count: mouse_down_count.clone(),
5968 });
5969 let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
5970 // Ensure window's root element is in a valid lifecycle state.
5971 presenter.borrow_mut().dispatch_event(
5972 Event::MouseDown(MouseButtonEvent {
5973 position: Default::default(),
5974 button: MouseButton::Left,
5975 ctrl: false,
5976 alt: false,
5977 shift: false,
5978 cmd: false,
5979 click_count: 1,
5980 }),
5981 cx,
5982 );
5983 assert_eq!(mouse_down_count.load(SeqCst), 1);
5984 }
5985
5986 #[crate::test(self)]
5987 fn test_entity_release_hooks(cx: &mut MutableAppContext) {
5988 struct Model {
5989 released: Rc<Cell<bool>>,
5990 }
5991
5992 struct View {
5993 released: Rc<Cell<bool>>,
5994 }
5995
5996 impl Entity for Model {
5997 type Event = ();
5998
5999 fn release(&mut self, _: &mut MutableAppContext) {
6000 self.released.set(true);
6001 }
6002 }
6003
6004 impl Entity for View {
6005 type Event = ();
6006
6007 fn release(&mut self, _: &mut MutableAppContext) {
6008 self.released.set(true);
6009 }
6010 }
6011
6012 impl super::View for View {
6013 fn ui_name() -> &'static str {
6014 "View"
6015 }
6016
6017 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6018 Empty::new().boxed()
6019 }
6020 }
6021
6022 let model_released = Rc::new(Cell::new(false));
6023 let model_release_observed = Rc::new(Cell::new(false));
6024 let view_released = Rc::new(Cell::new(false));
6025 let view_release_observed = Rc::new(Cell::new(false));
6026
6027 let model = cx.add_model(|_| Model {
6028 released: model_released.clone(),
6029 });
6030 let (window_id, view) = cx.add_window(Default::default(), |_| View {
6031 released: view_released.clone(),
6032 });
6033 assert!(!model_released.get());
6034 assert!(!view_released.get());
6035
6036 cx.observe_release(&model, {
6037 let model_release_observed = model_release_observed.clone();
6038 move |_, _| model_release_observed.set(true)
6039 })
6040 .detach();
6041 cx.observe_release(&view, {
6042 let view_release_observed = view_release_observed.clone();
6043 move |_, _| view_release_observed.set(true)
6044 })
6045 .detach();
6046
6047 cx.update(move |_| {
6048 drop(model);
6049 });
6050 assert!(model_released.get());
6051 assert!(model_release_observed.get());
6052
6053 drop(view);
6054 cx.remove_window(window_id);
6055 assert!(view_released.get());
6056 assert!(view_release_observed.get());
6057 }
6058
6059 #[crate::test(self)]
6060 fn test_view_events(cx: &mut MutableAppContext) {
6061 #[derive(Default)]
6062 struct View {
6063 events: Vec<usize>,
6064 }
6065
6066 impl Entity for View {
6067 type Event = usize;
6068 }
6069
6070 impl super::View for View {
6071 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6072 Empty::new().boxed()
6073 }
6074
6075 fn ui_name() -> &'static str {
6076 "View"
6077 }
6078 }
6079
6080 struct Model;
6081
6082 impl Entity for Model {
6083 type Event = usize;
6084 }
6085
6086 let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
6087 let handle_2 = cx.add_view(window_id, |_| View::default());
6088 let handle_3 = cx.add_model(|_| Model);
6089
6090 handle_1.update(cx, |_, cx| {
6091 cx.subscribe(&handle_2, move |me, emitter, event, cx| {
6092 me.events.push(*event);
6093
6094 cx.subscribe(&emitter, |me, _, event, _| {
6095 me.events.push(*event * 2);
6096 })
6097 .detach();
6098 })
6099 .detach();
6100
6101 cx.subscribe(&handle_3, |me, _, event, _| {
6102 me.events.push(*event);
6103 })
6104 .detach();
6105 });
6106
6107 handle_2.update(cx, |_, c| c.emit(7));
6108 assert_eq!(handle_1.read(cx).events, vec![7]);
6109
6110 handle_2.update(cx, |_, c| c.emit(5));
6111 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
6112
6113 handle_3.update(cx, |_, c| c.emit(9));
6114 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
6115 }
6116
6117 #[crate::test(self)]
6118 fn test_global_events(cx: &mut MutableAppContext) {
6119 #[derive(Clone, Debug, Eq, PartialEq)]
6120 struct GlobalEvent(u64);
6121
6122 let events = Rc::new(RefCell::new(Vec::new()));
6123 let first_subscription;
6124 let second_subscription;
6125
6126 {
6127 let events = events.clone();
6128 first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
6129 events.borrow_mut().push(("First", e.clone()));
6130 });
6131 }
6132
6133 {
6134 let events = events.clone();
6135 second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
6136 events.borrow_mut().push(("Second", e.clone()));
6137 });
6138 }
6139
6140 cx.update(|cx| {
6141 cx.emit_global(GlobalEvent(1));
6142 cx.emit_global(GlobalEvent(2));
6143 });
6144
6145 drop(first_subscription);
6146
6147 cx.update(|cx| {
6148 cx.emit_global(GlobalEvent(3));
6149 });
6150
6151 drop(second_subscription);
6152
6153 cx.update(|cx| {
6154 cx.emit_global(GlobalEvent(4));
6155 });
6156
6157 assert_eq!(
6158 &*events.borrow(),
6159 &[
6160 ("First", GlobalEvent(1)),
6161 ("Second", GlobalEvent(1)),
6162 ("First", GlobalEvent(2)),
6163 ("Second", GlobalEvent(2)),
6164 ("Second", GlobalEvent(3)),
6165 ]
6166 );
6167 }
6168
6169 #[crate::test(self)]
6170 fn test_global_events_emitted_before_subscription_in_same_update_cycle(
6171 cx: &mut MutableAppContext,
6172 ) {
6173 let events = Rc::new(RefCell::new(Vec::new()));
6174 cx.update(|cx| {
6175 {
6176 let events = events.clone();
6177 drop(cx.subscribe_global(move |_: &(), _| {
6178 events.borrow_mut().push("dropped before emit");
6179 }));
6180 }
6181
6182 {
6183 let events = events.clone();
6184 cx.subscribe_global(move |_: &(), _| {
6185 events.borrow_mut().push("before emit");
6186 })
6187 .detach();
6188 }
6189
6190 cx.emit_global(());
6191
6192 {
6193 let events = events.clone();
6194 cx.subscribe_global(move |_: &(), _| {
6195 events.borrow_mut().push("after emit");
6196 })
6197 .detach();
6198 }
6199 });
6200
6201 assert_eq!(*events.borrow(), ["before emit"]);
6202 }
6203
6204 #[crate::test(self)]
6205 fn test_global_nested_events(cx: &mut MutableAppContext) {
6206 #[derive(Clone, Debug, Eq, PartialEq)]
6207 struct GlobalEvent(u64);
6208
6209 let events = Rc::new(RefCell::new(Vec::new()));
6210
6211 {
6212 let events = events.clone();
6213 cx.subscribe_global(move |e: &GlobalEvent, cx| {
6214 events.borrow_mut().push(("Outer", e.clone()));
6215
6216 if e.0 == 1 {
6217 let events = events.clone();
6218 cx.subscribe_global(move |e: &GlobalEvent, _| {
6219 events.borrow_mut().push(("Inner", e.clone()));
6220 })
6221 .detach();
6222 }
6223 })
6224 .detach();
6225 }
6226
6227 cx.update(|cx| {
6228 cx.emit_global(GlobalEvent(1));
6229 cx.emit_global(GlobalEvent(2));
6230 cx.emit_global(GlobalEvent(3));
6231 });
6232 cx.update(|cx| {
6233 cx.emit_global(GlobalEvent(4));
6234 });
6235
6236 assert_eq!(
6237 &*events.borrow(),
6238 &[
6239 ("Outer", GlobalEvent(1)),
6240 ("Outer", GlobalEvent(2)),
6241 ("Outer", GlobalEvent(3)),
6242 ("Outer", GlobalEvent(4)),
6243 ("Inner", GlobalEvent(4)),
6244 ]
6245 );
6246 }
6247
6248 #[crate::test(self)]
6249 fn test_global(cx: &mut MutableAppContext) {
6250 type Global = usize;
6251
6252 let observation_count = Rc::new(RefCell::new(0));
6253 let subscription = cx.observe_global::<Global, _>({
6254 let observation_count = observation_count.clone();
6255 move |_| {
6256 *observation_count.borrow_mut() += 1;
6257 }
6258 });
6259
6260 assert!(!cx.has_global::<Global>());
6261 assert_eq!(cx.default_global::<Global>(), &0);
6262 assert_eq!(*observation_count.borrow(), 1);
6263 assert!(cx.has_global::<Global>());
6264 assert_eq!(
6265 cx.update_global::<Global, _, _>(|global, _| {
6266 *global = 1;
6267 "Update Result"
6268 }),
6269 "Update Result"
6270 );
6271 assert_eq!(*observation_count.borrow(), 2);
6272 assert_eq!(cx.global::<Global>(), &1);
6273
6274 drop(subscription);
6275 cx.update_global::<Global, _, _>(|global, _| {
6276 *global = 2;
6277 });
6278 assert_eq!(*observation_count.borrow(), 2);
6279
6280 type OtherGlobal = f32;
6281
6282 let observation_count = Rc::new(RefCell::new(0));
6283 cx.observe_global::<OtherGlobal, _>({
6284 let observation_count = observation_count.clone();
6285 move |_| {
6286 *observation_count.borrow_mut() += 1;
6287 }
6288 })
6289 .detach();
6290
6291 assert_eq!(
6292 cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
6293 assert_eq!(global, &0.0);
6294 *global = 2.0;
6295 "Default update result"
6296 }),
6297 "Default update result"
6298 );
6299 assert_eq!(cx.global::<OtherGlobal>(), &2.0);
6300 assert_eq!(*observation_count.borrow(), 1);
6301 }
6302
6303 #[crate::test(self)]
6304 fn test_dropping_subscribers(cx: &mut MutableAppContext) {
6305 struct View;
6306
6307 impl Entity for View {
6308 type Event = ();
6309 }
6310
6311 impl super::View for View {
6312 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6313 Empty::new().boxed()
6314 }
6315
6316 fn ui_name() -> &'static str {
6317 "View"
6318 }
6319 }
6320
6321 struct Model;
6322
6323 impl Entity for Model {
6324 type Event = ();
6325 }
6326
6327 let (window_id, _) = cx.add_window(Default::default(), |_| View);
6328 let observing_view = cx.add_view(window_id, |_| View);
6329 let emitting_view = cx.add_view(window_id, |_| View);
6330 let observing_model = cx.add_model(|_| Model);
6331 let observed_model = cx.add_model(|_| Model);
6332
6333 observing_view.update(cx, |_, cx| {
6334 cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
6335 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6336 });
6337 observing_model.update(cx, |_, cx| {
6338 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
6339 });
6340
6341 cx.update(|_| {
6342 drop(observing_view);
6343 drop(observing_model);
6344 });
6345
6346 emitting_view.update(cx, |_, cx| cx.emit(()));
6347 observed_model.update(cx, |_, cx| cx.emit(()));
6348 }
6349
6350 #[crate::test(self)]
6351 fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut MutableAppContext) {
6352 #[derive(Default)]
6353 struct TestView;
6354
6355 impl Entity for TestView {
6356 type Event = ();
6357 }
6358
6359 impl View for TestView {
6360 fn ui_name() -> &'static str {
6361 "TestView"
6362 }
6363
6364 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6365 Empty::new().boxed()
6366 }
6367 }
6368
6369 let events = Rc::new(RefCell::new(Vec::new()));
6370 cx.add_window(Default::default(), |cx| {
6371 drop(cx.subscribe(&cx.handle(), {
6372 let events = events.clone();
6373 move |_, _, _, _| events.borrow_mut().push("dropped before flush")
6374 }));
6375 cx.subscribe(&cx.handle(), {
6376 let events = events.clone();
6377 move |_, _, _, _| events.borrow_mut().push("before emit")
6378 })
6379 .detach();
6380 cx.emit(());
6381 cx.subscribe(&cx.handle(), {
6382 let events = events.clone();
6383 move |_, _, _, _| events.borrow_mut().push("after emit")
6384 })
6385 .detach();
6386 TestView
6387 });
6388 assert_eq!(*events.borrow(), ["before emit"]);
6389 }
6390
6391 #[crate::test(self)]
6392 fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
6393 #[derive(Default)]
6394 struct View {
6395 events: Vec<usize>,
6396 }
6397
6398 impl Entity for View {
6399 type Event = usize;
6400 }
6401
6402 impl super::View for View {
6403 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6404 Empty::new().boxed()
6405 }
6406
6407 fn ui_name() -> &'static str {
6408 "View"
6409 }
6410 }
6411
6412 #[derive(Default)]
6413 struct Model {
6414 count: usize,
6415 }
6416
6417 impl Entity for Model {
6418 type Event = ();
6419 }
6420
6421 let (_, view) = cx.add_window(Default::default(), |_| View::default());
6422 let model = cx.add_model(|_| Model::default());
6423
6424 view.update(cx, |_, c| {
6425 c.observe(&model, |me, observed, c| {
6426 me.events.push(observed.read(c).count)
6427 })
6428 .detach();
6429 });
6430
6431 model.update(cx, |model, c| {
6432 model.count = 11;
6433 c.notify();
6434 });
6435 assert_eq!(view.read(cx).events, vec![11]);
6436 }
6437
6438 #[crate::test(self)]
6439 fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut MutableAppContext) {
6440 #[derive(Default)]
6441 struct TestView;
6442
6443 impl Entity for TestView {
6444 type Event = ();
6445 }
6446
6447 impl View for TestView {
6448 fn ui_name() -> &'static str {
6449 "TestView"
6450 }
6451
6452 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6453 Empty::new().boxed()
6454 }
6455 }
6456
6457 let events = Rc::new(RefCell::new(Vec::new()));
6458 cx.add_window(Default::default(), |cx| {
6459 drop(cx.observe(&cx.handle(), {
6460 let events = events.clone();
6461 move |_, _, _| events.borrow_mut().push("dropped before flush")
6462 }));
6463 cx.observe(&cx.handle(), {
6464 let events = events.clone();
6465 move |_, _, _| events.borrow_mut().push("before notify")
6466 })
6467 .detach();
6468 cx.notify();
6469 cx.observe(&cx.handle(), {
6470 let events = events.clone();
6471 move |_, _, _| events.borrow_mut().push("after notify")
6472 })
6473 .detach();
6474 TestView
6475 });
6476 assert_eq!(*events.borrow(), ["before notify"]);
6477 }
6478
6479 #[crate::test(self)]
6480 fn test_dropping_observers(cx: &mut MutableAppContext) {
6481 struct View;
6482
6483 impl Entity for View {
6484 type Event = ();
6485 }
6486
6487 impl super::View for View {
6488 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6489 Empty::new().boxed()
6490 }
6491
6492 fn ui_name() -> &'static str {
6493 "View"
6494 }
6495 }
6496
6497 struct Model;
6498
6499 impl Entity for Model {
6500 type Event = ();
6501 }
6502
6503 let (window_id, _) = cx.add_window(Default::default(), |_| View);
6504 let observing_view = cx.add_view(window_id, |_| View);
6505 let observing_model = cx.add_model(|_| Model);
6506 let observed_model = cx.add_model(|_| Model);
6507
6508 observing_view.update(cx, |_, cx| {
6509 cx.observe(&observed_model, |_, _, _| {}).detach();
6510 });
6511 observing_model.update(cx, |_, cx| {
6512 cx.observe(&observed_model, |_, _, _| {}).detach();
6513 });
6514
6515 cx.update(|_| {
6516 drop(observing_view);
6517 drop(observing_model);
6518 });
6519
6520 observed_model.update(cx, |_, cx| cx.notify());
6521 }
6522
6523 #[crate::test(self)]
6524 fn test_dropping_subscriptions_during_callback(cx: &mut MutableAppContext) {
6525 struct Model;
6526
6527 impl Entity for Model {
6528 type Event = u64;
6529 }
6530
6531 // Events
6532 let observing_model = cx.add_model(|_| Model);
6533 let observed_model = cx.add_model(|_| Model);
6534
6535 let events = Rc::new(RefCell::new(Vec::new()));
6536
6537 observing_model.update(cx, |_, cx| {
6538 let events = events.clone();
6539 let subscription = Rc::new(RefCell::new(None));
6540 *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
6541 let subscription = subscription.clone();
6542 move |_, _, e, _| {
6543 subscription.borrow_mut().take();
6544 events.borrow_mut().push(e.clone());
6545 }
6546 }));
6547 });
6548
6549 observed_model.update(cx, |_, cx| {
6550 cx.emit(1);
6551 cx.emit(2);
6552 });
6553
6554 assert_eq!(*events.borrow(), [1]);
6555
6556 // Global Events
6557 #[derive(Clone, Debug, Eq, PartialEq)]
6558 struct GlobalEvent(u64);
6559
6560 let events = Rc::new(RefCell::new(Vec::new()));
6561
6562 {
6563 let events = events.clone();
6564 let subscription = Rc::new(RefCell::new(None));
6565 *subscription.borrow_mut() = Some(cx.subscribe_global({
6566 let subscription = subscription.clone();
6567 move |e: &GlobalEvent, _| {
6568 subscription.borrow_mut().take();
6569 events.borrow_mut().push(e.clone());
6570 }
6571 }));
6572 }
6573
6574 cx.update(|cx| {
6575 cx.emit_global(GlobalEvent(1));
6576 cx.emit_global(GlobalEvent(2));
6577 });
6578
6579 assert_eq!(*events.borrow(), [GlobalEvent(1)]);
6580
6581 // Model Observation
6582 let observing_model = cx.add_model(|_| Model);
6583 let observed_model = cx.add_model(|_| Model);
6584
6585 let observation_count = Rc::new(RefCell::new(0));
6586
6587 observing_model.update(cx, |_, cx| {
6588 let observation_count = observation_count.clone();
6589 let subscription = Rc::new(RefCell::new(None));
6590 *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
6591 let subscription = subscription.clone();
6592 move |_, _, _| {
6593 subscription.borrow_mut().take();
6594 *observation_count.borrow_mut() += 1;
6595 }
6596 }));
6597 });
6598
6599 observed_model.update(cx, |_, cx| {
6600 cx.notify();
6601 });
6602
6603 observed_model.update(cx, |_, cx| {
6604 cx.notify();
6605 });
6606
6607 assert_eq!(*observation_count.borrow(), 1);
6608
6609 // View Observation
6610 struct View;
6611
6612 impl Entity for View {
6613 type Event = ();
6614 }
6615
6616 impl super::View for View {
6617 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6618 Empty::new().boxed()
6619 }
6620
6621 fn ui_name() -> &'static str {
6622 "View"
6623 }
6624 }
6625
6626 let (window_id, _) = cx.add_window(Default::default(), |_| View);
6627 let observing_view = cx.add_view(window_id, |_| View);
6628 let observed_view = cx.add_view(window_id, |_| View);
6629
6630 let observation_count = Rc::new(RefCell::new(0));
6631 observing_view.update(cx, |_, cx| {
6632 let observation_count = observation_count.clone();
6633 let subscription = Rc::new(RefCell::new(None));
6634 *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
6635 let subscription = subscription.clone();
6636 move |_, _, _| {
6637 subscription.borrow_mut().take();
6638 *observation_count.borrow_mut() += 1;
6639 }
6640 }));
6641 });
6642
6643 observed_view.update(cx, |_, cx| {
6644 cx.notify();
6645 });
6646
6647 observed_view.update(cx, |_, cx| {
6648 cx.notify();
6649 });
6650
6651 assert_eq!(*observation_count.borrow(), 1);
6652
6653 // Global Observation
6654 let observation_count = Rc::new(RefCell::new(0));
6655 let subscription = Rc::new(RefCell::new(None));
6656 *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
6657 let observation_count = observation_count.clone();
6658 let subscription = subscription.clone();
6659 move |_| {
6660 subscription.borrow_mut().take();
6661 *observation_count.borrow_mut() += 1;
6662 }
6663 }));
6664
6665 cx.default_global::<()>();
6666 cx.set_global(());
6667 assert_eq!(*observation_count.borrow(), 1);
6668 }
6669
6670 #[crate::test(self)]
6671 fn test_focus(cx: &mut MutableAppContext) {
6672 struct View {
6673 name: String,
6674 events: Arc<Mutex<Vec<String>>>,
6675 }
6676
6677 impl Entity for View {
6678 type Event = ();
6679 }
6680
6681 impl super::View for View {
6682 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6683 Empty::new().boxed()
6684 }
6685
6686 fn ui_name() -> &'static str {
6687 "View"
6688 }
6689
6690 fn on_focus(&mut self, _: &mut ViewContext<Self>) {
6691 self.events.lock().push(format!("{} focused", &self.name));
6692 }
6693
6694 fn on_blur(&mut self, _: &mut ViewContext<Self>) {
6695 self.events.lock().push(format!("{} blurred", &self.name));
6696 }
6697 }
6698
6699 let view_events: Arc<Mutex<Vec<String>>> = Default::default();
6700 let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
6701 events: view_events.clone(),
6702 name: "view 1".to_string(),
6703 });
6704 let view_2 = cx.add_view(window_id, |_| View {
6705 events: view_events.clone(),
6706 name: "view 2".to_string(),
6707 });
6708
6709 let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
6710 view_1.update(cx, |_, cx| {
6711 cx.observe_focus(&view_2, {
6712 let observed_events = observed_events.clone();
6713 move |this, view, focused, cx| {
6714 let label = if focused { "focus" } else { "blur" };
6715 observed_events.lock().push(format!(
6716 "{} observed {}'s {}",
6717 this.name,
6718 view.read(cx).name,
6719 label
6720 ))
6721 }
6722 })
6723 .detach();
6724 });
6725 view_2.update(cx, |_, cx| {
6726 cx.observe_focus(&view_1, {
6727 let observed_events = observed_events.clone();
6728 move |this, view, focused, cx| {
6729 let label = if focused { "focus" } else { "blur" };
6730 observed_events.lock().push(format!(
6731 "{} observed {}'s {}",
6732 this.name,
6733 view.read(cx).name,
6734 label
6735 ))
6736 }
6737 })
6738 .detach();
6739 });
6740 assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6741 assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6742
6743 view_1.update(cx, |_, cx| {
6744 // Ensure only the latest focus is honored.
6745 cx.focus(&view_2);
6746 cx.focus(&view_1);
6747 cx.focus(&view_2);
6748 });
6749 assert_eq!(
6750 mem::take(&mut *view_events.lock()),
6751 ["view 1 blurred", "view 2 focused"],
6752 );
6753 assert_eq!(
6754 mem::take(&mut *observed_events.lock()),
6755 [
6756 "view 2 observed view 1's blur",
6757 "view 1 observed view 2's focus"
6758 ]
6759 );
6760
6761 view_1.update(cx, |_, cx| cx.focus(&view_1));
6762 assert_eq!(
6763 mem::take(&mut *view_events.lock()),
6764 ["view 2 blurred", "view 1 focused"],
6765 );
6766 assert_eq!(
6767 mem::take(&mut *observed_events.lock()),
6768 [
6769 "view 1 observed view 2's blur",
6770 "view 2 observed view 1's focus"
6771 ]
6772 );
6773
6774 view_1.update(cx, |_, cx| cx.focus(&view_2));
6775 assert_eq!(
6776 mem::take(&mut *view_events.lock()),
6777 ["view 1 blurred", "view 2 focused"],
6778 );
6779 assert_eq!(
6780 mem::take(&mut *observed_events.lock()),
6781 [
6782 "view 2 observed view 1's blur",
6783 "view 1 observed view 2's focus"
6784 ]
6785 );
6786
6787 view_1.update(cx, |_, _| drop(view_2));
6788 assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
6789 assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
6790 }
6791
6792 #[crate::test(self)]
6793 fn test_deserialize_actions(cx: &mut MutableAppContext) {
6794 #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6795 pub struct ComplexAction {
6796 arg: String,
6797 count: usize,
6798 }
6799
6800 actions!(test::something, [SimpleAction]);
6801 impl_actions!(test::something, [ComplexAction]);
6802
6803 cx.add_global_action(move |_: &SimpleAction, _: &mut MutableAppContext| {});
6804 cx.add_global_action(move |_: &ComplexAction, _: &mut MutableAppContext| {});
6805
6806 let action1 = cx
6807 .deserialize_action(
6808 "test::something::ComplexAction",
6809 Some(r#"{"arg": "a", "count": 5}"#),
6810 )
6811 .unwrap();
6812 let action2 = cx
6813 .deserialize_action("test::something::SimpleAction", None)
6814 .unwrap();
6815 assert_eq!(
6816 action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
6817 &ComplexAction {
6818 arg: "a".to_string(),
6819 count: 5,
6820 }
6821 );
6822 assert_eq!(
6823 action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
6824 &SimpleAction
6825 );
6826 }
6827
6828 #[crate::test(self)]
6829 fn test_dispatch_action(cx: &mut MutableAppContext) {
6830 struct ViewA {
6831 id: usize,
6832 }
6833
6834 impl Entity for ViewA {
6835 type Event = ();
6836 }
6837
6838 impl View for ViewA {
6839 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6840 Empty::new().boxed()
6841 }
6842
6843 fn ui_name() -> &'static str {
6844 "View"
6845 }
6846 }
6847
6848 struct ViewB {
6849 id: usize,
6850 }
6851
6852 impl Entity for ViewB {
6853 type Event = ();
6854 }
6855
6856 impl View for ViewB {
6857 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
6858 Empty::new().boxed()
6859 }
6860
6861 fn ui_name() -> &'static str {
6862 "View"
6863 }
6864 }
6865
6866 #[derive(Clone, Default, Deserialize, PartialEq)]
6867 pub struct Action(pub String);
6868
6869 impl_actions!(test, [Action]);
6870
6871 let actions = Rc::new(RefCell::new(Vec::new()));
6872
6873 cx.add_global_action({
6874 let actions = actions.clone();
6875 move |_: &Action, _: &mut MutableAppContext| {
6876 actions.borrow_mut().push("global".to_string());
6877 }
6878 });
6879
6880 cx.add_action({
6881 let actions = actions.clone();
6882 move |view: &mut ViewA, action: &Action, cx| {
6883 assert_eq!(action.0, "bar");
6884 cx.propagate_action();
6885 actions.borrow_mut().push(format!("{} a", view.id));
6886 }
6887 });
6888
6889 cx.add_action({
6890 let actions = actions.clone();
6891 move |view: &mut ViewA, _: &Action, cx| {
6892 if view.id != 1 {
6893 cx.add_view(|cx| {
6894 cx.propagate_action(); // Still works on a nested ViewContext
6895 ViewB { id: 5 }
6896 });
6897 }
6898 actions.borrow_mut().push(format!("{} b", view.id));
6899 }
6900 });
6901
6902 cx.add_action({
6903 let actions = actions.clone();
6904 move |view: &mut ViewB, _: &Action, cx| {
6905 cx.propagate_action();
6906 actions.borrow_mut().push(format!("{} c", view.id));
6907 }
6908 });
6909
6910 cx.add_action({
6911 let actions = actions.clone();
6912 move |view: &mut ViewB, _: &Action, cx| {
6913 cx.propagate_action();
6914 actions.borrow_mut().push(format!("{} d", view.id));
6915 }
6916 });
6917
6918 cx.capture_action({
6919 let actions = actions.clone();
6920 move |view: &mut ViewA, _: &Action, cx| {
6921 cx.propagate_action();
6922 actions.borrow_mut().push(format!("{} capture", view.id));
6923 }
6924 });
6925
6926 let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
6927 let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
6928 let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
6929 let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
6930
6931 let observed_actions = Rc::new(RefCell::new(Vec::new()));
6932 cx.observe_actions({
6933 let observed_actions = observed_actions.clone();
6934 move |action_id, _| observed_actions.borrow_mut().push(action_id)
6935 })
6936 .detach();
6937
6938 cx.dispatch_action(
6939 window_id,
6940 vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
6941 &Action("bar".to_string()),
6942 );
6943
6944 assert_eq!(
6945 *actions.borrow(),
6946 vec![
6947 "1 capture",
6948 "3 capture",
6949 "4 d",
6950 "4 c",
6951 "3 b",
6952 "3 a",
6953 "2 d",
6954 "2 c",
6955 "1 b"
6956 ]
6957 );
6958 assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
6959
6960 // Remove view_1, which doesn't propagate the action
6961 actions.borrow_mut().clear();
6962 cx.dispatch_action(
6963 window_id,
6964 vec![view_2.id(), view_3.id(), view_4.id()],
6965 &Action("bar".to_string()),
6966 );
6967
6968 assert_eq!(
6969 *actions.borrow(),
6970 vec![
6971 "3 capture",
6972 "4 d",
6973 "4 c",
6974 "3 b",
6975 "3 a",
6976 "2 d",
6977 "2 c",
6978 "global"
6979 ]
6980 );
6981 assert_eq!(
6982 *observed_actions.borrow(),
6983 [Action::default().id(), Action::default().id()]
6984 );
6985 }
6986
6987 #[crate::test(self)]
6988 fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
6989 #[derive(Clone, Deserialize, PartialEq)]
6990 pub struct Action(String);
6991
6992 impl_actions!(test, [Action]);
6993
6994 struct View {
6995 id: usize,
6996 keymap_context: keymap::Context,
6997 }
6998
6999 impl Entity for View {
7000 type Event = ();
7001 }
7002
7003 impl super::View for View {
7004 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7005 Empty::new().boxed()
7006 }
7007
7008 fn ui_name() -> &'static str {
7009 "View"
7010 }
7011
7012 fn keymap_context(&self, _: &AppContext) -> keymap::Context {
7013 self.keymap_context.clone()
7014 }
7015 }
7016
7017 impl View {
7018 fn new(id: usize) -> Self {
7019 View {
7020 id,
7021 keymap_context: keymap::Context::default(),
7022 }
7023 }
7024 }
7025
7026 let mut view_1 = View::new(1);
7027 let mut view_2 = View::new(2);
7028 let mut view_3 = View::new(3);
7029 view_1.keymap_context.set.insert("a".into());
7030 view_2.keymap_context.set.insert("a".into());
7031 view_2.keymap_context.set.insert("b".into());
7032 view_3.keymap_context.set.insert("a".into());
7033 view_3.keymap_context.set.insert("b".into());
7034 view_3.keymap_context.set.insert("c".into());
7035
7036 let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
7037 let view_2 = cx.add_view(window_id, |_| view_2);
7038 let view_3 = cx.add_view(window_id, |_| view_3);
7039
7040 // This keymap's only binding dispatches an action on view 2 because that view will have
7041 // "a" and "b" in its context, but not "c".
7042 cx.add_bindings(vec![keymap::Binding::new(
7043 "a",
7044 Action("a".to_string()),
7045 Some("a && b && !c"),
7046 )]);
7047
7048 cx.add_bindings(vec![keymap::Binding::new(
7049 "b",
7050 Action("b".to_string()),
7051 None,
7052 )]);
7053
7054 let actions = Rc::new(RefCell::new(Vec::new()));
7055 cx.add_action({
7056 let actions = actions.clone();
7057 move |view: &mut View, action: &Action, cx| {
7058 if action.0 == "a" {
7059 actions.borrow_mut().push(format!("{} a", view.id));
7060 } else {
7061 actions
7062 .borrow_mut()
7063 .push(format!("{} {}", view.id, action.0));
7064 cx.propagate_action();
7065 }
7066 }
7067 });
7068
7069 cx.add_global_action({
7070 let actions = actions.clone();
7071 move |action: &Action, _| {
7072 actions.borrow_mut().push(format!("global {}", action.0));
7073 }
7074 });
7075
7076 cx.dispatch_keystroke(
7077 window_id,
7078 vec![view_1.id(), view_2.id(), view_3.id()],
7079 &Keystroke::parse("a").unwrap(),
7080 );
7081
7082 assert_eq!(&*actions.borrow(), &["2 a"]);
7083
7084 actions.borrow_mut().clear();
7085 cx.dispatch_keystroke(
7086 window_id,
7087 vec![view_1.id(), view_2.id(), view_3.id()],
7088 &Keystroke::parse("b").unwrap(),
7089 );
7090
7091 assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
7092 }
7093
7094 #[crate::test(self)]
7095 async fn test_model_condition(cx: &mut TestAppContext) {
7096 struct Counter(usize);
7097
7098 impl super::Entity for Counter {
7099 type Event = ();
7100 }
7101
7102 impl Counter {
7103 fn inc(&mut self, cx: &mut ModelContext<Self>) {
7104 self.0 += 1;
7105 cx.notify();
7106 }
7107 }
7108
7109 let model = cx.add_model(|_| Counter(0));
7110
7111 let condition1 = model.condition(&cx, |model, _| model.0 == 2);
7112 let condition2 = model.condition(&cx, |model, _| model.0 == 3);
7113 smol::pin!(condition1, condition2);
7114
7115 model.update(cx, |model, cx| model.inc(cx));
7116 assert_eq!(poll_once(&mut condition1).await, None);
7117 assert_eq!(poll_once(&mut condition2).await, None);
7118
7119 model.update(cx, |model, cx| model.inc(cx));
7120 assert_eq!(poll_once(&mut condition1).await, Some(()));
7121 assert_eq!(poll_once(&mut condition2).await, None);
7122
7123 model.update(cx, |model, cx| model.inc(cx));
7124 assert_eq!(poll_once(&mut condition2).await, Some(()));
7125
7126 model.update(cx, |_, cx| cx.notify());
7127 }
7128
7129 #[crate::test(self)]
7130 #[should_panic]
7131 async fn test_model_condition_timeout(cx: &mut TestAppContext) {
7132 struct Model;
7133
7134 impl super::Entity for Model {
7135 type Event = ();
7136 }
7137
7138 let model = cx.add_model(|_| Model);
7139 model.condition(&cx, |_, _| false).await;
7140 }
7141
7142 #[crate::test(self)]
7143 #[should_panic(expected = "model dropped with pending condition")]
7144 async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
7145 struct Model;
7146
7147 impl super::Entity for Model {
7148 type Event = ();
7149 }
7150
7151 let model = cx.add_model(|_| Model);
7152 let condition = model.condition(&cx, |_, _| false);
7153 cx.update(|_| drop(model));
7154 condition.await;
7155 }
7156
7157 #[crate::test(self)]
7158 async fn test_view_condition(cx: &mut TestAppContext) {
7159 struct Counter(usize);
7160
7161 impl super::Entity for Counter {
7162 type Event = ();
7163 }
7164
7165 impl super::View for Counter {
7166 fn ui_name() -> &'static str {
7167 "test view"
7168 }
7169
7170 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7171 Empty::new().boxed()
7172 }
7173 }
7174
7175 impl Counter {
7176 fn inc(&mut self, cx: &mut ViewContext<Self>) {
7177 self.0 += 1;
7178 cx.notify();
7179 }
7180 }
7181
7182 let (_, view) = cx.add_window(|_| Counter(0));
7183
7184 let condition1 = view.condition(&cx, |view, _| view.0 == 2);
7185 let condition2 = view.condition(&cx, |view, _| view.0 == 3);
7186 smol::pin!(condition1, condition2);
7187
7188 view.update(cx, |view, cx| view.inc(cx));
7189 assert_eq!(poll_once(&mut condition1).await, None);
7190 assert_eq!(poll_once(&mut condition2).await, None);
7191
7192 view.update(cx, |view, cx| view.inc(cx));
7193 assert_eq!(poll_once(&mut condition1).await, Some(()));
7194 assert_eq!(poll_once(&mut condition2).await, None);
7195
7196 view.update(cx, |view, cx| view.inc(cx));
7197 assert_eq!(poll_once(&mut condition2).await, Some(()));
7198 view.update(cx, |_, cx| cx.notify());
7199 }
7200
7201 #[crate::test(self)]
7202 #[should_panic]
7203 async fn test_view_condition_timeout(cx: &mut TestAppContext) {
7204 struct View;
7205
7206 impl super::Entity for View {
7207 type Event = ();
7208 }
7209
7210 impl super::View for View {
7211 fn ui_name() -> &'static str {
7212 "test view"
7213 }
7214
7215 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7216 Empty::new().boxed()
7217 }
7218 }
7219
7220 let (_, view) = cx.add_window(|_| View);
7221 view.condition(&cx, |_, _| false).await;
7222 }
7223
7224 #[crate::test(self)]
7225 #[should_panic(expected = "view dropped with pending condition")]
7226 async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
7227 struct View;
7228
7229 impl super::Entity for View {
7230 type Event = ();
7231 }
7232
7233 impl super::View for View {
7234 fn ui_name() -> &'static str {
7235 "test view"
7236 }
7237
7238 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7239 Empty::new().boxed()
7240 }
7241 }
7242
7243 let window_id = cx.add_window(|_| View).0;
7244 let view = cx.add_view(window_id, |_| View);
7245
7246 let condition = view.condition(&cx, |_, _| false);
7247 cx.update(|_| drop(view));
7248 condition.await;
7249 }
7250
7251 #[crate::test(self)]
7252 fn test_refresh_windows(cx: &mut MutableAppContext) {
7253 struct View(usize);
7254
7255 impl super::Entity for View {
7256 type Event = ();
7257 }
7258
7259 impl super::View for View {
7260 fn ui_name() -> &'static str {
7261 "test view"
7262 }
7263
7264 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7265 Empty::new().named(format!("render count: {}", post_inc(&mut self.0)))
7266 }
7267 }
7268
7269 let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
7270 let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
7271
7272 assert_eq!(
7273 presenter.borrow().rendered_views[&root_view.id()].name(),
7274 Some("render count: 0")
7275 );
7276
7277 let view = cx.add_view(window_id, |cx| {
7278 cx.refresh_windows();
7279 View(0)
7280 });
7281
7282 assert_eq!(
7283 presenter.borrow().rendered_views[&root_view.id()].name(),
7284 Some("render count: 1")
7285 );
7286 assert_eq!(
7287 presenter.borrow().rendered_views[&view.id()].name(),
7288 Some("render count: 0")
7289 );
7290
7291 cx.update(|cx| cx.refresh_windows());
7292 assert_eq!(
7293 presenter.borrow().rendered_views[&root_view.id()].name(),
7294 Some("render count: 2")
7295 );
7296 assert_eq!(
7297 presenter.borrow().rendered_views[&view.id()].name(),
7298 Some("render count: 1")
7299 );
7300
7301 cx.update(|cx| {
7302 cx.refresh_windows();
7303 drop(view);
7304 });
7305 assert_eq!(
7306 presenter.borrow().rendered_views[&root_view.id()].name(),
7307 Some("render count: 3")
7308 );
7309 assert_eq!(presenter.borrow().rendered_views.len(), 1);
7310 }
7311
7312 #[crate::test(self)]
7313 async fn test_window_activation(cx: &mut TestAppContext) {
7314 struct View(&'static str);
7315
7316 impl super::Entity for View {
7317 type Event = ();
7318 }
7319
7320 impl super::View for View {
7321 fn ui_name() -> &'static str {
7322 "test view"
7323 }
7324
7325 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
7326 Empty::new().boxed()
7327 }
7328 }
7329
7330 let events = Rc::new(RefCell::new(Vec::new()));
7331 let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7332 cx.observe_window_activation({
7333 let events = events.clone();
7334 move |this, active, _| events.borrow_mut().push((this.0, active))
7335 })
7336 .detach();
7337 View("window 1")
7338 });
7339 assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
7340
7341 let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7342 cx.observe_window_activation({
7343 let events = events.clone();
7344 move |this, active, _| events.borrow_mut().push((this.0, active))
7345 })
7346 .detach();
7347 View("window 2")
7348 });
7349 assert_eq!(
7350 mem::take(&mut *events.borrow_mut()),
7351 [("window 1", false), ("window 2", true)]
7352 );
7353
7354 let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
7355 cx.observe_window_activation({
7356 let events = events.clone();
7357 move |this, active, _| events.borrow_mut().push((this.0, active))
7358 })
7359 .detach();
7360 View("window 3")
7361 });
7362 assert_eq!(
7363 mem::take(&mut *events.borrow_mut()),
7364 [("window 2", false), ("window 3", true)]
7365 );
7366
7367 cx.simulate_window_activation(Some(window_2));
7368 assert_eq!(
7369 mem::take(&mut *events.borrow_mut()),
7370 [("window 3", false), ("window 2", true)]
7371 );
7372
7373 cx.simulate_window_activation(Some(window_1));
7374 assert_eq!(
7375 mem::take(&mut *events.borrow_mut()),
7376 [("window 2", false), ("window 1", true)]
7377 );
7378
7379 cx.simulate_window_activation(Some(window_3));
7380 assert_eq!(
7381 mem::take(&mut *events.borrow_mut()),
7382 [("window 1", false), ("window 3", true)]
7383 );
7384
7385 cx.simulate_window_activation(Some(window_3));
7386 assert_eq!(mem::take(&mut *events.borrow_mut()), []);
7387 }
7388}