app.rs

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