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