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