app.rs

  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, AppMetadata, AssetSource, Context,
 13    DispatchPhase, DisplayId, Executor, FocusEvent, FocusHandle, FocusId, KeyBinding, Keymap,
 14    LayoutId, MainThread, MainThreadOnly, Platform, SharedString, SubscriberSet, Subscription,
 15    SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, Window, WindowContext,
 16    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            })
 95        }))
 96    }
 97
 98    pub fn run<F>(self, on_finish_launching: F)
 99    where
100        F: 'static + FnOnce(&mut MainThread<AppContext>),
101    {
102        let this = self.0.clone();
103        let platform = self.0.lock().platform.clone();
104        platform.borrow_on_main_thread().run(Box::new(move || {
105            let cx = &mut *this.lock();
106            let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
107            on_finish_launching(cx);
108        }));
109    }
110
111    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
112    where
113        F: 'static + FnMut(Vec<String>, &mut AppContext),
114    {
115        let this = Arc::downgrade(&self.0);
116        self.0
117            .lock()
118            .platform
119            .borrow_on_main_thread()
120            .on_open_urls(Box::new(move |urls| {
121                if let Some(app) = this.upgrade() {
122                    callback(urls, &mut app.lock());
123                }
124            }));
125        self
126    }
127
128    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
129    where
130        F: 'static + FnMut(&mut AppContext),
131    {
132        let this = Arc::downgrade(&self.0);
133        self.0
134            .lock()
135            .platform
136            .borrow_on_main_thread()
137            .on_reopen(Box::new(move || {
138                if let Some(app) = this.upgrade() {
139                    callback(&mut app.lock());
140                }
141            }));
142        self
143    }
144
145    pub fn metadata(&self) -> AppMetadata {
146        self.0.lock().app_metadata.clone()
147    }
148
149    pub fn executor(&self) -> Executor {
150        self.0.lock().executor.clone()
151    }
152
153    pub fn text_system(&self) -> Arc<TextSystem> {
154        self.0.lock().text_system.clone()
155    }
156}
157
158type Handler = Box<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>;
159type Listener = Box<dyn Fn(&dyn Any, &mut AppContext) -> bool + Send + Sync + 'static>;
160type ReleaseListener = Box<dyn Fn(&mut dyn Any, &mut AppContext) + Send + Sync + 'static>;
161type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
162type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
163
164pub struct AppContext {
165    this: Weak<Mutex<AppContext>>,
166    pub(crate) platform: MainThreadOnly<dyn Platform>,
167    app_metadata: AppMetadata,
168    text_system: Arc<TextSystem>,
169    flushing_effects: bool,
170    pending_updates: usize,
171    pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
172    pub(crate) executor: Executor,
173    pub(crate) svg_renderer: SvgRenderer,
174    pub(crate) image_cache: ImageCache,
175    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
176    pub(crate) globals_by_type: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
177    pub(crate) unit_entity: Handle<()>,
178    pub(crate) entities: EntityMap,
179    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
180    pub(crate) keymap: Arc<RwLock<Keymap>>,
181    pub(crate) global_action_listeners:
182        HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send + Sync>>>,
183    action_builders: HashMap<SharedString, ActionBuilder>,
184    pending_effects: VecDeque<Effect>,
185    pub(crate) pending_notifications: HashSet<EntityId>,
186    pub(crate) pending_global_notifications: HashSet<TypeId>,
187    pub(crate) observers: SubscriberSet<EntityId, Handler>,
188    pub(crate) event_listeners: SubscriberSet<EntityId, Listener>,
189    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
190    pub(crate) global_observers: SubscriberSet<TypeId, Listener>,
191    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
192    pub(crate) propagate_event: bool,
193}
194
195impl AppContext {
196    pub fn app_metadata(&self) -> AppMetadata {
197        self.app_metadata.clone()
198    }
199
200    pub fn refresh(&mut self) {
201        self.pending_effects.push_back(Effect::Refresh);
202    }
203
204    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
205        self.pending_updates += 1;
206        let result = update(self);
207        if !self.flushing_effects && self.pending_updates == 1 {
208            self.flushing_effects = true;
209            self.flush_effects();
210            self.flushing_effects = false;
211        }
212        self.pending_updates -= 1;
213        result
214    }
215
216    pub(crate) fn read_window<R>(
217        &mut self,
218        id: WindowId,
219        read: impl FnOnce(&WindowContext) -> R,
220    ) -> Result<R> {
221        let window = self
222            .windows
223            .get(id)
224            .ok_or_else(|| anyhow!("window not found"))?
225            .as_ref()
226            .unwrap();
227        Ok(read(&WindowContext::immutable(self, &window)))
228    }
229
230    pub(crate) fn update_window<R>(
231        &mut self,
232        id: WindowId,
233        update: impl FnOnce(&mut WindowContext) -> R,
234    ) -> Result<R> {
235        self.update(|cx| {
236            let mut window = cx
237                .windows
238                .get_mut(id)
239                .ok_or_else(|| anyhow!("window not found"))?
240                .take()
241                .unwrap();
242
243            let result = update(&mut WindowContext::mutable(cx, &mut window));
244
245            cx.windows
246                .get_mut(id)
247                .ok_or_else(|| anyhow!("window not found"))?
248                .replace(window);
249
250            Ok(result)
251        })
252    }
253
254    pub(crate) fn push_effect(&mut self, effect: Effect) {
255        match &effect {
256            Effect::Notify { emitter } => {
257                if !self.pending_notifications.insert(*emitter) {
258                    return;
259                }
260            }
261            Effect::NotifyGlobalObservers { global_type } => {
262                if !self.pending_global_notifications.insert(*global_type) {
263                    return;
264                }
265            }
266            _ => {}
267        };
268
269        self.pending_effects.push_back(effect);
270    }
271
272    fn flush_effects(&mut self) {
273        loop {
274            self.release_dropped_entities();
275            self.release_dropped_focus_handles();
276            if let Some(effect) = self.pending_effects.pop_front() {
277                match effect {
278                    Effect::Notify { emitter } => {
279                        self.apply_notify_effect(emitter);
280                    }
281                    Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
282                    Effect::FocusChanged { window_id, focused } => {
283                        self.apply_focus_changed_effect(window_id, focused);
284                    }
285                    Effect::Refresh => {
286                        self.apply_refresh_effect();
287                    }
288                    Effect::NotifyGlobalObservers { global_type } => {
289                        self.apply_notify_global_observers_effect(global_type);
290                    }
291                }
292            } else {
293                break;
294            }
295        }
296
297        let dirty_window_ids = self
298            .windows
299            .iter()
300            .filter_map(|(window_id, window)| {
301                let window = window.as_ref().unwrap();
302                if window.dirty {
303                    Some(window_id)
304                } else {
305                    None
306                }
307            })
308            .collect::<SmallVec<[_; 8]>>();
309
310        for dirty_window_id in dirty_window_ids {
311            self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
312        }
313    }
314
315    fn release_dropped_entities(&mut self) {
316        loop {
317            let dropped = self.entities.take_dropped();
318            if dropped.is_empty() {
319                break;
320            }
321
322            for (entity_id, mut entity) in dropped {
323                self.observers.remove(&entity_id);
324                self.event_listeners.remove(&entity_id);
325                for release_callback in self.release_listeners.remove(&entity_id) {
326                    release_callback(&mut entity, self);
327                }
328            }
329        }
330    }
331
332    fn release_dropped_focus_handles(&mut self) {
333        let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();
334        for window_id in window_ids {
335            self.update_window(window_id, |cx| {
336                let mut blur_window = false;
337                let focus = cx.window.focus;
338                cx.window.focus_handles.write().retain(|handle_id, count| {
339                    if count.load(SeqCst) == 0 {
340                        if focus == Some(handle_id) {
341                            blur_window = true;
342                        }
343                        false
344                    } else {
345                        true
346                    }
347                });
348
349                if blur_window {
350                    cx.blur();
351                }
352            })
353            .unwrap();
354        }
355    }
356
357    fn apply_notify_effect(&mut self, emitter: EntityId) {
358        self.pending_notifications.remove(&emitter);
359        self.observers
360            .clone()
361            .retain(&emitter, |handler| handler(self));
362    }
363
364    fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
365        self.event_listeners
366            .clone()
367            .retain(&emitter, |handler| handler(&event, self));
368    }
369
370    fn apply_focus_changed_effect(&mut self, window_id: WindowId, focused: Option<FocusId>) {
371        self.update_window(window_id, |cx| {
372            if cx.window.focus == focused {
373                let mut listeners = mem::take(&mut cx.window.focus_listeners);
374                let focused =
375                    focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
376                let blurred = cx
377                    .window
378                    .last_blur
379                    .take()
380                    .unwrap()
381                    .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
382                if focused.is_some() || blurred.is_some() {
383                    let event = FocusEvent { focused, blurred };
384                    for listener in &listeners {
385                        listener(&event, cx);
386                    }
387                }
388
389                listeners.extend(cx.window.focus_listeners.drain(..));
390                cx.window.focus_listeners = listeners;
391            }
392        })
393        .ok();
394    }
395
396    fn apply_refresh_effect(&mut self) {
397        for window in self.windows.values_mut() {
398            if let Some(window) = window.as_mut() {
399                window.dirty = true;
400            }
401        }
402    }
403
404    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
405        self.pending_global_notifications.insert(type_id);
406        let global = self.globals_by_type.remove(&type_id).unwrap();
407        self.global_observers
408            .clone()
409            .retain(&type_id, |observer| observer(global.as_ref(), self));
410        self.globals_by_type.insert(type_id, global);
411    }
412
413    pub fn to_async(&self) -> AsyncAppContext {
414        AsyncAppContext {
415            app: unsafe { mem::transmute(self.this.clone()) },
416            executor: self.executor.clone(),
417        }
418    }
419
420    pub fn executor(&self) -> &Executor {
421        &self.executor
422    }
423
424    pub fn run_on_main<R>(
425        &mut self,
426        f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
427    ) -> Task<R>
428    where
429        R: Send + 'static,
430    {
431        if self.executor.is_main_thread() {
432            Task::ready(f(unsafe {
433                mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
434            }))
435        } else {
436            let this = self.this.upgrade().unwrap();
437            self.executor.run_on_main(move || {
438                let cx = &mut *this.lock();
439                cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
440            })
441        }
442    }
443
444    pub fn spawn_on_main<F, R>(
445        &self,
446        f: impl FnOnce(&mut MainThread<AppContext>) -> F + Send + 'static,
447    ) -> Task<R>
448    where
449        F: Future<Output = R> + 'static,
450        R: Send + 'static,
451    {
452        let this = self.this.upgrade().unwrap();
453        self.executor.spawn_on_main(move || {
454            let cx = &mut *this.lock();
455            cx.update(|cx| {
456                f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
457            })
458        })
459    }
460
461    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
462    where
463        Fut: Future<Output = R> + Send + 'static,
464        R: Send + 'static,
465    {
466        let cx = self.to_async();
467        self.executor.spawn(async move {
468            let future = f(cx);
469            future.await
470        })
471    }
472
473    pub fn text_system(&self) -> &Arc<TextSystem> {
474        &self.text_system
475    }
476
477    pub fn text_style(&self) -> TextStyle {
478        let mut style = TextStyle::default();
479        for refinement in &self.text_style_stack {
480            style.refine(refinement);
481        }
482        style
483    }
484
485    pub fn has_global<G: 'static>(&self) -> bool {
486        self.globals_by_type.contains_key(&TypeId::of::<G>())
487    }
488
489    pub fn global<G: 'static>(&self) -> &G {
490        self.globals_by_type
491            .get(&TypeId::of::<G>())
492            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
493            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
494            .unwrap()
495    }
496
497    pub fn try_global<G: 'static>(&self) -> Option<&G> {
498        self.globals_by_type
499            .get(&TypeId::of::<G>())
500            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
501    }
502
503    pub fn global_mut<G: 'static>(&mut self) -> &mut G {
504        let global_type = TypeId::of::<G>();
505        self.push_effect(Effect::NotifyGlobalObservers { global_type });
506        self.globals_by_type
507            .get_mut(&global_type)
508            .and_then(|any_state| any_state.downcast_mut::<G>())
509            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
510            .unwrap()
511    }
512
513    pub fn default_global<G: 'static + Default + Sync + Send>(&mut self) -> &mut G {
514        let global_type = TypeId::of::<G>();
515        self.push_effect(Effect::NotifyGlobalObservers { global_type });
516        self.globals_by_type
517            .insert(global_type, Box::new(G::default()));
518        self.globals_by_type
519            .get_mut(&global_type)
520            .unwrap()
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
737#[cfg(test)]
738mod tests {
739    use super::AppContext;
740
741    #[test]
742    fn test_app_context_send_sync() {
743        // This will not compile if `AppContext` does not implement `Send`
744        fn assert_send<T: Send>() {}
745        assert_send::<AppContext>();
746    }
747}