1mod async_context;
2mod entity_map;
3mod model_context;
4#[cfg(any(test, feature = "test-support"))]
5mod test_context;
6
7pub use async_context::*;
8use derive_more::{Deref, DerefMut};
9pub use entity_map::*;
10pub use model_context::*;
11use refineable::Refineable;
12use smol::future::FutureExt;
13#[cfg(any(test, feature = "test-support"))]
14pub use test_context::*;
15use time::UtcOffset;
16
17use crate::{
18 current_platform, image_cache::ImageCache, init_app_menus, Action, ActionRegistry, Any,
19 AnyView, AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
20 DispatchPhase, DisplayId, Entity, EventEmitter, ForegroundExecutor, KeyBinding, Keymap,
21 Keystroke, LayoutId, Menu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render,
22 SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement,
23 TextSystem, View, ViewContext, Window, WindowContext, WindowHandle, WindowId,
24};
25use anyhow::{anyhow, Result};
26use collections::{FxHashMap, FxHashSet, VecDeque};
27use futures::{channel::oneshot, future::LocalBoxFuture, Future};
28use parking_lot::Mutex;
29use slotmap::SlotMap;
30use std::{
31 any::{type_name, TypeId},
32 cell::{Ref, RefCell, RefMut},
33 marker::PhantomData,
34 mem,
35 ops::{Deref, DerefMut},
36 path::{Path, PathBuf},
37 rc::{Rc, Weak},
38 sync::{atomic::Ordering::SeqCst, Arc},
39 time::Duration,
40};
41use util::{
42 http::{self, HttpClient},
43 ResultExt,
44};
45
46/// Temporary(?) wrapper around RefCell<AppContext> to help us debug any double borrows.
47/// Strongly consider removing after stabilization.
48pub struct AppCell {
49 app: RefCell<AppContext>,
50}
51
52impl AppCell {
53 #[track_caller]
54 pub fn borrow(&self) -> AppRef {
55 if option_env!("TRACK_THREAD_BORROWS").is_some() {
56 let thread_id = std::thread::current().id();
57 eprintln!("borrowed {thread_id:?}");
58 }
59 AppRef(self.app.borrow())
60 }
61
62 #[track_caller]
63 pub fn borrow_mut(&self) -> AppRefMut {
64 if option_env!("TRACK_THREAD_BORROWS").is_some() {
65 let thread_id = std::thread::current().id();
66 eprintln!("borrowed {thread_id:?}");
67 }
68 AppRefMut(self.app.borrow_mut())
69 }
70}
71
72#[derive(Deref, DerefMut)]
73pub struct AppRef<'a>(Ref<'a, AppContext>);
74
75impl<'a> Drop for AppRef<'a> {
76 fn drop(&mut self) {
77 if option_env!("TRACK_THREAD_BORROWS").is_some() {
78 let thread_id = std::thread::current().id();
79 eprintln!("dropped borrow from {thread_id:?}");
80 }
81 }
82}
83
84#[derive(Deref, DerefMut)]
85pub struct AppRefMut<'a>(RefMut<'a, AppContext>);
86
87impl<'a> Drop for AppRefMut<'a> {
88 fn drop(&mut self) {
89 if option_env!("TRACK_THREAD_BORROWS").is_some() {
90 let thread_id = std::thread::current().id();
91 eprintln!("dropped {thread_id:?}");
92 }
93 }
94}
95
96pub struct App(Rc<AppCell>);
97
98/// Represents an application before it is fully launched. Once your app is
99/// configured, you'll start the app with `App::run`.
100impl App {
101 /// Builds an app with the given asset source.
102 pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
103 Self(AppContext::new(
104 current_platform(),
105 asset_source,
106 http::client(),
107 ))
108 }
109
110 /// Start the application. The provided callback will be called once the
111 /// app is fully launched.
112 pub fn run<F>(self, on_finish_launching: F)
113 where
114 F: 'static + FnOnce(&mut AppContext),
115 {
116 let this = self.0.clone();
117 let platform = self.0.borrow().platform.clone();
118 platform.run(Box::new(move || {
119 let cx = &mut *this.borrow_mut();
120 on_finish_launching(cx);
121 }));
122 }
123
124 /// Register a handler to be invoked when the platform instructs the application
125 /// to open one or more URLs.
126 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
127 where
128 F: 'static + FnMut(Vec<String>, &mut AppContext),
129 {
130 let this = Rc::downgrade(&self.0);
131 self.0.borrow().platform.on_open_urls(Box::new(move |urls| {
132 if let Some(app) = this.upgrade() {
133 callback(urls, &mut app.borrow_mut());
134 }
135 }));
136 self
137 }
138
139 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
140 where
141 F: 'static + FnMut(&mut AppContext),
142 {
143 let this = Rc::downgrade(&self.0);
144 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
145 if let Some(app) = this.upgrade() {
146 callback(&mut app.borrow_mut());
147 }
148 }));
149 self
150 }
151
152 pub fn metadata(&self) -> AppMetadata {
153 self.0.borrow().app_metadata.clone()
154 }
155
156 pub fn background_executor(&self) -> BackgroundExecutor {
157 self.0.borrow().background_executor.clone()
158 }
159
160 pub fn foreground_executor(&self) -> ForegroundExecutor {
161 self.0.borrow().foreground_executor.clone()
162 }
163
164 pub fn text_system(&self) -> Arc<TextSystem> {
165 self.0.borrow().text_system.clone()
166 }
167}
168
169pub(crate) type FrameCallback = Box<dyn FnOnce(&mut AppContext)>;
170type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
171type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
172type KeystrokeObserver = Box<dyn FnMut(&KeystrokeEvent, &mut WindowContext) + 'static>;
173type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
174type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
175type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
176
177// struct FrameConsumer {
178// next_frame_callbacks: Vec<FrameCallback>,
179// task: Task<()>,
180// display_linker
181// }
182
183pub struct AppContext {
184 pub(crate) this: Weak<AppCell>,
185 pub(crate) platform: Rc<dyn Platform>,
186 app_metadata: AppMetadata,
187 text_system: Arc<TextSystem>,
188 flushing_effects: bool,
189 pending_updates: usize,
190 pub(crate) actions: Rc<ActionRegistry>,
191 pub(crate) active_drag: Option<AnyDrag>,
192 pub(crate) active_tooltip: Option<AnyTooltip>,
193 pub(crate) next_frame_callbacks: FxHashMap<DisplayId, Vec<FrameCallback>>,
194 pub(crate) frame_consumers: FxHashMap<DisplayId, Task<()>>,
195 pub(crate) background_executor: BackgroundExecutor,
196 pub(crate) foreground_executor: ForegroundExecutor,
197 pub(crate) svg_renderer: SvgRenderer,
198 asset_source: Arc<dyn AssetSource>,
199 pub(crate) image_cache: ImageCache,
200 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
201 pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
202 pub(crate) entities: EntityMap,
203 pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
204 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
205 pub(crate) keymap: Arc<Mutex<Keymap>>,
206 pub(crate) global_action_listeners:
207 FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
208 pending_effects: VecDeque<Effect>,
209 pub(crate) pending_notifications: FxHashSet<EntityId>,
210 pub(crate) pending_global_notifications: FxHashSet<TypeId>,
211 pub(crate) observers: SubscriberSet<EntityId, Handler>,
212 // TypeId is the type of the event that the listener callback expects
213 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
214 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
215 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
216 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
217 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
218 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
219 pub(crate) propagate_event: bool,
220}
221
222impl AppContext {
223 pub(crate) fn new(
224 platform: Rc<dyn Platform>,
225 asset_source: Arc<dyn AssetSource>,
226 http_client: Arc<dyn HttpClient>,
227 ) -> Rc<AppCell> {
228 let executor = platform.background_executor();
229 let foreground_executor = platform.foreground_executor();
230 assert!(
231 executor.is_main_thread(),
232 "must construct App on main thread"
233 );
234
235 let text_system = Arc::new(TextSystem::new(platform.text_system()));
236 let entities = EntityMap::new();
237
238 let app_metadata = AppMetadata {
239 os_name: platform.os_name(),
240 os_version: platform.os_version().ok(),
241 app_version: platform.app_version().ok(),
242 };
243
244 let app = Rc::new_cyclic(|this| AppCell {
245 app: RefCell::new(AppContext {
246 this: this.clone(),
247 platform: platform.clone(),
248 app_metadata,
249 text_system,
250 actions: Rc::new(ActionRegistry::default()),
251 flushing_effects: false,
252 pending_updates: 0,
253 active_drag: None,
254 active_tooltip: None,
255 next_frame_callbacks: FxHashMap::default(),
256 frame_consumers: FxHashMap::default(),
257 background_executor: executor,
258 foreground_executor,
259 svg_renderer: SvgRenderer::new(asset_source.clone()),
260 asset_source,
261 image_cache: ImageCache::new(http_client),
262 text_style_stack: Vec::new(),
263 globals_by_type: FxHashMap::default(),
264 entities,
265 new_view_observers: SubscriberSet::new(),
266 windows: SlotMap::with_key(),
267 keymap: Arc::new(Mutex::new(Keymap::default())),
268 global_action_listeners: FxHashMap::default(),
269 pending_effects: VecDeque::new(),
270 pending_notifications: FxHashSet::default(),
271 pending_global_notifications: FxHashSet::default(),
272 observers: SubscriberSet::new(),
273 event_listeners: SubscriberSet::new(),
274 release_listeners: SubscriberSet::new(),
275 keystroke_observers: SubscriberSet::new(),
276 global_observers: SubscriberSet::new(),
277 quit_observers: SubscriberSet::new(),
278 layout_id_buffer: Default::default(),
279 propagate_event: true,
280 }),
281 });
282
283 init_app_menus(platform.as_ref(), &mut app.borrow_mut());
284
285 platform.on_quit(Box::new({
286 let cx = app.clone();
287 move || {
288 cx.borrow_mut().shutdown();
289 }
290 }));
291
292 app
293 }
294
295 /// Quit the application gracefully. Handlers registered with `ModelContext::on_app_quit`
296 /// will be given 100ms to complete before exiting.
297 pub fn shutdown(&mut self) {
298 let mut futures = Vec::new();
299
300 for observer in self.quit_observers.remove(&()) {
301 futures.push(observer(self));
302 }
303
304 self.windows.clear();
305 self.flush_effects();
306
307 let futures = futures::future::join_all(futures);
308 if self
309 .background_executor
310 .block_with_timeout(Duration::from_millis(100), futures)
311 .is_err()
312 {
313 log::error!("timed out waiting on app_will_quit");
314 }
315 }
316
317 pub fn quit(&mut self) {
318 self.platform.quit();
319 }
320
321 pub fn app_metadata(&self) -> AppMetadata {
322 self.app_metadata.clone()
323 }
324
325 /// Schedules all windows in the application to be redrawn. This can be called
326 /// multiple times in an update cycle and still result in a single redraw.
327 pub fn refresh(&mut self) {
328 self.pending_effects.push_back(Effect::Refresh);
329 }
330 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
331 self.pending_updates += 1;
332 let result = update(self);
333 if !self.flushing_effects && self.pending_updates == 1 {
334 self.flushing_effects = true;
335 self.flush_effects();
336 self.flushing_effects = false;
337 }
338 self.pending_updates -= 1;
339 result
340 }
341
342 pub fn observe<W, E>(
343 &mut self,
344 entity: &E,
345 mut on_notify: impl FnMut(E, &mut AppContext) + 'static,
346 ) -> Subscription
347 where
348 W: 'static,
349 E: Entity<W>,
350 {
351 self.observe_internal(entity, move |e, cx| {
352 on_notify(e, cx);
353 true
354 })
355 }
356
357 pub fn observe_internal<W, E>(
358 &mut self,
359 entity: &E,
360 mut on_notify: impl FnMut(E, &mut AppContext) -> bool + 'static,
361 ) -> Subscription
362 where
363 W: 'static,
364 E: Entity<W>,
365 {
366 let entity_id = entity.entity_id();
367 let handle = entity.downgrade();
368 let (subscription, activate) = self.observers.insert(
369 entity_id,
370 Box::new(move |cx| {
371 if let Some(handle) = E::upgrade_from(&handle) {
372 on_notify(handle, cx)
373 } else {
374 false
375 }
376 }),
377 );
378 self.defer(move |_| activate());
379 subscription
380 }
381
382 pub fn subscribe<T, E, Evt>(
383 &mut self,
384 entity: &E,
385 mut on_event: impl FnMut(E, &Evt, &mut AppContext) + 'static,
386 ) -> Subscription
387 where
388 T: 'static + EventEmitter<Evt>,
389 E: Entity<T>,
390 Evt: 'static,
391 {
392 self.subscribe_internal(entity, move |entity, event, cx| {
393 on_event(entity, event, cx);
394 true
395 })
396 }
397
398 pub(crate) fn subscribe_internal<T, E, Evt>(
399 &mut self,
400 entity: &E,
401 mut on_event: impl FnMut(E, &Evt, &mut AppContext) -> bool + 'static,
402 ) -> Subscription
403 where
404 T: 'static + EventEmitter<Evt>,
405 E: Entity<T>,
406 Evt: 'static,
407 {
408 let entity_id = entity.entity_id();
409 let entity = entity.downgrade();
410 let (subscription, activate) = self.event_listeners.insert(
411 entity_id,
412 (
413 TypeId::of::<Evt>(),
414 Box::new(move |event, cx| {
415 let event: &Evt = event.downcast_ref().expect("invalid event type");
416 if let Some(handle) = E::upgrade_from(&entity) {
417 on_event(handle, event, cx)
418 } else {
419 false
420 }
421 }),
422 ),
423 );
424 self.defer(move |_| activate());
425 subscription
426 }
427
428 pub fn windows(&self) -> Vec<AnyWindowHandle> {
429 self.windows
430 .values()
431 .filter_map(|window| Some(window.as_ref()?.handle))
432 .collect()
433 }
434
435 pub fn active_window(&self) -> Option<AnyWindowHandle> {
436 self.platform.active_window()
437 }
438
439 /// Opens a new window with the given option and the root view returned by the given function.
440 /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
441 /// functionality.
442 pub fn open_window<V: 'static + Render>(
443 &mut self,
444 options: crate::WindowOptions,
445 build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
446 ) -> WindowHandle<V> {
447 self.update(|cx| {
448 let id = cx.windows.insert(None);
449 let handle = WindowHandle::new(id);
450 let mut window = Window::new(handle.into(), options, cx);
451 let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
452 window.root_view.replace(root_view.into());
453 cx.windows.get_mut(id).unwrap().replace(window);
454 handle
455 })
456 }
457
458 /// Instructs the platform to activate the application by bringing it to the foreground.
459 pub fn activate(&self, ignoring_other_apps: bool) {
460 self.platform.activate(ignoring_other_apps);
461 }
462
463 pub fn hide(&self) {
464 self.platform.hide();
465 }
466
467 pub fn hide_other_apps(&self) {
468 self.platform.hide_other_apps();
469 }
470
471 pub fn unhide_other_apps(&self) {
472 self.platform.unhide_other_apps();
473 }
474
475 /// Returns the list of currently active displays.
476 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
477 self.platform.displays()
478 }
479
480 /// Writes data to the platform clipboard.
481 pub fn write_to_clipboard(&self, item: ClipboardItem) {
482 self.platform.write_to_clipboard(item)
483 }
484
485 /// Reads data from the platform clipboard.
486 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
487 self.platform.read_from_clipboard()
488 }
489
490 /// Writes credentials to the platform keychain.
491 pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
492 self.platform.write_credentials(url, username, password)
493 }
494
495 /// Reads credentials from the platform keychain.
496 pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
497 self.platform.read_credentials(url)
498 }
499
500 /// Deletes credentials from the platform keychain.
501 pub fn delete_credentials(&self, url: &str) -> Result<()> {
502 self.platform.delete_credentials(url)
503 }
504
505 /// Directs the platform's default browser to open the given URL.
506 pub fn open_url(&self, url: &str) {
507 self.platform.open_url(url);
508 }
509
510 pub fn app_path(&self) -> Result<PathBuf> {
511 self.platform.app_path()
512 }
513
514 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
515 self.platform.path_for_auxiliary_executable(name)
516 }
517
518 pub fn double_click_interval(&self) -> Duration {
519 self.platform.double_click_interval()
520 }
521
522 pub fn prompt_for_paths(
523 &self,
524 options: PathPromptOptions,
525 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
526 self.platform.prompt_for_paths(options)
527 }
528
529 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
530 self.platform.prompt_for_new_path(directory)
531 }
532
533 pub fn reveal_path(&self, path: &Path) {
534 self.platform.reveal_path(path)
535 }
536
537 pub fn should_auto_hide_scrollbars(&self) -> bool {
538 self.platform.should_auto_hide_scrollbars()
539 }
540
541 pub fn restart(&self) {
542 self.platform.restart()
543 }
544
545 pub fn local_timezone(&self) -> UtcOffset {
546 self.platform.local_timezone()
547 }
548
549 pub(crate) fn push_effect(&mut self, effect: Effect) {
550 match &effect {
551 Effect::Notify { emitter } => {
552 if !self.pending_notifications.insert(*emitter) {
553 return;
554 }
555 }
556 Effect::NotifyGlobalObservers { global_type } => {
557 if !self.pending_global_notifications.insert(*global_type) {
558 return;
559 }
560 }
561 _ => {}
562 };
563
564 self.pending_effects.push_back(effect);
565 }
566
567 /// Called at the end of AppContext::update to complete any side effects
568 /// such as notifying observers, emitting events, etc. Effects can themselves
569 /// cause effects, so we continue looping until all effects are processed.
570 fn flush_effects(&mut self) {
571 loop {
572 self.release_dropped_entities();
573 self.release_dropped_focus_handles();
574
575 if let Some(effect) = self.pending_effects.pop_front() {
576 match effect {
577 Effect::Notify { emitter } => {
578 self.apply_notify_effect(emitter);
579 }
580
581 Effect::Emit {
582 emitter,
583 event_type,
584 event,
585 } => self.apply_emit_effect(emitter, event_type, event),
586
587 Effect::Refresh => {
588 self.apply_refresh_effect();
589 }
590
591 Effect::NotifyGlobalObservers { global_type } => {
592 self.apply_notify_global_observers_effect(global_type);
593 }
594
595 Effect::Defer { callback } => {
596 self.apply_defer_effect(callback);
597 }
598 }
599 } else {
600 for window in self.windows.values() {
601 if let Some(window) = window.as_ref() {
602 if window.dirty {
603 window.platform_window.invalidate();
604 }
605 }
606 }
607
608 #[cfg(any(test, feature = "test-support"))]
609 for window in self
610 .windows
611 .values()
612 .filter_map(|window| {
613 let window = window.as_ref()?;
614 (window.dirty || window.focus_invalidated).then_some(window.handle)
615 })
616 .collect::<Vec<_>>()
617 {
618 self.update_window(window, |_, cx| cx.draw()).unwrap();
619 }
620
621 if self.pending_effects.is_empty() {
622 break;
623 }
624 }
625 }
626 }
627
628 /// Repeatedly called during `flush_effects` to release any entities whose
629 /// reference count has become zero. We invoke any release observers before dropping
630 /// each entity.
631 fn release_dropped_entities(&mut self) {
632 loop {
633 let dropped = self.entities.take_dropped();
634 if dropped.is_empty() {
635 break;
636 }
637
638 for (entity_id, mut entity) in dropped {
639 self.observers.remove(&entity_id);
640 self.event_listeners.remove(&entity_id);
641 for release_callback in self.release_listeners.remove(&entity_id) {
642 release_callback(entity.as_mut(), self);
643 }
644 }
645 }
646 }
647
648 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
649 fn release_dropped_focus_handles(&mut self) {
650 for window_handle in self.windows() {
651 window_handle
652 .update(self, |_, cx| {
653 let mut blur_window = false;
654 let focus = cx.window.focus;
655 cx.window.focus_handles.write().retain(|handle_id, count| {
656 if count.load(SeqCst) == 0 {
657 if focus == Some(handle_id) {
658 blur_window = true;
659 }
660 false
661 } else {
662 true
663 }
664 });
665
666 if blur_window {
667 cx.blur();
668 }
669 })
670 .unwrap();
671 }
672 }
673
674 fn apply_notify_effect(&mut self, emitter: EntityId) {
675 self.pending_notifications.remove(&emitter);
676
677 self.observers
678 .clone()
679 .retain(&emitter, |handler| handler(self));
680 }
681
682 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
683 self.event_listeners
684 .clone()
685 .retain(&emitter, |(stored_type, handler)| {
686 if *stored_type == event_type {
687 handler(event.as_ref(), self)
688 } else {
689 true
690 }
691 });
692 }
693
694 fn apply_refresh_effect(&mut self) {
695 for window in self.windows.values_mut() {
696 if let Some(window) = window.as_mut() {
697 window.dirty = true;
698 }
699 }
700 }
701
702 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
703 self.pending_global_notifications.remove(&type_id);
704 self.global_observers
705 .clone()
706 .retain(&type_id, |observer| observer(self));
707 }
708
709 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
710 callback(self);
711 }
712
713 /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
714 /// so it can be held across `await` points.
715 pub fn to_async(&self) -> AsyncAppContext {
716 AsyncAppContext {
717 app: unsafe { mem::transmute(self.this.clone()) },
718 background_executor: self.background_executor.clone(),
719 foreground_executor: self.foreground_executor.clone(),
720 }
721 }
722
723 /// Obtains a reference to the executor, which can be used to spawn futures.
724 pub fn background_executor(&self) -> &BackgroundExecutor {
725 &self.background_executor
726 }
727
728 /// Obtains a reference to the executor, which can be used to spawn futures.
729 pub fn foreground_executor(&self) -> &ForegroundExecutor {
730 &self.foreground_executor
731 }
732
733 /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
734 /// with AsyncAppContext, which allows the application state to be accessed across await points.
735 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
736 where
737 Fut: Future<Output = R> + 'static,
738 R: 'static,
739 {
740 self.foreground_executor.spawn(f(self.to_async()))
741 }
742
743 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
744 /// that are currently on the stack to be returned to the app.
745 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
746 self.push_effect(Effect::Defer {
747 callback: Box::new(f),
748 });
749 }
750
751 /// Accessor for the application's asset source, which is provided when constructing the `App`.
752 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
753 &self.asset_source
754 }
755
756 /// Accessor for the text system.
757 pub fn text_system(&self) -> &Arc<TextSystem> {
758 &self.text_system
759 }
760
761 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
762 pub fn text_style(&self) -> TextStyle {
763 let mut style = TextStyle::default();
764 for refinement in &self.text_style_stack {
765 style.refine(refinement);
766 }
767 style
768 }
769
770 /// Check whether a global of the given type has been assigned.
771 pub fn has_global<G: 'static>(&self) -> bool {
772 self.globals_by_type.contains_key(&TypeId::of::<G>())
773 }
774
775 /// Access the global of the given type. Panics if a global for that type has not been assigned.
776 #[track_caller]
777 pub fn global<G: 'static>(&self) -> &G {
778 self.globals_by_type
779 .get(&TypeId::of::<G>())
780 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
781 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
782 .unwrap()
783 }
784
785 /// Access the global of the given type if a value has been assigned.
786 pub fn try_global<G: 'static>(&self) -> Option<&G> {
787 self.globals_by_type
788 .get(&TypeId::of::<G>())
789 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
790 }
791
792 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
793 #[track_caller]
794 pub fn global_mut<G: 'static>(&mut self) -> &mut G {
795 let global_type = TypeId::of::<G>();
796 self.push_effect(Effect::NotifyGlobalObservers { global_type });
797 self.globals_by_type
798 .get_mut(&global_type)
799 .and_then(|any_state| any_state.downcast_mut::<G>())
800 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
801 .unwrap()
802 }
803
804 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
805 /// yet been assigned.
806 pub fn default_global<G: 'static + Default>(&mut self) -> &mut G {
807 let global_type = TypeId::of::<G>();
808 self.push_effect(Effect::NotifyGlobalObservers { global_type });
809 self.globals_by_type
810 .entry(global_type)
811 .or_insert_with(|| Box::<G>::default())
812 .downcast_mut::<G>()
813 .unwrap()
814 }
815
816 /// Set the value of the global of the given type.
817 pub fn set_global<G: Any>(&mut self, global: G) {
818 let global_type = TypeId::of::<G>();
819 self.push_effect(Effect::NotifyGlobalObservers { global_type });
820 self.globals_by_type.insert(global_type, Box::new(global));
821 }
822
823 /// Clear all stored globals. Does not notify global observers.
824 #[cfg(any(test, feature = "test-support"))]
825 pub fn clear_globals(&mut self) {
826 self.globals_by_type.drain();
827 }
828
829 /// Remove the global of the given type from the app context. Does not notify global observers.
830 pub fn remove_global<G: Any>(&mut self) -> G {
831 let global_type = TypeId::of::<G>();
832 *self
833 .globals_by_type
834 .remove(&global_type)
835 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
836 .downcast()
837 .unwrap()
838 }
839
840 /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
841 /// your closure with mutable access to the `AppContext` and the global simultaneously.
842 pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
843 let mut global = self.lease_global::<G>();
844 let result = f(&mut global, self);
845 self.end_global_lease(global);
846 result
847 }
848
849 /// Register a callback to be invoked when a global of the given type is updated.
850 pub fn observe_global<G: 'static>(
851 &mut self,
852 mut f: impl FnMut(&mut Self) + 'static,
853 ) -> Subscription {
854 let (subscription, activate) = self.global_observers.insert(
855 TypeId::of::<G>(),
856 Box::new(move |cx| {
857 f(cx);
858 true
859 }),
860 );
861 self.defer(move |_| activate());
862 subscription
863 }
864
865 /// Move the global of the given type to the stack.
866 pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
867 GlobalLease::new(
868 self.globals_by_type
869 .remove(&TypeId::of::<G>())
870 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
871 .unwrap(),
872 )
873 }
874
875 /// Restore the global of the given type after it is moved to the stack.
876 pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
877 let global_type = TypeId::of::<G>();
878 self.push_effect(Effect::NotifyGlobalObservers { global_type });
879 self.globals_by_type.insert(global_type, lease.global);
880 }
881
882 pub fn observe_new_views<V: 'static>(
883 &mut self,
884 on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
885 ) -> Subscription {
886 let (subscription, activate) = self.new_view_observers.insert(
887 TypeId::of::<V>(),
888 Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
889 any_view
890 .downcast::<V>()
891 .unwrap()
892 .update(cx, |view_state, cx| {
893 on_new(view_state, cx);
894 })
895 }),
896 );
897 activate();
898 subscription
899 }
900
901 pub fn observe_release<E, T>(
902 &mut self,
903 handle: &E,
904 on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
905 ) -> Subscription
906 where
907 E: Entity<T>,
908 T: 'static,
909 {
910 let (subscription, activate) = self.release_listeners.insert(
911 handle.entity_id(),
912 Box::new(move |entity, cx| {
913 let entity = entity.downcast_mut().expect("invalid entity type");
914 on_release(entity, cx)
915 }),
916 );
917 activate();
918 subscription
919 }
920
921 pub fn observe_keystrokes(
922 &mut self,
923 f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
924 ) -> Subscription {
925 let (subscription, activate) = self.keystroke_observers.insert((), Box::new(f));
926 activate();
927 subscription
928 }
929
930 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
931 self.text_style_stack.push(text_style);
932 }
933
934 pub(crate) fn pop_text_style(&mut self) {
935 self.text_style_stack.pop();
936 }
937
938 /// Register key bindings.
939 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
940 self.keymap.lock().add_bindings(bindings);
941 self.pending_effects.push_back(Effect::Refresh);
942 }
943
944 /// Register a global listener for actions invoked via the keyboard.
945 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
946 self.global_action_listeners
947 .entry(TypeId::of::<A>())
948 .or_default()
949 .push(Rc::new(move |action, phase, cx| {
950 if phase == DispatchPhase::Bubble {
951 let action = action.downcast_ref().unwrap();
952 listener(action, cx)
953 }
954 }));
955 }
956
957 /// Event handlers propagate events by default. Call this method to stop dispatching to
958 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
959 /// the opposite of [propagate]. It's also possible to cancel a call to [propagate] by
960 /// calling this method before effects are flushed.
961 pub fn stop_propagation(&mut self) {
962 self.propagate_event = false;
963 }
964
965 /// Action handlers stop propagation by default during the bubble phase of action dispatch
966 /// dispatching to action handlers higher in the element tree. This is the opposite of
967 /// [stop_propagation]. It's also possible to cancel a call to [stop_propagate] by calling
968 /// this method before effects are flushed.
969 pub fn propagate(&mut self) {
970 self.propagate_event = true;
971 }
972
973 pub fn build_action(
974 &self,
975 name: &str,
976 data: Option<serde_json::Value>,
977 ) -> Result<Box<dyn Action>> {
978 self.actions.build_action(name, data)
979 }
980
981 pub fn all_action_names(&self) -> &[SharedString] {
982 self.actions.all_action_names()
983 }
984
985 pub fn on_app_quit<Fut>(
986 &mut self,
987 mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
988 ) -> Subscription
989 where
990 Fut: 'static + Future<Output = ()>,
991 {
992 let (subscription, activate) = self.quit_observers.insert(
993 (),
994 Box::new(move |cx| {
995 let future = on_quit(cx);
996 future.boxed_local()
997 }),
998 );
999 activate();
1000 subscription
1001 }
1002
1003 pub(crate) fn clear_pending_keystrokes(&mut self) {
1004 for window in self.windows() {
1005 window
1006 .update(self, |_, cx| {
1007 cx.window
1008 .rendered_frame
1009 .dispatch_tree
1010 .clear_pending_keystrokes();
1011 cx.window
1012 .next_frame
1013 .dispatch_tree
1014 .clear_pending_keystrokes();
1015 })
1016 .ok();
1017 }
1018 }
1019
1020 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1021 if let Some(window) = self.active_window() {
1022 if let Ok(window_action_available) =
1023 window.update(self, |_, cx| cx.is_action_available(action))
1024 {
1025 return window_action_available;
1026 }
1027 }
1028
1029 self.global_action_listeners
1030 .contains_key(&action.as_any().type_id())
1031 }
1032
1033 pub fn set_menus(&mut self, menus: Vec<Menu>) {
1034 self.platform.set_menus(menus, &self.keymap.lock());
1035 }
1036
1037 pub fn dispatch_action(&mut self, action: &dyn Action) {
1038 if let Some(active_window) = self.active_window() {
1039 active_window
1040 .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1041 .log_err();
1042 } else {
1043 self.propagate_event = true;
1044
1045 if let Some(mut global_listeners) = self
1046 .global_action_listeners
1047 .remove(&action.as_any().type_id())
1048 {
1049 for listener in &global_listeners {
1050 listener(action.as_any(), DispatchPhase::Capture, self);
1051 if !self.propagate_event {
1052 break;
1053 }
1054 }
1055
1056 global_listeners.extend(
1057 self.global_action_listeners
1058 .remove(&action.as_any().type_id())
1059 .unwrap_or_default(),
1060 );
1061
1062 self.global_action_listeners
1063 .insert(action.as_any().type_id(), global_listeners);
1064 }
1065
1066 if self.propagate_event {
1067 if let Some(mut global_listeners) = self
1068 .global_action_listeners
1069 .remove(&action.as_any().type_id())
1070 {
1071 for listener in global_listeners.iter().rev() {
1072 listener(action.as_any(), DispatchPhase::Bubble, self);
1073 if !self.propagate_event {
1074 break;
1075 }
1076 }
1077
1078 global_listeners.extend(
1079 self.global_action_listeners
1080 .remove(&action.as_any().type_id())
1081 .unwrap_or_default(),
1082 );
1083
1084 self.global_action_listeners
1085 .insert(action.as_any().type_id(), global_listeners);
1086 }
1087 }
1088 }
1089 }
1090
1091 pub fn has_active_drag(&self) -> bool {
1092 self.active_drag.is_some()
1093 }
1094
1095 pub fn active_drag<T: 'static>(&self) -> Option<&T> {
1096 self.active_drag
1097 .as_ref()
1098 .and_then(|drag| drag.value.downcast_ref())
1099 }
1100}
1101
1102impl Context for AppContext {
1103 type Result<T> = T;
1104
1105 /// Build an entity that is owned by the application. The given function will be invoked with
1106 /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
1107 /// which can be used to access the entity in a context.
1108 fn new_model<T: 'static>(
1109 &mut self,
1110 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1111 ) -> Model<T> {
1112 self.update(|cx| {
1113 let slot = cx.entities.reserve();
1114 let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1115 cx.entities.insert(slot, entity)
1116 })
1117 }
1118
1119 /// Update the entity referenced by the given model. The function is passed a mutable reference to the
1120 /// entity along with a `ModelContext` for the entity.
1121 fn update_model<T: 'static, R>(
1122 &mut self,
1123 model: &Model<T>,
1124 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1125 ) -> R {
1126 self.update(|cx| {
1127 let mut entity = cx.entities.lease(model);
1128 let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1129 cx.entities.end_lease(entity);
1130 result
1131 })
1132 }
1133
1134 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1135 where
1136 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1137 {
1138 self.update(|cx| {
1139 let mut window = cx
1140 .windows
1141 .get_mut(handle.id)
1142 .ok_or_else(|| anyhow!("window not found"))?
1143 .take()
1144 .unwrap();
1145
1146 let root_view = window.root_view.clone().unwrap();
1147 let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1148
1149 if window.removed {
1150 cx.windows.remove(handle.id);
1151 } else {
1152 cx.windows
1153 .get_mut(handle.id)
1154 .ok_or_else(|| anyhow!("window not found"))?
1155 .replace(window);
1156 }
1157
1158 Ok(result)
1159 })
1160 }
1161
1162 fn read_model<T, R>(
1163 &self,
1164 handle: &Model<T>,
1165 read: impl FnOnce(&T, &AppContext) -> R,
1166 ) -> Self::Result<R>
1167 where
1168 T: 'static,
1169 {
1170 let entity = self.entities.read(handle);
1171 read(entity, self)
1172 }
1173
1174 fn read_window<T, R>(
1175 &self,
1176 window: &WindowHandle<T>,
1177 read: impl FnOnce(View<T>, &AppContext) -> R,
1178 ) -> Result<R>
1179 where
1180 T: 'static,
1181 {
1182 let window = self
1183 .windows
1184 .get(window.id)
1185 .ok_or_else(|| anyhow!("window not found"))?
1186 .as_ref()
1187 .unwrap();
1188
1189 let root_view = window.root_view.clone().unwrap();
1190 let view = root_view
1191 .downcast::<T>()
1192 .map_err(|_| anyhow!("root view's type has changed"))?;
1193
1194 Ok(read(view, self))
1195 }
1196}
1197
1198/// These effects are processed at the end of each application update cycle.
1199pub(crate) enum Effect {
1200 Notify {
1201 emitter: EntityId,
1202 },
1203 Emit {
1204 emitter: EntityId,
1205 event_type: TypeId,
1206 event: Box<dyn Any>,
1207 },
1208 Refresh,
1209 NotifyGlobalObservers {
1210 global_type: TypeId,
1211 },
1212 Defer {
1213 callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1214 },
1215}
1216
1217/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1218pub(crate) struct GlobalLease<G: 'static> {
1219 global: Box<dyn Any>,
1220 global_type: PhantomData<G>,
1221}
1222
1223impl<G: 'static> GlobalLease<G> {
1224 fn new(global: Box<dyn Any>) -> Self {
1225 GlobalLease {
1226 global,
1227 global_type: PhantomData,
1228 }
1229 }
1230}
1231
1232impl<G: 'static> Deref for GlobalLease<G> {
1233 type Target = G;
1234
1235 fn deref(&self) -> &Self::Target {
1236 self.global.downcast_ref().unwrap()
1237 }
1238}
1239
1240impl<G: 'static> DerefMut for GlobalLease<G> {
1241 fn deref_mut(&mut self) -> &mut Self::Target {
1242 self.global.downcast_mut().unwrap()
1243 }
1244}
1245
1246/// Contains state associated with an active drag operation, started by dragging an element
1247/// within the window or by dragging into the app from the underlying platform.
1248pub struct AnyDrag {
1249 pub view: AnyView,
1250 pub value: Box<dyn Any>,
1251 pub cursor_offset: Point<Pixels>,
1252}
1253
1254#[derive(Clone)]
1255pub(crate) struct AnyTooltip {
1256 pub view: AnyView,
1257 pub cursor_offset: Point<Pixels>,
1258}
1259
1260#[derive(Debug)]
1261pub struct KeystrokeEvent {
1262 pub keystroke: Keystroke,
1263 pub action: Option<Box<dyn Action>>,
1264}