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