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