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