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