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