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