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