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