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