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