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