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
229 pub fn app_metadata(&self) -> AppMetadata {
230 self.app_metadata.clone()
231 }
232
233 pub fn refresh(&mut self) {
234 self.pending_effects.push_back(Effect::Refresh);
235 }
236
237 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
238 self.pending_updates += 1;
239 let result = update(self);
240 if !self.flushing_effects && self.pending_updates == 1 {
241 self.flushing_effects = true;
242 self.flush_effects();
243 self.flushing_effects = false;
244 }
245 self.pending_updates -= 1;
246 result
247 }
248
249 pub(crate) fn read_window<R>(
250 &mut self,
251 id: WindowId,
252 read: impl FnOnce(&WindowContext) -> R,
253 ) -> Result<R> {
254 let window = self
255 .windows
256 .get(id)
257 .ok_or_else(|| anyhow!("window not found"))?
258 .as_ref()
259 .unwrap();
260 Ok(read(&WindowContext::immutable(self, &window)))
261 }
262
263 pub(crate) fn update_window<R>(
264 &mut self,
265 id: WindowId,
266 update: impl FnOnce(&mut WindowContext) -> R,
267 ) -> Result<R> {
268 self.update(|cx| {
269 let mut window = cx
270 .windows
271 .get_mut(id)
272 .ok_or_else(|| anyhow!("window not found"))?
273 .take()
274 .unwrap();
275
276 let result = update(&mut WindowContext::mutable(cx, &mut window));
277
278 cx.windows
279 .get_mut(id)
280 .ok_or_else(|| anyhow!("window not found"))?
281 .replace(window);
282
283 Ok(result)
284 })
285 }
286
287 pub(crate) fn push_effect(&mut self, effect: Effect) {
288 match &effect {
289 Effect::Notify { emitter } => {
290 if !self.pending_notifications.insert(*emitter) {
291 return;
292 }
293 }
294 Effect::NotifyGlobalObservers { global_type } => {
295 if !self.pending_global_notifications.insert(*global_type) {
296 return;
297 }
298 }
299 _ => {}
300 };
301
302 self.pending_effects.push_back(effect);
303 }
304
305 fn flush_effects(&mut self) {
306 loop {
307 self.release_dropped_entities();
308 self.release_dropped_focus_handles();
309 if let Some(effect) = self.pending_effects.pop_front() {
310 match effect {
311 Effect::Notify { emitter } => {
312 self.apply_notify_effect(emitter);
313 }
314 Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
315 Effect::FocusChanged { window_id, focused } => {
316 self.apply_focus_changed_effect(window_id, focused);
317 }
318 Effect::Refresh => {
319 self.apply_refresh_effect();
320 }
321 Effect::NotifyGlobalObservers { global_type } => {
322 self.apply_notify_global_observers_effect(global_type);
323 }
324 Effect::Defer { callback } => {
325 self.apply_defer_effect(callback);
326 }
327 }
328 } else {
329 break;
330 }
331 }
332
333 let dirty_window_ids = self
334 .windows
335 .iter()
336 .filter_map(|(window_id, window)| {
337 let window = window.as_ref().unwrap();
338 if window.dirty {
339 Some(window_id)
340 } else {
341 None
342 }
343 })
344 .collect::<SmallVec<[_; 8]>>();
345
346 for dirty_window_id in dirty_window_ids {
347 self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
348 }
349 }
350
351 fn release_dropped_entities(&mut self) {
352 loop {
353 let dropped = self.entities.take_dropped();
354 if dropped.is_empty() {
355 break;
356 }
357
358 for (entity_id, mut entity) in dropped {
359 self.observers.remove(&entity_id);
360 self.event_listeners.remove(&entity_id);
361 for mut release_callback in self.release_listeners.remove(&entity_id) {
362 release_callback(&mut entity, self);
363 }
364 }
365 }
366 }
367
368 fn release_dropped_focus_handles(&mut self) {
369 let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();
370 for window_id in window_ids {
371 self.update_window(window_id, |cx| {
372 let mut blur_window = false;
373 let focus = cx.window.focus;
374 cx.window.focus_handles.write().retain(|handle_id, count| {
375 if count.load(SeqCst) == 0 {
376 if focus == Some(handle_id) {
377 blur_window = true;
378 }
379 false
380 } else {
381 true
382 }
383 });
384
385 if blur_window {
386 cx.blur();
387 }
388 })
389 .unwrap();
390 }
391 }
392
393 fn apply_notify_effect(&mut self, emitter: EntityId) {
394 self.pending_notifications.remove(&emitter);
395 self.observers
396 .clone()
397 .retain(&emitter, |handler| handler(self));
398 }
399
400 fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
401 self.event_listeners
402 .clone()
403 .retain(&emitter, |handler| handler(&event, self));
404 }
405
406 fn apply_focus_changed_effect(&mut self, window_id: WindowId, focused: Option<FocusId>) {
407 self.update_window(window_id, |cx| {
408 if cx.window.focus == focused {
409 let mut listeners = mem::take(&mut cx.window.focus_listeners);
410 let focused =
411 focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
412 let blurred = cx
413 .window
414 .last_blur
415 .take()
416 .unwrap()
417 .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
418 if focused.is_some() || blurred.is_some() {
419 let event = FocusEvent { focused, blurred };
420 for listener in &listeners {
421 listener(&event, cx);
422 }
423 }
424
425 listeners.extend(cx.window.focus_listeners.drain(..));
426 cx.window.focus_listeners = listeners;
427 }
428 })
429 .ok();
430 }
431
432 fn apply_refresh_effect(&mut self) {
433 for window in self.windows.values_mut() {
434 if let Some(window) = window.as_mut() {
435 window.dirty = true;
436 }
437 }
438 }
439
440 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
441 self.pending_global_notifications.remove(&type_id);
442 self.global_observers
443 .clone()
444 .retain(&type_id, |observer| observer(self));
445 }
446
447 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + Send + Sync + 'static>) {
448 callback(self);
449 }
450
451 pub fn to_async(&self) -> AsyncAppContext {
452 AsyncAppContext {
453 app: unsafe { mem::transmute(self.this.clone()) },
454 executor: self.executor.clone(),
455 }
456 }
457
458 pub fn executor(&self) -> &Executor {
459 &self.executor
460 }
461
462 pub fn run_on_main<R>(
463 &mut self,
464 f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
465 ) -> Task<R>
466 where
467 R: Send + 'static,
468 {
469 if self.executor.is_main_thread() {
470 Task::ready(f(unsafe {
471 mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
472 }))
473 } else {
474 let this = self.this.upgrade().unwrap();
475 self.executor.run_on_main(move || {
476 let cx = &mut *this.lock();
477 cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
478 })
479 }
480 }
481
482 pub fn spawn_on_main<F, R>(
483 &self,
484 f: impl FnOnce(MainThread<AsyncAppContext>) -> F + Send + 'static,
485 ) -> Task<R>
486 where
487 F: Future<Output = R> + 'static,
488 R: Send + 'static,
489 {
490 let cx = self.to_async();
491 self.executor.spawn_on_main(move || f(MainThread(cx)))
492 }
493
494 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
495 where
496 Fut: Future<Output = R> + Send + 'static,
497 R: Send + 'static,
498 {
499 let cx = self.to_async();
500 self.executor.spawn(async move {
501 let future = f(cx);
502 future.await
503 })
504 }
505
506 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static + Send + Sync) {
507 self.push_effect(Effect::Defer {
508 callback: Box::new(f),
509 });
510 }
511
512 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
513 &self.asset_source
514 }
515
516 pub fn text_system(&self) -> &Arc<TextSystem> {
517 &self.text_system
518 }
519
520 pub fn text_style(&self) -> TextStyle {
521 let mut style = TextStyle::default();
522 for refinement in &self.text_style_stack {
523 style.refine(refinement);
524 }
525 style
526 }
527
528 pub fn has_global<G: 'static>(&self) -> bool {
529 self.globals_by_type.contains_key(&TypeId::of::<G>())
530 }
531
532 pub fn global<G: 'static>(&self) -> &G {
533 self.globals_by_type
534 .get(&TypeId::of::<G>())
535 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
536 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
537 .unwrap()
538 }
539
540 pub fn try_global<G: 'static>(&self) -> Option<&G> {
541 self.globals_by_type
542 .get(&TypeId::of::<G>())
543 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
544 }
545
546 pub fn global_mut<G: 'static>(&mut self) -> &mut G {
547 let global_type = TypeId::of::<G>();
548 self.push_effect(Effect::NotifyGlobalObservers { global_type });
549 self.globals_by_type
550 .get_mut(&global_type)
551 .and_then(|any_state| any_state.downcast_mut::<G>())
552 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
553 .unwrap()
554 }
555
556 pub fn default_global<G: 'static + Default + Sync + Send>(&mut self) -> &mut G {
557 let global_type = TypeId::of::<G>();
558 self.push_effect(Effect::NotifyGlobalObservers { global_type });
559 self.globals_by_type
560 .entry(global_type)
561 .or_insert_with(|| Box::new(G::default()))
562 .downcast_mut::<G>()
563 .unwrap()
564 }
565
566 pub fn set_global<G: Any + Send + Sync>(&mut self, global: G) {
567 let global_type = TypeId::of::<G>();
568 self.push_effect(Effect::NotifyGlobalObservers { global_type });
569 self.globals_by_type.insert(global_type, Box::new(global));
570 }
571
572 pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
573 let mut global = self.lease_global::<G>();
574 let result = f(&mut global, self);
575 self.end_global_lease(global);
576 result
577 }
578
579 pub fn observe_global<G: 'static>(
580 &mut self,
581 mut f: impl FnMut(&mut Self) + Send + Sync + 'static,
582 ) -> Subscription {
583 self.global_observers.insert(
584 TypeId::of::<G>(),
585 Box::new(move |cx| {
586 f(cx);
587 true
588 }),
589 )
590 }
591
592 pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
593 GlobalLease::new(
594 self.globals_by_type
595 .remove(&TypeId::of::<G>())
596 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
597 .unwrap(),
598 )
599 }
600
601 pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
602 let global_type = TypeId::of::<G>();
603 self.push_effect(Effect::NotifyGlobalObservers { global_type });
604 self.globals_by_type.insert(global_type, lease.global);
605 }
606
607 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
608 self.text_style_stack.push(text_style);
609 }
610
611 pub(crate) fn pop_text_style(&mut self) {
612 self.text_style_stack.pop();
613 }
614
615 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
616 self.keymap.write().add_bindings(bindings);
617 self.pending_effects.push_back(Effect::Refresh);
618 }
619
620 pub fn on_action<A: Action>(
621 &mut self,
622 listener: impl Fn(&A, &mut Self) + Send + Sync + 'static,
623 ) {
624 self.global_action_listeners
625 .entry(TypeId::of::<A>())
626 .or_default()
627 .push(Box::new(move |action, phase, cx| {
628 if phase == DispatchPhase::Bubble {
629 let action = action.as_any().downcast_ref().unwrap();
630 listener(action, cx)
631 }
632 }));
633 }
634
635 pub fn register_action_type<A: Action>(&mut self) {
636 self.action_builders.insert(A::qualified_name(), A::build);
637 }
638
639 pub fn build_action(
640 &mut self,
641 name: &str,
642 params: Option<serde_json::Value>,
643 ) -> Result<Box<dyn Action>> {
644 let build = self
645 .action_builders
646 .get(name)
647 .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
648 (build)(params)
649 }
650
651 pub fn stop_propagation(&mut self) {
652 self.propagate_event = false;
653 }
654}
655
656impl Context for AppContext {
657 type EntityContext<'a, 'w, T> = ModelContext<'a, T>;
658 type Result<T> = T;
659
660 fn entity<T: Any + Send + Sync>(
661 &mut self,
662 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
663 ) -> Handle<T> {
664 self.update(|cx| {
665 let slot = cx.entities.reserve();
666 let entity = build_entity(&mut ModelContext::mutable(cx, slot.downgrade()));
667 cx.entities.insert(slot, entity)
668 })
669 }
670
671 fn update_entity<T: 'static, R>(
672 &mut self,
673 handle: &Handle<T>,
674 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
675 ) -> R {
676 self.update(|cx| {
677 let mut entity = cx.entities.lease(handle);
678 let result = update(
679 &mut entity,
680 &mut ModelContext::mutable(cx, handle.downgrade()),
681 );
682 cx.entities.end_lease(entity);
683 result
684 })
685 }
686}
687
688impl<C> MainThread<C>
689where
690 C: Borrow<AppContext>,
691{
692 pub(crate) fn platform(&self) -> &dyn Platform {
693 self.0.borrow().platform.borrow_on_main_thread()
694 }
695
696 pub fn activate(&self, ignoring_other_apps: bool) {
697 self.platform().activate(ignoring_other_apps);
698 }
699
700 pub fn write_to_clipboard(&self, item: ClipboardItem) {
701 self.platform().write_to_clipboard(item)
702 }
703
704 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
705 self.platform().read_from_clipboard()
706 }
707
708 pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
709 self.platform().write_credentials(url, username, password)
710 }
711
712 pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
713 self.platform().read_credentials(url)
714 }
715
716 pub fn delete_credentials(&self, url: &str) -> Result<()> {
717 self.platform().delete_credentials(url)
718 }
719
720 pub fn open_url(&self, url: &str) {
721 self.platform().open_url(url);
722 }
723}
724
725impl MainThread<AppContext> {
726 fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
727 self.0.update(|cx| {
728 update(unsafe {
729 std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
730 })
731 })
732 }
733
734 pub(crate) fn update_window<R>(
735 &mut self,
736 id: WindowId,
737 update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
738 ) -> Result<R> {
739 self.0.update_window(id, |cx| {
740 update(unsafe {
741 std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
742 })
743 })
744 }
745
746 pub fn open_window<V: 'static>(
747 &mut self,
748 options: crate::WindowOptions,
749 build_root_view: impl FnOnce(&mut WindowContext) -> View<V> + Send + 'static,
750 ) -> WindowHandle<V> {
751 self.update(|cx| {
752 let id = cx.windows.insert(None);
753 let handle = WindowHandle::new(id);
754 let mut window = Window::new(handle.into(), options, cx);
755 let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
756 window.root_view.replace(root_view.into_any());
757 cx.windows.get_mut(id).unwrap().replace(window);
758 handle
759 })
760 }
761
762 pub fn update_global<G: 'static + Send + Sync, R>(
763 &mut self,
764 update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
765 ) -> R {
766 self.0.update_global(|global, cx| {
767 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
768 update(global, cx)
769 })
770 }
771}
772
773pub(crate) enum Effect {
774 Notify {
775 emitter: EntityId,
776 },
777 Emit {
778 emitter: EntityId,
779 event: Box<dyn Any + Send + Sync + 'static>,
780 },
781 FocusChanged {
782 window_id: WindowId,
783 focused: Option<FocusId>,
784 },
785 Refresh,
786 NotifyGlobalObservers {
787 global_type: TypeId,
788 },
789 Defer {
790 callback: Box<dyn FnOnce(&mut AppContext) + Send + Sync + 'static>,
791 },
792}
793
794pub(crate) struct GlobalLease<G: 'static> {
795 global: AnyBox,
796 global_type: PhantomData<G>,
797}
798
799impl<G: 'static> GlobalLease<G> {
800 fn new(global: AnyBox) -> Self {
801 GlobalLease {
802 global,
803 global_type: PhantomData,
804 }
805 }
806}
807
808impl<G: 'static> Deref for GlobalLease<G> {
809 type Target = G;
810
811 fn deref(&self) -> &Self::Target {
812 self.global.downcast_ref().unwrap()
813 }
814}
815
816impl<G: 'static> DerefMut for GlobalLease<G> {
817 fn deref_mut(&mut self) -> &mut Self::Target {
818 self.global.downcast_mut().unwrap()
819 }
820}
821
822pub(crate) struct AnyDrag {
823 pub drag_handle_view: Option<AnyView>,
824 pub cursor_offset: Point<Pixels>,
825 pub state: AnyBox,
826 pub state_type: TypeId,
827}
828
829#[cfg(test)]
830mod tests {
831 use super::AppContext;
832
833 #[test]
834 fn test_app_context_send_sync() {
835 // This will not compile if `AppContext` does not implement `Send`
836 fn assert_send<T: Send>() {}
837 assert_send::<AppContext>();
838 }
839}