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