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