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