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