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