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