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 window_id(&self) -> usize {
2771 self.window_id
2772 }
2773
2774 pub fn view_id(&self) -> usize {
2775 self.view_id
2776 }
2777
2778 pub fn foreground(&self) -> &Rc<executor::Foreground> {
2779 self.window_context.foreground()
2780 }
2781
2782 pub fn background_executor(&self) -> &Arc<executor::Background> {
2783 &self.window_context.background
2784 }
2785
2786 pub fn platform(&self) -> &Arc<dyn Platform> {
2787 self.window_context.platform()
2788 }
2789
2790 pub fn prompt_for_paths(
2791 &self,
2792 options: PathPromptOptions,
2793 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2794 self.window_context.prompt_for_paths(options)
2795 }
2796
2797 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2798 self.window_context.prompt_for_new_path(directory)
2799 }
2800
2801 pub fn reveal_path(&self, path: &Path) {
2802 self.window_context.reveal_path(path)
2803 }
2804
2805 pub fn focus(&mut self, handle: &AnyViewHandle) {
2806 self.window_context
2807 .focus(handle.window_id, Some(handle.view_id));
2808 }
2809
2810 pub fn focus_self(&mut self) {
2811 let window_id = self.window_id;
2812 let view_id = self.view_id;
2813 self.window_context.focus(window_id, Some(view_id));
2814 }
2815
2816 pub fn is_self_focused(&self) -> bool {
2817 self.window.focused_view_id == Some(self.view_id)
2818 }
2819
2820 pub fn is_parent_view_focused(&self) -> bool {
2821 if let Some(parent_view_id) = self.ancestors(self.view_id).next().clone() {
2822 self.focused_view_id() == Some(parent_view_id)
2823 } else {
2824 false
2825 }
2826 }
2827
2828 pub fn focus_parent_view(&mut self) {
2829 let next = self.ancestors(self.view_id).next().clone();
2830 if let Some(parent_view_id) = next {
2831 let window_id = self.window_id;
2832 self.window_context.focus(window_id, Some(parent_view_id));
2833 }
2834 }
2835
2836 pub fn is_child(&self, view: impl Into<AnyViewHandle>) -> bool {
2837 let view = view.into();
2838 if self.window_id != view.window_id {
2839 return false;
2840 }
2841 self.ancestors(view.view_id)
2842 .skip(1) // Skip self id
2843 .any(|parent| parent == self.view_id)
2844 }
2845
2846 pub fn blur(&mut self) {
2847 let window_id = self.window_id;
2848 self.window_context.focus(window_id, None);
2849 }
2850
2851 pub fn on_window_should_close<F>(&mut self, mut callback: F)
2852 where
2853 F: 'static + FnMut(&mut V, &mut ViewContext<V>) -> bool,
2854 {
2855 let window_id = self.window_id;
2856 let view = self.weak_handle();
2857 self.pending_effects
2858 .push_back(Effect::WindowShouldCloseSubscription {
2859 window_id,
2860 callback: Box::new(move |cx| {
2861 cx.update_window(window_id, |cx| {
2862 if let Some(view) = view.upgrade(cx) {
2863 view.update(cx, |view, cx| callback(view, cx))
2864 } else {
2865 true
2866 }
2867 })
2868 .unwrap_or(true)
2869 }),
2870 });
2871 }
2872
2873 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2874 where
2875 E: Entity,
2876 E::Event: 'static,
2877 H: Handle<E>,
2878 F: 'static + FnMut(&mut V, H, &E::Event, &mut ViewContext<V>),
2879 {
2880 let subscriber = self.weak_handle();
2881 self.window_context
2882 .subscribe_internal(handle, move |emitter, event, cx| {
2883 if let Some(subscriber) = subscriber.upgrade(cx) {
2884 subscriber.update(cx, |subscriber, cx| {
2885 callback(subscriber, emitter, event, cx);
2886 });
2887 true
2888 } else {
2889 false
2890 }
2891 })
2892 }
2893
2894 pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2895 where
2896 E: Entity,
2897 H: Handle<E>,
2898 F: 'static + FnMut(&mut V, H, &mut ViewContext<V>),
2899 {
2900 let window_id = self.window_id;
2901 let observer = self.weak_handle();
2902 self.window_context
2903 .observe_internal(handle, move |observed, cx| {
2904 cx.update_window(window_id, |cx| {
2905 if let Some(observer) = observer.upgrade(cx) {
2906 observer.update(cx, |observer, cx| {
2907 callback(observer, observed, cx);
2908 });
2909 true
2910 } else {
2911 false
2912 }
2913 })
2914 .unwrap_or(false)
2915 })
2916 }
2917
2918 pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
2919 where
2920 G: Any,
2921 F: 'static + FnMut(&mut V, &mut ViewContext<V>),
2922 {
2923 let window_id = self.window_id;
2924 let observer = self.weak_handle();
2925 self.window_context.observe_global::<G, _>(move |cx| {
2926 cx.update_window(window_id, |cx| {
2927 if let Some(observer) = observer.upgrade(cx) {
2928 observer.update(cx, |observer, cx| callback(observer, cx));
2929 }
2930 });
2931 })
2932 }
2933
2934 pub fn observe_focus<F, W>(&mut self, handle: &ViewHandle<W>, mut callback: F) -> Subscription
2935 where
2936 F: 'static + FnMut(&mut V, ViewHandle<W>, bool, &mut ViewContext<V>),
2937 W: View,
2938 {
2939 let observer = self.weak_handle();
2940 self.window_context
2941 .observe_focus(handle, move |observed, focused, cx| {
2942 if let Some(observer) = observer.upgrade(cx) {
2943 observer.update(cx, |observer, cx| {
2944 callback(observer, observed, focused, cx);
2945 });
2946 true
2947 } else {
2948 false
2949 }
2950 })
2951 }
2952
2953 pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2954 where
2955 E: Entity,
2956 H: Handle<E>,
2957 F: 'static + FnMut(&mut V, &E, &mut ViewContext<V>),
2958 {
2959 let window_id = self.window_id;
2960 let observer = self.weak_handle();
2961 self.window_context
2962 .observe_release(handle, move |released, cx| {
2963 cx.update_window(window_id, |cx| {
2964 if let Some(observer) = observer.upgrade(cx) {
2965 observer.update(cx, |observer, cx| {
2966 callback(observer, released, cx);
2967 });
2968 }
2969 });
2970 })
2971 }
2972
2973 pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
2974 where
2975 F: 'static + FnMut(&mut V, TypeId, &mut ViewContext<V>),
2976 {
2977 let window_id = self.window_id;
2978 let observer = self.weak_handle();
2979 self.window_context.observe_actions(move |action_id, cx| {
2980 cx.update_window(window_id, |cx| {
2981 if let Some(observer) = observer.upgrade(cx) {
2982 observer.update(cx, |observer, cx| {
2983 callback(observer, action_id, cx);
2984 });
2985 }
2986 });
2987 })
2988 }
2989
2990 pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
2991 where
2992 F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
2993 {
2994 let observer = self.weak_handle();
2995 self.window_context
2996 .observe_window_activation(move |active, cx| {
2997 if let Some(observer) = observer.upgrade(cx) {
2998 observer.update(cx, |observer, cx| {
2999 callback(observer, active, cx);
3000 });
3001 true
3002 } else {
3003 false
3004 }
3005 })
3006 }
3007
3008 pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3009 where
3010 F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3011 {
3012 let observer = self.weak_handle();
3013 self.window_context.observe_fullscreen(move |active, cx| {
3014 if let Some(observer) = observer.upgrade(cx) {
3015 observer.update(cx, |observer, cx| {
3016 callback(observer, active, cx);
3017 });
3018 true
3019 } else {
3020 false
3021 }
3022 })
3023 }
3024
3025 pub fn observe_keystrokes<F>(&mut self, mut callback: F) -> Subscription
3026 where
3027 F: 'static
3028 + FnMut(
3029 &mut V,
3030 &Keystroke,
3031 Option<&Box<dyn Action>>,
3032 &MatchResult,
3033 &mut ViewContext<V>,
3034 ) -> bool,
3035 {
3036 let observer = self.weak_handle();
3037 self.window_context
3038 .observe_keystrokes(move |keystroke, result, handled_by, cx| {
3039 if let Some(observer) = observer.upgrade(cx) {
3040 observer.update(cx, |observer, cx| {
3041 callback(observer, keystroke, handled_by, result, cx);
3042 });
3043 true
3044 } else {
3045 false
3046 }
3047 })
3048 }
3049
3050 pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
3051 where
3052 F: 'static + FnMut(&mut V, WindowBounds, Uuid, &mut ViewContext<V>),
3053 {
3054 let observer = self.weak_handle();
3055 self.window_context
3056 .observe_window_bounds(move |bounds, display, cx| {
3057 if let Some(observer) = observer.upgrade(cx) {
3058 observer.update(cx, |observer, cx| {
3059 callback(observer, bounds, display, cx);
3060 });
3061 true
3062 } else {
3063 false
3064 }
3065 })
3066 }
3067
3068 pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
3069 where
3070 F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3071 {
3072 let window_id = self.window_id;
3073 let observer = self.weak_handle();
3074 self.window_context.observe_active_labeled_tasks(move |cx| {
3075 cx.update_window(window_id, |cx| {
3076 if let Some(observer) = observer.upgrade(cx) {
3077 observer.update(cx, |observer, cx| {
3078 callback(observer, cx);
3079 });
3080 true
3081 } else {
3082 false
3083 }
3084 })
3085 .unwrap_or(false)
3086 })
3087 }
3088
3089 pub fn emit(&mut self, payload: V::Event) {
3090 self.window_context
3091 .pending_effects
3092 .push_back(Effect::Event {
3093 entity_id: self.view_id,
3094 payload: Box::new(payload),
3095 });
3096 }
3097
3098 pub fn notify(&mut self) {
3099 let window_id = self.window_id;
3100 let view_id = self.view_id;
3101 self.window_context.notify_view(window_id, view_id);
3102 }
3103
3104 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>)) {
3105 let handle = self.handle();
3106 self.window_context
3107 .defer(move |cx| handle.update(cx, |view, cx| callback(view, cx)))
3108 }
3109
3110 pub fn after_window_update(
3111 &mut self,
3112 callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>),
3113 ) {
3114 let window_id = self.window_id;
3115 let handle = self.handle();
3116 self.window_context.after_window_update(move |cx| {
3117 cx.update_window(window_id, |cx| {
3118 handle.update(cx, |view, cx| {
3119 callback(view, cx);
3120 })
3121 });
3122 })
3123 }
3124
3125 pub fn propagate_action(&mut self) {
3126 self.window_context.halt_action_dispatch = false;
3127 }
3128
3129 pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
3130 where
3131 F: FnOnce(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3132 Fut: 'static + Future<Output = S>,
3133 S: 'static,
3134 {
3135 let handle = self.weak_handle();
3136 self.window_context
3137 .spawn_labeled(task_label, |cx| f(handle, cx))
3138 }
3139
3140 pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
3141 where
3142 F: FnOnce(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3143 Fut: 'static + Future<Output = S>,
3144 S: 'static,
3145 {
3146 let handle = self.weak_handle();
3147 self.window_context.spawn(|cx| f(handle, cx))
3148 }
3149
3150 pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3151 let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3152 MouseState {
3153 hovered: self.window.hovered_region_ids.contains(®ion_id),
3154 clicked: self
3155 .window
3156 .clicked_region_ids
3157 .get(®ion_id)
3158 .and_then(|_| self.window.clicked_button),
3159 accessed_hovered: false,
3160 accessed_clicked: false,
3161 }
3162 }
3163
3164 pub fn element_state<Tag: 'static, T: 'static>(
3165 &mut self,
3166 element_id: usize,
3167 initial: T,
3168 ) -> ElementStateHandle<T> {
3169 let id = ElementStateId {
3170 view_id: self.view_id(),
3171 element_id,
3172 tag: TypeId::of::<Tag>(),
3173 };
3174 self.element_states
3175 .entry(id)
3176 .or_insert_with(|| Box::new(initial));
3177 ElementStateHandle::new(id, self.frame_count, &self.ref_counts)
3178 }
3179
3180 pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3181 &mut self,
3182 element_id: usize,
3183 ) -> ElementStateHandle<T> {
3184 self.element_state::<Tag, T>(element_id, T::default())
3185 }
3186}
3187
3188impl<V> BorrowAppContext for ViewContext<'_, '_, V> {
3189 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3190 BorrowAppContext::read_with(&*self.window_context, f)
3191 }
3192
3193 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3194 BorrowAppContext::update(&mut *self.window_context, f)
3195 }
3196}
3197
3198impl<V> BorrowWindowContext for ViewContext<'_, '_, V> {
3199 fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3200 BorrowWindowContext::read_with(&*self.window_context, window_id, f)
3201 }
3202
3203 fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3204 BorrowWindowContext::update(&mut *self.window_context, window_id, f)
3205 }
3206}
3207
3208pub struct LayoutContext<'a, 'b, 'c, V: View> {
3209 view_context: &'c mut ViewContext<'a, 'b, V>,
3210 new_parents: &'c mut HashMap<usize, usize>,
3211 views_to_notify_if_ancestors_change: &'c mut HashSet<usize>,
3212 pub refreshing: bool,
3213}
3214
3215impl<'a, 'b, 'c, V: View> LayoutContext<'a, 'b, 'c, V> {
3216 pub fn new(
3217 view_context: &'c mut ViewContext<'a, 'b, V>,
3218 new_parents: &'c mut HashMap<usize, usize>,
3219 views_to_notify_if_ancestors_change: &'c mut HashSet<usize>,
3220 refreshing: bool,
3221 ) -> Self {
3222 Self {
3223 view_context,
3224 new_parents,
3225 views_to_notify_if_ancestors_change,
3226 refreshing,
3227 }
3228 }
3229
3230 pub fn view_context(&mut self) -> &mut ViewContext<'a, 'b, V> {
3231 self.view_context
3232 }
3233}
3234
3235impl<'a, 'b, 'c, V: View> Deref for LayoutContext<'a, 'b, 'c, V> {
3236 type Target = ViewContext<'a, 'b, V>;
3237
3238 fn deref(&self) -> &Self::Target {
3239 &self.view_context
3240 }
3241}
3242
3243impl<V: View> DerefMut for LayoutContext<'_, '_, '_, V> {
3244 fn deref_mut(&mut self) -> &mut Self::Target {
3245 &mut self.view_context
3246 }
3247}
3248
3249impl<V: View> BorrowAppContext for LayoutContext<'_, '_, '_, V> {
3250 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3251 BorrowAppContext::read_with(&*self.view_context, f)
3252 }
3253
3254 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3255 BorrowAppContext::update(&mut *self.view_context, f)
3256 }
3257}
3258
3259impl<V: View> BorrowWindowContext for LayoutContext<'_, '_, '_, V> {
3260 fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3261 BorrowWindowContext::read_with(&*self.view_context, window_id, f)
3262 }
3263
3264 fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3265 BorrowWindowContext::update(&mut *self.view_context, window_id, f)
3266 }
3267}
3268
3269pub struct EventContext<'a, 'b, 'c, V: View> {
3270 view_context: &'c mut ViewContext<'a, 'b, V>,
3271 pub(crate) handled: bool,
3272}
3273
3274impl<'a, 'b, 'c, V: View> EventContext<'a, 'b, 'c, V> {
3275 pub(crate) fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
3276 EventContext {
3277 view_context,
3278 handled: true,
3279 }
3280 }
3281
3282 pub fn propagate_event(&mut self) {
3283 self.handled = false;
3284 }
3285}
3286
3287impl<'a, 'b, 'c, V: View> Deref for EventContext<'a, 'b, 'c, V> {
3288 type Target = ViewContext<'a, 'b, V>;
3289
3290 fn deref(&self) -> &Self::Target {
3291 &self.view_context
3292 }
3293}
3294
3295impl<V: View> DerefMut for EventContext<'_, '_, '_, V> {
3296 fn deref_mut(&mut self) -> &mut Self::Target {
3297 &mut self.view_context
3298 }
3299}
3300
3301impl<V: View> BorrowAppContext for EventContext<'_, '_, '_, V> {
3302 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3303 BorrowAppContext::read_with(&*self.view_context, f)
3304 }
3305
3306 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3307 BorrowAppContext::update(&mut *self.view_context, f)
3308 }
3309}
3310
3311impl<V: View> BorrowWindowContext for EventContext<'_, '_, '_, V> {
3312 fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3313 BorrowWindowContext::read_with(&*self.view_context, window_id, f)
3314 }
3315
3316 fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3317 BorrowWindowContext::update(&mut *self.view_context, window_id, f)
3318 }
3319}
3320
3321pub(crate) enum Reference<'a, T> {
3322 Immutable(&'a T),
3323 Mutable(&'a mut T),
3324}
3325
3326impl<'a, T> Deref for Reference<'a, T> {
3327 type Target = T;
3328
3329 fn deref(&self) -> &Self::Target {
3330 match self {
3331 Reference::Immutable(target) => target,
3332 Reference::Mutable(target) => target,
3333 }
3334 }
3335}
3336
3337impl<'a, T> DerefMut for Reference<'a, T> {
3338 fn deref_mut(&mut self) -> &mut Self::Target {
3339 match self {
3340 Reference::Immutable(_) => {
3341 panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
3342 }
3343 Reference::Mutable(target) => target,
3344 }
3345 }
3346}
3347
3348#[derive(Debug, Clone, Default)]
3349pub struct MouseState {
3350 pub(crate) hovered: bool,
3351 pub(crate) clicked: Option<MouseButton>,
3352 pub(crate) accessed_hovered: bool,
3353 pub(crate) accessed_clicked: bool,
3354}
3355
3356impl MouseState {
3357 pub fn hovered(&mut self) -> bool {
3358 self.accessed_hovered = true;
3359 self.hovered
3360 }
3361
3362 pub fn clicked(&mut self) -> Option<MouseButton> {
3363 self.accessed_clicked = true;
3364 self.clicked
3365 }
3366
3367 pub fn accessed_hovered(&self) -> bool {
3368 self.accessed_hovered
3369 }
3370
3371 pub fn accessed_clicked(&self) -> bool {
3372 self.accessed_clicked
3373 }
3374}
3375
3376pub trait Handle<T> {
3377 type Weak: 'static;
3378 fn id(&self) -> usize;
3379 fn location(&self) -> EntityLocation;
3380 fn downgrade(&self) -> Self::Weak;
3381 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3382 where
3383 Self: Sized;
3384}
3385
3386pub trait WeakHandle {
3387 fn id(&self) -> usize;
3388}
3389
3390#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3391pub enum EntityLocation {
3392 Model(usize),
3393 View(usize, usize),
3394}
3395
3396pub struct ModelHandle<T: Entity> {
3397 any_handle: AnyModelHandle,
3398 model_type: PhantomData<T>,
3399}
3400
3401impl<T: Entity> Deref for ModelHandle<T> {
3402 type Target = AnyModelHandle;
3403
3404 fn deref(&self) -> &Self::Target {
3405 &self.any_handle
3406 }
3407}
3408
3409impl<T: Entity> ModelHandle<T> {
3410 fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3411 Self {
3412 any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
3413 model_type: PhantomData,
3414 }
3415 }
3416
3417 pub fn downgrade(&self) -> WeakModelHandle<T> {
3418 WeakModelHandle::new(self.model_id)
3419 }
3420
3421 pub fn id(&self) -> usize {
3422 self.model_id
3423 }
3424
3425 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3426 cx.read_model(self)
3427 }
3428
3429 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3430 where
3431 C: BorrowAppContext,
3432 F: FnOnce(&T, &AppContext) -> S,
3433 {
3434 cx.read_with(|cx| read(self.read(cx), cx))
3435 }
3436
3437 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3438 where
3439 C: BorrowAppContext,
3440 F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3441 {
3442 let mut update = Some(update);
3443 cx.update(|cx| {
3444 cx.update_model(self, &mut |model, cx| {
3445 let update = update.take().unwrap();
3446 update(model, cx)
3447 })
3448 })
3449 }
3450}
3451
3452impl<T: Entity> Clone for ModelHandle<T> {
3453 fn clone(&self) -> Self {
3454 Self::new(self.model_id, &self.ref_counts)
3455 }
3456}
3457
3458impl<T: Entity> PartialEq for ModelHandle<T> {
3459 fn eq(&self, other: &Self) -> bool {
3460 self.model_id == other.model_id
3461 }
3462}
3463
3464impl<T: Entity> Eq for ModelHandle<T> {}
3465
3466impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3467 fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3468 self.model_id == other.model_id
3469 }
3470}
3471
3472impl<T: Entity> Hash for ModelHandle<T> {
3473 fn hash<H: Hasher>(&self, state: &mut H) {
3474 self.model_id.hash(state);
3475 }
3476}
3477
3478impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3479 fn borrow(&self) -> &usize {
3480 &self.model_id
3481 }
3482}
3483
3484impl<T: Entity> Debug for ModelHandle<T> {
3485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3486 f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3487 .field(&self.model_id)
3488 .finish()
3489 }
3490}
3491
3492unsafe impl<T: Entity> Send for ModelHandle<T> {}
3493unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3494
3495impl<T: Entity> Handle<T> for ModelHandle<T> {
3496 type Weak = WeakModelHandle<T>;
3497
3498 fn id(&self) -> usize {
3499 self.model_id
3500 }
3501
3502 fn location(&self) -> EntityLocation {
3503 EntityLocation::Model(self.model_id)
3504 }
3505
3506 fn downgrade(&self) -> Self::Weak {
3507 self.downgrade()
3508 }
3509
3510 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3511 where
3512 Self: Sized,
3513 {
3514 weak.upgrade(cx)
3515 }
3516}
3517
3518pub struct WeakModelHandle<T> {
3519 any_handle: AnyWeakModelHandle,
3520 model_type: PhantomData<T>,
3521}
3522
3523impl<T> WeakModelHandle<T> {
3524 pub fn into_any(self) -> AnyWeakModelHandle {
3525 self.any_handle
3526 }
3527}
3528
3529impl<T> Deref for WeakModelHandle<T> {
3530 type Target = AnyWeakModelHandle;
3531
3532 fn deref(&self) -> &Self::Target {
3533 &self.any_handle
3534 }
3535}
3536
3537impl<T> WeakHandle for WeakModelHandle<T> {
3538 fn id(&self) -> usize {
3539 self.model_id
3540 }
3541}
3542
3543unsafe impl<T> Send for WeakModelHandle<T> {}
3544unsafe impl<T> Sync for WeakModelHandle<T> {}
3545
3546impl<T: Entity> WeakModelHandle<T> {
3547 fn new(model_id: usize) -> Self {
3548 Self {
3549 any_handle: AnyWeakModelHandle {
3550 model_id,
3551 model_type: TypeId::of::<T>(),
3552 },
3553 model_type: PhantomData,
3554 }
3555 }
3556
3557 pub fn id(&self) -> usize {
3558 self.model_id
3559 }
3560
3561 pub fn is_upgradable(&self, cx: &impl BorrowAppContext) -> bool {
3562 cx.read_with(|cx| cx.model_handle_is_upgradable(self))
3563 }
3564
3565 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<T>> {
3566 cx.read_with(|cx| cx.upgrade_model_handle(self))
3567 }
3568}
3569
3570impl<T> Hash for WeakModelHandle<T> {
3571 fn hash<H: Hasher>(&self, state: &mut H) {
3572 self.model_id.hash(state)
3573 }
3574}
3575
3576impl<T> PartialEq for WeakModelHandle<T> {
3577 fn eq(&self, other: &Self) -> bool {
3578 self.model_id == other.model_id
3579 }
3580}
3581
3582impl<T> Eq for WeakModelHandle<T> {}
3583
3584impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
3585 fn eq(&self, other: &ModelHandle<T>) -> bool {
3586 self.model_id == other.model_id
3587 }
3588}
3589
3590impl<T> Clone for WeakModelHandle<T> {
3591 fn clone(&self) -> Self {
3592 Self {
3593 any_handle: self.any_handle.clone(),
3594 model_type: PhantomData,
3595 }
3596 }
3597}
3598
3599impl<T> Copy for WeakModelHandle<T> {}
3600
3601#[repr(transparent)]
3602pub struct ViewHandle<T> {
3603 any_handle: AnyViewHandle,
3604 view_type: PhantomData<T>,
3605}
3606
3607impl<T> Deref for ViewHandle<T> {
3608 type Target = AnyViewHandle;
3609
3610 fn deref(&self) -> &Self::Target {
3611 &self.any_handle
3612 }
3613}
3614
3615impl<T: View> ViewHandle<T> {
3616 fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3617 Self {
3618 any_handle: AnyViewHandle::new(
3619 window_id,
3620 view_id,
3621 TypeId::of::<T>(),
3622 ref_counts.clone(),
3623 ),
3624 view_type: PhantomData,
3625 }
3626 }
3627
3628 pub fn downgrade(&self) -> WeakViewHandle<T> {
3629 WeakViewHandle::new(self.window_id, self.view_id)
3630 }
3631
3632 pub fn into_any(self) -> AnyViewHandle {
3633 self.any_handle
3634 }
3635
3636 pub fn window_id(&self) -> usize {
3637 self.window_id
3638 }
3639
3640 pub fn id(&self) -> usize {
3641 self.view_id
3642 }
3643
3644 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3645 cx.read_view(self)
3646 }
3647
3648 pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3649 where
3650 C: BorrowWindowContext,
3651 F: FnOnce(&T, &ViewContext<T>) -> S,
3652 {
3653 cx.read_with(self.window_id, |cx| {
3654 let cx = ViewContext::immutable(cx, self.view_id);
3655 read(cx.read_view(self), &cx)
3656 })
3657 }
3658
3659 pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3660 where
3661 C: BorrowWindowContext,
3662 F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3663 {
3664 let mut update = Some(update);
3665
3666 cx.update(self.window_id, |cx| {
3667 cx.update_view(self, &mut |view, cx| {
3668 let update = update.take().unwrap();
3669 update(view, cx)
3670 })
3671 })
3672 }
3673
3674 pub fn is_focused(&self, cx: &WindowContext) -> bool {
3675 cx.focused_view_id() == Some(self.view_id)
3676 }
3677}
3678
3679impl<T: View> Clone for ViewHandle<T> {
3680 fn clone(&self) -> Self {
3681 ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3682 }
3683}
3684
3685impl<T> PartialEq for ViewHandle<T> {
3686 fn eq(&self, other: &Self) -> bool {
3687 self.window_id == other.window_id && self.view_id == other.view_id
3688 }
3689}
3690
3691impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3692 fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3693 self.window_id == other.window_id && self.view_id == other.view_id
3694 }
3695}
3696
3697impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3698 fn eq(&self, other: &ViewHandle<T>) -> bool {
3699 self.window_id == other.window_id && self.view_id == other.view_id
3700 }
3701}
3702
3703impl<T> Eq for ViewHandle<T> {}
3704
3705impl<T> Hash for ViewHandle<T> {
3706 fn hash<H: Hasher>(&self, state: &mut H) {
3707 self.window_id.hash(state);
3708 self.view_id.hash(state);
3709 }
3710}
3711
3712impl<T> Debug for ViewHandle<T> {
3713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3714 f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3715 .field("window_id", &self.window_id)
3716 .field("view_id", &self.view_id)
3717 .finish()
3718 }
3719}
3720
3721impl<T: View> Handle<T> for ViewHandle<T> {
3722 type Weak = WeakViewHandle<T>;
3723
3724 fn id(&self) -> usize {
3725 self.view_id
3726 }
3727
3728 fn location(&self) -> EntityLocation {
3729 EntityLocation::View(self.window_id, self.view_id)
3730 }
3731
3732 fn downgrade(&self) -> Self::Weak {
3733 self.downgrade()
3734 }
3735
3736 fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3737 where
3738 Self: Sized,
3739 {
3740 weak.upgrade(cx)
3741 }
3742}
3743
3744pub struct AnyViewHandle {
3745 window_id: usize,
3746 view_id: usize,
3747 view_type: TypeId,
3748 ref_counts: Arc<Mutex<RefCounts>>,
3749
3750 #[cfg(any(test, feature = "test-support"))]
3751 handle_id: usize,
3752}
3753
3754impl AnyViewHandle {
3755 fn new(
3756 window_id: usize,
3757 view_id: usize,
3758 view_type: TypeId,
3759 ref_counts: Arc<Mutex<RefCounts>>,
3760 ) -> Self {
3761 ref_counts.lock().inc_view(window_id, view_id);
3762
3763 #[cfg(any(test, feature = "test-support"))]
3764 let handle_id = ref_counts
3765 .lock()
3766 .leak_detector
3767 .lock()
3768 .handle_created(None, view_id);
3769
3770 Self {
3771 window_id,
3772 view_id,
3773 view_type,
3774 ref_counts,
3775 #[cfg(any(test, feature = "test-support"))]
3776 handle_id,
3777 }
3778 }
3779
3780 pub fn window_id(&self) -> usize {
3781 self.window_id
3782 }
3783
3784 pub fn id(&self) -> usize {
3785 self.view_id
3786 }
3787
3788 pub fn is<T: 'static>(&self) -> bool {
3789 TypeId::of::<T>() == self.view_type
3790 }
3791
3792 pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3793 if self.is::<T>() {
3794 Some(ViewHandle {
3795 any_handle: self,
3796 view_type: PhantomData,
3797 })
3798 } else {
3799 None
3800 }
3801 }
3802
3803 pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
3804 if self.is::<T>() {
3805 Some(unsafe { mem::transmute(self) })
3806 } else {
3807 None
3808 }
3809 }
3810
3811 pub fn downgrade(&self) -> AnyWeakViewHandle {
3812 AnyWeakViewHandle {
3813 window_id: self.window_id,
3814 view_id: self.view_id,
3815 view_type: self.view_type,
3816 }
3817 }
3818
3819 pub fn view_type(&self) -> TypeId {
3820 self.view_type
3821 }
3822
3823 pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a>) -> serde_json::Value {
3824 cx.views
3825 .get(&(self.window_id, self.view_id))
3826 .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
3827 }
3828}
3829
3830impl Clone for AnyViewHandle {
3831 fn clone(&self) -> Self {
3832 Self::new(
3833 self.window_id,
3834 self.view_id,
3835 self.view_type,
3836 self.ref_counts.clone(),
3837 )
3838 }
3839}
3840
3841impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
3842 fn eq(&self, other: &ViewHandle<T>) -> bool {
3843 self.window_id == other.window_id && self.view_id == other.view_id
3844 }
3845}
3846
3847impl Drop for AnyViewHandle {
3848 fn drop(&mut self) {
3849 self.ref_counts
3850 .lock()
3851 .dec_view(self.window_id, self.view_id);
3852 #[cfg(any(test, feature = "test-support"))]
3853 self.ref_counts
3854 .lock()
3855 .leak_detector
3856 .lock()
3857 .handle_dropped(self.view_id, self.handle_id);
3858 }
3859}
3860
3861pub struct AnyModelHandle {
3862 model_id: usize,
3863 model_type: TypeId,
3864 ref_counts: Arc<Mutex<RefCounts>>,
3865
3866 #[cfg(any(test, feature = "test-support"))]
3867 handle_id: usize,
3868}
3869
3870impl AnyModelHandle {
3871 fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3872 ref_counts.lock().inc_model(model_id);
3873
3874 #[cfg(any(test, feature = "test-support"))]
3875 let handle_id = ref_counts
3876 .lock()
3877 .leak_detector
3878 .lock()
3879 .handle_created(None, model_id);
3880
3881 Self {
3882 model_id,
3883 model_type,
3884 ref_counts,
3885
3886 #[cfg(any(test, feature = "test-support"))]
3887 handle_id,
3888 }
3889 }
3890
3891 pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3892 if self.is::<T>() {
3893 Some(ModelHandle {
3894 any_handle: self,
3895 model_type: PhantomData,
3896 })
3897 } else {
3898 None
3899 }
3900 }
3901
3902 pub fn downgrade(&self) -> AnyWeakModelHandle {
3903 AnyWeakModelHandle {
3904 model_id: self.model_id,
3905 model_type: self.model_type,
3906 }
3907 }
3908
3909 pub fn is<T: Entity>(&self) -> bool {
3910 self.model_type == TypeId::of::<T>()
3911 }
3912
3913 pub fn model_type(&self) -> TypeId {
3914 self.model_type
3915 }
3916}
3917
3918impl Clone for AnyModelHandle {
3919 fn clone(&self) -> Self {
3920 Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3921 }
3922}
3923
3924impl Drop for AnyModelHandle {
3925 fn drop(&mut self) {
3926 let mut ref_counts = self.ref_counts.lock();
3927 ref_counts.dec_model(self.model_id);
3928
3929 #[cfg(any(test, feature = "test-support"))]
3930 ref_counts
3931 .leak_detector
3932 .lock()
3933 .handle_dropped(self.model_id, self.handle_id);
3934 }
3935}
3936
3937#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
3938pub struct AnyWeakModelHandle {
3939 model_id: usize,
3940 model_type: TypeId,
3941}
3942
3943impl AnyWeakModelHandle {
3944 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyModelHandle> {
3945 cx.read_with(|cx| cx.upgrade_any_model_handle(self))
3946 }
3947
3948 pub fn model_type(&self) -> TypeId {
3949 self.model_type
3950 }
3951
3952 fn is<T: 'static>(&self) -> bool {
3953 TypeId::of::<T>() == self.model_type
3954 }
3955
3956 pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
3957 if self.is::<T>() {
3958 let result = Some(WeakModelHandle {
3959 any_handle: self,
3960 model_type: PhantomData,
3961 });
3962
3963 result
3964 } else {
3965 None
3966 }
3967 }
3968}
3969
3970#[derive(Debug, Copy)]
3971pub struct WeakViewHandle<T> {
3972 any_handle: AnyWeakViewHandle,
3973 view_type: PhantomData<T>,
3974}
3975
3976impl<T> WeakHandle for WeakViewHandle<T> {
3977 fn id(&self) -> usize {
3978 self.view_id
3979 }
3980}
3981
3982impl<V: View> WeakViewHandle<V> {
3983 fn new(window_id: usize, view_id: usize) -> Self {
3984 Self {
3985 any_handle: AnyWeakViewHandle {
3986 window_id,
3987 view_id,
3988 view_type: TypeId::of::<V>(),
3989 },
3990 view_type: PhantomData,
3991 }
3992 }
3993
3994 pub fn id(&self) -> usize {
3995 self.view_id
3996 }
3997
3998 pub fn window_id(&self) -> usize {
3999 self.window_id
4000 }
4001
4002 pub fn into_any(self) -> AnyWeakViewHandle {
4003 self.any_handle
4004 }
4005
4006 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ViewHandle<V>> {
4007 cx.read_with(|cx| cx.upgrade_view_handle(self))
4008 }
4009
4010 pub fn read_with<T>(
4011 &self,
4012 cx: &AsyncAppContext,
4013 read: impl FnOnce(&V, &ViewContext<V>) -> T,
4014 ) -> Result<T> {
4015 cx.read(|cx| {
4016 let handle = cx
4017 .upgrade_view_handle(self)
4018 .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4019 cx.read_window(self.window_id, |cx| handle.read_with(cx, read))
4020 .ok_or_else(|| anyhow!("window was removed"))
4021 })
4022 }
4023
4024 pub fn update<T>(
4025 &self,
4026 cx: &mut AsyncAppContext,
4027 update: impl FnOnce(&mut V, &mut ViewContext<V>) -> T,
4028 ) -> Result<T> {
4029 cx.update(|cx| {
4030 let handle = cx
4031 .upgrade_view_handle(self)
4032 .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4033 cx.update_window(self.window_id, |cx| handle.update(cx, update))
4034 .ok_or_else(|| anyhow!("window was removed"))
4035 })
4036 }
4037}
4038
4039impl<T> Deref for WeakViewHandle<T> {
4040 type Target = AnyWeakViewHandle;
4041
4042 fn deref(&self) -> &Self::Target {
4043 &self.any_handle
4044 }
4045}
4046
4047impl<T> Clone for WeakViewHandle<T> {
4048 fn clone(&self) -> Self {
4049 Self {
4050 any_handle: self.any_handle.clone(),
4051 view_type: PhantomData,
4052 }
4053 }
4054}
4055
4056impl<T> PartialEq for WeakViewHandle<T> {
4057 fn eq(&self, other: &Self) -> bool {
4058 self.window_id == other.window_id && self.view_id == other.view_id
4059 }
4060}
4061
4062impl<T> Eq for WeakViewHandle<T> {}
4063
4064impl<T> Hash for WeakViewHandle<T> {
4065 fn hash<H: Hasher>(&self, state: &mut H) {
4066 self.any_handle.hash(state);
4067 }
4068}
4069
4070#[derive(Debug, Clone, Copy)]
4071pub struct AnyWeakViewHandle {
4072 window_id: usize,
4073 view_id: usize,
4074 view_type: TypeId,
4075}
4076
4077impl AnyWeakViewHandle {
4078 pub fn id(&self) -> usize {
4079 self.view_id
4080 }
4081
4082 fn is<T: 'static>(&self) -> bool {
4083 TypeId::of::<T>() == self.view_type
4084 }
4085
4086 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyViewHandle> {
4087 cx.read_with(|cx| cx.upgrade_any_view_handle(self))
4088 }
4089
4090 pub fn downcast<T: View>(self) -> Option<WeakViewHandle<T>> {
4091 if self.is::<T>() {
4092 Some(WeakViewHandle {
4093 any_handle: self,
4094 view_type: PhantomData,
4095 })
4096 } else {
4097 None
4098 }
4099 }
4100}
4101
4102impl Hash for AnyWeakViewHandle {
4103 fn hash<H: Hasher>(&self, state: &mut H) {
4104 self.window_id.hash(state);
4105 self.view_id.hash(state);
4106 self.view_type.hash(state);
4107 }
4108}
4109
4110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4111pub struct ElementStateId {
4112 view_id: usize,
4113 element_id: usize,
4114 tag: TypeId,
4115}
4116
4117pub struct ElementStateHandle<T> {
4118 value_type: PhantomData<T>,
4119 id: ElementStateId,
4120 ref_counts: Weak<Mutex<RefCounts>>,
4121}
4122
4123impl<T: 'static> ElementStateHandle<T> {
4124 fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4125 ref_counts.lock().inc_element_state(id, frame_id);
4126 Self {
4127 value_type: PhantomData,
4128 id,
4129 ref_counts: Arc::downgrade(ref_counts),
4130 }
4131 }
4132
4133 pub fn id(&self) -> ElementStateId {
4134 self.id
4135 }
4136
4137 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4138 cx.element_states
4139 .get(&self.id)
4140 .unwrap()
4141 .downcast_ref()
4142 .unwrap()
4143 }
4144
4145 pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4146 where
4147 C: DerefMut<Target = D>,
4148 D: DerefMut<Target = AppContext>,
4149 {
4150 let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4151 let result = f(element_state.downcast_mut().unwrap(), cx);
4152 cx.deref_mut().element_states.insert(self.id, element_state);
4153 result
4154 }
4155}
4156
4157impl<T> Drop for ElementStateHandle<T> {
4158 fn drop(&mut self) {
4159 if let Some(ref_counts) = self.ref_counts.upgrade() {
4160 ref_counts.lock().dec_element_state(self.id);
4161 }
4162 }
4163}
4164
4165#[must_use]
4166pub enum Subscription {
4167 Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4168 Observation(callback_collection::Subscription<usize, ObservationCallback>),
4169 GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4170 GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4171 FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4172 WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
4173 WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
4174 WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
4175 KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
4176 ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4177 ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4178 ActiveLabeledTasksObservation(
4179 callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4180 ),
4181}
4182
4183impl Subscription {
4184 pub fn id(&self) -> usize {
4185 match self {
4186 Subscription::Subscription(subscription) => subscription.id(),
4187 Subscription::Observation(subscription) => subscription.id(),
4188 Subscription::GlobalSubscription(subscription) => subscription.id(),
4189 Subscription::GlobalObservation(subscription) => subscription.id(),
4190 Subscription::FocusObservation(subscription) => subscription.id(),
4191 Subscription::WindowActivationObservation(subscription) => subscription.id(),
4192 Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4193 Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4194 Subscription::KeystrokeObservation(subscription) => subscription.id(),
4195 Subscription::ReleaseObservation(subscription) => subscription.id(),
4196 Subscription::ActionObservation(subscription) => subscription.id(),
4197 Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4198 }
4199 }
4200
4201 pub fn detach(&mut self) {
4202 match self {
4203 Subscription::Subscription(subscription) => subscription.detach(),
4204 Subscription::GlobalSubscription(subscription) => subscription.detach(),
4205 Subscription::Observation(subscription) => subscription.detach(),
4206 Subscription::GlobalObservation(subscription) => subscription.detach(),
4207 Subscription::FocusObservation(subscription) => subscription.detach(),
4208 Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4209 Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4210 Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4211 Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4212 Subscription::ReleaseObservation(subscription) => subscription.detach(),
4213 Subscription::ActionObservation(subscription) => subscription.detach(),
4214 Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4215 }
4216 }
4217}
4218
4219#[cfg(test)]
4220mod tests {
4221 use super::*;
4222 use crate::{
4223 actions,
4224 elements::*,
4225 impl_actions,
4226 platform::{MouseButton, MouseButtonEvent},
4227 window::ChildView,
4228 };
4229 use itertools::Itertools;
4230 use postage::{sink::Sink, stream::Stream};
4231 use serde::Deserialize;
4232 use smol::future::poll_once;
4233 use std::{
4234 cell::Cell,
4235 sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4236 };
4237
4238 #[crate::test(self)]
4239 fn test_model_handles(cx: &mut AppContext) {
4240 struct Model {
4241 other: Option<ModelHandle<Model>>,
4242 events: Vec<String>,
4243 }
4244
4245 impl Entity for Model {
4246 type Event = usize;
4247 }
4248
4249 impl Model {
4250 fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4251 if let Some(other) = other.as_ref() {
4252 cx.observe(other, |me, _, _| {
4253 me.events.push("notified".into());
4254 })
4255 .detach();
4256 cx.subscribe(other, |me, _, event, _| {
4257 me.events.push(format!("observed event {}", event));
4258 })
4259 .detach();
4260 }
4261
4262 Self {
4263 other,
4264 events: Vec::new(),
4265 }
4266 }
4267 }
4268
4269 let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4270 let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4271 assert_eq!(cx.models.len(), 2);
4272
4273 handle_1.update(cx, |model, cx| {
4274 model.events.push("updated".into());
4275 cx.emit(1);
4276 cx.notify();
4277 cx.emit(2);
4278 });
4279 assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4280 assert_eq!(
4281 handle_2.read(cx).events,
4282 vec![
4283 "observed event 1".to_string(),
4284 "notified".to_string(),
4285 "observed event 2".to_string(),
4286 ]
4287 );
4288
4289 handle_2.update(cx, |model, _| {
4290 drop(handle_1);
4291 model.other.take();
4292 });
4293
4294 assert_eq!(cx.models.len(), 1);
4295 assert!(cx.subscriptions.is_empty());
4296 assert!(cx.observations.is_empty());
4297 }
4298
4299 #[crate::test(self)]
4300 fn test_model_events(cx: &mut AppContext) {
4301 #[derive(Default)]
4302 struct Model {
4303 events: Vec<usize>,
4304 }
4305
4306 impl Entity for Model {
4307 type Event = usize;
4308 }
4309
4310 let handle_1 = cx.add_model(|_| Model::default());
4311 let handle_2 = cx.add_model(|_| Model::default());
4312
4313 handle_1.update(cx, |_, cx| {
4314 cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4315 model.events.push(*event);
4316
4317 cx.subscribe(&emitter, |model, _, event, _| {
4318 model.events.push(*event * 2);
4319 })
4320 .detach();
4321 })
4322 .detach();
4323 });
4324
4325 handle_2.update(cx, |_, c| c.emit(7));
4326 assert_eq!(handle_1.read(cx).events, vec![7]);
4327
4328 handle_2.update(cx, |_, c| c.emit(5));
4329 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4330 }
4331
4332 #[crate::test(self)]
4333 fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4334 #[derive(Default)]
4335 struct Model;
4336
4337 impl Entity for Model {
4338 type Event = ();
4339 }
4340
4341 let events = Rc::new(RefCell::new(Vec::new()));
4342 cx.add_model(|cx| {
4343 drop(cx.subscribe(&cx.handle(), {
4344 let events = events.clone();
4345 move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4346 }));
4347 cx.subscribe(&cx.handle(), {
4348 let events = events.clone();
4349 move |_, _, _, _| events.borrow_mut().push("before emit")
4350 })
4351 .detach();
4352 cx.emit(());
4353 cx.subscribe(&cx.handle(), {
4354 let events = events.clone();
4355 move |_, _, _, _| events.borrow_mut().push("after emit")
4356 })
4357 .detach();
4358 Model
4359 });
4360 assert_eq!(*events.borrow(), ["before emit"]);
4361 }
4362
4363 #[crate::test(self)]
4364 fn test_observe_and_notify_from_model(cx: &mut AppContext) {
4365 #[derive(Default)]
4366 struct Model {
4367 count: usize,
4368 events: Vec<usize>,
4369 }
4370
4371 impl Entity for Model {
4372 type Event = ();
4373 }
4374
4375 let handle_1 = cx.add_model(|_| Model::default());
4376 let handle_2 = cx.add_model(|_| Model::default());
4377
4378 handle_1.update(cx, |_, c| {
4379 c.observe(&handle_2, move |model, observed, c| {
4380 model.events.push(observed.read(c).count);
4381 c.observe(&observed, |model, observed, c| {
4382 model.events.push(observed.read(c).count * 2);
4383 })
4384 .detach();
4385 })
4386 .detach();
4387 });
4388
4389 handle_2.update(cx, |model, c| {
4390 model.count = 7;
4391 c.notify()
4392 });
4393 assert_eq!(handle_1.read(cx).events, vec![7]);
4394
4395 handle_2.update(cx, |model, c| {
4396 model.count = 5;
4397 c.notify()
4398 });
4399 assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4400 }
4401
4402 #[crate::test(self)]
4403 fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4404 #[derive(Default)]
4405 struct Model;
4406
4407 impl Entity for Model {
4408 type Event = ();
4409 }
4410
4411 let events = Rc::new(RefCell::new(Vec::new()));
4412 cx.add_model(|cx| {
4413 drop(cx.observe(&cx.handle(), {
4414 let events = events.clone();
4415 move |_, _, _| events.borrow_mut().push("dropped before flush")
4416 }));
4417 cx.observe(&cx.handle(), {
4418 let events = events.clone();
4419 move |_, _, _| events.borrow_mut().push("before notify")
4420 })
4421 .detach();
4422 cx.notify();
4423 cx.observe(&cx.handle(), {
4424 let events = events.clone();
4425 move |_, _, _| events.borrow_mut().push("after notify")
4426 })
4427 .detach();
4428 Model
4429 });
4430 assert_eq!(*events.borrow(), ["before notify"]);
4431 }
4432
4433 #[crate::test(self)]
4434 fn test_defer_and_after_window_update(cx: &mut TestAppContext) {
4435 struct View {
4436 render_count: usize,
4437 }
4438
4439 impl Entity for View {
4440 type Event = usize;
4441 }
4442
4443 impl super::View for View {
4444 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4445 post_inc(&mut self.render_count);
4446 Empty::new().into_any()
4447 }
4448
4449 fn ui_name() -> &'static str {
4450 "View"
4451 }
4452 }
4453
4454 let (_, view) = cx.add_window(|_| View { render_count: 0 });
4455 let called_defer = Rc::new(AtomicBool::new(false));
4456 let called_after_window_update = Rc::new(AtomicBool::new(false));
4457
4458 view.update(cx, |this, cx| {
4459 assert_eq!(this.render_count, 1);
4460 cx.defer({
4461 let called_defer = called_defer.clone();
4462 move |this, _| {
4463 assert_eq!(this.render_count, 1);
4464 called_defer.store(true, SeqCst);
4465 }
4466 });
4467 cx.after_window_update({
4468 let called_after_window_update = called_after_window_update.clone();
4469 move |this, cx| {
4470 assert_eq!(this.render_count, 2);
4471 called_after_window_update.store(true, SeqCst);
4472 cx.notify();
4473 }
4474 });
4475 assert!(!called_defer.load(SeqCst));
4476 assert!(!called_after_window_update.load(SeqCst));
4477 cx.notify();
4478 });
4479
4480 assert!(called_defer.load(SeqCst));
4481 assert!(called_after_window_update.load(SeqCst));
4482 assert_eq!(view.read_with(cx, |view, _| view.render_count), 3);
4483 }
4484
4485 #[crate::test(self)]
4486 fn test_view_handles(cx: &mut TestAppContext) {
4487 struct View {
4488 other: Option<ViewHandle<View>>,
4489 events: Vec<String>,
4490 }
4491
4492 impl Entity for View {
4493 type Event = usize;
4494 }
4495
4496 impl super::View for View {
4497 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4498 Empty::new().into_any()
4499 }
4500
4501 fn ui_name() -> &'static str {
4502 "View"
4503 }
4504 }
4505
4506 impl View {
4507 fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4508 if let Some(other) = other.as_ref() {
4509 cx.subscribe(other, |me, _, event, _| {
4510 me.events.push(format!("observed event {}", event));
4511 })
4512 .detach();
4513 }
4514 Self {
4515 other,
4516 events: Vec::new(),
4517 }
4518 }
4519 }
4520
4521 let (window_id, _root_view) = cx.add_window(|cx| View::new(None, cx));
4522 let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4523 let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4524 assert_eq!(cx.read(|cx| cx.views.len()), 3);
4525
4526 handle_1.update(cx, |view, cx| {
4527 view.events.push("updated".into());
4528 cx.emit(1);
4529 cx.emit(2);
4530 });
4531 handle_1.read_with(cx, |view, _| {
4532 assert_eq!(view.events, vec!["updated".to_string()]);
4533 });
4534 handle_2.read_with(cx, |view, _| {
4535 assert_eq!(
4536 view.events,
4537 vec![
4538 "observed event 1".to_string(),
4539 "observed event 2".to_string(),
4540 ]
4541 );
4542 });
4543
4544 handle_2.update(cx, |view, _| {
4545 drop(handle_1);
4546 view.other.take();
4547 });
4548
4549 cx.read(|cx| {
4550 assert_eq!(cx.views.len(), 2);
4551 assert!(cx.subscriptions.is_empty());
4552 assert!(cx.observations.is_empty());
4553 });
4554 }
4555
4556 #[crate::test(self)]
4557 fn test_add_window(cx: &mut AppContext) {
4558 struct View {
4559 mouse_down_count: Arc<AtomicUsize>,
4560 }
4561
4562 impl Entity for View {
4563 type Event = ();
4564 }
4565
4566 impl super::View for View {
4567 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
4568 enum Handler {}
4569 let mouse_down_count = self.mouse_down_count.clone();
4570 MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new())
4571 .on_down(MouseButton::Left, move |_, _, _| {
4572 mouse_down_count.fetch_add(1, SeqCst);
4573 })
4574 .into_any()
4575 }
4576
4577 fn ui_name() -> &'static str {
4578 "View"
4579 }
4580 }
4581
4582 let mouse_down_count = Arc::new(AtomicUsize::new(0));
4583 let (window_id, _) = cx.add_window(Default::default(), |_| View {
4584 mouse_down_count: mouse_down_count.clone(),
4585 });
4586
4587 cx.update_window(window_id, |cx| {
4588 // Ensure window's root element is in a valid lifecycle state.
4589 cx.dispatch_event(
4590 Event::MouseDown(MouseButtonEvent {
4591 position: Default::default(),
4592 button: MouseButton::Left,
4593 modifiers: Default::default(),
4594 click_count: 1,
4595 }),
4596 false,
4597 );
4598 assert_eq!(mouse_down_count.load(SeqCst), 1);
4599 });
4600 }
4601
4602 #[crate::test(self)]
4603 fn test_entity_release_hooks(cx: &mut AppContext) {
4604 struct Model {
4605 released: Rc<Cell<bool>>,
4606 }
4607
4608 struct View {
4609 released: Rc<Cell<bool>>,
4610 }
4611
4612 impl Entity for Model {
4613 type Event = ();
4614
4615 fn release(&mut self, _: &mut AppContext) {
4616 self.released.set(true);
4617 }
4618 }
4619
4620 impl Entity for View {
4621 type Event = ();
4622
4623 fn release(&mut self, _: &mut AppContext) {
4624 self.released.set(true);
4625 }
4626 }
4627
4628 impl super::View for View {
4629 fn ui_name() -> &'static str {
4630 "View"
4631 }
4632
4633 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4634 Empty::new().into_any()
4635 }
4636 }
4637
4638 let model_released = Rc::new(Cell::new(false));
4639 let model_release_observed = Rc::new(Cell::new(false));
4640 let view_released = Rc::new(Cell::new(false));
4641 let view_release_observed = Rc::new(Cell::new(false));
4642
4643 let model = cx.add_model(|_| Model {
4644 released: model_released.clone(),
4645 });
4646 let (window_id, view) = cx.add_window(Default::default(), |_| View {
4647 released: view_released.clone(),
4648 });
4649 assert!(!model_released.get());
4650 assert!(!view_released.get());
4651
4652 cx.observe_release(&model, {
4653 let model_release_observed = model_release_observed.clone();
4654 move |_, _| model_release_observed.set(true)
4655 })
4656 .detach();
4657 cx.observe_release(&view, {
4658 let view_release_observed = view_release_observed.clone();
4659 move |_, _| view_release_observed.set(true)
4660 })
4661 .detach();
4662
4663 cx.update(move |_| {
4664 drop(model);
4665 });
4666 assert!(model_released.get());
4667 assert!(model_release_observed.get());
4668
4669 drop(view);
4670 cx.update_window(window_id, |cx| cx.remove_window());
4671 assert!(view_released.get());
4672 assert!(view_release_observed.get());
4673 }
4674
4675 #[crate::test(self)]
4676 fn test_view_events(cx: &mut TestAppContext) {
4677 struct Model;
4678
4679 impl Entity for Model {
4680 type Event = String;
4681 }
4682
4683 let (window_id, handle_1) = cx.add_window(|_| TestView::default());
4684 let handle_2 = cx.add_view(window_id, |_| TestView::default());
4685 let handle_3 = cx.add_model(|_| Model);
4686
4687 handle_1.update(cx, |_, cx| {
4688 cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4689 me.events.push(event.clone());
4690
4691 cx.subscribe(&emitter, |me, _, event, _| {
4692 me.events.push(format!("{event} from inner"));
4693 })
4694 .detach();
4695 })
4696 .detach();
4697
4698 cx.subscribe(&handle_3, |me, _, event, _| {
4699 me.events.push(event.clone());
4700 })
4701 .detach();
4702 });
4703
4704 handle_2.update(cx, |_, c| c.emit("7".into()));
4705 handle_1.read_with(cx, |view, _| assert_eq!(view.events, ["7"]));
4706
4707 handle_2.update(cx, |_, c| c.emit("5".into()));
4708 handle_1.read_with(cx, |view, _| {
4709 assert_eq!(view.events, ["7", "5", "5 from inner"])
4710 });
4711
4712 handle_3.update(cx, |_, c| c.emit("9".into()));
4713 handle_1.read_with(cx, |view, _| {
4714 assert_eq!(view.events, ["7", "5", "5 from inner", "9"])
4715 });
4716 }
4717
4718 #[crate::test(self)]
4719 fn test_global_events(cx: &mut AppContext) {
4720 #[derive(Clone, Debug, Eq, PartialEq)]
4721 struct GlobalEvent(u64);
4722
4723 let events = Rc::new(RefCell::new(Vec::new()));
4724 let first_subscription;
4725 let second_subscription;
4726
4727 {
4728 let events = events.clone();
4729 first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4730 events.borrow_mut().push(("First", e.clone()));
4731 });
4732 }
4733
4734 {
4735 let events = events.clone();
4736 second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4737 events.borrow_mut().push(("Second", e.clone()));
4738 });
4739 }
4740
4741 cx.update(|cx| {
4742 cx.emit_global(GlobalEvent(1));
4743 cx.emit_global(GlobalEvent(2));
4744 });
4745
4746 drop(first_subscription);
4747
4748 cx.update(|cx| {
4749 cx.emit_global(GlobalEvent(3));
4750 });
4751
4752 drop(second_subscription);
4753
4754 cx.update(|cx| {
4755 cx.emit_global(GlobalEvent(4));
4756 });
4757
4758 assert_eq!(
4759 &*events.borrow(),
4760 &[
4761 ("First", GlobalEvent(1)),
4762 ("Second", GlobalEvent(1)),
4763 ("First", GlobalEvent(2)),
4764 ("Second", GlobalEvent(2)),
4765 ("Second", GlobalEvent(3)),
4766 ]
4767 );
4768 }
4769
4770 #[crate::test(self)]
4771 fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
4772 let events = Rc::new(RefCell::new(Vec::new()));
4773 cx.update(|cx| {
4774 {
4775 let events = events.clone();
4776 drop(cx.subscribe_global(move |_: &(), _| {
4777 events.borrow_mut().push("dropped before emit");
4778 }));
4779 }
4780
4781 {
4782 let events = events.clone();
4783 cx.subscribe_global(move |_: &(), _| {
4784 events.borrow_mut().push("before emit");
4785 })
4786 .detach();
4787 }
4788
4789 cx.emit_global(());
4790
4791 {
4792 let events = events.clone();
4793 cx.subscribe_global(move |_: &(), _| {
4794 events.borrow_mut().push("after emit");
4795 })
4796 .detach();
4797 }
4798 });
4799
4800 assert_eq!(*events.borrow(), ["before emit"]);
4801 }
4802
4803 #[crate::test(self)]
4804 fn test_global_nested_events(cx: &mut AppContext) {
4805 #[derive(Clone, Debug, Eq, PartialEq)]
4806 struct GlobalEvent(u64);
4807
4808 let events = Rc::new(RefCell::new(Vec::new()));
4809
4810 {
4811 let events = events.clone();
4812 cx.subscribe_global(move |e: &GlobalEvent, cx| {
4813 events.borrow_mut().push(("Outer", e.clone()));
4814
4815 if e.0 == 1 {
4816 let events = events.clone();
4817 cx.subscribe_global(move |e: &GlobalEvent, _| {
4818 events.borrow_mut().push(("Inner", e.clone()));
4819 })
4820 .detach();
4821 }
4822 })
4823 .detach();
4824 }
4825
4826 cx.update(|cx| {
4827 cx.emit_global(GlobalEvent(1));
4828 cx.emit_global(GlobalEvent(2));
4829 cx.emit_global(GlobalEvent(3));
4830 });
4831 cx.update(|cx| {
4832 cx.emit_global(GlobalEvent(4));
4833 });
4834
4835 assert_eq!(
4836 &*events.borrow(),
4837 &[
4838 ("Outer", GlobalEvent(1)),
4839 ("Outer", GlobalEvent(2)),
4840 ("Outer", GlobalEvent(3)),
4841 ("Outer", GlobalEvent(4)),
4842 ("Inner", GlobalEvent(4)),
4843 ]
4844 );
4845 }
4846
4847 #[crate::test(self)]
4848 fn test_global(cx: &mut AppContext) {
4849 type Global = usize;
4850
4851 let observation_count = Rc::new(RefCell::new(0));
4852 let subscription = cx.observe_global::<Global, _>({
4853 let observation_count = observation_count.clone();
4854 move |_| {
4855 *observation_count.borrow_mut() += 1;
4856 }
4857 });
4858
4859 assert!(!cx.has_global::<Global>());
4860 assert_eq!(cx.default_global::<Global>(), &0);
4861 assert_eq!(*observation_count.borrow(), 1);
4862 assert!(cx.has_global::<Global>());
4863 assert_eq!(
4864 cx.update_global::<Global, _, _>(|global, _| {
4865 *global = 1;
4866 "Update Result"
4867 }),
4868 "Update Result"
4869 );
4870 assert_eq!(*observation_count.borrow(), 2);
4871 assert_eq!(cx.global::<Global>(), &1);
4872
4873 drop(subscription);
4874 cx.update_global::<Global, _, _>(|global, _| {
4875 *global = 2;
4876 });
4877 assert_eq!(*observation_count.borrow(), 2);
4878
4879 type OtherGlobal = f32;
4880
4881 let observation_count = Rc::new(RefCell::new(0));
4882 cx.observe_global::<OtherGlobal, _>({
4883 let observation_count = observation_count.clone();
4884 move |_| {
4885 *observation_count.borrow_mut() += 1;
4886 }
4887 })
4888 .detach();
4889
4890 assert_eq!(
4891 cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
4892 assert_eq!(global, &0.0);
4893 *global = 2.0;
4894 "Default update result"
4895 }),
4896 "Default update result"
4897 );
4898 assert_eq!(cx.global::<OtherGlobal>(), &2.0);
4899 assert_eq!(*observation_count.borrow(), 1);
4900 }
4901
4902 #[crate::test(self)]
4903 fn test_dropping_subscribers(cx: &mut TestAppContext) {
4904 struct Model;
4905
4906 impl Entity for Model {
4907 type Event = ();
4908 }
4909
4910 let (window_id, _root_view) = cx.add_window(|_| TestView::default());
4911 let observing_view = cx.add_view(window_id, |_| TestView::default());
4912 let emitting_view = cx.add_view(window_id, |_| TestView::default());
4913 let observing_model = cx.add_model(|_| Model);
4914 let observed_model = cx.add_model(|_| Model);
4915
4916 observing_view.update(cx, |_, cx| {
4917 cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4918 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4919 });
4920 observing_model.update(cx, |_, cx| {
4921 cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4922 });
4923
4924 cx.update(|_| {
4925 drop(observing_view);
4926 drop(observing_model);
4927 });
4928
4929 emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
4930 observed_model.update(cx, |_, cx| cx.emit(()));
4931 }
4932
4933 #[crate::test(self)]
4934 fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4935 let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
4936 drop(cx.subscribe(&cx.handle(), {
4937 move |this, _, _, _| this.events.push("dropped before flush".into())
4938 }));
4939 cx.subscribe(&cx.handle(), {
4940 move |this, _, _, _| this.events.push("before emit".into())
4941 })
4942 .detach();
4943 cx.emit("the event".into());
4944 cx.subscribe(&cx.handle(), {
4945 move |this, _, _, _| this.events.push("after emit".into())
4946 })
4947 .detach();
4948 TestView { events: Vec::new() }
4949 });
4950
4951 assert_eq!(view.read(cx).events, ["before emit"]);
4952 }
4953
4954 #[crate::test(self)]
4955 fn test_observe_and_notify_from_view(cx: &mut TestAppContext) {
4956 #[derive(Default)]
4957 struct Model {
4958 state: String,
4959 }
4960
4961 impl Entity for Model {
4962 type Event = ();
4963 }
4964
4965 let (_, view) = cx.add_window(|_| TestView::default());
4966 let model = cx.add_model(|_| Model {
4967 state: "old-state".into(),
4968 });
4969
4970 view.update(cx, |_, c| {
4971 c.observe(&model, |me, observed, cx| {
4972 me.events.push(observed.read(cx).state.clone())
4973 })
4974 .detach();
4975 });
4976
4977 model.update(cx, |model, cx| {
4978 model.state = "new-state".into();
4979 cx.notify();
4980 });
4981 view.read_with(cx, |view, _| assert_eq!(view.events, ["new-state"]));
4982 }
4983
4984 #[crate::test(self)]
4985 fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4986 let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
4987 drop(cx.observe(&cx.handle(), {
4988 move |this, _, _| this.events.push("dropped before flush".into())
4989 }));
4990 cx.observe(&cx.handle(), {
4991 move |this, _, _| this.events.push("before notify".into())
4992 })
4993 .detach();
4994 cx.notify();
4995 cx.observe(&cx.handle(), {
4996 move |this, _, _| this.events.push("after notify".into())
4997 })
4998 .detach();
4999 TestView { events: Vec::new() }
5000 });
5001
5002 assert_eq!(view.read(cx).events, ["before notify"]);
5003 }
5004
5005 #[crate::test(self)]
5006 fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut TestAppContext) {
5007 struct Model;
5008 impl Entity for Model {
5009 type Event = ();
5010 }
5011
5012 let model = cx.add_model(|_| Model);
5013 let (_, view) = cx.add_window(|_| TestView::default());
5014
5015 view.update(cx, |_, cx| {
5016 model.update(cx, |_, cx| cx.notify());
5017 drop(cx.observe(&model, move |this, _, _| {
5018 this.events.push("model notified".into());
5019 }));
5020 model.update(cx, |_, cx| cx.notify());
5021 });
5022
5023 for _ in 0..3 {
5024 model.update(cx, |_, cx| cx.notify());
5025 }
5026 view.read_with(cx, |view, _| assert_eq!(view.events, Vec::<&str>::new()));
5027 }
5028
5029 #[crate::test(self)]
5030 fn test_dropping_observers(cx: &mut TestAppContext) {
5031 struct Model;
5032
5033 impl Entity for Model {
5034 type Event = ();
5035 }
5036
5037 let (window_id, _root_view) = cx.add_window(|_| TestView::default());
5038 let observing_view = cx.add_view(window_id, |_| TestView::default());
5039 let observing_model = cx.add_model(|_| Model);
5040 let observed_model = cx.add_model(|_| Model);
5041
5042 observing_view.update(cx, |_, cx| {
5043 cx.observe(&observed_model, |_, _, _| {}).detach();
5044 });
5045 observing_model.update(cx, |_, cx| {
5046 cx.observe(&observed_model, |_, _, _| {}).detach();
5047 });
5048
5049 cx.update(|_| {
5050 drop(observing_view);
5051 drop(observing_model);
5052 });
5053
5054 observed_model.update(cx, |_, cx| cx.notify());
5055 }
5056
5057 #[crate::test(self)]
5058 fn test_dropping_subscriptions_during_callback(cx: &mut TestAppContext) {
5059 struct Model;
5060
5061 impl Entity for Model {
5062 type Event = u64;
5063 }
5064
5065 // Events
5066 let observing_model = cx.add_model(|_| Model);
5067 let observed_model = cx.add_model(|_| Model);
5068
5069 let events = Rc::new(RefCell::new(Vec::new()));
5070
5071 observing_model.update(cx, |_, cx| {
5072 let events = events.clone();
5073 let subscription = Rc::new(RefCell::new(None));
5074 *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5075 let subscription = subscription.clone();
5076 move |_, _, e, _| {
5077 subscription.borrow_mut().take();
5078 events.borrow_mut().push(*e);
5079 }
5080 }));
5081 });
5082
5083 observed_model.update(cx, |_, cx| {
5084 cx.emit(1);
5085 cx.emit(2);
5086 });
5087
5088 assert_eq!(*events.borrow(), [1]);
5089
5090 // Global Events
5091 #[derive(Clone, Debug, Eq, PartialEq)]
5092 struct GlobalEvent(u64);
5093
5094 let events = Rc::new(RefCell::new(Vec::new()));
5095
5096 {
5097 let events = events.clone();
5098 let subscription = Rc::new(RefCell::new(None));
5099 *subscription.borrow_mut() = Some(cx.subscribe_global({
5100 let subscription = subscription.clone();
5101 move |e: &GlobalEvent, _| {
5102 subscription.borrow_mut().take();
5103 events.borrow_mut().push(e.clone());
5104 }
5105 }));
5106 }
5107
5108 cx.update(|cx| {
5109 cx.emit_global(GlobalEvent(1));
5110 cx.emit_global(GlobalEvent(2));
5111 });
5112
5113 assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5114
5115 // Model Observation
5116 let observing_model = cx.add_model(|_| Model);
5117 let observed_model = cx.add_model(|_| Model);
5118
5119 let observation_count = Rc::new(RefCell::new(0));
5120
5121 observing_model.update(cx, |_, cx| {
5122 let observation_count = observation_count.clone();
5123 let subscription = Rc::new(RefCell::new(None));
5124 *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5125 let subscription = subscription.clone();
5126 move |_, _, _| {
5127 subscription.borrow_mut().take();
5128 *observation_count.borrow_mut() += 1;
5129 }
5130 }));
5131 });
5132
5133 observed_model.update(cx, |_, cx| {
5134 cx.notify();
5135 });
5136
5137 observed_model.update(cx, |_, cx| {
5138 cx.notify();
5139 });
5140
5141 assert_eq!(*observation_count.borrow(), 1);
5142
5143 // View Observation
5144 struct View;
5145
5146 impl Entity for View {
5147 type Event = ();
5148 }
5149
5150 impl super::View for View {
5151 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5152 Empty::new().into_any()
5153 }
5154
5155 fn ui_name() -> &'static str {
5156 "View"
5157 }
5158 }
5159
5160 let (window_id, _root_view) = cx.add_window(|_| View);
5161 let observing_view = cx.add_view(window_id, |_| View);
5162 let observed_view = cx.add_view(window_id, |_| View);
5163
5164 let observation_count = Rc::new(RefCell::new(0));
5165 observing_view.update(cx, |_, cx| {
5166 let observation_count = observation_count.clone();
5167 let subscription = Rc::new(RefCell::new(None));
5168 *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5169 let subscription = subscription.clone();
5170 move |_, _, _| {
5171 subscription.borrow_mut().take();
5172 *observation_count.borrow_mut() += 1;
5173 }
5174 }));
5175 });
5176
5177 observed_view.update(cx, |_, cx| {
5178 cx.notify();
5179 });
5180
5181 observed_view.update(cx, |_, cx| {
5182 cx.notify();
5183 });
5184
5185 assert_eq!(*observation_count.borrow(), 1);
5186
5187 // Global Observation
5188 let observation_count = Rc::new(RefCell::new(0));
5189 let subscription = Rc::new(RefCell::new(None));
5190 *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5191 let observation_count = observation_count.clone();
5192 let subscription = subscription.clone();
5193 move |_| {
5194 subscription.borrow_mut().take();
5195 *observation_count.borrow_mut() += 1;
5196 }
5197 }));
5198
5199 cx.update(|cx| {
5200 cx.default_global::<()>();
5201 cx.set_global(());
5202 });
5203 assert_eq!(*observation_count.borrow(), 1);
5204 }
5205
5206 #[crate::test(self)]
5207 fn test_focus(cx: &mut TestAppContext) {
5208 struct View {
5209 name: String,
5210 events: Arc<Mutex<Vec<String>>>,
5211 child: Option<AnyViewHandle>,
5212 }
5213
5214 impl Entity for View {
5215 type Event = ();
5216 }
5217
5218 impl super::View for View {
5219 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5220 self.child
5221 .as_ref()
5222 .map(|child| ChildView::new(child, cx).into_any())
5223 .unwrap_or(Empty::new().into_any())
5224 }
5225
5226 fn ui_name() -> &'static str {
5227 "View"
5228 }
5229
5230 fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5231 if cx.handle().id() == focused.id() {
5232 self.events.lock().push(format!("{} focused", &self.name));
5233 }
5234 }
5235
5236 fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5237 if cx.handle().id() == blurred.id() {
5238 self.events.lock().push(format!("{} blurred", &self.name));
5239 }
5240 }
5241 }
5242
5243 let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5244 let (window_id, view_1) = cx.add_window(|_| View {
5245 events: view_events.clone(),
5246 name: "view 1".to_string(),
5247 child: None,
5248 });
5249 let view_2 = cx
5250 .update_window(window_id, |cx| {
5251 let view_2 = cx.add_view(|_| View {
5252 events: view_events.clone(),
5253 name: "view 2".to_string(),
5254 child: None,
5255 });
5256 view_1.update(cx, |view_1, cx| {
5257 view_1.child = Some(view_2.clone().into_any());
5258 cx.notify();
5259 });
5260 view_2
5261 })
5262 .unwrap();
5263
5264 let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5265 view_1.update(cx, |_, cx| {
5266 cx.observe_focus(&view_2, {
5267 let observed_events = observed_events.clone();
5268 move |this, view, focused, cx| {
5269 let label = if focused { "focus" } else { "blur" };
5270 observed_events.lock().push(format!(
5271 "{} observed {}'s {}",
5272 this.name,
5273 view.read(cx).name,
5274 label
5275 ))
5276 }
5277 })
5278 .detach();
5279 });
5280 view_2.update(cx, |_, cx| {
5281 cx.observe_focus(&view_1, {
5282 let observed_events = observed_events.clone();
5283 move |this, view, focused, cx| {
5284 let label = if focused { "focus" } else { "blur" };
5285 observed_events.lock().push(format!(
5286 "{} observed {}'s {}",
5287 this.name,
5288 view.read(cx).name,
5289 label
5290 ))
5291 }
5292 })
5293 .detach();
5294 });
5295 assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5296 assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5297
5298 view_1.update(cx, |_, cx| {
5299 // Ensure only the last focus event is honored.
5300 cx.focus(&view_2);
5301 cx.focus(&view_1);
5302 cx.focus(&view_2);
5303 });
5304
5305 cx.read_window(window_id, |cx| {
5306 assert!(cx.is_child_focused(&view_1));
5307 assert!(!cx.is_child_focused(&view_2));
5308 });
5309 assert_eq!(
5310 mem::take(&mut *view_events.lock()),
5311 ["view 1 blurred", "view 2 focused"],
5312 );
5313 assert_eq!(
5314 mem::take(&mut *observed_events.lock()),
5315 [
5316 "view 2 observed view 1's blur",
5317 "view 1 observed view 2's focus"
5318 ]
5319 );
5320
5321 view_1.update(cx, |_, cx| cx.focus(&view_1));
5322 cx.read_window(window_id, |cx| {
5323 assert!(!cx.is_child_focused(&view_1));
5324 assert!(!cx.is_child_focused(&view_2));
5325 });
5326 assert_eq!(
5327 mem::take(&mut *view_events.lock()),
5328 ["view 2 blurred", "view 1 focused"],
5329 );
5330 assert_eq!(
5331 mem::take(&mut *observed_events.lock()),
5332 [
5333 "view 1 observed view 2's blur",
5334 "view 2 observed view 1's focus"
5335 ]
5336 );
5337
5338 view_1.update(cx, |_, cx| cx.focus(&view_2));
5339 assert_eq!(
5340 mem::take(&mut *view_events.lock()),
5341 ["view 1 blurred", "view 2 focused"],
5342 );
5343 assert_eq!(
5344 mem::take(&mut *observed_events.lock()),
5345 [
5346 "view 2 observed view 1's blur",
5347 "view 1 observed view 2's focus"
5348 ]
5349 );
5350
5351 println!("=====================");
5352 view_1.update(cx, |view, _| {
5353 drop(view_2);
5354 view.child = None;
5355 });
5356 assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5357 assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5358 }
5359
5360 #[crate::test(self)]
5361 fn test_deserialize_actions(cx: &mut AppContext) {
5362 #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5363 pub struct ComplexAction {
5364 arg: String,
5365 count: usize,
5366 }
5367
5368 actions!(test::something, [SimpleAction]);
5369 impl_actions!(test::something, [ComplexAction]);
5370
5371 cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
5372 cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
5373
5374 let action1 = cx
5375 .deserialize_action(
5376 "test::something::ComplexAction",
5377 Some(r#"{"arg": "a", "count": 5}"#),
5378 )
5379 .unwrap();
5380 let action2 = cx
5381 .deserialize_action("test::something::SimpleAction", None)
5382 .unwrap();
5383 assert_eq!(
5384 action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
5385 &ComplexAction {
5386 arg: "a".to_string(),
5387 count: 5,
5388 }
5389 );
5390 assert_eq!(
5391 action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
5392 &SimpleAction
5393 );
5394 }
5395
5396 #[crate::test(self)]
5397 fn test_dispatch_action(cx: &mut AppContext) {
5398 struct ViewA {
5399 id: usize,
5400 child: Option<AnyViewHandle>,
5401 }
5402
5403 impl Entity for ViewA {
5404 type Event = ();
5405 }
5406
5407 impl View for ViewA {
5408 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5409 self.child
5410 .as_ref()
5411 .map(|child| ChildView::new(child, cx).into_any())
5412 .unwrap_or(Empty::new().into_any())
5413 }
5414
5415 fn ui_name() -> &'static str {
5416 "View"
5417 }
5418 }
5419
5420 struct ViewB {
5421 id: usize,
5422 child: Option<AnyViewHandle>,
5423 }
5424
5425 impl Entity for ViewB {
5426 type Event = ();
5427 }
5428
5429 impl View for ViewB {
5430 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5431 self.child
5432 .as_ref()
5433 .map(|child| ChildView::new(child, cx).into_any())
5434 .unwrap_or(Empty::new().into_any())
5435 }
5436
5437 fn ui_name() -> &'static str {
5438 "View"
5439 }
5440 }
5441
5442 #[derive(Clone, Default, Deserialize, PartialEq)]
5443 pub struct Action(pub String);
5444
5445 impl_actions!(test, [Action]);
5446
5447 let actions = Rc::new(RefCell::new(Vec::new()));
5448
5449 cx.add_global_action({
5450 let actions = actions.clone();
5451 move |_: &Action, _: &mut AppContext| {
5452 actions.borrow_mut().push("global".to_string());
5453 }
5454 });
5455
5456 cx.add_action({
5457 let actions = actions.clone();
5458 move |view: &mut ViewA, action: &Action, cx| {
5459 assert_eq!(action.0, "bar");
5460 cx.propagate_action();
5461 actions.borrow_mut().push(format!("{} a", view.id));
5462 }
5463 });
5464
5465 cx.add_action({
5466 let actions = actions.clone();
5467 move |view: &mut ViewA, _: &Action, cx| {
5468 if view.id != 1 {
5469 cx.add_view(|cx| {
5470 cx.propagate_action(); // Still works on a nested ViewContext
5471 ViewB { id: 5, child: None }
5472 });
5473 }
5474 actions.borrow_mut().push(format!("{} b", view.id));
5475 }
5476 });
5477
5478 cx.add_action({
5479 let actions = actions.clone();
5480 move |view: &mut ViewB, _: &Action, cx| {
5481 cx.propagate_action();
5482 actions.borrow_mut().push(format!("{} c", view.id));
5483 }
5484 });
5485
5486 cx.add_action({
5487 let actions = actions.clone();
5488 move |view: &mut ViewB, _: &Action, cx| {
5489 cx.propagate_action();
5490 actions.borrow_mut().push(format!("{} d", view.id));
5491 }
5492 });
5493
5494 cx.capture_action({
5495 let actions = actions.clone();
5496 move |view: &mut ViewA, _: &Action, cx| {
5497 cx.propagate_action();
5498 actions.borrow_mut().push(format!("{} capture", view.id));
5499 }
5500 });
5501
5502 let observed_actions = Rc::new(RefCell::new(Vec::new()));
5503 cx.observe_actions({
5504 let observed_actions = observed_actions.clone();
5505 move |action_id, _| observed_actions.borrow_mut().push(action_id)
5506 })
5507 .detach();
5508
5509 let (window_id, view_1) =
5510 cx.add_window(Default::default(), |_| ViewA { id: 1, child: None });
5511 let view_2 = cx
5512 .update_window(window_id, |cx| {
5513 let child = cx.add_view(|_| ViewB { id: 2, child: None });
5514 view_1.update(cx, |view, cx| {
5515 view.child = Some(child.clone().into_any());
5516 cx.notify();
5517 });
5518 child
5519 })
5520 .unwrap();
5521 let view_3 = cx
5522 .update_window(window_id, |cx| {
5523 let child = cx.add_view(|_| ViewA { id: 3, child: None });
5524 view_2.update(cx, |view, cx| {
5525 view.child = Some(child.clone().into_any());
5526 cx.notify();
5527 });
5528 child
5529 })
5530 .unwrap();
5531 let view_4 = cx
5532 .update_window(window_id, |cx| {
5533 let child = cx.add_view(|_| ViewB { id: 4, child: None });
5534 view_3.update(cx, |view, cx| {
5535 view.child = Some(child.clone().into_any());
5536 cx.notify();
5537 });
5538 child
5539 })
5540 .unwrap();
5541
5542 cx.update_window(window_id, |cx| {
5543 cx.dispatch_action(Some(view_4.id()), &Action("bar".to_string()))
5544 });
5545
5546 assert_eq!(
5547 *actions.borrow(),
5548 vec![
5549 "1 capture",
5550 "3 capture",
5551 "4 d",
5552 "4 c",
5553 "3 b",
5554 "3 a",
5555 "2 d",
5556 "2 c",
5557 "1 b"
5558 ]
5559 );
5560 assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
5561
5562 // Remove view_1, which doesn't propagate the action
5563
5564 let (window_id, view_2) =
5565 cx.add_window(Default::default(), |_| ViewB { id: 2, child: None });
5566 let view_3 = cx
5567 .update_window(window_id, |cx| {
5568 let child = cx.add_view(|_| ViewA { id: 3, child: None });
5569 view_2.update(cx, |view, cx| {
5570 view.child = Some(child.clone().into_any());
5571 cx.notify();
5572 });
5573 child
5574 })
5575 .unwrap();
5576 let view_4 = cx
5577 .update_window(window_id, |cx| {
5578 let child = cx.add_view(|_| ViewB { id: 4, child: None });
5579 view_3.update(cx, |view, cx| {
5580 view.child = Some(child.clone().into_any());
5581 cx.notify();
5582 });
5583 child
5584 })
5585 .unwrap();
5586
5587 actions.borrow_mut().clear();
5588 cx.update_window(window_id, |cx| {
5589 cx.dispatch_action(Some(view_4.id()), &Action("bar".to_string()))
5590 });
5591
5592 assert_eq!(
5593 *actions.borrow(),
5594 vec![
5595 "3 capture",
5596 "4 d",
5597 "4 c",
5598 "3 b",
5599 "3 a",
5600 "2 d",
5601 "2 c",
5602 "global"
5603 ]
5604 );
5605 assert_eq!(
5606 *observed_actions.borrow(),
5607 [Action::default().id(), Action::default().id()]
5608 );
5609 }
5610
5611 #[crate::test(self)]
5612 fn test_dispatch_keystroke(cx: &mut AppContext) {
5613 #[derive(Clone, Deserialize, PartialEq)]
5614 pub struct Action(String);
5615
5616 impl_actions!(test, [Action]);
5617
5618 struct View {
5619 id: usize,
5620 keymap_context: KeymapContext,
5621 child: Option<AnyViewHandle>,
5622 }
5623
5624 impl Entity for View {
5625 type Event = ();
5626 }
5627
5628 impl super::View for View {
5629 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5630 self.child
5631 .as_ref()
5632 .map(|child| ChildView::new(child, cx).into_any())
5633 .unwrap_or(Empty::new().into_any())
5634 }
5635
5636 fn ui_name() -> &'static str {
5637 "View"
5638 }
5639
5640 fn keymap_context(&self, _: &AppContext) -> KeymapContext {
5641 self.keymap_context.clone()
5642 }
5643 }
5644
5645 impl View {
5646 fn new(id: usize) -> Self {
5647 View {
5648 id,
5649 keymap_context: KeymapContext::default(),
5650 child: None,
5651 }
5652 }
5653 }
5654
5655 let mut view_1 = View::new(1);
5656 let mut view_2 = View::new(2);
5657 let mut view_3 = View::new(3);
5658 view_1.keymap_context.add_identifier("a");
5659 view_2.keymap_context.add_identifier("a");
5660 view_2.keymap_context.add_identifier("b");
5661 view_3.keymap_context.add_identifier("a");
5662 view_3.keymap_context.add_identifier("b");
5663 view_3.keymap_context.add_identifier("c");
5664
5665 let (window_id, _view_1) = cx.add_window(Default::default(), |cx| {
5666 let view_2 = cx.add_view(|cx| {
5667 let view_3 = cx.add_view(|cx| {
5668 cx.focus_self();
5669 view_3
5670 });
5671 view_2.child = Some(view_3.into_any());
5672 view_2
5673 });
5674 view_1.child = Some(view_2.into_any());
5675 view_1
5676 });
5677
5678 // This binding only dispatches an action on view 2 because that view will have
5679 // "a" and "b" in its context, but not "c".
5680 cx.add_bindings(vec![Binding::new(
5681 "a",
5682 Action("a".to_string()),
5683 Some("a && b && !c"),
5684 )]);
5685
5686 cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
5687
5688 // This binding only dispatches an action on views 2 and 3, because they have
5689 // a parent view with a in its context
5690 cx.add_bindings(vec![Binding::new(
5691 "c",
5692 Action("c".to_string()),
5693 Some("b > c"),
5694 )]);
5695
5696 // This binding only dispatches an action on view 2, because they have
5697 // a parent view with a in its context
5698 cx.add_bindings(vec![Binding::new(
5699 "d",
5700 Action("d".to_string()),
5701 Some("a && !b > b"),
5702 )]);
5703
5704 let actions = Rc::new(RefCell::new(Vec::new()));
5705 cx.add_action({
5706 let actions = actions.clone();
5707 move |view: &mut View, action: &Action, cx| {
5708 actions
5709 .borrow_mut()
5710 .push(format!("{} {}", view.id, action.0));
5711
5712 if action.0 == "b" {
5713 cx.propagate_action();
5714 }
5715 }
5716 });
5717
5718 cx.add_global_action({
5719 let actions = actions.clone();
5720 move |action: &Action, _| {
5721 actions.borrow_mut().push(format!("global {}", action.0));
5722 }
5723 });
5724
5725 cx.update_window(window_id, |cx| {
5726 cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
5727 });
5728 assert_eq!(&*actions.borrow(), &["2 a"]);
5729 actions.borrow_mut().clear();
5730
5731 cx.update_window(window_id, |cx| {
5732 cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
5733 });
5734
5735 assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5736 actions.borrow_mut().clear();
5737
5738 cx.update_window(window_id, |cx| {
5739 cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
5740 });
5741 assert_eq!(&*actions.borrow(), &["3 c"]);
5742 actions.borrow_mut().clear();
5743
5744 cx.update_window(window_id, |cx| {
5745 cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
5746 });
5747 assert_eq!(&*actions.borrow(), &["2 d"]);
5748 actions.borrow_mut().clear();
5749 }
5750
5751 #[crate::test(self)]
5752 fn test_keystrokes_for_action(cx: &mut AppContext) {
5753 actions!(test, [Action1, Action2, GlobalAction]);
5754
5755 struct View1 {
5756 child: ViewHandle<View2>,
5757 }
5758 struct View2 {}
5759
5760 impl Entity for View1 {
5761 type Event = ();
5762 }
5763 impl Entity for View2 {
5764 type Event = ();
5765 }
5766
5767 impl super::View for View1 {
5768 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
5769 ChildView::new(&self.child, cx).into_any()
5770 }
5771 fn ui_name() -> &'static str {
5772 "View1"
5773 }
5774 }
5775 impl super::View for View2 {
5776 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5777 Empty::new().into_any()
5778 }
5779 fn ui_name() -> &'static str {
5780 "View2"
5781 }
5782 }
5783
5784 let (window_id, view_1) = cx.add_window(Default::default(), |cx| {
5785 let view_2 = cx.add_view(|cx| {
5786 cx.focus_self();
5787 View2 {}
5788 });
5789 View1 { child: view_2 }
5790 });
5791 let view_2 = view_1.read(cx).child.clone();
5792
5793 cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
5794 cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
5795 cx.add_global_action(|_: &GlobalAction, _| {});
5796
5797 cx.add_bindings(vec![
5798 Binding::new("a", Action1, Some("View1")),
5799 Binding::new("b", Action2, Some("View1 > View2")),
5800 Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
5801 ]);
5802
5803 cx.update_window(window_id, |cx| {
5804 // Sanity check
5805 assert_eq!(
5806 cx.keystrokes_for_action(view_1.id(), &Action1)
5807 .unwrap()
5808 .as_slice(),
5809 &[Keystroke::parse("a").unwrap()]
5810 );
5811 assert_eq!(
5812 cx.keystrokes_for_action(view_2.id(), &Action2)
5813 .unwrap()
5814 .as_slice(),
5815 &[Keystroke::parse("b").unwrap()]
5816 );
5817
5818 // The 'a' keystroke propagates up the view tree from view_2
5819 // to view_1. The action, Action1, is handled by view_1.
5820 assert_eq!(
5821 cx.keystrokes_for_action(view_2.id(), &Action1)
5822 .unwrap()
5823 .as_slice(),
5824 &[Keystroke::parse("a").unwrap()]
5825 );
5826
5827 // Actions that are handled below the current view don't have bindings
5828 assert_eq!(cx.keystrokes_for_action(view_1.id(), &Action2), None);
5829
5830 // Actions that are handled in other branches of the tree should not have a binding
5831 assert_eq!(cx.keystrokes_for_action(view_2.id(), &GlobalAction), None);
5832
5833 // Check that global actions do not have a binding, even if a binding does exist in another view
5834 assert_eq!(
5835 &available_actions(view_1.id(), cx),
5836 &[
5837 ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5838 ("test::GlobalAction", vec![])
5839 ],
5840 );
5841
5842 // Check that view 1 actions and bindings are available even when called from view 2
5843 assert_eq!(
5844 &available_actions(view_2.id(), cx),
5845 &[
5846 ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5847 ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
5848 ("test::GlobalAction", vec![]),
5849 ],
5850 );
5851 });
5852
5853 // Produces a list of actions and key bindings
5854 fn available_actions(
5855 view_id: usize,
5856 cx: &WindowContext,
5857 ) -> Vec<(&'static str, Vec<Keystroke>)> {
5858 cx.available_actions(view_id)
5859 .map(|(action_name, _, bindings)| {
5860 (
5861 action_name,
5862 bindings
5863 .iter()
5864 .map(|binding| binding.keystrokes()[0].clone())
5865 .collect::<Vec<_>>(),
5866 )
5867 })
5868 .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
5869 .collect()
5870 }
5871 }
5872
5873 #[crate::test(self)]
5874 async fn test_model_condition(cx: &mut TestAppContext) {
5875 struct Counter(usize);
5876
5877 impl super::Entity for Counter {
5878 type Event = ();
5879 }
5880
5881 impl Counter {
5882 fn inc(&mut self, cx: &mut ModelContext<Self>) {
5883 self.0 += 1;
5884 cx.notify();
5885 }
5886 }
5887
5888 let model = cx.add_model(|_| Counter(0));
5889
5890 let condition1 = model.condition(cx, |model, _| model.0 == 2);
5891 let condition2 = model.condition(cx, |model, _| model.0 == 3);
5892 smol::pin!(condition1, condition2);
5893
5894 model.update(cx, |model, cx| model.inc(cx));
5895 assert_eq!(poll_once(&mut condition1).await, None);
5896 assert_eq!(poll_once(&mut condition2).await, None);
5897
5898 model.update(cx, |model, cx| model.inc(cx));
5899 assert_eq!(poll_once(&mut condition1).await, Some(()));
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 condition2).await, Some(()));
5904
5905 model.update(cx, |_, cx| cx.notify());
5906 }
5907
5908 #[crate::test(self)]
5909 #[should_panic]
5910 async fn test_model_condition_timeout(cx: &mut TestAppContext) {
5911 struct Model;
5912
5913 impl super::Entity for Model {
5914 type Event = ();
5915 }
5916
5917 let model = cx.add_model(|_| Model);
5918 model.condition(cx, |_, _| false).await;
5919 }
5920
5921 #[crate::test(self)]
5922 #[should_panic(expected = "model dropped with pending condition")]
5923 async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
5924 struct Model;
5925
5926 impl super::Entity for Model {
5927 type Event = ();
5928 }
5929
5930 let model = cx.add_model(|_| Model);
5931 let condition = model.condition(cx, |_, _| false);
5932 cx.update(|_| drop(model));
5933 condition.await;
5934 }
5935
5936 #[crate::test(self)]
5937 async fn test_view_condition(cx: &mut TestAppContext) {
5938 struct Counter(usize);
5939
5940 impl super::Entity for Counter {
5941 type Event = ();
5942 }
5943
5944 impl super::View for Counter {
5945 fn ui_name() -> &'static str {
5946 "test view"
5947 }
5948
5949 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5950 Empty::new().into_any()
5951 }
5952 }
5953
5954 impl Counter {
5955 fn inc(&mut self, cx: &mut ViewContext<Self>) {
5956 self.0 += 1;
5957 cx.notify();
5958 }
5959 }
5960
5961 let (_, view) = cx.add_window(|_| Counter(0));
5962
5963 let condition1 = view.condition(cx, |view, _| view.0 == 2);
5964 let condition2 = view.condition(cx, |view, _| view.0 == 3);
5965 smol::pin!(condition1, condition2);
5966
5967 view.update(cx, |view, cx| view.inc(cx));
5968 assert_eq!(poll_once(&mut condition1).await, None);
5969 assert_eq!(poll_once(&mut condition2).await, None);
5970
5971 view.update(cx, |view, cx| view.inc(cx));
5972 assert_eq!(poll_once(&mut condition1).await, Some(()));
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 condition2).await, Some(()));
5977 view.update(cx, |_, cx| cx.notify());
5978 }
5979
5980 #[crate::test(self)]
5981 #[should_panic]
5982 async fn test_view_condition_timeout(cx: &mut TestAppContext) {
5983 let (_, view) = cx.add_window(|_| TestView::default());
5984 view.condition(cx, |_, _| false).await;
5985 }
5986
5987 #[crate::test(self)]
5988 #[should_panic(expected = "view dropped with pending condition")]
5989 async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
5990 let (window_id, _root_view) = cx.add_window(|_| TestView::default());
5991 let view = cx.add_view(window_id, |_| TestView::default());
5992
5993 let condition = view.condition(cx, |_, _| false);
5994 cx.update(|_| drop(view));
5995 condition.await;
5996 }
5997
5998 #[crate::test(self)]
5999 fn test_refresh_windows(cx: &mut AppContext) {
6000 struct View(usize);
6001
6002 impl super::Entity for View {
6003 type Event = ();
6004 }
6005
6006 impl super::View for View {
6007 fn ui_name() -> &'static str {
6008 "test view"
6009 }
6010
6011 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6012 Empty::new().into_any_named(format!("render count: {}", post_inc(&mut self.0)))
6013 }
6014 }
6015
6016 let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6017 cx.update_window(window_id, |cx| {
6018 assert_eq!(
6019 cx.window.rendered_views[&root_view.id()].name(),
6020 Some("render count: 0")
6021 );
6022 });
6023
6024 let view = cx
6025 .update_window(window_id, |cx| {
6026 cx.refresh_windows();
6027 cx.add_view(|_| View(0))
6028 })
6029 .unwrap();
6030
6031 cx.update_window(window_id, |cx| {
6032 assert_eq!(
6033 cx.window.rendered_views[&root_view.id()].name(),
6034 Some("render count: 1")
6035 );
6036 assert_eq!(
6037 cx.window.rendered_views[&view.id()].name(),
6038 Some("render count: 0")
6039 );
6040 });
6041
6042 cx.update(|cx| cx.refresh_windows());
6043
6044 cx.update_window(window_id, |cx| {
6045 assert_eq!(
6046 cx.window.rendered_views[&root_view.id()].name(),
6047 Some("render count: 2")
6048 );
6049 assert_eq!(
6050 cx.window.rendered_views[&view.id()].name(),
6051 Some("render count: 1")
6052 );
6053 });
6054
6055 cx.update(|cx| {
6056 cx.refresh_windows();
6057 drop(view);
6058 });
6059
6060 cx.update_window(window_id, |cx| {
6061 assert_eq!(
6062 cx.window.rendered_views[&root_view.id()].name(),
6063 Some("render count: 3")
6064 );
6065 assert_eq!(cx.window.rendered_views.len(), 1);
6066 });
6067 }
6068
6069 #[crate::test(self)]
6070 async fn test_labeled_tasks(cx: &mut TestAppContext) {
6071 assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6072 let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
6073 let task = cx
6074 .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
6075
6076 assert_eq!(
6077 Some("Test Label"),
6078 cx.update(|cx| cx.active_labeled_tasks().next())
6079 );
6080 sender
6081 .send(())
6082 .await
6083 .expect("Could not send message to complete task");
6084 task.await;
6085
6086 assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6087 }
6088
6089 #[crate::test(self)]
6090 async fn test_window_activation(cx: &mut TestAppContext) {
6091 struct View(&'static str);
6092
6093 impl super::Entity for View {
6094 type Event = ();
6095 }
6096
6097 impl super::View for View {
6098 fn ui_name() -> &'static str {
6099 "test view"
6100 }
6101
6102 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6103 Empty::new().into_any()
6104 }
6105 }
6106
6107 let events = Rc::new(RefCell::new(Vec::new()));
6108 let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6109 cx.observe_window_activation({
6110 let events = events.clone();
6111 move |this, active, _| events.borrow_mut().push((this.0, active))
6112 })
6113 .detach();
6114 View("window 1")
6115 });
6116 assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6117
6118 let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6119 cx.observe_window_activation({
6120 let events = events.clone();
6121 move |this, active, _| events.borrow_mut().push((this.0, active))
6122 })
6123 .detach();
6124 View("window 2")
6125 });
6126 assert_eq!(
6127 mem::take(&mut *events.borrow_mut()),
6128 [("window 1", false), ("window 2", true)]
6129 );
6130
6131 let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6132 cx.observe_window_activation({
6133 let events = events.clone();
6134 move |this, active, _| events.borrow_mut().push((this.0, active))
6135 })
6136 .detach();
6137 View("window 3")
6138 });
6139 assert_eq!(
6140 mem::take(&mut *events.borrow_mut()),
6141 [("window 2", false), ("window 3", true)]
6142 );
6143
6144 cx.simulate_window_activation(Some(window_2));
6145 assert_eq!(
6146 mem::take(&mut *events.borrow_mut()),
6147 [("window 3", false), ("window 2", true)]
6148 );
6149
6150 cx.simulate_window_activation(Some(window_1));
6151 assert_eq!(
6152 mem::take(&mut *events.borrow_mut()),
6153 [("window 2", false), ("window 1", true)]
6154 );
6155
6156 cx.simulate_window_activation(Some(window_3));
6157 assert_eq!(
6158 mem::take(&mut *events.borrow_mut()),
6159 [("window 1", false), ("window 3", true)]
6160 );
6161
6162 cx.simulate_window_activation(Some(window_3));
6163 assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6164 }
6165
6166 #[crate::test(self)]
6167 fn test_child_view(cx: &mut TestAppContext) {
6168 struct Child {
6169 rendered: Rc<Cell<bool>>,
6170 dropped: Rc<Cell<bool>>,
6171 }
6172
6173 impl super::Entity for Child {
6174 type Event = ();
6175 }
6176
6177 impl super::View for Child {
6178 fn ui_name() -> &'static str {
6179 "child view"
6180 }
6181
6182 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6183 self.rendered.set(true);
6184 Empty::new().into_any()
6185 }
6186 }
6187
6188 impl Drop for Child {
6189 fn drop(&mut self) {
6190 self.dropped.set(true);
6191 }
6192 }
6193
6194 struct Parent {
6195 child: Option<ViewHandle<Child>>,
6196 }
6197
6198 impl super::Entity for Parent {
6199 type Event = ();
6200 }
6201
6202 impl super::View for Parent {
6203 fn ui_name() -> &'static str {
6204 "parent view"
6205 }
6206
6207 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6208 if let Some(child) = self.child.as_ref() {
6209 ChildView::new(child, cx).into_any()
6210 } else {
6211 Empty::new().into_any()
6212 }
6213 }
6214 }
6215
6216 let child_rendered = Rc::new(Cell::new(false));
6217 let child_dropped = Rc::new(Cell::new(false));
6218 let (_, root_view) = cx.add_window(|cx| Parent {
6219 child: Some(cx.add_view(|_| Child {
6220 rendered: child_rendered.clone(),
6221 dropped: child_dropped.clone(),
6222 })),
6223 });
6224 assert!(child_rendered.take());
6225 assert!(!child_dropped.take());
6226
6227 root_view.update(cx, |view, cx| {
6228 view.child.take();
6229 cx.notify();
6230 });
6231 assert!(!child_rendered.take());
6232 assert!(child_dropped.take());
6233 }
6234
6235 #[derive(Default)]
6236 struct TestView {
6237 events: Vec<String>,
6238 }
6239
6240 impl Entity for TestView {
6241 type Event = String;
6242 }
6243
6244 impl View for TestView {
6245 fn ui_name() -> &'static str {
6246 "TestView"
6247 }
6248
6249 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6250 Empty::new().into_any()
6251 }
6252 }
6253}