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