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