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