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