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