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