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