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