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