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