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