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