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