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