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;
26use slotmap::SlotMap;
27use std::{
28 any::{type_name, Any, TypeId},
29 borrow::Borrow,
30 marker::PhantomData,
31 mem,
32 ops::{Deref, DerefMut},
33 path::PathBuf,
34 sync::{atomic::Ordering::SeqCst, Arc, Weak},
35 time::Duration,
36};
37use util::http::{self, HttpClient};
38
39pub struct App(Arc<Mutex<AppContext>>);
40
41impl App {
42 pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
43 Self(AppContext::new(
44 current_platform(),
45 asset_source,
46 http::client(),
47 ))
48 }
49
50 pub fn run<F>(self, on_finish_launching: F)
51 where
52 F: 'static + FnOnce(&mut MainThread<AppContext>),
53 {
54 let this = self.0.clone();
55 let platform = self.0.lock().platform.clone();
56 platform.borrow_on_main_thread().run(Box::new(move || {
57 let cx = &mut *this.lock();
58 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
59 on_finish_launching(cx);
60 }));
61 }
62
63 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
64 where
65 F: 'static + FnMut(Vec<String>, &mut AppContext),
66 {
67 let this = Arc::downgrade(&self.0);
68 self.0
69 .lock()
70 .platform
71 .borrow_on_main_thread()
72 .on_open_urls(Box::new(move |urls| {
73 if let Some(app) = this.upgrade() {
74 callback(urls, &mut app.lock());
75 }
76 }));
77 self
78 }
79
80 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
81 where
82 F: 'static + FnMut(&mut AppContext),
83 {
84 let this = Arc::downgrade(&self.0);
85 self.0
86 .lock()
87 .platform
88 .borrow_on_main_thread()
89 .on_reopen(Box::new(move || {
90 if let Some(app) = this.upgrade() {
91 callback(&mut app.lock());
92 }
93 }));
94 self
95 }
96
97 pub fn metadata(&self) -> AppMetadata {
98 self.0.lock().app_metadata.clone()
99 }
100
101 pub fn executor(&self) -> Executor {
102 self.0.lock().executor.clone()
103 }
104
105 pub fn text_system(&self) -> Arc<TextSystem> {
106 self.0.lock().text_system.clone()
107 }
108}
109
110type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
111type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
112type Handler = Box<dyn FnMut(&mut AppContext) -> bool + Send + 'static>;
113type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + Send + 'static>;
114type QuitHandler = Box<dyn FnMut(&mut AppContext) -> BoxFuture<'static, ()> + Send + 'static>;
115type ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + Send + '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) entities: EntityMap,
133 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
134 pub(crate) keymap: Arc<Mutex<Keymap>>,
135 pub(crate) global_action_listeners:
136 HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send>>>,
137 action_builders: HashMap<SharedString, ActionBuilder>,
138 pending_effects: VecDeque<Effect>,
139 pub(crate) pending_notifications: HashSet<EntityId>,
140 pub(crate) pending_global_notifications: HashSet<TypeId>,
141 pub(crate) observers: SubscriberSet<EntityId, Handler>,
142 pub(crate) event_listeners: SubscriberSet<EntityId, Listener>,
143 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
144 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
145 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
146 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
147 pub(crate) propagate_event: bool,
148}
149
150impl AppContext {
151 pub(crate) fn new(
152 platform: Arc<dyn Platform>,
153 asset_source: Arc<dyn AssetSource>,
154 http_client: Arc<dyn HttpClient>,
155 ) -> Arc<Mutex<Self>> {
156 let executor = platform.executor();
157 assert!(
158 executor.is_main_thread(),
159 "must construct App on main thread"
160 );
161
162 let text_system = Arc::new(TextSystem::new(platform.text_system()));
163 let entities = EntityMap::new();
164
165 let app_metadata = AppMetadata {
166 os_name: platform.os_name(),
167 os_version: platform.os_version().ok(),
168 app_version: platform.app_version().ok(),
169 };
170
171 Arc::new_cyclic(|this| {
172 Mutex::new(AppContext {
173 this: this.clone(),
174 text_system,
175 platform: MainThreadOnly::new(platform, executor.clone()),
176 app_metadata,
177 flushing_effects: false,
178 pending_updates: 0,
179 next_frame_callbacks: Default::default(),
180 executor,
181 svg_renderer: SvgRenderer::new(asset_source.clone()),
182 asset_source,
183 image_cache: ImageCache::new(http_client),
184 text_style_stack: Vec::new(),
185 globals_by_type: HashMap::default(),
186 entities,
187 windows: SlotMap::with_key(),
188 keymap: Arc::new(Mutex::new(Keymap::default())),
189 global_action_listeners: HashMap::default(),
190 action_builders: HashMap::default(),
191 pending_effects: VecDeque::new(),
192 pending_notifications: HashSet::default(),
193 pending_global_notifications: HashSet::default(),
194 observers: SubscriberSet::new(),
195 event_listeners: SubscriberSet::new(),
196 release_listeners: SubscriberSet::new(),
197 global_observers: SubscriberSet::new(),
198 quit_observers: SubscriberSet::new(),
199 layout_id_buffer: Default::default(),
200 propagate_event: true,
201 active_drag: None,
202 })
203 })
204 }
205
206 pub fn quit(&mut self) {
207 let mut futures = Vec::new();
208
209 self.quit_observers.clone().retain(&(), |observer| {
210 futures.push(observer(self));
211 true
212 });
213
214 self.windows.clear();
215 self.flush_effects();
216
217 let futures = futures::future::join_all(futures);
218 if self
219 .executor
220 .block_with_timeout(Duration::from_millis(100), futures)
221 .is_err()
222 {
223 log::error!("timed out waiting on app_will_quit");
224 }
225
226 self.globals_by_type.clear();
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.as_ref(), 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 + '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) {
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 + 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>(&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 + '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.lock().add_bindings(bindings);
617 self.pending_effects.push_back(Effect::Refresh);
618 }
619
620 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + Send + 'static) {
621 self.global_action_listeners
622 .entry(TypeId::of::<A>())
623 .or_default()
624 .push(Box::new(move |action, phase, cx| {
625 if phase == DispatchPhase::Bubble {
626 let action = action.as_any().downcast_ref().unwrap();
627 listener(action, cx)
628 }
629 }));
630 }
631
632 pub fn register_action_type<A: Action>(&mut self) {
633 self.action_builders.insert(A::qualified_name(), A::build);
634 }
635
636 pub fn build_action(
637 &mut self,
638 name: &str,
639 params: Option<serde_json::Value>,
640 ) -> Result<Box<dyn Action>> {
641 let build = self
642 .action_builders
643 .get(name)
644 .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
645 (build)(params)
646 }
647
648 pub fn stop_propagation(&mut self) {
649 self.propagate_event = false;
650 }
651}
652
653impl Context for AppContext {
654 type EntityContext<'a, T> = ModelContext<'a, T>;
655 type Result<T> = T;
656
657 fn entity<T: 'static + Send>(
658 &mut self,
659 build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
660 ) -> Handle<T> {
661 self.update(|cx| {
662 let slot = cx.entities.reserve();
663 let entity = build_entity(&mut ModelContext::mutable(cx, slot.downgrade()));
664 cx.entities.insert(slot, entity)
665 })
666 }
667
668 fn update_entity<T: 'static, R>(
669 &mut self,
670 handle: &Handle<T>,
671 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
672 ) -> R {
673 self.update(|cx| {
674 let mut entity = cx.entities.lease(handle);
675 let result = update(
676 &mut entity,
677 &mut ModelContext::mutable(cx, handle.downgrade()),
678 );
679 cx.entities.end_lease(entity);
680 result
681 })
682 }
683}
684
685impl<C> MainThread<C>
686where
687 C: Borrow<AppContext>,
688{
689 pub(crate) fn platform(&self) -> &dyn Platform {
690 self.0.borrow().platform.borrow_on_main_thread()
691 }
692
693 pub fn activate(&self, ignoring_other_apps: bool) {
694 self.platform().activate(ignoring_other_apps);
695 }
696
697 pub fn write_to_clipboard(&self, item: ClipboardItem) {
698 self.platform().write_to_clipboard(item)
699 }
700
701 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
702 self.platform().read_from_clipboard()
703 }
704
705 pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
706 self.platform().write_credentials(url, username, password)
707 }
708
709 pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
710 self.platform().read_credentials(url)
711 }
712
713 pub fn delete_credentials(&self, url: &str) -> Result<()> {
714 self.platform().delete_credentials(url)
715 }
716
717 pub fn open_url(&self, url: &str) {
718 self.platform().open_url(url);
719 }
720
721 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
722 self.platform().path_for_auxiliary_executable(name)
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, 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 + '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 + '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}