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