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