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 return 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 /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
661 pub fn should_auto_hide_scrollbars(&self) -> bool {
662 self.platform.should_auto_hide_scrollbars()
663 }
664
665 /// Restart the application.
666 pub fn restart(&self, binary_path: Option<PathBuf>) {
667 self.platform.restart(binary_path)
668 }
669
670 /// Updates the http client assigned to GPUI
671 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
672 self.http_client = new_client;
673 }
674
675 /// Returns the http client assigned to GPUI
676 pub fn http_client(&self) -> Arc<dyn HttpClient> {
677 self.http_client.clone()
678 }
679
680 /// Returns the SVG renderer GPUI uses
681 pub(crate) fn svg_renderer(&self) -> SvgRenderer {
682 self.svg_renderer.clone()
683 }
684
685 pub(crate) fn push_effect(&mut self, effect: Effect) {
686 match &effect {
687 Effect::Notify { emitter } => {
688 if !self.pending_notifications.insert(*emitter) {
689 return;
690 }
691 }
692 Effect::NotifyGlobalObservers { global_type } => {
693 if !self.pending_global_notifications.insert(*global_type) {
694 return;
695 }
696 }
697 _ => {}
698 };
699
700 self.pending_effects.push_back(effect);
701 }
702
703 /// Called at the end of [`AppContext::update`] to complete any side effects
704 /// such as notifying observers, emitting events, etc. Effects can themselves
705 /// cause effects, so we continue looping until all effects are processed.
706 fn flush_effects(&mut self) {
707 loop {
708 self.release_dropped_entities();
709 self.release_dropped_focus_handles();
710
711 if let Some(effect) = self.pending_effects.pop_front() {
712 match effect {
713 Effect::Notify { emitter } => {
714 self.apply_notify_effect(emitter);
715 }
716
717 Effect::Emit {
718 emitter,
719 event_type,
720 event,
721 } => self.apply_emit_effect(emitter, event_type, event),
722
723 Effect::Refresh => {
724 self.apply_refresh_effect();
725 }
726
727 Effect::NotifyGlobalObservers { global_type } => {
728 self.apply_notify_global_observers_effect(global_type);
729 }
730
731 Effect::Defer { callback } => {
732 self.apply_defer_effect(callback);
733 }
734 }
735 } else {
736 #[cfg(any(test, feature = "test-support"))]
737 for window in self
738 .windows
739 .values()
740 .filter_map(|window| {
741 let window = window.as_ref()?;
742 window.dirty.get().then_some(window.handle)
743 })
744 .collect::<Vec<_>>()
745 {
746 self.update_window(window, |_, cx| cx.draw()).unwrap();
747 }
748
749 if self.pending_effects.is_empty() {
750 break;
751 }
752 }
753 }
754 }
755
756 /// Repeatedly called during `flush_effects` to release any entities whose
757 /// reference count has become zero. We invoke any release observers before dropping
758 /// each entity.
759 fn release_dropped_entities(&mut self) {
760 loop {
761 let dropped = self.entities.take_dropped();
762 if dropped.is_empty() {
763 break;
764 }
765
766 for (entity_id, mut entity) in dropped {
767 self.observers.remove(&entity_id);
768 self.event_listeners.remove(&entity_id);
769 for release_callback in self.release_listeners.remove(&entity_id) {
770 release_callback(entity.as_mut(), self);
771 }
772 }
773 }
774 }
775
776 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
777 fn release_dropped_focus_handles(&mut self) {
778 for window_handle in self.windows() {
779 window_handle
780 .update(self, |_, cx| {
781 let mut blur_window = false;
782 let focus = cx.window.focus;
783 cx.window.focus_handles.write().retain(|handle_id, count| {
784 if count.load(SeqCst) == 0 {
785 if focus == Some(handle_id) {
786 blur_window = true;
787 }
788 false
789 } else {
790 true
791 }
792 });
793
794 if blur_window {
795 cx.blur();
796 }
797 })
798 .unwrap();
799 }
800 }
801
802 fn apply_notify_effect(&mut self, emitter: EntityId) {
803 self.pending_notifications.remove(&emitter);
804
805 self.observers
806 .clone()
807 .retain(&emitter, |handler| handler(self));
808 }
809
810 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
811 self.event_listeners
812 .clone()
813 .retain(&emitter, |(stored_type, handler)| {
814 if *stored_type == event_type {
815 handler(event.as_ref(), self)
816 } else {
817 true
818 }
819 });
820 }
821
822 fn apply_refresh_effect(&mut self) {
823 for window in self.windows.values_mut() {
824 if let Some(window) = window.as_mut() {
825 window.dirty.set(true);
826 }
827 }
828 }
829
830 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
831 self.pending_global_notifications.remove(&type_id);
832 self.global_observers
833 .clone()
834 .retain(&type_id, |observer| observer(self));
835 }
836
837 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
838 callback(self);
839 }
840
841 /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
842 /// so it can be held across `await` points.
843 pub fn to_async(&self) -> AsyncAppContext {
844 AsyncAppContext {
845 app: self.this.clone(),
846 background_executor: self.background_executor.clone(),
847 foreground_executor: self.foreground_executor.clone(),
848 }
849 }
850
851 /// Obtains a reference to the executor, which can be used to spawn futures.
852 pub fn background_executor(&self) -> &BackgroundExecutor {
853 &self.background_executor
854 }
855
856 /// Obtains a reference to the executor, which can be used to spawn futures.
857 pub fn foreground_executor(&self) -> &ForegroundExecutor {
858 &self.foreground_executor
859 }
860
861 /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
862 /// with [AsyncAppContext], which allows the application state to be accessed across await points.
863 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
864 where
865 Fut: Future<Output = R> + 'static,
866 R: 'static,
867 {
868 self.foreground_executor.spawn(f(self.to_async()))
869 }
870
871 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
872 /// that are currently on the stack to be returned to the app.
873 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
874 self.push_effect(Effect::Defer {
875 callback: Box::new(f),
876 });
877 }
878
879 /// Accessor for the application's asset source, which is provided when constructing the `App`.
880 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
881 &self.asset_source
882 }
883
884 /// Accessor for the text system.
885 pub fn text_system(&self) -> &Arc<TextSystem> {
886 &self.text_system
887 }
888
889 /// Check whether a global of the given type has been assigned.
890 pub fn has_global<G: Global>(&self) -> bool {
891 self.globals_by_type.contains_key(&TypeId::of::<G>())
892 }
893
894 /// Access the global of the given type. Panics if a global for that type has not been assigned.
895 #[track_caller]
896 pub fn global<G: Global>(&self) -> &G {
897 self.globals_by_type
898 .get(&TypeId::of::<G>())
899 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
900 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
901 .unwrap()
902 }
903
904 /// Access the global of the given type if a value has been assigned.
905 pub fn try_global<G: Global>(&self) -> Option<&G> {
906 self.globals_by_type
907 .get(&TypeId::of::<G>())
908 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
909 }
910
911 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
912 #[track_caller]
913 pub fn global_mut<G: Global>(&mut self) -> &mut G {
914 let global_type = TypeId::of::<G>();
915 self.push_effect(Effect::NotifyGlobalObservers { global_type });
916 self.globals_by_type
917 .get_mut(&global_type)
918 .and_then(|any_state| any_state.downcast_mut::<G>())
919 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
920 .unwrap()
921 }
922
923 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
924 /// yet been assigned.
925 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
926 let global_type = TypeId::of::<G>();
927 self.push_effect(Effect::NotifyGlobalObservers { global_type });
928 self.globals_by_type
929 .entry(global_type)
930 .or_insert_with(|| Box::<G>::default())
931 .downcast_mut::<G>()
932 .unwrap()
933 }
934
935 /// Sets the value of the global of the given type.
936 pub fn set_global<G: Global>(&mut self, global: G) {
937 let global_type = TypeId::of::<G>();
938 self.push_effect(Effect::NotifyGlobalObservers { global_type });
939 self.globals_by_type.insert(global_type, Box::new(global));
940 }
941
942 /// Clear all stored globals. Does not notify global observers.
943 #[cfg(any(test, feature = "test-support"))]
944 pub fn clear_globals(&mut self) {
945 self.globals_by_type.drain();
946 }
947
948 /// Remove the global of the given type from the app context. Does not notify global observers.
949 pub fn remove_global<G: Global>(&mut self) -> G {
950 let global_type = TypeId::of::<G>();
951 self.push_effect(Effect::NotifyGlobalObservers { global_type });
952 *self
953 .globals_by_type
954 .remove(&global_type)
955 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
956 .downcast()
957 .unwrap()
958 }
959
960 /// Register a callback to be invoked when a global of the given type is updated.
961 pub fn observe_global<G: Global>(
962 &mut self,
963 mut f: impl FnMut(&mut Self) + 'static,
964 ) -> Subscription {
965 let (subscription, activate) = self.global_observers.insert(
966 TypeId::of::<G>(),
967 Box::new(move |cx| {
968 f(cx);
969 true
970 }),
971 );
972 self.defer(move |_| activate());
973 subscription
974 }
975
976 /// Move the global of the given type to the stack.
977 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
978 GlobalLease::new(
979 self.globals_by_type
980 .remove(&TypeId::of::<G>())
981 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
982 .unwrap(),
983 )
984 }
985
986 /// Restore the global of the given type after it is moved to the stack.
987 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
988 let global_type = TypeId::of::<G>();
989 self.push_effect(Effect::NotifyGlobalObservers { global_type });
990 self.globals_by_type.insert(global_type, lease.global);
991 }
992
993 pub(crate) fn new_view_observer(
994 &mut self,
995 key: TypeId,
996 value: NewViewListener,
997 ) -> Subscription {
998 let (subscription, activate) = self.new_view_observers.insert(key, value);
999 activate();
1000 subscription
1001 }
1002 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1003 /// The function will be passed a mutable reference to the view along with an appropriate context.
1004 pub fn observe_new_views<V: 'static>(
1005 &mut self,
1006 on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
1007 ) -> Subscription {
1008 self.new_view_observer(
1009 TypeId::of::<V>(),
1010 Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
1011 any_view
1012 .downcast::<V>()
1013 .unwrap()
1014 .update(cx, |view_state, cx| {
1015 on_new(view_state, cx);
1016 })
1017 }),
1018 )
1019 }
1020
1021 /// Observe the release of a model or view. The callback is invoked after the model or view
1022 /// has no more strong references but before it has been dropped.
1023 pub fn observe_release<E, T>(
1024 &mut self,
1025 handle: &E,
1026 on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
1027 ) -> Subscription
1028 where
1029 E: Entity<T>,
1030 T: 'static,
1031 {
1032 let (subscription, activate) = self.release_listeners.insert(
1033 handle.entity_id(),
1034 Box::new(move |entity, cx| {
1035 let entity = entity.downcast_mut().expect("invalid entity type");
1036 on_release(entity, cx)
1037 }),
1038 );
1039 activate();
1040 subscription
1041 }
1042
1043 /// Register a callback to be invoked when a keystroke is received by the application
1044 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1045 /// and that this API will not be invoked if the event's propagation is stopped.
1046 pub fn observe_keystrokes(
1047 &mut self,
1048 f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
1049 ) -> Subscription {
1050 fn inner(
1051 keystroke_observers: &mut SubscriberSet<(), KeystrokeObserver>,
1052 handler: KeystrokeObserver,
1053 ) -> Subscription {
1054 let (subscription, activate) = keystroke_observers.insert((), handler);
1055 activate();
1056 subscription
1057 }
1058 inner(&mut self.keystroke_observers, Box::new(f))
1059 }
1060
1061 /// Register key bindings.
1062 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1063 self.keymap.borrow_mut().add_bindings(bindings);
1064 self.pending_effects.push_back(Effect::Refresh);
1065 }
1066
1067 /// Clear all key bindings in the app.
1068 pub fn clear_key_bindings(&mut self) {
1069 self.keymap.borrow_mut().clear();
1070 self.pending_effects.push_back(Effect::Refresh);
1071 }
1072
1073 /// Register a global listener for actions invoked via the keyboard.
1074 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1075 self.global_action_listeners
1076 .entry(TypeId::of::<A>())
1077 .or_default()
1078 .push(Rc::new(move |action, phase, cx| {
1079 if phase == DispatchPhase::Bubble {
1080 let action = action.downcast_ref().unwrap();
1081 listener(action, cx)
1082 }
1083 }));
1084 }
1085
1086 /// Event handlers propagate events by default. Call this method to stop dispatching to
1087 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1088 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1089 /// calling this method before effects are flushed.
1090 pub fn stop_propagation(&mut self) {
1091 self.propagate_event = false;
1092 }
1093
1094 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1095 /// dispatching to action handlers higher in the element tree. This is the opposite of
1096 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1097 /// this method before effects are flushed.
1098 pub fn propagate(&mut self) {
1099 self.propagate_event = true;
1100 }
1101
1102 /// Build an action from some arbitrary data, typically a keymap entry.
1103 pub fn build_action(
1104 &self,
1105 name: &str,
1106 data: Option<serde_json::Value>,
1107 ) -> Result<Box<dyn Action>> {
1108 self.actions.build_action(name, data)
1109 }
1110
1111 /// Get a list of all action names that have been registered.
1112 /// in the application. Note that registration only allows for
1113 /// actions to be built dynamically, and is unrelated to binding
1114 /// actions in the element tree.
1115 pub fn all_action_names(&self) -> &[SharedString] {
1116 self.actions.all_action_names()
1117 }
1118
1119 /// Register a callback to be invoked when the application is about to quit.
1120 /// It is not possible to cancel the quit event at this point.
1121 pub fn on_app_quit<Fut>(
1122 &mut self,
1123 mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1124 ) -> Subscription
1125 where
1126 Fut: 'static + Future<Output = ()>,
1127 {
1128 let (subscription, activate) = self.quit_observers.insert(
1129 (),
1130 Box::new(move |cx| {
1131 let future = on_quit(cx);
1132 future.boxed_local()
1133 }),
1134 );
1135 activate();
1136 subscription
1137 }
1138
1139 pub(crate) fn clear_pending_keystrokes(&mut self) {
1140 for window in self.windows() {
1141 window
1142 .update(self, |_, cx| {
1143 cx.clear_pending_keystrokes();
1144 })
1145 .ok();
1146 }
1147 }
1148
1149 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1150 /// the bindings in the element tree, and any global action listeners.
1151 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1152 let mut action_available = false;
1153 if let Some(window) = self.active_window() {
1154 if let Ok(window_action_available) =
1155 window.update(self, |_, cx| cx.is_action_available(action))
1156 {
1157 action_available = window_action_available;
1158 }
1159 }
1160
1161 action_available
1162 || self
1163 .global_action_listeners
1164 .contains_key(&action.as_any().type_id())
1165 }
1166
1167 /// Sets the menu bar for this application. This will replace any existing menu bar.
1168 pub fn set_menus(&mut self, menus: Vec<Menu>) {
1169 self.platform.set_menus(menus, &self.keymap.borrow());
1170 }
1171
1172 /// Gets the menu bar for this application.
1173 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1174 self.platform.get_menus()
1175 }
1176
1177 /// Sets the right click menu for the app icon in the dock
1178 pub fn set_dock_menu(&mut self, menus: Vec<MenuItem>) {
1179 self.platform.set_dock_menu(menus, &self.keymap.borrow());
1180 }
1181
1182 /// Adds given path to the bottom of the list of recent paths for the application.
1183 /// The list is usually shown on the application icon's context menu in the dock,
1184 /// and allows to open the recent files via that context menu.
1185 /// If the path is already in the list, it will be moved to the bottom of the list.
1186 pub fn add_recent_document(&mut self, path: &Path) {
1187 self.platform.add_recent_document(path);
1188 }
1189
1190 /// Dispatch an action to the currently active window or global action handler
1191 /// See [action::Action] for more information on how actions work
1192 pub fn dispatch_action(&mut self, action: &dyn Action) {
1193 if let Some(active_window) = self.active_window() {
1194 active_window
1195 .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1196 .log_err();
1197 } else {
1198 self.dispatch_global_action(action);
1199 }
1200 }
1201
1202 fn dispatch_global_action(&mut self, action: &dyn Action) {
1203 self.propagate_event = true;
1204
1205 if let Some(mut global_listeners) = self
1206 .global_action_listeners
1207 .remove(&action.as_any().type_id())
1208 {
1209 for listener in &global_listeners {
1210 listener(action.as_any(), DispatchPhase::Capture, self);
1211 if !self.propagate_event {
1212 break;
1213 }
1214 }
1215
1216 global_listeners.extend(
1217 self.global_action_listeners
1218 .remove(&action.as_any().type_id())
1219 .unwrap_or_default(),
1220 );
1221
1222 self.global_action_listeners
1223 .insert(action.as_any().type_id(), global_listeners);
1224 }
1225
1226 if self.propagate_event {
1227 if let Some(mut global_listeners) = self
1228 .global_action_listeners
1229 .remove(&action.as_any().type_id())
1230 {
1231 for listener in global_listeners.iter().rev() {
1232 listener(action.as_any(), DispatchPhase::Bubble, self);
1233 if !self.propagate_event {
1234 break;
1235 }
1236 }
1237
1238 global_listeners.extend(
1239 self.global_action_listeners
1240 .remove(&action.as_any().type_id())
1241 .unwrap_or_default(),
1242 );
1243
1244 self.global_action_listeners
1245 .insert(action.as_any().type_id(), global_listeners);
1246 }
1247 }
1248 }
1249
1250 /// Is there currently something being dragged?
1251 pub fn has_active_drag(&self) -> bool {
1252 self.active_drag.is_some()
1253 }
1254
1255 /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1256 /// prompts with this custom implementation.
1257 pub fn set_prompt_builder(
1258 &mut self,
1259 renderer: impl Fn(
1260 PromptLevel,
1261 &str,
1262 Option<&str>,
1263 &[&str],
1264 PromptHandle,
1265 &mut WindowContext,
1266 ) -> RenderablePromptHandle
1267 + 'static,
1268 ) {
1269 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1270 }
1271
1272 /// Remove an asset from GPUI's cache
1273 pub fn remove_cached_asset<A: Asset + 'static>(&mut self, source: &A::Source) {
1274 let asset_id = (TypeId::of::<A>(), hash(source));
1275 self.loading_assets.remove(&asset_id);
1276 }
1277
1278 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1279 ///
1280 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1281 /// time, and the results of this call will be cached
1282 ///
1283 /// This asset will not be cached by default, see [Self::use_cached_asset]
1284 pub fn fetch_asset<A: Asset + 'static>(
1285 &mut self,
1286 source: &A::Source,
1287 ) -> (Shared<Task<A::Output>>, bool) {
1288 let asset_id = (TypeId::of::<A>(), hash(source));
1289 let mut is_first = false;
1290 let task = self
1291 .loading_assets
1292 .remove(&asset_id)
1293 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1294 .unwrap_or_else(|| {
1295 is_first = true;
1296 let future = A::load(source.clone(), self);
1297 let task = self.background_executor().spawn(future).shared();
1298 task
1299 });
1300
1301 self.loading_assets.insert(asset_id, Box::new(task.clone()));
1302
1303 (task, is_first)
1304 }
1305}
1306
1307impl Context for AppContext {
1308 type Result<T> = T;
1309
1310 /// Build an entity that is owned by the application. The given function will be invoked with
1311 /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1312 /// which can be used to access the entity in a context.
1313 fn new_model<T: 'static>(
1314 &mut self,
1315 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1316 ) -> Model<T> {
1317 self.update(|cx| {
1318 let slot = cx.entities.reserve();
1319 let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1320 cx.entities.insert(slot, entity)
1321 })
1322 }
1323
1324 fn reserve_model<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1325 Reservation(self.entities.reserve())
1326 }
1327
1328 fn insert_model<T: 'static>(
1329 &mut self,
1330 reservation: Reservation<T>,
1331 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1332 ) -> Self::Result<Model<T>> {
1333 self.update(|cx| {
1334 let slot = reservation.0;
1335 let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1336 cx.entities.insert(slot, entity)
1337 })
1338 }
1339
1340 /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1341 /// entity along with a `ModelContext` for the entity.
1342 fn update_model<T: 'static, R>(
1343 &mut self,
1344 model: &Model<T>,
1345 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1346 ) -> R {
1347 self.update(|cx| {
1348 let mut entity = cx.entities.lease(model);
1349 let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1350 cx.entities.end_lease(entity);
1351 result
1352 })
1353 }
1354
1355 fn read_model<T, R>(
1356 &self,
1357 handle: &Model<T>,
1358 read: impl FnOnce(&T, &AppContext) -> R,
1359 ) -> Self::Result<R>
1360 where
1361 T: 'static,
1362 {
1363 let entity = self.entities.read(handle);
1364 read(entity, self)
1365 }
1366
1367 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1368 where
1369 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1370 {
1371 self.update(|cx| {
1372 let mut window = cx
1373 .windows
1374 .get_mut(handle.id)
1375 .ok_or_else(|| anyhow!("window not found"))?
1376 .take()
1377 .ok_or_else(|| anyhow!("window not found"))?;
1378
1379 let root_view = window.root_view.clone().unwrap();
1380 let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1381
1382 if window.removed {
1383 cx.window_handles.remove(&handle.id);
1384 cx.windows.remove(handle.id);
1385 } else {
1386 cx.windows
1387 .get_mut(handle.id)
1388 .ok_or_else(|| anyhow!("window not found"))?
1389 .replace(window);
1390 }
1391
1392 Ok(result)
1393 })
1394 }
1395
1396 fn read_window<T, R>(
1397 &self,
1398 window: &WindowHandle<T>,
1399 read: impl FnOnce(View<T>, &AppContext) -> R,
1400 ) -> Result<R>
1401 where
1402 T: 'static,
1403 {
1404 let window = self
1405 .windows
1406 .get(window.id)
1407 .ok_or_else(|| anyhow!("window not found"))?
1408 .as_ref()
1409 .unwrap();
1410
1411 let root_view = window.root_view.clone().unwrap();
1412 let view = root_view
1413 .downcast::<T>()
1414 .map_err(|_| anyhow!("root view's type has changed"))?;
1415
1416 Ok(read(view, self))
1417 }
1418}
1419
1420/// These effects are processed at the end of each application update cycle.
1421pub(crate) enum Effect {
1422 Notify {
1423 emitter: EntityId,
1424 },
1425 Emit {
1426 emitter: EntityId,
1427 event_type: TypeId,
1428 event: Box<dyn Any>,
1429 },
1430 Refresh,
1431 NotifyGlobalObservers {
1432 global_type: TypeId,
1433 },
1434 Defer {
1435 callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1436 },
1437}
1438
1439/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1440pub(crate) struct GlobalLease<G: Global> {
1441 global: Box<dyn Any>,
1442 global_type: PhantomData<G>,
1443}
1444
1445impl<G: Global> GlobalLease<G> {
1446 fn new(global: Box<dyn Any>) -> Self {
1447 GlobalLease {
1448 global,
1449 global_type: PhantomData,
1450 }
1451 }
1452}
1453
1454impl<G: Global> Deref for GlobalLease<G> {
1455 type Target = G;
1456
1457 fn deref(&self) -> &Self::Target {
1458 self.global.downcast_ref().unwrap()
1459 }
1460}
1461
1462impl<G: Global> DerefMut for GlobalLease<G> {
1463 fn deref_mut(&mut self) -> &mut Self::Target {
1464 self.global.downcast_mut().unwrap()
1465 }
1466}
1467
1468/// Contains state associated with an active drag operation, started by dragging an element
1469/// within the window or by dragging into the app from the underlying platform.
1470pub struct AnyDrag {
1471 /// The view used to render this drag
1472 pub view: AnyView,
1473
1474 /// The value of the dragged item, to be dropped
1475 pub value: Box<dyn Any>,
1476
1477 /// This is used to render the dragged item in the same place
1478 /// on the original element that the drag was initiated
1479 pub cursor_offset: Point<Pixels>,
1480}
1481
1482/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1483/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1484#[derive(Clone)]
1485pub struct AnyTooltip {
1486 /// The view used to display the tooltip
1487 pub view: AnyView,
1488
1489 /// The absolute position of the mouse when the tooltip was deployed.
1490 pub mouse_position: Point<Pixels>,
1491}
1492
1493/// A keystroke event, and potentially the associated action
1494#[derive(Debug)]
1495pub struct KeystrokeEvent {
1496 /// The keystroke that occurred
1497 pub keystroke: Keystroke,
1498
1499 /// The action that was resolved for the keystroke, if any
1500 pub action: Option<Box<dyn Action>>,
1501}