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