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