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