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