1mod async_context;
2mod entity_map;
3mod model_context;
4
5pub use async_context::*;
6pub use entity_map::*;
7pub use model_context::*;
8use refineable::Refineable;
9use smallvec::SmallVec;
10
11use crate::{
12 current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AppMetadata, AssetSource,
13 Context, DispatchPhase, DisplayId, Executor, FocusEvent, FocusHandle, FocusId, KeyBinding,
14 Keymap, LayoutId, MainThread, MainThreadOnly, Pixels, Platform, Point, SharedString,
15 SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem,
16 View, Window, WindowContext, WindowHandle, WindowId,
17};
18use anyhow::{anyhow, Result};
19use collections::{HashMap, HashSet, VecDeque};
20use futures::Future;
21use parking_lot::{Mutex, RwLock};
22use slotmap::SlotMap;
23use std::{
24 any::{type_name, Any, TypeId},
25 mem,
26 sync::{atomic::Ordering::SeqCst, Arc, Weak},
27};
28use util::http::{self, HttpClient};
29
30pub struct App(Arc<Mutex<AppContext>>);
31
32impl App {
33 pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
34 let http_client = http::client();
35 Self::new(current_platform(), asset_source, http_client)
36 }
37
38 #[cfg(any(test, feature = "test"))]
39 pub fn test() -> Self {
40 let platform = Arc::new(super::TestPlatform::new());
41 let asset_source = Arc::new(());
42 let http_client = util::http::FakeHttpClient::with_404_response();
43 Self::new(platform, asset_source, http_client)
44 }
45
46 fn new(
47 platform: Arc<dyn Platform>,
48 asset_source: Arc<dyn AssetSource>,
49 http_client: Arc<dyn HttpClient>,
50 ) -> Self {
51 let executor = platform.executor();
52 assert!(
53 executor.is_main_thread(),
54 "must construct App on main thread"
55 );
56
57 let text_system = Arc::new(TextSystem::new(platform.text_system()));
58 let entities = EntityMap::new();
59 let unit_entity = entities.insert(entities.reserve(), ());
60 let app_metadata = AppMetadata {
61 os_name: platform.os_name(),
62 os_version: platform.os_version().ok(),
63 app_version: platform.app_version().ok(),
64 };
65 Self(Arc::new_cyclic(|this| {
66 Mutex::new(AppContext {
67 this: this.clone(),
68 text_system,
69 platform: MainThreadOnly::new(platform, executor.clone()),
70 app_metadata,
71 flushing_effects: false,
72 pending_updates: 0,
73 next_frame_callbacks: Default::default(),
74 executor,
75 svg_renderer: SvgRenderer::new(asset_source),
76 image_cache: ImageCache::new(http_client),
77 text_style_stack: Vec::new(),
78 globals_by_type: HashMap::default(),
79 unit_entity,
80 entities,
81 windows: SlotMap::with_key(),
82 keymap: Arc::new(RwLock::new(Keymap::default())),
83 global_action_listeners: HashMap::default(),
84 action_builders: HashMap::default(),
85 pending_effects: VecDeque::new(),
86 pending_notifications: HashSet::default(),
87 pending_global_notifications: HashSet::default(),
88 observers: SubscriberSet::new(),
89 event_listeners: SubscriberSet::new(),
90 release_listeners: SubscriberSet::new(),
91 global_observers: SubscriberSet::new(),
92 layout_id_buffer: Default::default(),
93 propagate_event: true,
94 active_drag: None,
95 })
96 }))
97 }
98
99 pub fn run<F>(self, on_finish_launching: F)
100 where
101 F: 'static + FnOnce(&mut MainThread<AppContext>),
102 {
103 let this = self.0.clone();
104 let platform = self.0.lock().platform.clone();
105 platform.borrow_on_main_thread().run(Box::new(move || {
106 let cx = &mut *this.lock();
107 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
108 on_finish_launching(cx);
109 }));
110 }
111
112 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
113 where
114 F: 'static + FnMut(Vec<String>, &mut AppContext),
115 {
116 let this = Arc::downgrade(&self.0);
117 self.0
118 .lock()
119 .platform
120 .borrow_on_main_thread()
121 .on_open_urls(Box::new(move |urls| {
122 if let Some(app) = this.upgrade() {
123 callback(urls, &mut app.lock());
124 }
125 }));
126 self
127 }
128
129 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
130 where
131 F: 'static + FnMut(&mut AppContext),
132 {
133 let this = Arc::downgrade(&self.0);
134 self.0
135 .lock()
136 .platform
137 .borrow_on_main_thread()
138 .on_reopen(Box::new(move || {
139 if let Some(app) = this.upgrade() {
140 callback(&mut app.lock());
141 }
142 }));
143 self
144 }
145
146 pub fn metadata(&self) -> AppMetadata {
147 self.0.lock().app_metadata.clone()
148 }
149
150 pub fn executor(&self) -> Executor {
151 self.0.lock().executor.clone()
152 }
153
154 pub fn text_system(&self) -> Arc<TextSystem> {
155 self.0.lock().text_system.clone()
156 }
157}
158
159type Handler = Box<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>;
160type Listener = Box<dyn Fn(&dyn Any, &mut AppContext) -> bool + Send + Sync + 'static>;
161type ReleaseListener = Box<dyn Fn(&mut dyn Any, &mut AppContext) + Send + Sync + 'static>;
162type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
163type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
164
165pub struct AppContext {
166 this: Weak<Mutex<AppContext>>,
167 pub(crate) platform: MainThreadOnly<dyn Platform>,
168 app_metadata: AppMetadata,
169 text_system: Arc<TextSystem>,
170 flushing_effects: bool,
171 pending_updates: usize,
172 pub(crate) active_drag: Option<AnyDrag>,
173 pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
174 pub(crate) executor: Executor,
175 pub(crate) svg_renderer: SvgRenderer,
176 pub(crate) image_cache: ImageCache,
177 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
178 pub(crate) globals_by_type: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
179 pub(crate) unit_entity: Handle<()>,
180 pub(crate) entities: EntityMap,
181 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
182 pub(crate) keymap: Arc<RwLock<Keymap>>,
183 pub(crate) global_action_listeners:
184 HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send + Sync>>>,
185 action_builders: HashMap<SharedString, ActionBuilder>,
186 pending_effects: VecDeque<Effect>,
187 pub(crate) pending_notifications: HashSet<EntityId>,
188 pub(crate) pending_global_notifications: HashSet<TypeId>,
189 pub(crate) observers: SubscriberSet<EntityId, Handler>,
190 pub(crate) event_listeners: SubscriberSet<EntityId, Listener>,
191 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
192 pub(crate) global_observers: SubscriberSet<TypeId, Listener>,
193 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
194 pub(crate) propagate_event: bool,
195}
196
197impl AppContext {
198 pub fn app_metadata(&self) -> AppMetadata {
199 self.app_metadata.clone()
200 }
201
202 pub fn refresh(&mut self) {
203 self.pending_effects.push_back(Effect::Refresh);
204 }
205
206 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
207 self.pending_updates += 1;
208 let result = update(self);
209 if !self.flushing_effects && self.pending_updates == 1 {
210 self.flushing_effects = true;
211 self.flush_effects();
212 self.flushing_effects = false;
213 }
214 self.pending_updates -= 1;
215 result
216 }
217
218 pub(crate) fn read_window<R>(
219 &mut self,
220 id: WindowId,
221 read: impl FnOnce(&WindowContext) -> R,
222 ) -> Result<R> {
223 let window = self
224 .windows
225 .get(id)
226 .ok_or_else(|| anyhow!("window not found"))?
227 .as_ref()
228 .unwrap();
229 Ok(read(&WindowContext::immutable(self, &window)))
230 }
231
232 pub(crate) fn update_window<R>(
233 &mut self,
234 id: WindowId,
235 update: impl FnOnce(&mut WindowContext) -> R,
236 ) -> Result<R> {
237 self.update(|cx| {
238 let mut window = cx
239 .windows
240 .get_mut(id)
241 .ok_or_else(|| anyhow!("window not found"))?
242 .take()
243 .unwrap();
244
245 let result = update(&mut WindowContext::mutable(cx, &mut window));
246
247 cx.windows
248 .get_mut(id)
249 .ok_or_else(|| anyhow!("window not found"))?
250 .replace(window);
251
252 Ok(result)
253 })
254 }
255
256 pub(crate) fn push_effect(&mut self, effect: Effect) {
257 match &effect {
258 Effect::Notify { emitter } => {
259 if !self.pending_notifications.insert(*emitter) {
260 return;
261 }
262 }
263 Effect::NotifyGlobalObservers { global_type } => {
264 if !self.pending_global_notifications.insert(*global_type) {
265 return;
266 }
267 }
268 _ => {}
269 };
270
271 self.pending_effects.push_back(effect);
272 }
273
274 fn flush_effects(&mut self) {
275 loop {
276 self.release_dropped_entities();
277 self.release_dropped_focus_handles();
278 if let Some(effect) = self.pending_effects.pop_front() {
279 match effect {
280 Effect::Notify { emitter } => {
281 self.apply_notify_effect(emitter);
282 }
283 Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
284 Effect::FocusChanged { window_id, focused } => {
285 self.apply_focus_changed_effect(window_id, focused);
286 }
287 Effect::Refresh => {
288 self.apply_refresh_effect();
289 }
290 Effect::NotifyGlobalObservers { global_type } => {
291 self.apply_notify_global_observers_effect(global_type);
292 }
293 }
294 } else {
295 break;
296 }
297 }
298
299 let dirty_window_ids = self
300 .windows
301 .iter()
302 .filter_map(|(window_id, window)| {
303 let window = window.as_ref().unwrap();
304 if window.dirty {
305 Some(window_id)
306 } else {
307 None
308 }
309 })
310 .collect::<SmallVec<[_; 8]>>();
311
312 for dirty_window_id in dirty_window_ids {
313 self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
314 }
315 }
316
317 fn release_dropped_entities(&mut self) {
318 loop {
319 let dropped = self.entities.take_dropped();
320 if dropped.is_empty() {
321 break;
322 }
323
324 for (entity_id, mut entity) in dropped {
325 self.observers.remove(&entity_id);
326 self.event_listeners.remove(&entity_id);
327 for release_callback in self.release_listeners.remove(&entity_id) {
328 release_callback(&mut entity, self);
329 }
330 }
331 }
332 }
333
334 fn release_dropped_focus_handles(&mut self) {
335 let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();
336 for window_id in window_ids {
337 self.update_window(window_id, |cx| {
338 let mut blur_window = false;
339 let focus = cx.window.focus;
340 cx.window.focus_handles.write().retain(|handle_id, count| {
341 if count.load(SeqCst) == 0 {
342 if focus == Some(handle_id) {
343 blur_window = true;
344 }
345 false
346 } else {
347 true
348 }
349 });
350
351 if blur_window {
352 cx.blur();
353 }
354 })
355 .unwrap();
356 }
357 }
358
359 fn apply_notify_effect(&mut self, emitter: EntityId) {
360 self.pending_notifications.remove(&emitter);
361 self.observers
362 .clone()
363 .retain(&emitter, |handler| handler(self));
364 }
365
366 fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
367 self.event_listeners
368 .clone()
369 .retain(&emitter, |handler| handler(&event, self));
370 }
371
372 fn apply_focus_changed_effect(&mut self, window_id: WindowId, focused: Option<FocusId>) {
373 self.update_window(window_id, |cx| {
374 if cx.window.focus == focused {
375 let mut listeners = mem::take(&mut cx.window.focus_listeners);
376 let focused =
377 focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
378 let blurred = cx
379 .window
380 .last_blur
381 .take()
382 .unwrap()
383 .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
384 if focused.is_some() || blurred.is_some() {
385 let event = FocusEvent { focused, blurred };
386 for listener in &listeners {
387 listener(&event, cx);
388 }
389 }
390
391 listeners.extend(cx.window.focus_listeners.drain(..));
392 cx.window.focus_listeners = listeners;
393 }
394 })
395 .ok();
396 }
397
398 fn apply_refresh_effect(&mut self) {
399 for window in self.windows.values_mut() {
400 if let Some(window) = window.as_mut() {
401 window.dirty = true;
402 }
403 }
404 }
405
406 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
407 self.pending_global_notifications.insert(type_id);
408 let global = self.globals_by_type.remove(&type_id).unwrap();
409 self.global_observers
410 .clone()
411 .retain(&type_id, |observer| observer(global.as_ref(), self));
412 self.globals_by_type.insert(type_id, global);
413 }
414
415 pub fn to_async(&self) -> AsyncAppContext {
416 AsyncAppContext {
417 app: unsafe { mem::transmute(self.this.clone()) },
418 executor: self.executor.clone(),
419 }
420 }
421
422 pub fn executor(&self) -> &Executor {
423 &self.executor
424 }
425
426 pub fn run_on_main<R>(
427 &mut self,
428 f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
429 ) -> Task<R>
430 where
431 R: Send + 'static,
432 {
433 if self.executor.is_main_thread() {
434 Task::ready(f(unsafe {
435 mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
436 }))
437 } else {
438 let this = self.this.upgrade().unwrap();
439 self.executor.run_on_main(move || {
440 let cx = &mut *this.lock();
441 cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
442 })
443 }
444 }
445
446 pub fn spawn_on_main<F, R>(
447 &self,
448 f: impl FnOnce(&mut MainThread<AppContext>) -> F + Send + 'static,
449 ) -> Task<R>
450 where
451 F: Future<Output = R> + 'static,
452 R: Send + 'static,
453 {
454 let this = self.this.upgrade().unwrap();
455 self.executor.spawn_on_main(move || {
456 let cx = &mut *this.lock();
457 cx.update(|cx| {
458 f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
459 })
460 })
461 }
462
463 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
464 where
465 Fut: Future<Output = R> + Send + 'static,
466 R: Send + 'static,
467 {
468 let cx = self.to_async();
469 self.executor.spawn(async move {
470 let future = f(cx);
471 future.await
472 })
473 }
474
475 pub fn text_system(&self) -> &Arc<TextSystem> {
476 &self.text_system
477 }
478
479 pub fn text_style(&self) -> TextStyle {
480 let mut style = TextStyle::default();
481 for refinement in &self.text_style_stack {
482 style.refine(refinement);
483 }
484 style
485 }
486
487 pub fn has_global<G: 'static>(&self) -> bool {
488 self.globals_by_type.contains_key(&TypeId::of::<G>())
489 }
490
491 pub fn global<G: 'static>(&self) -> &G {
492 self.globals_by_type
493 .get(&TypeId::of::<G>())
494 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
495 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
496 .unwrap()
497 }
498
499 pub fn try_global<G: 'static>(&self) -> Option<&G> {
500 self.globals_by_type
501 .get(&TypeId::of::<G>())
502 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
503 }
504
505 pub fn global_mut<G: 'static>(&mut self) -> &mut G {
506 let global_type = TypeId::of::<G>();
507 self.push_effect(Effect::NotifyGlobalObservers { global_type });
508 self.globals_by_type
509 .get_mut(&global_type)
510 .and_then(|any_state| any_state.downcast_mut::<G>())
511 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
512 .unwrap()
513 }
514
515 pub fn default_global_mut<G: 'static + Default + Sync + Send>(&mut self) -> &mut G {
516 let global_type = TypeId::of::<G>();
517 self.push_effect(Effect::NotifyGlobalObservers { global_type });
518 self.globals_by_type
519 .entry(global_type)
520 .or_insert_with(|| Box::new(G::default()))
521 .downcast_mut::<G>()
522 .unwrap()
523 }
524
525 pub fn set_global<T: Send + Sync + 'static>(&mut self, global: T) {
526 let global_type = TypeId::of::<T>();
527 self.push_effect(Effect::NotifyGlobalObservers { global_type });
528 self.globals_by_type.insert(global_type, Box::new(global));
529 }
530
531 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
532 where
533 G: 'static + Send + Sync,
534 {
535 let mut global = self.lease_global::<G>();
536 let result = f(global.as_mut(), self);
537 self.restore_global(global);
538 result
539 }
540
541 pub fn observe_global<G: 'static>(
542 &mut self,
543 f: impl Fn(&G, &mut Self) + Send + Sync + 'static,
544 ) -> Subscription {
545 self.global_observers.insert(
546 TypeId::of::<G>(),
547 Box::new(move |global, cx| {
548 f(global.downcast_ref::<G>().unwrap(), cx);
549 true
550 }),
551 )
552 }
553
554 pub(crate) fn lease_global<G: 'static + Send + Sync>(&mut self) -> Box<G> {
555 self.globals_by_type
556 .remove(&TypeId::of::<G>())
557 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
558 .unwrap()
559 .downcast()
560 .unwrap()
561 }
562
563 pub(crate) fn restore_global<G: 'static + Send + Sync>(&mut self, global: Box<G>) {
564 let global_type = TypeId::of::<G>();
565 self.push_effect(Effect::NotifyGlobalObservers { global_type });
566 self.globals_by_type.insert(global_type, global);
567 }
568
569 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
570 self.text_style_stack.push(text_style);
571 }
572
573 pub(crate) fn pop_text_style(&mut self) {
574 self.text_style_stack.pop();
575 }
576
577 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
578 self.keymap.write().add_bindings(bindings);
579 self.pending_effects.push_back(Effect::Refresh);
580 }
581
582 pub fn on_action<A: Action>(
583 &mut self,
584 listener: impl Fn(&A, &mut Self) + Send + Sync + 'static,
585 ) {
586 self.global_action_listeners
587 .entry(TypeId::of::<A>())
588 .or_default()
589 .push(Box::new(move |action, phase, cx| {
590 if phase == DispatchPhase::Bubble {
591 let action = action.as_any().downcast_ref().unwrap();
592 listener(action, cx)
593 }
594 }));
595 }
596
597 pub fn register_action_type<A: Action>(&mut self) {
598 self.action_builders.insert(A::qualified_name(), A::build);
599 }
600
601 pub fn build_action(
602 &mut self,
603 name: &str,
604 params: Option<serde_json::Value>,
605 ) -> Result<Box<dyn Action>> {
606 let build = self
607 .action_builders
608 .get(name)
609 .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
610 (build)(params)
611 }
612
613 pub fn stop_propagation(&mut self) {
614 self.propagate_event = false;
615 }
616}
617
618impl Context for AppContext {
619 type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T>;
620 type Result<T> = T;
621
622 fn entity<T: Send + Sync + 'static>(
623 &mut self,
624 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
625 ) -> Handle<T> {
626 self.update(|cx| {
627 let slot = cx.entities.reserve();
628 let entity = build_entity(&mut ModelContext::mutable(cx, slot.id));
629 cx.entities.insert(slot, entity)
630 })
631 }
632
633 fn update_entity<T: Send + Sync + 'static, R>(
634 &mut self,
635 handle: &Handle<T>,
636 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
637 ) -> R {
638 self.update(|cx| {
639 let mut entity = cx.entities.lease(handle);
640 let result = update(&mut entity, &mut ModelContext::mutable(cx, handle.id));
641 cx.entities.end_lease(entity);
642 result
643 })
644 }
645}
646
647impl MainThread<AppContext> {
648 fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
649 self.0.update(|cx| {
650 update(unsafe {
651 std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
652 })
653 })
654 }
655
656 pub(crate) fn update_window<R>(
657 &mut self,
658 id: WindowId,
659 update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
660 ) -> Result<R> {
661 self.0.update_window(id, |cx| {
662 update(unsafe {
663 std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
664 })
665 })
666 }
667
668 pub(crate) fn platform(&self) -> &dyn Platform {
669 self.platform.borrow_on_main_thread()
670 }
671
672 pub fn activate(&self, ignoring_other_apps: bool) {
673 self.platform().activate(ignoring_other_apps);
674 }
675
676 pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
677 self.platform().write_credentials(url, username, password)
678 }
679
680 pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
681 self.platform().read_credentials(url)
682 }
683
684 pub fn delete_credentials(&self, url: &str) -> Result<()> {
685 self.platform().delete_credentials(url)
686 }
687
688 pub fn open_url(&self, url: &str) {
689 self.platform().open_url(url);
690 }
691
692 pub fn open_window<S: 'static + Send + Sync>(
693 &mut self,
694 options: crate::WindowOptions,
695 build_root_view: impl FnOnce(&mut WindowContext) -> View<S> + Send + 'static,
696 ) -> WindowHandle<S> {
697 self.update(|cx| {
698 let id = cx.windows.insert(None);
699 let handle = WindowHandle::new(id);
700 let mut window = Window::new(handle.into(), options, cx);
701 let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
702 window.root_view.replace(root_view.into_any());
703 cx.windows.get_mut(id).unwrap().replace(window);
704 handle
705 })
706 }
707
708 pub fn update_global<G: 'static + Send + Sync, R>(
709 &mut self,
710 update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
711 ) -> R {
712 self.0.update_global(|global, cx| {
713 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
714 update(global, cx)
715 })
716 }
717}
718
719pub(crate) enum Effect {
720 Notify {
721 emitter: EntityId,
722 },
723 Emit {
724 emitter: EntityId,
725 event: Box<dyn Any + Send + Sync + 'static>,
726 },
727 FocusChanged {
728 window_id: WindowId,
729 focused: Option<FocusId>,
730 },
731 Refresh,
732 NotifyGlobalObservers {
733 global_type: TypeId,
734 },
735}
736
737pub(crate) struct AnyDrag {
738 pub drag_handle_view: AnyView,
739 pub cursor_offset: Point<Pixels>,
740 pub state: AnyBox,
741 pub state_type: TypeId,
742}
743
744#[cfg(test)]
745mod tests {
746 use super::AppContext;
747
748 #[test]
749 fn test_app_context_send_sync() {
750 // This will not compile if `AppContext` does not implement `Send`
751 fn assert_send<T: Send>() {}
752 assert_send::<AppContext>();
753 }
754}