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::*;
14use uuid::Uuid;
15
16use crate::{
17 current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AnyWindowHandle,
18 AppMetadata, AssetSource, ClipboardItem, Context, DispatchPhase, DisplayId, Entity, Executor,
19 FocusEvent, FocusHandle, FocusId, KeyBinding, Keymap, LayoutId, MainThread, MainThreadOnly,
20 Pixels, Platform, PlatformDisplay, Point, Render, SharedString, SubscriberSet, Subscription,
21 SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, ViewContext, Window,
22 WindowContext, WindowHandle, WindowId,
23};
24use anyhow::{anyhow, Result};
25use collections::{HashMap, HashSet, VecDeque};
26use futures::{future::BoxFuture, Future};
27use parking_lot::Mutex;
28use slotmap::SlotMap;
29use std::{
30 any::{type_name, Any, TypeId},
31 borrow::Borrow,
32 marker::PhantomData,
33 mem,
34 ops::{Deref, DerefMut},
35 path::PathBuf,
36 rc::Rc,
37 sync::{atomic::Ordering::SeqCst, Arc, Weak},
38 time::Duration,
39};
40use util::http::{self, HttpClient};
41
42pub struct App(Arc<Mutex<AppContext>>);
43
44/// Represents an application before it is fully launched. Once your app is
45/// configured, you'll start the app with `App::run`.
46impl App {
47 /// Builds an app with the given asset source.
48 pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
49 Self(AppContext::new(
50 current_platform(),
51 asset_source,
52 http::client(),
53 ))
54 }
55
56 /// Start the application. The provided callback will be called once the
57 /// app is fully launched.
58 pub fn run<F>(self, on_finish_launching: F)
59 where
60 F: 'static + FnOnce(&mut MainThread<AppContext>),
61 {
62 let this = self.0.clone();
63 let platform = self.0.lock().platform.clone();
64 platform.borrow_on_main_thread().run(Box::new(move || {
65 let cx = &mut *this.lock();
66 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
67 on_finish_launching(cx);
68 }));
69 }
70
71 /// Register a handler to be invoked when the platform instructs the application
72 /// to open one or more URLs.
73 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
74 where
75 F: 'static + FnMut(Vec<String>, &mut AppContext),
76 {
77 let this = Arc::downgrade(&self.0);
78 self.0
79 .lock()
80 .platform
81 .borrow_on_main_thread()
82 .on_open_urls(Box::new(move |urls| {
83 if let Some(app) = this.upgrade() {
84 callback(urls, &mut app.lock());
85 }
86 }));
87 self
88 }
89
90 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
91 where
92 F: 'static + FnMut(&mut AppContext),
93 {
94 let this = Arc::downgrade(&self.0);
95 self.0
96 .lock()
97 .platform
98 .borrow_on_main_thread()
99 .on_reopen(Box::new(move || {
100 if let Some(app) = this.upgrade() {
101 callback(&mut app.lock());
102 }
103 }));
104 self
105 }
106
107 pub fn metadata(&self) -> AppMetadata {
108 self.0.lock().app_metadata.clone()
109 }
110
111 pub fn executor(&self) -> Executor {
112 self.0.lock().executor.clone()
113 }
114
115 pub fn text_system(&self) -> Arc<TextSystem> {
116 self.0.lock().text_system.clone()
117 }
118}
119
120type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
121type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
122type Handler = Box<dyn FnMut(&mut AppContext) -> bool + Send + 'static>;
123type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + Send + 'static>;
124type QuitHandler = Box<dyn FnMut(&mut AppContext) -> BoxFuture<'static, ()> + Send + 'static>;
125type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + Send + 'static>;
126
127pub struct AppContext {
128 this: Weak<Mutex<AppContext>>,
129 pub(crate) platform: MainThreadOnly<dyn Platform>,
130 app_metadata: AppMetadata,
131 text_system: Arc<TextSystem>,
132 flushing_effects: bool,
133 pending_updates: usize,
134 pub(crate) active_drag: Option<AnyDrag>,
135 pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
136 pub(crate) executor: Executor,
137 pub(crate) svg_renderer: SvgRenderer,
138 asset_source: Arc<dyn AssetSource>,
139 pub(crate) image_cache: ImageCache,
140 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
141 pub(crate) globals_by_type: HashMap<TypeId, AnyBox>,
142 pub(crate) entities: EntityMap,
143 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
144 pub(crate) keymap: Arc<Mutex<Keymap>>,
145 pub(crate) global_action_listeners:
146 HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send>>>,
147 action_builders: HashMap<SharedString, ActionBuilder>,
148 pending_effects: VecDeque<Effect>,
149 pub(crate) pending_notifications: HashSet<EntityId>,
150 pub(crate) pending_global_notifications: HashSet<TypeId>,
151 pub(crate) observers: SubscriberSet<EntityId, Handler>,
152 pub(crate) event_listeners: SubscriberSet<EntityId, Listener>,
153 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
154 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
155 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
156 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
157 pub(crate) propagate_event: bool,
158}
159
160impl AppContext {
161 pub(crate) fn new(
162 platform: Arc<dyn Platform>,
163 asset_source: Arc<dyn AssetSource>,
164 http_client: Arc<dyn HttpClient>,
165 ) -> Arc<Mutex<Self>> {
166 let executor = platform.executor();
167 assert!(
168 executor.is_main_thread(),
169 "must construct App on main thread"
170 );
171
172 let text_system = Arc::new(TextSystem::new(platform.text_system()));
173 let entities = EntityMap::new();
174
175 let app_metadata = AppMetadata {
176 os_name: platform.os_name(),
177 os_version: platform.os_version().ok(),
178 app_version: platform.app_version().ok(),
179 };
180
181 Arc::new_cyclic(|this| {
182 Mutex::new(AppContext {
183 this: this.clone(),
184 text_system,
185 platform: MainThreadOnly::new(platform, executor.clone()),
186 app_metadata,
187 flushing_effects: false,
188 pending_updates: 0,
189 next_frame_callbacks: Default::default(),
190 executor,
191 svg_renderer: SvgRenderer::new(asset_source.clone()),
192 asset_source,
193 image_cache: ImageCache::new(http_client),
194 text_style_stack: Vec::new(),
195 globals_by_type: HashMap::default(),
196 entities,
197 windows: SlotMap::with_key(),
198 keymap: Arc::new(Mutex::new(Keymap::default())),
199 global_action_listeners: HashMap::default(),
200 action_builders: HashMap::default(),
201 pending_effects: VecDeque::new(),
202 pending_notifications: HashSet::default(),
203 pending_global_notifications: HashSet::default(),
204 observers: SubscriberSet::new(),
205 event_listeners: SubscriberSet::new(),
206 release_listeners: SubscriberSet::new(),
207 global_observers: SubscriberSet::new(),
208 quit_observers: SubscriberSet::new(),
209 layout_id_buffer: Default::default(),
210 propagate_event: true,
211 active_drag: None,
212 })
213 })
214 }
215
216 /// Quit the application gracefully. Handlers registered with `ModelContext::on_app_quit`
217 /// will be given 100ms to complete before exiting.
218 pub fn quit(&mut self) {
219 let mut futures = Vec::new();
220
221 self.quit_observers.clone().retain(&(), |observer| {
222 futures.push(observer(self));
223 true
224 });
225
226 self.windows.clear();
227 self.flush_effects();
228
229 let futures = futures::future::join_all(futures);
230 if self
231 .executor
232 .block_with_timeout(Duration::from_millis(100), futures)
233 .is_err()
234 {
235 log::error!("timed out waiting on app_will_quit");
236 }
237
238 self.globals_by_type.clear();
239 }
240
241 pub fn app_metadata(&self) -> AppMetadata {
242 self.app_metadata.clone()
243 }
244
245 /// Schedules all windows in the application to be redrawn. This can be called
246 /// multiple times in an update cycle and still result in a single redraw.
247 pub fn refresh(&mut self) {
248 self.pending_effects.push_back(Effect::Refresh);
249 }
250
251 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
252 self.pending_updates += 1;
253 let result = update(self);
254 if !self.flushing_effects && self.pending_updates == 1 {
255 self.flushing_effects = true;
256 self.flush_effects();
257 self.flushing_effects = false;
258 }
259 self.pending_updates -= 1;
260 result
261 }
262
263 pub fn windows(&self) -> Vec<AnyWindowHandle> {
264 self.windows
265 .values()
266 .filter_map(|window| Some(window.as_ref()?.handle.clone()))
267 .collect()
268 }
269
270 pub(crate) fn read_window<R>(
271 &mut self,
272 handle: AnyWindowHandle,
273 read: impl FnOnce(&WindowContext) -> R,
274 ) -> Result<R> {
275 let window = self
276 .windows
277 .get(handle.id)
278 .ok_or_else(|| anyhow!("window not found"))?
279 .as_ref()
280 .unwrap();
281 Ok(read(&WindowContext::immutable(self, &window)))
282 }
283
284 pub(crate) fn update_window<R>(
285 &mut self,
286 handle: AnyWindowHandle,
287 update: impl FnOnce(&mut WindowContext) -> R,
288 ) -> Result<R> {
289 self.update(|cx| {
290 let mut window = cx
291 .windows
292 .get_mut(handle.id)
293 .ok_or_else(|| anyhow!("window not found"))?
294 .take()
295 .unwrap();
296
297 let result = update(&mut WindowContext::mutable(cx, &mut window));
298
299 cx.windows
300 .get_mut(handle.id)
301 .ok_or_else(|| anyhow!("window not found"))?
302 .replace(window);
303
304 Ok(result)
305 })
306 }
307
308 pub fn update_window_root<V, R>(
309 &mut self,
310 handle: &WindowHandle<V>,
311 update: impl FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> R,
312 ) -> Result<R>
313 where
314 V: 'static + Send,
315 {
316 self.update_window(handle.any_handle, |cx| {
317 let root_view = cx
318 .window
319 .root_view
320 .as_ref()
321 .unwrap()
322 .clone()
323 .downcast()
324 .unwrap();
325 root_view.update(cx, update)
326 })
327 }
328
329 pub(crate) fn push_effect(&mut self, effect: Effect) {
330 match &effect {
331 Effect::Notify { emitter } => {
332 if !self.pending_notifications.insert(*emitter) {
333 return;
334 }
335 }
336 Effect::NotifyGlobalObservers { global_type } => {
337 if !self.pending_global_notifications.insert(*global_type) {
338 return;
339 }
340 }
341 _ => {}
342 };
343
344 self.pending_effects.push_back(effect);
345 }
346
347 /// Called at the end of AppContext::update to complete any side effects
348 /// such as notifying observers, emitting events, etc. Effects can themselves
349 /// cause effects, so we continue looping until all effects are processed.
350 fn flush_effects(&mut self) {
351 loop {
352 self.release_dropped_entities();
353 self.release_dropped_focus_handles();
354 if let Some(effect) = self.pending_effects.pop_front() {
355 match effect {
356 Effect::Notify { emitter } => {
357 self.apply_notify_effect(emitter);
358 }
359 Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
360 Effect::FocusChanged {
361 window_handle,
362 focused,
363 } => {
364 self.apply_focus_changed_effect(window_handle, focused);
365 }
366 Effect::Refresh => {
367 self.apply_refresh_effect();
368 }
369 Effect::NotifyGlobalObservers { global_type } => {
370 self.apply_notify_global_observers_effect(global_type);
371 }
372 Effect::Defer { callback } => {
373 self.apply_defer_effect(callback);
374 }
375 }
376 } else {
377 break;
378 }
379 }
380
381 let dirty_window_ids = self
382 .windows
383 .iter()
384 .filter_map(|(_, window)| {
385 let window = window.as_ref().unwrap();
386 if window.dirty {
387 Some(window.handle.clone())
388 } else {
389 None
390 }
391 })
392 .collect::<SmallVec<[_; 8]>>();
393
394 for dirty_window_handle in dirty_window_ids {
395 self.update_window(dirty_window_handle, |cx| cx.draw())
396 .unwrap();
397 }
398 }
399
400 /// Repeatedly called during `flush_effects` to release any entities whose
401 /// reference count has become zero. We invoke any release observers before dropping
402 /// each entity.
403 fn release_dropped_entities(&mut self) {
404 loop {
405 let dropped = self.entities.take_dropped();
406 if dropped.is_empty() {
407 break;
408 }
409
410 for (entity_id, mut entity) in dropped {
411 self.observers.remove(&entity_id);
412 self.event_listeners.remove(&entity_id);
413 for release_callback in self.release_listeners.remove(&entity_id) {
414 release_callback(&mut entity, self);
415 }
416 }
417 }
418 }
419
420 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
421 /// For now, we simply blur the window if this happens, but we may want to support invoking
422 /// a window blur handler to restore focus to some logical element.
423 fn release_dropped_focus_handles(&mut self) {
424 for window_handle in self.windows() {
425 self.update_window(window_handle, |cx| {
426 let mut blur_window = false;
427 let focus = cx.window.focus;
428 cx.window.focus_handles.write().retain(|handle_id, count| {
429 if count.load(SeqCst) == 0 {
430 if focus == Some(handle_id) {
431 blur_window = true;
432 }
433 false
434 } else {
435 true
436 }
437 });
438
439 if blur_window {
440 cx.blur();
441 }
442 })
443 .unwrap();
444 }
445 }
446
447 fn apply_notify_effect(&mut self, emitter: EntityId) {
448 self.pending_notifications.remove(&emitter);
449 self.observers
450 .clone()
451 .retain(&emitter, |handler| handler(self));
452 }
453
454 fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
455 self.event_listeners
456 .clone()
457 .retain(&emitter, |handler| handler(event.as_ref(), self));
458 }
459
460 fn apply_focus_changed_effect(
461 &mut self,
462 window_handle: AnyWindowHandle,
463 focused: Option<FocusId>,
464 ) {
465 self.update_window(window_handle, |cx| {
466 if cx.window.focus == focused {
467 let mut listeners = mem::take(&mut cx.window.focus_listeners);
468 let focused =
469 focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
470 let blurred = cx
471 .window
472 .last_blur
473 .take()
474 .unwrap()
475 .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
476 if focused.is_some() || blurred.is_some() {
477 let event = FocusEvent { focused, blurred };
478 for listener in &listeners {
479 listener(&event, cx);
480 }
481 }
482
483 listeners.extend(cx.window.focus_listeners.drain(..));
484 cx.window.focus_listeners = listeners;
485 }
486 })
487 .ok();
488 }
489
490 fn apply_refresh_effect(&mut self) {
491 for window in self.windows.values_mut() {
492 if let Some(window) = window.as_mut() {
493 window.dirty = true;
494 }
495 }
496 }
497
498 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
499 self.pending_global_notifications.remove(&type_id);
500 self.global_observers
501 .clone()
502 .retain(&type_id, |observer| observer(self));
503 }
504
505 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + Send + 'static>) {
506 callback(self);
507 }
508
509 /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
510 /// so it can be held across `await` points.
511 pub fn to_async(&self) -> AsyncAppContext {
512 AsyncAppContext {
513 app: unsafe { mem::transmute(self.this.clone()) },
514 executor: self.executor.clone(),
515 }
516 }
517
518 /// Obtains a reference to the executor, which can be used to spawn futures.
519 pub fn executor(&self) -> &Executor {
520 &self.executor
521 }
522
523 /// Runs the given closure on the main thread, where interaction with the platform
524 /// is possible. The given closure will be invoked with a `MainThread<AppContext>`, which
525 /// has platform-specific methods that aren't present on `AppContext`.
526 pub fn run_on_main<R>(
527 &mut self,
528 f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
529 ) -> Task<R>
530 where
531 R: Send + 'static,
532 {
533 if self.executor.is_main_thread() {
534 Task::ready(f(unsafe {
535 mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
536 }))
537 } else {
538 let this = self.this.upgrade().unwrap();
539 self.executor.run_on_main(move || {
540 let cx = &mut *this.lock();
541 cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
542 })
543 }
544 }
545
546 /// Spawns the future returned by the given function on the main thread, where interaction with
547 /// the platform is possible. The given closure will be invoked with a `MainThread<AsyncAppContext>`,
548 /// which has platform-specific methods that aren't present on `AsyncAppContext`. The future will be
549 /// polled exclusively on the main thread.
550 // todo!("I think we need somehow to prevent the MainThread<AsyncAppContext> from implementing Send")
551 pub fn spawn_on_main<F, R>(
552 &self,
553 f: impl FnOnce(MainThread<AsyncAppContext>) -> F + Send + 'static,
554 ) -> Task<R>
555 where
556 F: Future<Output = R> + 'static,
557 R: Send + 'static,
558 {
559 let cx = self.to_async();
560 self.executor.spawn_on_main(move || f(MainThread(cx)))
561 }
562
563 /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
564 /// with AsyncAppContext, which allows the application state to be accessed across await points.
565 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
566 where
567 Fut: Future<Output = R> + Send + 'static,
568 R: Send + 'static,
569 {
570 let cx = self.to_async();
571 self.executor.spawn(async move {
572 let future = f(cx);
573 future.await
574 })
575 }
576
577 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
578 /// that are currently on the stack to be returned to the app.
579 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static + Send) {
580 self.push_effect(Effect::Defer {
581 callback: Box::new(f),
582 });
583 }
584
585 /// Accessor for the application's asset source, which is provided when constructing the `App`.
586 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
587 &self.asset_source
588 }
589
590 /// Accessor for the text system.
591 pub fn text_system(&self) -> &Arc<TextSystem> {
592 &self.text_system
593 }
594
595 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
596 pub fn text_style(&self) -> TextStyle {
597 let mut style = TextStyle::default();
598 for refinement in &self.text_style_stack {
599 style.refine(refinement);
600 }
601 style
602 }
603
604 /// Check whether a global of the given type has been assigned.
605 pub fn has_global<G: 'static>(&self) -> bool {
606 self.globals_by_type.contains_key(&TypeId::of::<G>())
607 }
608
609 /// Access the global of the given type. Panics if a global for that type has not been assigned.
610 pub fn global<G: 'static>(&self) -> &G {
611 self.globals_by_type
612 .get(&TypeId::of::<G>())
613 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
614 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
615 .unwrap()
616 }
617
618 /// Access the global of the given type if a value has been assigned.
619 pub fn try_global<G: 'static>(&self) -> Option<&G> {
620 self.globals_by_type
621 .get(&TypeId::of::<G>())
622 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
623 }
624
625 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
626 pub fn global_mut<G: 'static>(&mut self) -> &mut G {
627 let global_type = TypeId::of::<G>();
628 self.push_effect(Effect::NotifyGlobalObservers { global_type });
629 self.globals_by_type
630 .get_mut(&global_type)
631 .and_then(|any_state| any_state.downcast_mut::<G>())
632 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
633 .unwrap()
634 }
635
636 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
637 /// yet been assigned.
638 pub fn default_global<G: 'static + Default + Send>(&mut self) -> &mut G {
639 let global_type = TypeId::of::<G>();
640 self.push_effect(Effect::NotifyGlobalObservers { global_type });
641 self.globals_by_type
642 .entry(global_type)
643 .or_insert_with(|| Box::new(G::default()))
644 .downcast_mut::<G>()
645 .unwrap()
646 }
647
648 /// Set the value of the global of the given type.
649 pub fn set_global<G: Any + Send>(&mut self, global: G) {
650 let global_type = TypeId::of::<G>();
651 self.push_effect(Effect::NotifyGlobalObservers { global_type });
652 self.globals_by_type.insert(global_type, Box::new(global));
653 }
654
655 /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
656 /// your closure with mutable access to the `AppContext` and the global simultaneously.
657 pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
658 let mut global = self.lease_global::<G>();
659 let result = f(&mut global, self);
660 self.end_global_lease(global);
661 result
662 }
663
664 /// Register a callback to be invoked when a global of the given type is updated.
665 pub fn observe_global<G: 'static>(
666 &mut self,
667 mut f: impl FnMut(&mut Self) + Send + 'static,
668 ) -> Subscription {
669 self.global_observers.insert(
670 TypeId::of::<G>(),
671 Box::new(move |cx| {
672 f(cx);
673 true
674 }),
675 )
676 }
677
678 pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = SharedString> + 'a {
679 self.action_builders.keys().cloned()
680 }
681
682 /// Move the global of the given type to the stack.
683 pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
684 GlobalLease::new(
685 self.globals_by_type
686 .remove(&TypeId::of::<G>())
687 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
688 .unwrap(),
689 )
690 }
691
692 /// Restore the global of the given type after it is moved to the stack.
693 pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
694 let global_type = TypeId::of::<G>();
695 self.push_effect(Effect::NotifyGlobalObservers { global_type });
696 self.globals_by_type.insert(global_type, lease.global);
697 }
698
699 pub fn observe_release<E, T>(
700 &mut self,
701 handle: &E,
702 on_release: impl FnOnce(&mut T, &mut AppContext) + Send + 'static,
703 ) -> Subscription
704 where
705 E: Entity<T>,
706 T: 'static,
707 {
708 self.release_listeners.insert(
709 handle.entity_id(),
710 Box::new(move |entity, cx| {
711 let entity = entity.downcast_mut().expect("invalid entity type");
712 on_release(entity, cx)
713 }),
714 )
715 }
716
717 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
718 self.text_style_stack.push(text_style);
719 }
720
721 pub(crate) fn pop_text_style(&mut self) {
722 self.text_style_stack.pop();
723 }
724
725 /// Register key bindings.
726 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
727 self.keymap.lock().add_bindings(bindings);
728 self.pending_effects.push_back(Effect::Refresh);
729 }
730
731 /// Register a global listener for actions invoked via the keyboard.
732 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + Send + 'static) {
733 self.global_action_listeners
734 .entry(TypeId::of::<A>())
735 .or_default()
736 .push(Box::new(move |action, phase, cx| {
737 if phase == DispatchPhase::Bubble {
738 let action = action.as_any().downcast_ref().unwrap();
739 listener(action, cx)
740 }
741 }));
742 }
743
744 /// Register an action type to allow it to be referenced in keymaps.
745 pub fn register_action_type<A: Action>(&mut self) {
746 self.action_builders.insert(A::qualified_name(), A::build);
747 }
748
749 /// Construct an action based on its name and parameters.
750 pub fn build_action(
751 &mut self,
752 name: &str,
753 params: Option<serde_json::Value>,
754 ) -> Result<Box<dyn Action>> {
755 let build = self
756 .action_builders
757 .get(name)
758 .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
759 (build)(params)
760 }
761
762 /// Halt propagation of a mouse event, keyboard event, or action. This prevents listeners
763 /// that have not yet been invoked from receiving the event.
764 pub fn stop_propagation(&mut self) {
765 self.propagate_event = false;
766 }
767}
768
769impl Context for AppContext {
770 type ModelContext<'a, T> = ModelContext<'a, T>;
771 type Result<T> = T;
772
773 /// Build an entity that is owned by the application. The given function will be invoked with
774 /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
775 /// which can be used to access the entity in a context.
776 fn build_model<T: 'static + Send>(
777 &mut self,
778 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
779 ) -> Model<T> {
780 self.update(|cx| {
781 let slot = cx.entities.reserve();
782 let entity = build_model(&mut ModelContext::mutable(cx, slot.downgrade()));
783 cx.entities.insert(slot, entity)
784 })
785 }
786
787 /// Update the entity referenced by the given model. The function is passed a mutable reference to the
788 /// entity along with a `ModelContext` for the entity.
789 fn update_model<T: 'static, R>(
790 &mut self,
791 model: &Model<T>,
792 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
793 ) -> R {
794 self.update(|cx| {
795 let mut entity = cx.entities.lease(model);
796 let result = update(
797 &mut entity,
798 &mut ModelContext::mutable(cx, model.downgrade()),
799 );
800 cx.entities.end_lease(entity);
801 result
802 })
803 }
804}
805
806impl<C> MainThread<C>
807where
808 C: Borrow<AppContext>,
809{
810 pub(crate) fn platform(&self) -> &dyn Platform {
811 self.0.borrow().platform.borrow_on_main_thread()
812 }
813
814 /// Instructs the platform to activate the application by bringing it to the foreground.
815 pub fn activate(&self, ignoring_other_apps: bool) {
816 self.platform().activate(ignoring_other_apps);
817 }
818
819 /// Writes data to the platform clipboard.
820 pub fn write_to_clipboard(&self, item: ClipboardItem) {
821 self.platform().write_to_clipboard(item)
822 }
823
824 /// Reads data from the platform clipboard.
825 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
826 self.platform().read_from_clipboard()
827 }
828
829 /// Writes credentials to the platform keychain.
830 pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
831 self.platform().write_credentials(url, username, password)
832 }
833
834 /// Reads credentials from the platform keychain.
835 pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
836 self.platform().read_credentials(url)
837 }
838
839 /// Deletes credentials from the platform keychain.
840 pub fn delete_credentials(&self, url: &str) -> Result<()> {
841 self.platform().delete_credentials(url)
842 }
843
844 /// Directs the platform's default browser to open the given URL.
845 pub fn open_url(&self, url: &str) {
846 self.platform().open_url(url);
847 }
848
849 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
850 self.platform().path_for_auxiliary_executable(name)
851 }
852
853 pub fn display_for_uuid(&self, uuid: Uuid) -> Option<Rc<dyn PlatformDisplay>> {
854 self.platform()
855 .displays()
856 .into_iter()
857 .find(|display| display.uuid().ok() == Some(uuid))
858 }
859}
860
861impl MainThread<AppContext> {
862 fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
863 self.0.update(|cx| {
864 update(unsafe {
865 std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
866 })
867 })
868 }
869
870 pub fn update_window<R>(
871 &mut self,
872 handle: AnyWindowHandle,
873 update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
874 ) -> Result<R> {
875 self.0.update_window(handle, |cx| {
876 update(unsafe {
877 std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
878 })
879 })
880 }
881
882 pub fn update_window_root<V, R>(
883 &mut self,
884 handle: &WindowHandle<V>,
885 update: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, '_, V>>) -> R,
886 ) -> Result<R>
887 where
888 V: 'static + Send,
889 {
890 self.update_window(handle.any_handle, |cx| {
891 let root_view = cx
892 .window
893 .root_view
894 .as_ref()
895 .unwrap()
896 .clone()
897 .downcast()
898 .unwrap();
899 root_view.update(cx, update)
900 })
901 }
902
903 /// Opens a new window with the given option and the root view returned by the given function.
904 /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
905 /// functionality.
906 pub fn open_window<V: Render>(
907 &mut self,
908 options: crate::WindowOptions,
909 build_root_view: impl FnOnce(&mut WindowContext) -> View<V> + Send + 'static,
910 ) -> WindowHandle<V> {
911 self.update(|cx| {
912 let id = cx.windows.insert(None);
913 let handle = WindowHandle::new(id);
914 let mut window = Window::new(handle.into(), options, cx);
915 let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
916 window.root_view.replace(root_view.into());
917 cx.windows.get_mut(id).unwrap().replace(window);
918 handle
919 })
920 }
921
922 /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
923 /// your closure with mutable access to the `MainThread<AppContext>` and the global simultaneously.
924 pub fn update_global<G: 'static + Send, R>(
925 &mut self,
926 update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
927 ) -> R {
928 self.0.update_global(|global, cx| {
929 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
930 update(global, cx)
931 })
932 }
933}
934
935/// These effects are processed at the end of each application update cycle.
936pub(crate) enum Effect {
937 Notify {
938 emitter: EntityId,
939 },
940 Emit {
941 emitter: EntityId,
942 event: Box<dyn Any + Send + 'static>,
943 },
944 FocusChanged {
945 window_handle: AnyWindowHandle,
946 focused: Option<FocusId>,
947 },
948 Refresh,
949 NotifyGlobalObservers {
950 global_type: TypeId,
951 },
952 Defer {
953 callback: Box<dyn FnOnce(&mut AppContext) + Send + 'static>,
954 },
955}
956
957/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
958pub(crate) struct GlobalLease<G: 'static> {
959 global: AnyBox,
960 global_type: PhantomData<G>,
961}
962
963impl<G: 'static> GlobalLease<G> {
964 fn new(global: AnyBox) -> Self {
965 GlobalLease {
966 global,
967 global_type: PhantomData,
968 }
969 }
970}
971
972impl<G: 'static> Deref for GlobalLease<G> {
973 type Target = G;
974
975 fn deref(&self) -> &Self::Target {
976 self.global.downcast_ref().unwrap()
977 }
978}
979
980impl<G: 'static> DerefMut for GlobalLease<G> {
981 fn deref_mut(&mut self) -> &mut Self::Target {
982 self.global.downcast_mut().unwrap()
983 }
984}
985
986/// Contains state associated with an active drag operation, started by dragging an element
987/// within the window or by dragging into the app from the underlying platform.
988pub(crate) struct AnyDrag {
989 pub view: AnyView,
990 pub cursor_offset: Point<Pixels>,
991}
992
993#[cfg(test)]
994mod tests {
995 use super::AppContext;
996
997 #[test]
998 fn test_app_context_send_sync() {
999 // This will not compile if `AppContext` does not implement `Send`
1000 fn assert_send<T: Send>() {}
1001 assert_send::<AppContext>();
1002 }
1003}