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