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(&self, url: &str, username: &str, password: &[u8]) -> 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) -> 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) -> 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 iniital 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 for window in self.windows.values() {
651 if let Some(window) = window.as_ref() {
652 if window.dirty {
653 window.platform_window.invalidate();
654 }
655 }
656 }
657
658 #[cfg(any(test, feature = "test-support"))]
659 for window in self
660 .windows
661 .values()
662 .filter_map(|window| {
663 let window = window.as_ref()?;
664 (window.dirty || window.focus_invalidated).then_some(window.handle)
665 })
666 .collect::<Vec<_>>()
667 {
668 self.update_window(window, |_, cx| cx.draw()).unwrap();
669 }
670
671 if self.pending_effects.is_empty() {
672 break;
673 }
674 }
675 }
676 }
677
678 /// Repeatedly called during `flush_effects` to release any entities whose
679 /// reference count has become zero. We invoke any release observers before dropping
680 /// each entity.
681 fn release_dropped_entities(&mut self) {
682 loop {
683 let dropped = self.entities.take_dropped();
684 if dropped.is_empty() {
685 break;
686 }
687
688 for (entity_id, mut entity) in dropped {
689 self.observers.remove(&entity_id);
690 self.event_listeners.remove(&entity_id);
691 for release_callback in self.release_listeners.remove(&entity_id) {
692 release_callback(entity.as_mut(), self);
693 }
694 }
695 }
696 }
697
698 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
699 fn release_dropped_focus_handles(&mut self) {
700 for window_handle in self.windows() {
701 window_handle
702 .update(self, |_, cx| {
703 let mut blur_window = false;
704 let focus = cx.window.focus;
705 cx.window.focus_handles.write().retain(|handle_id, count| {
706 if count.load(SeqCst) == 0 {
707 if focus == Some(handle_id) {
708 blur_window = true;
709 }
710 false
711 } else {
712 true
713 }
714 });
715
716 if blur_window {
717 cx.blur();
718 }
719 })
720 .unwrap();
721 }
722 }
723
724 fn apply_notify_effect(&mut self, emitter: EntityId) {
725 self.pending_notifications.remove(&emitter);
726
727 self.observers
728 .clone()
729 .retain(&emitter, |handler| handler(self));
730 }
731
732 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
733 self.event_listeners
734 .clone()
735 .retain(&emitter, |(stored_type, handler)| {
736 if *stored_type == event_type {
737 handler(event.as_ref(), self)
738 } else {
739 true
740 }
741 });
742 }
743
744 fn apply_refresh_effect(&mut self) {
745 for window in self.windows.values_mut() {
746 if let Some(window) = window.as_mut() {
747 window.dirty = true;
748 }
749 }
750 }
751
752 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
753 self.pending_global_notifications.remove(&type_id);
754 self.global_observers
755 .clone()
756 .retain(&type_id, |observer| observer(self));
757 }
758
759 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
760 callback(self);
761 }
762
763 /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
764 /// so it can be held across `await` points.
765 pub fn to_async(&self) -> AsyncAppContext {
766 AsyncAppContext {
767 app: self.this.clone(),
768 background_executor: self.background_executor.clone(),
769 foreground_executor: self.foreground_executor.clone(),
770 }
771 }
772
773 /// Obtains a reference to the executor, which can be used to spawn futures.
774 pub fn background_executor(&self) -> &BackgroundExecutor {
775 &self.background_executor
776 }
777
778 /// Obtains a reference to the executor, which can be used to spawn futures.
779 pub fn foreground_executor(&self) -> &ForegroundExecutor {
780 &self.foreground_executor
781 }
782
783 /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
784 /// with [AsyncAppContext], which allows the application state to be accessed across await points.
785 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
786 where
787 Fut: Future<Output = R> + 'static,
788 R: 'static,
789 {
790 self.foreground_executor.spawn(f(self.to_async()))
791 }
792
793 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
794 /// that are currently on the stack to be returned to the app.
795 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
796 self.push_effect(Effect::Defer {
797 callback: Box::new(f),
798 });
799 }
800
801 /// Accessor for the application's asset source, which is provided when constructing the `App`.
802 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
803 &self.asset_source
804 }
805
806 /// Accessor for the text system.
807 pub fn text_system(&self) -> &Arc<TextSystem> {
808 &self.text_system
809 }
810
811 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
812 pub fn text_style(&self) -> TextStyle {
813 let mut style = TextStyle::default();
814 for refinement in &self.text_style_stack {
815 style.refine(refinement);
816 }
817 style
818 }
819
820 /// Check whether a global of the given type has been assigned.
821 pub fn has_global<G: 'static>(&self) -> bool {
822 self.globals_by_type.contains_key(&TypeId::of::<G>())
823 }
824
825 /// Access the global of the given type. Panics if a global for that type has not been assigned.
826 #[track_caller]
827 pub fn global<G: 'static>(&self) -> &G {
828 self.globals_by_type
829 .get(&TypeId::of::<G>())
830 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
831 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
832 .unwrap()
833 }
834
835 /// Access the global of the given type if a value has been assigned.
836 pub fn try_global<G: 'static>(&self) -> Option<&G> {
837 self.globals_by_type
838 .get(&TypeId::of::<G>())
839 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
840 }
841
842 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
843 #[track_caller]
844 pub fn global_mut<G: 'static>(&mut self) -> &mut G {
845 let global_type = TypeId::of::<G>();
846 self.push_effect(Effect::NotifyGlobalObservers { global_type });
847 self.globals_by_type
848 .get_mut(&global_type)
849 .and_then(|any_state| any_state.downcast_mut::<G>())
850 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
851 .unwrap()
852 }
853
854 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
855 /// yet been assigned.
856 pub fn default_global<G: 'static + Default>(&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 .entry(global_type)
861 .or_insert_with(|| Box::<G>::default())
862 .downcast_mut::<G>()
863 .unwrap()
864 }
865
866 /// Sets the value of the global of the given type.
867 pub fn set_global<G: Any>(&mut self, global: G) {
868 let global_type = TypeId::of::<G>();
869 self.push_effect(Effect::NotifyGlobalObservers { global_type });
870 self.globals_by_type.insert(global_type, Box::new(global));
871 }
872
873 /// Clear all stored globals. Does not notify global observers.
874 #[cfg(any(test, feature = "test-support"))]
875 pub fn clear_globals(&mut self) {
876 self.globals_by_type.drain();
877 }
878
879 /// Remove the global of the given type from the app context. Does not notify global observers.
880 pub fn remove_global<G: Any>(&mut self) -> G {
881 let global_type = TypeId::of::<G>();
882 self.push_effect(Effect::NotifyGlobalObservers { global_type });
883 *self
884 .globals_by_type
885 .remove(&global_type)
886 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
887 .downcast()
888 .unwrap()
889 }
890
891 /// Updates the global of the given type with a closure. Unlike `global_mut`, this method provides
892 /// your closure with mutable access to the `AppContext` and the global simultaneously.
893 pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
894 self.update(|cx| {
895 let mut global = cx.lease_global::<G>();
896 let result = f(&mut global, cx);
897 cx.end_global_lease(global);
898 result
899 })
900 }
901
902 /// Register a callback to be invoked when a global of the given type is updated.
903 pub fn observe_global<G: 'static>(
904 &mut self,
905 mut f: impl FnMut(&mut Self) + 'static,
906 ) -> Subscription {
907 let (subscription, activate) = self.global_observers.insert(
908 TypeId::of::<G>(),
909 Box::new(move |cx| {
910 f(cx);
911 true
912 }),
913 );
914 self.defer(move |_| activate());
915 subscription
916 }
917
918 /// Move the global of the given type to the stack.
919 pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
920 GlobalLease::new(
921 self.globals_by_type
922 .remove(&TypeId::of::<G>())
923 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
924 .unwrap(),
925 )
926 }
927
928 /// Restore the global of the given type after it is moved to the stack.
929 pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
930 let global_type = TypeId::of::<G>();
931 self.push_effect(Effect::NotifyGlobalObservers { global_type });
932 self.globals_by_type.insert(global_type, lease.global);
933 }
934
935 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
936 /// The function will be passed a mutable reference to the view along with an appropriate context.
937 pub fn observe_new_views<V: 'static>(
938 &mut self,
939 on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
940 ) -> Subscription {
941 let (subscription, activate) = self.new_view_observers.insert(
942 TypeId::of::<V>(),
943 Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
944 any_view
945 .downcast::<V>()
946 .unwrap()
947 .update(cx, |view_state, cx| {
948 on_new(view_state, cx);
949 })
950 }),
951 );
952 activate();
953 subscription
954 }
955
956 /// Observe the release of a model or view. The callback is invoked after the model or view
957 /// has no more strong references but before it has been dropped.
958 pub fn observe_release<E, T>(
959 &mut self,
960 handle: &E,
961 on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
962 ) -> Subscription
963 where
964 E: Entity<T>,
965 T: 'static,
966 {
967 let (subscription, activate) = self.release_listeners.insert(
968 handle.entity_id(),
969 Box::new(move |entity, cx| {
970 let entity = entity.downcast_mut().expect("invalid entity type");
971 on_release(entity, cx)
972 }),
973 );
974 activate();
975 subscription
976 }
977
978 /// Register a callback to be invoked when a keystroke is received by the application
979 /// in any window. Note that this fires after all other action and event mechanisms have resolved
980 /// and that this API will not be invoked if the event's propagation is stopped.
981 pub fn observe_keystrokes(
982 &mut self,
983 f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
984 ) -> Subscription {
985 let (subscription, activate) = self.keystroke_observers.insert((), Box::new(f));
986 activate();
987 subscription
988 }
989
990 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
991 self.text_style_stack.push(text_style);
992 }
993
994 pub(crate) fn pop_text_style(&mut self) {
995 self.text_style_stack.pop();
996 }
997
998 /// Register key bindings.
999 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1000 self.keymap.borrow_mut().add_bindings(bindings);
1001 self.pending_effects.push_back(Effect::Refresh);
1002 }
1003
1004 /// Clear all key bindings in the app.
1005 pub fn clear_key_bindings(&mut self) {
1006 self.keymap.borrow_mut().clear();
1007 self.pending_effects.push_back(Effect::Refresh);
1008 }
1009
1010 /// Register a global listener for actions invoked via the keyboard.
1011 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1012 self.global_action_listeners
1013 .entry(TypeId::of::<A>())
1014 .or_default()
1015 .push(Rc::new(move |action, phase, cx| {
1016 if phase == DispatchPhase::Bubble {
1017 let action = action.downcast_ref().unwrap();
1018 listener(action, cx)
1019 }
1020 }));
1021 }
1022
1023 /// Event handlers propagate events by default. Call this method to stop dispatching to
1024 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1025 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1026 /// calling this method before effects are flushed.
1027 pub fn stop_propagation(&mut self) {
1028 self.propagate_event = false;
1029 }
1030
1031 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1032 /// dispatching to action handlers higher in the element tree. This is the opposite of
1033 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1034 /// this method before effects are flushed.
1035 pub fn propagate(&mut self) {
1036 self.propagate_event = true;
1037 }
1038
1039 /// Build an action from some arbitrary data, typically a keymap entry.
1040 pub fn build_action(
1041 &self,
1042 name: &str,
1043 data: Option<serde_json::Value>,
1044 ) -> Result<Box<dyn Action>> {
1045 self.actions.build_action(name, data)
1046 }
1047
1048 /// Get a list of all action names that have been registered.
1049 /// in the application. Note that registration only allows for
1050 /// actions to be built dynamically, and is unrelated to binding
1051 /// actions in the element tree.
1052 pub fn all_action_names(&self) -> &[SharedString] {
1053 self.actions.all_action_names()
1054 }
1055
1056 /// Register a callback to be invoked when the application is about to quit.
1057 /// It is not possible to cancel the quit event at this point.
1058 pub fn on_app_quit<Fut>(
1059 &mut self,
1060 mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1061 ) -> Subscription
1062 where
1063 Fut: 'static + Future<Output = ()>,
1064 {
1065 let (subscription, activate) = self.quit_observers.insert(
1066 (),
1067 Box::new(move |cx| {
1068 let future = on_quit(cx);
1069 future.boxed_local()
1070 }),
1071 );
1072 activate();
1073 subscription
1074 }
1075
1076 pub(crate) fn clear_pending_keystrokes(&mut self) {
1077 for window in self.windows() {
1078 window
1079 .update(self, |_, cx| {
1080 cx.window
1081 .rendered_frame
1082 .dispatch_tree
1083 .clear_pending_keystrokes();
1084 cx.window
1085 .next_frame
1086 .dispatch_tree
1087 .clear_pending_keystrokes();
1088 })
1089 .ok();
1090 }
1091 }
1092
1093 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1094 /// the bindings in the element tree, and any global action listeners.
1095 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1096 if let Some(window) = self.active_window() {
1097 if let Ok(window_action_available) =
1098 window.update(self, |_, cx| cx.is_action_available(action))
1099 {
1100 return window_action_available;
1101 }
1102 }
1103
1104 self.global_action_listeners
1105 .contains_key(&action.as_any().type_id())
1106 }
1107
1108 /// Sets the menu bar for this application. This will replace any existing menu bar.
1109 pub fn set_menus(&mut self, menus: Vec<Menu>) {
1110 self.platform.set_menus(menus, &self.keymap.borrow());
1111 }
1112
1113 /// Dispatch an action to the currently active window or global action handler
1114 /// See [action::Action] for more information on how actions work
1115 pub fn dispatch_action(&mut self, action: &dyn Action) {
1116 if let Some(active_window) = self.active_window() {
1117 active_window
1118 .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1119 .log_err();
1120 } else {
1121 self.propagate_event = true;
1122
1123 if let Some(mut global_listeners) = self
1124 .global_action_listeners
1125 .remove(&action.as_any().type_id())
1126 {
1127 for listener in &global_listeners {
1128 listener(action.as_any(), DispatchPhase::Capture, self);
1129 if !self.propagate_event {
1130 break;
1131 }
1132 }
1133
1134 global_listeners.extend(
1135 self.global_action_listeners
1136 .remove(&action.as_any().type_id())
1137 .unwrap_or_default(),
1138 );
1139
1140 self.global_action_listeners
1141 .insert(action.as_any().type_id(), global_listeners);
1142 }
1143
1144 if self.propagate_event {
1145 if let Some(mut global_listeners) = self
1146 .global_action_listeners
1147 .remove(&action.as_any().type_id())
1148 {
1149 for listener in global_listeners.iter().rev() {
1150 listener(action.as_any(), DispatchPhase::Bubble, self);
1151 if !self.propagate_event {
1152 break;
1153 }
1154 }
1155
1156 global_listeners.extend(
1157 self.global_action_listeners
1158 .remove(&action.as_any().type_id())
1159 .unwrap_or_default(),
1160 );
1161
1162 self.global_action_listeners
1163 .insert(action.as_any().type_id(), global_listeners);
1164 }
1165 }
1166 }
1167 }
1168
1169 /// Is there currently something being dragged?
1170 pub fn has_active_drag(&self) -> bool {
1171 self.active_drag.is_some()
1172 }
1173}
1174
1175impl Context for AppContext {
1176 type Result<T> = T;
1177
1178 /// Build an entity that is owned by the application. The given function will be invoked with
1179 /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1180 /// which can be used to access the entity in a context.
1181 fn new_model<T: 'static>(
1182 &mut self,
1183 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1184 ) -> Model<T> {
1185 self.update(|cx| {
1186 let slot = cx.entities.reserve();
1187 let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1188 cx.entities.insert(slot, entity)
1189 })
1190 }
1191
1192 /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1193 /// entity along with a `ModelContext` for the entity.
1194 fn update_model<T: 'static, R>(
1195 &mut self,
1196 model: &Model<T>,
1197 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1198 ) -> R {
1199 self.update(|cx| {
1200 let mut entity = cx.entities.lease(model);
1201 let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1202 cx.entities.end_lease(entity);
1203 result
1204 })
1205 }
1206
1207 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1208 where
1209 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1210 {
1211 self.update(|cx| {
1212 let mut window = cx
1213 .windows
1214 .get_mut(handle.id)
1215 .ok_or_else(|| anyhow!("window not found"))?
1216 .take()
1217 .unwrap();
1218
1219 let root_view = window.root_view.clone().unwrap();
1220 let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1221
1222 if window.removed {
1223 cx.windows.remove(handle.id);
1224 } else {
1225 cx.windows
1226 .get_mut(handle.id)
1227 .ok_or_else(|| anyhow!("window not found"))?
1228 .replace(window);
1229 }
1230
1231 Ok(result)
1232 })
1233 }
1234
1235 fn read_model<T, R>(
1236 &self,
1237 handle: &Model<T>,
1238 read: impl FnOnce(&T, &AppContext) -> R,
1239 ) -> Self::Result<R>
1240 where
1241 T: 'static,
1242 {
1243 let entity = self.entities.read(handle);
1244 read(entity, self)
1245 }
1246
1247 fn read_window<T, R>(
1248 &self,
1249 window: &WindowHandle<T>,
1250 read: impl FnOnce(View<T>, &AppContext) -> R,
1251 ) -> Result<R>
1252 where
1253 T: 'static,
1254 {
1255 let window = self
1256 .windows
1257 .get(window.id)
1258 .ok_or_else(|| anyhow!("window not found"))?
1259 .as_ref()
1260 .unwrap();
1261
1262 let root_view = window.root_view.clone().unwrap();
1263 let view = root_view
1264 .downcast::<T>()
1265 .map_err(|_| anyhow!("root view's type has changed"))?;
1266
1267 Ok(read(view, self))
1268 }
1269}
1270
1271/// These effects are processed at the end of each application update cycle.
1272pub(crate) enum Effect {
1273 Notify {
1274 emitter: EntityId,
1275 },
1276 Emit {
1277 emitter: EntityId,
1278 event_type: TypeId,
1279 event: Box<dyn Any>,
1280 },
1281 Refresh,
1282 NotifyGlobalObservers {
1283 global_type: TypeId,
1284 },
1285 Defer {
1286 callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1287 },
1288}
1289
1290/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1291pub(crate) struct GlobalLease<G: 'static> {
1292 global: Box<dyn Any>,
1293 global_type: PhantomData<G>,
1294}
1295
1296impl<G: 'static> GlobalLease<G> {
1297 fn new(global: Box<dyn Any>) -> Self {
1298 GlobalLease {
1299 global,
1300 global_type: PhantomData,
1301 }
1302 }
1303}
1304
1305impl<G: 'static> Deref for GlobalLease<G> {
1306 type Target = G;
1307
1308 fn deref(&self) -> &Self::Target {
1309 self.global.downcast_ref().unwrap()
1310 }
1311}
1312
1313impl<G: 'static> DerefMut for GlobalLease<G> {
1314 fn deref_mut(&mut self) -> &mut Self::Target {
1315 self.global.downcast_mut().unwrap()
1316 }
1317}
1318
1319/// Contains state associated with an active drag operation, started by dragging an element
1320/// within the window or by dragging into the app from the underlying platform.
1321pub struct AnyDrag {
1322 /// The view used to render this drag
1323 pub view: AnyView,
1324
1325 /// The value of the dragged item, to be dropped
1326 pub value: Box<dyn Any>,
1327
1328 /// This is used to render the dragged item in the same place
1329 /// on the original element that the drag was initiated
1330 pub cursor_offset: Point<Pixels>,
1331}
1332
1333/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1334/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1335#[derive(Clone)]
1336pub struct AnyTooltip {
1337 /// The view used to display the tooltip
1338 pub view: AnyView,
1339
1340 /// The offset from the cursor to use, relative to the parent view
1341 pub cursor_offset: Point<Pixels>,
1342}
1343
1344/// A keystroke event, and potentially the associated action
1345#[derive(Debug)]
1346pub struct KeystrokeEvent {
1347 /// The keystroke that occurred
1348 pub keystroke: Keystroke,
1349
1350 /// The action that was resolved for the keystroke, if any
1351 pub action: Option<Box<dyn Action>>,
1352}