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