1mod async_context;
2mod entity_map;
3mod model_context;
4
5pub use async_context::*;
6pub use entity_map::*;
7pub use model_context::*;
8use refineable::Refineable;
9use smallvec::SmallVec;
10
11use crate::{
12 current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AppMetadata, AssetSource,
13 Context, DispatchPhase, DisplayId, Executor, FocusEvent, FocusHandle, FocusId, KeyBinding,
14 Keymap, LayoutId, MainThread, MainThreadOnly, Pixels, Platform, Point, SharedString,
15 SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem,
16 View, Window, WindowContext, WindowHandle, WindowId,
17};
18use anyhow::{anyhow, Result};
19use collections::{HashMap, HashSet, VecDeque};
20use futures::{future::BoxFuture, Future};
21use parking_lot::{Mutex, RwLock};
22use slotmap::SlotMap;
23use std::{
24 any::{type_name, Any, TypeId},
25 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 mut 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 active_drag: None,
97 })
98 }))
99 }
100
101 pub fn run<F>(self, on_finish_launching: F)
102 where
103 F: 'static + FnOnce(&mut MainThread<AppContext>),
104 {
105 let this = self.0.clone();
106 let platform = self.0.lock().platform.clone();
107 platform.borrow_on_main_thread().run(Box::new(move || {
108 let cx = &mut *this.lock();
109 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
110 on_finish_launching(cx);
111 }));
112 }
113
114 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
115 where
116 F: 'static + FnMut(Vec<String>, &mut AppContext),
117 {
118 let this = Arc::downgrade(&self.0);
119 self.0
120 .lock()
121 .platform
122 .borrow_on_main_thread()
123 .on_open_urls(Box::new(move |urls| {
124 if let Some(app) = this.upgrade() {
125 callback(urls, &mut app.lock());
126 }
127 }));
128 self
129 }
130
131 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
132 where
133 F: 'static + FnMut(&mut AppContext),
134 {
135 let this = Arc::downgrade(&self.0);
136 self.0
137 .lock()
138 .platform
139 .borrow_on_main_thread()
140 .on_reopen(Box::new(move || {
141 if let Some(app) = this.upgrade() {
142 callback(&mut app.lock());
143 }
144 }));
145 self
146 }
147
148 pub fn metadata(&self) -> AppMetadata {
149 self.0.lock().app_metadata.clone()
150 }
151
152 pub fn executor(&self) -> Executor {
153 self.0.lock().executor.clone()
154 }
155
156 pub fn text_system(&self) -> Arc<TextSystem> {
157 self.0.lock().text_system.clone()
158 }
159}
160
161type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
162type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
163type Handler = Box<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>;
164type Listener = Box<dyn Fn(&dyn Any, &mut AppContext) -> bool + Send + Sync + 'static>;
165type QuitHandler = Box<dyn Fn(&mut AppContext) -> BoxFuture<'static, ()> + Send + Sync + 'static>;
166type ReleaseListener = Box<dyn Fn(&mut dyn Any, &mut AppContext) + Send + Sync + 'static>;
167
168pub struct AppContext {
169 this: Weak<Mutex<AppContext>>,
170 pub(crate) platform: MainThreadOnly<dyn Platform>,
171 app_metadata: AppMetadata,
172 text_system: Arc<TextSystem>,
173 flushing_effects: bool,
174 pending_updates: usize,
175 pub(crate) active_drag: Option<AnyDrag>,
176 pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
177 pub(crate) executor: Executor,
178 pub(crate) svg_renderer: SvgRenderer,
179 pub(crate) image_cache: ImageCache,
180 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
181 pub(crate) globals_by_type: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
182 pub(crate) unit_entity: Handle<()>,
183 pub(crate) entities: EntityMap,
184 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
185 pub(crate) keymap: Arc<RwLock<Keymap>>,
186 pub(crate) global_action_listeners:
187 HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send + Sync>>>,
188 action_builders: HashMap<SharedString, ActionBuilder>,
189 pending_effects: VecDeque<Effect>,
190 pub(crate) pending_notifications: HashSet<EntityId>,
191 pub(crate) pending_global_notifications: HashSet<TypeId>,
192 pub(crate) observers: SubscriberSet<EntityId, Handler>,
193 pub(crate) event_listeners: SubscriberSet<EntityId, Listener>,
194 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
195 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
196 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
197 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
198 pub(crate) propagate_event: bool,
199}
200
201impl AppContext {
202 pub fn quit(&mut self) {
203 let mut futures = Vec::new();
204
205 self.quit_observers.clone().retain(&(), |observer| {
206 futures.push(observer(self));
207 true
208 });
209
210 self.windows.clear();
211 self.flush_effects();
212
213 let futures = futures::future::join_all(futures);
214 if self
215 .executor
216 .block_with_timeout(Duration::from_millis(100), futures)
217 .is_err()
218 {
219 log::error!("timed out waiting on app_will_quit");
220 }
221 }
222
223 pub fn app_metadata(&self) -> AppMetadata {
224 self.app_metadata.clone()
225 }
226
227 pub fn refresh(&mut self) {
228 self.pending_effects.push_back(Effect::Refresh);
229 }
230
231 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
232 self.pending_updates += 1;
233 let result = update(self);
234 if !self.flushing_effects && self.pending_updates == 1 {
235 self.flushing_effects = true;
236 self.flush_effects();
237 self.flushing_effects = false;
238 }
239 self.pending_updates -= 1;
240 result
241 }
242
243 pub(crate) fn read_window<R>(
244 &mut self,
245 id: WindowId,
246 read: impl FnOnce(&WindowContext) -> R,
247 ) -> Result<R> {
248 let window = self
249 .windows
250 .get(id)
251 .ok_or_else(|| anyhow!("window not found"))?
252 .as_ref()
253 .unwrap();
254 Ok(read(&WindowContext::immutable(self, &window)))
255 }
256
257 pub(crate) fn update_window<R>(
258 &mut self,
259 id: WindowId,
260 update: impl FnOnce(&mut WindowContext) -> R,
261 ) -> Result<R> {
262 self.update(|cx| {
263 let mut window = cx
264 .windows
265 .get_mut(id)
266 .ok_or_else(|| anyhow!("window not found"))?
267 .take()
268 .unwrap();
269
270 let result = update(&mut WindowContext::mutable(cx, &mut window));
271
272 cx.windows
273 .get_mut(id)
274 .ok_or_else(|| anyhow!("window not found"))?
275 .replace(window);
276
277 Ok(result)
278 })
279 }
280
281 pub(crate) fn push_effect(&mut self, effect: Effect) {
282 match &effect {
283 Effect::Notify { emitter } => {
284 if !self.pending_notifications.insert(*emitter) {
285 return;
286 }
287 }
288 Effect::NotifyGlobalObservers { global_type } => {
289 if !self.pending_global_notifications.insert(*global_type) {
290 return;
291 }
292 }
293 _ => {}
294 };
295
296 self.pending_effects.push_back(effect);
297 }
298
299 fn flush_effects(&mut self) {
300 loop {
301 self.release_dropped_entities();
302 self.release_dropped_focus_handles();
303 if let Some(effect) = self.pending_effects.pop_front() {
304 match effect {
305 Effect::Notify { emitter } => {
306 self.apply_notify_effect(emitter);
307 }
308 Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
309 Effect::FocusChanged { window_id, focused } => {
310 self.apply_focus_changed_effect(window_id, focused);
311 }
312 Effect::Refresh => {
313 self.apply_refresh_effect();
314 }
315 Effect::NotifyGlobalObservers { global_type } => {
316 self.apply_notify_global_observers_effect(global_type);
317 }
318 }
319 } else {
320 break;
321 }
322 }
323
324 let dirty_window_ids = self
325 .windows
326 .iter()
327 .filter_map(|(window_id, window)| {
328 let window = window.as_ref().unwrap();
329 if window.dirty {
330 Some(window_id)
331 } else {
332 None
333 }
334 })
335 .collect::<SmallVec<[_; 8]>>();
336
337 for dirty_window_id in dirty_window_ids {
338 self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
339 }
340 }
341
342 fn release_dropped_entities(&mut self) {
343 loop {
344 let dropped = self.entities.take_dropped();
345 if dropped.is_empty() {
346 break;
347 }
348
349 for (entity_id, mut entity) in dropped {
350 self.observers.remove(&entity_id);
351 self.event_listeners.remove(&entity_id);
352 for release_callback in self.release_listeners.remove(&entity_id) {
353 release_callback(&mut entity, self);
354 }
355 }
356 }
357 }
358
359 fn release_dropped_focus_handles(&mut self) {
360 let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();
361 for window_id in window_ids {
362 self.update_window(window_id, |cx| {
363 let mut blur_window = false;
364 let focus = cx.window.focus;
365 cx.window.focus_handles.write().retain(|handle_id, count| {
366 if count.load(SeqCst) == 0 {
367 if focus == Some(handle_id) {
368 blur_window = true;
369 }
370 false
371 } else {
372 true
373 }
374 });
375
376 if blur_window {
377 cx.blur();
378 }
379 })
380 .unwrap();
381 }
382 }
383
384 fn apply_notify_effect(&mut self, emitter: EntityId) {
385 self.pending_notifications.remove(&emitter);
386 self.observers
387 .clone()
388 .retain(&emitter, |handler| handler(self));
389 }
390
391 fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
392 self.event_listeners
393 .clone()
394 .retain(&emitter, |handler| handler(&event, self));
395 }
396
397 fn apply_focus_changed_effect(&mut self, window_id: WindowId, focused: Option<FocusId>) {
398 self.update_window(window_id, |cx| {
399 if cx.window.focus == focused {
400 let mut listeners = mem::take(&mut cx.window.focus_listeners);
401 let focused =
402 focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
403 let blurred = cx
404 .window
405 .last_blur
406 .take()
407 .unwrap()
408 .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
409 if focused.is_some() || blurred.is_some() {
410 let event = FocusEvent { focused, blurred };
411 for listener in &listeners {
412 listener(&event, cx);
413 }
414 }
415
416 listeners.extend(cx.window.focus_listeners.drain(..));
417 cx.window.focus_listeners = listeners;
418 }
419 })
420 .ok();
421 }
422
423 fn apply_refresh_effect(&mut self) {
424 for window in self.windows.values_mut() {
425 if let Some(window) = window.as_mut() {
426 window.dirty = true;
427 }
428 }
429 }
430
431 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
432 self.pending_global_notifications.remove(&type_id);
433 self.global_observers
434 .clone()
435 .retain(&type_id, |observer| observer(self));
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(&mut Self) + Send + Sync + 'static,
567 ) -> Subscription {
568 self.global_observers.insert(
569 TypeId::of::<G>(),
570 Box::new(move |cx| {
571 f(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.entity_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(
664 &mut entity,
665 &mut ModelContext::mutable(cx, handle.entity_id),
666 );
667 cx.entities.end_lease(entity);
668 result
669 })
670 }
671}
672
673impl MainThread<AppContext> {
674 fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
675 self.0.update(|cx| {
676 update(unsafe {
677 std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
678 })
679 })
680 }
681
682 pub(crate) fn update_window<R>(
683 &mut self,
684 id: WindowId,
685 update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
686 ) -> Result<R> {
687 self.0.update_window(id, |cx| {
688 update(unsafe {
689 std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
690 })
691 })
692 }
693
694 pub(crate) fn platform(&self) -> &dyn Platform {
695 self.platform.borrow_on_main_thread()
696 }
697
698 pub fn activate(&self, ignoring_other_apps: bool) {
699 self.platform().activate(ignoring_other_apps);
700 }
701
702 pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
703 self.platform().write_credentials(url, username, password)
704 }
705
706 pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
707 self.platform().read_credentials(url)
708 }
709
710 pub fn delete_credentials(&self, url: &str) -> Result<()> {
711 self.platform().delete_credentials(url)
712 }
713
714 pub fn open_url(&self, url: &str) {
715 self.platform().open_url(url);
716 }
717
718 pub fn open_window<S: 'static + Send + Sync>(
719 &mut self,
720 options: crate::WindowOptions,
721 build_root_view: impl FnOnce(&mut WindowContext) -> View<S> + Send + 'static,
722 ) -> WindowHandle<S> {
723 self.update(|cx| {
724 let id = cx.windows.insert(None);
725 let handle = WindowHandle::new(id);
726 let mut window = Window::new(handle.into(), options, cx);
727 let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
728 window.root_view.replace(root_view.into_any());
729 cx.windows.get_mut(id).unwrap().replace(window);
730 handle
731 })
732 }
733
734 pub fn update_global<G: 'static + Send + Sync, R>(
735 &mut self,
736 update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
737 ) -> R {
738 self.0.update_global(|global, cx| {
739 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
740 update(global, cx)
741 })
742 }
743}
744
745pub(crate) enum Effect {
746 Notify {
747 emitter: EntityId,
748 },
749 Emit {
750 emitter: EntityId,
751 event: Box<dyn Any + Send + Sync + 'static>,
752 },
753 FocusChanged {
754 window_id: WindowId,
755 focused: Option<FocusId>,
756 },
757 Refresh,
758 NotifyGlobalObservers {
759 global_type: TypeId,
760 },
761}
762
763pub(crate) struct AnyDrag {
764 pub drag_handle_view: AnyView,
765 pub cursor_offset: Point<Pixels>,
766 pub state: AnyBox,
767 pub state_type: TypeId,
768}
769
770#[cfg(test)]
771mod tests {
772 use super::AppContext;
773
774 #[test]
775 fn test_app_context_send_sync() {
776 // This will not compile if `AppContext` does not implement `Send`
777 fn assert_send<T: Send>() {}
778 assert_send::<AppContext>();
779 }
780}