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