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