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