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