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