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