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