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