1use std::{
2 any::{type_name, TypeId},
3 cell::{Ref, RefCell, RefMut},
4 marker::PhantomData,
5 mem,
6 ops::{Deref, DerefMut},
7 path::{Path, PathBuf},
8 rc::{Rc, Weak},
9 sync::{atomic::Ordering::SeqCst, Arc},
10 time::Duration,
11};
12
13use anyhow::{anyhow, Result};
14use derive_more::{Deref, DerefMut};
15use futures::{
16 channel::oneshot,
17 future::{LocalBoxFuture, Shared},
18 Future, FutureExt,
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 current_platform, hash, init_app_menus, Action, ActionBuildError, ActionRegistry, Any, AnyView,
34 AnyWindowHandle, AppContext, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem,
35 DispatchPhase, DisplayId, EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global,
36 KeyBinding, Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels,
37 Platform, PlatformDisplay, Point, PromptBuilder, PromptHandle, PromptLevel, Render,
38 RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
39 Subscription, SvgRenderer, Task, TextSystem, Window, WindowAppearance, WindowHandle, WindowId,
40 WindowInvalidator,
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 a list of available screen capture sources.
654 pub fn screen_capture_sources(
655 &self,
656 ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
657 self.platform.screen_capture_sources()
658 }
659
660 /// Returns the display with the given ID, if one exists.
661 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
662 self.displays()
663 .iter()
664 .find(|display| display.id() == id)
665 .cloned()
666 }
667
668 /// Returns the appearance of the application's windows.
669 pub fn window_appearance(&self) -> WindowAppearance {
670 self.platform.window_appearance()
671 }
672
673 /// Writes data to the primary selection buffer.
674 /// Only available on Linux.
675 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
676 pub fn write_to_primary(&self, item: ClipboardItem) {
677 self.platform.write_to_primary(item)
678 }
679
680 /// Writes data to the platform clipboard.
681 pub fn write_to_clipboard(&self, item: ClipboardItem) {
682 self.platform.write_to_clipboard(item)
683 }
684
685 /// Reads data from the primary selection buffer.
686 /// Only available on Linux.
687 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
688 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
689 self.platform.read_from_primary()
690 }
691
692 /// Reads data from the platform clipboard.
693 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
694 self.platform.read_from_clipboard()
695 }
696
697 /// Writes credentials to the platform keychain.
698 pub fn write_credentials(
699 &self,
700 url: &str,
701 username: &str,
702 password: &[u8],
703 ) -> Task<Result<()>> {
704 self.platform.write_credentials(url, username, password)
705 }
706
707 /// Reads credentials from the platform keychain.
708 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
709 self.platform.read_credentials(url)
710 }
711
712 /// Deletes credentials from the platform keychain.
713 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
714 self.platform.delete_credentials(url)
715 }
716
717 /// Directs the platform's default browser to open the given URL.
718 pub fn open_url(&self, url: &str) {
719 self.platform.open_url(url);
720 }
721
722 /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
723 /// opened by the current app.
724 ///
725 /// On some platforms (e.g. macOS) you may be able to register URL schemes
726 /// as part of app distribution, but this method exists to let you register
727 /// schemes at runtime.
728 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
729 self.platform.register_url_scheme(scheme)
730 }
731
732 /// Returns the full pathname of the current app bundle.
733 ///
734 /// Returns an error if the app is not being run from a bundle.
735 pub fn app_path(&self) -> Result<PathBuf> {
736 self.platform.app_path()
737 }
738
739 /// On Linux, returns the name of the compositor in use.
740 ///
741 /// Returns an empty string on other platforms.
742 pub fn compositor_name(&self) -> &'static str {
743 self.platform.compositor_name()
744 }
745
746 /// Returns the file URL of the executable with the specified name in the application bundle
747 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
748 self.platform.path_for_auxiliary_executable(name)
749 }
750
751 /// Displays a platform modal for selecting paths.
752 ///
753 /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
754 /// If cancelled, a `None` will be relayed instead.
755 /// May return an error on Linux if the file picker couldn't be opened.
756 pub fn prompt_for_paths(
757 &self,
758 options: PathPromptOptions,
759 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
760 self.platform.prompt_for_paths(options)
761 }
762
763 /// Displays a platform modal for selecting a new path where a file can be saved.
764 ///
765 /// The provided directory will be used to set the initial location.
766 /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
767 /// If cancelled, a `None` will be relayed instead.
768 /// May return an error on Linux if the file picker couldn't be opened.
769 pub fn prompt_for_new_path(
770 &self,
771 directory: &Path,
772 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
773 self.platform.prompt_for_new_path(directory)
774 }
775
776 /// Reveals the specified path at the platform level, such as in Finder on macOS.
777 pub fn reveal_path(&self, path: &Path) {
778 self.platform.reveal_path(path)
779 }
780
781 /// Opens the specified path with the system's default application.
782 pub fn open_with_system(&self, path: &Path) {
783 self.platform.open_with_system(path)
784 }
785
786 /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
787 pub fn should_auto_hide_scrollbars(&self) -> bool {
788 self.platform.should_auto_hide_scrollbars()
789 }
790
791 /// Restarts the application.
792 pub fn restart(&self, binary_path: Option<PathBuf>) {
793 self.platform.restart(binary_path)
794 }
795
796 /// Returns the HTTP client for the application.
797 pub fn http_client(&self) -> Arc<dyn HttpClient> {
798 self.http_client.clone()
799 }
800
801 /// Sets the HTTP client for the application.
802 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
803 self.http_client = new_client;
804 }
805
806 /// Returns the SVG renderer used by the application.
807 pub fn svg_renderer(&self) -> SvgRenderer {
808 self.svg_renderer.clone()
809 }
810
811 pub(crate) fn push_effect(&mut self, effect: Effect) {
812 match &effect {
813 Effect::Notify { emitter } => {
814 if !self.pending_notifications.insert(*emitter) {
815 return;
816 }
817 }
818 Effect::NotifyGlobalObservers { global_type } => {
819 if !self.pending_global_notifications.insert(*global_type) {
820 return;
821 }
822 }
823 _ => {}
824 };
825
826 self.pending_effects.push_back(effect);
827 }
828
829 /// Called at the end of [`App::update`] to complete any side effects
830 /// such as notifying observers, emitting events, etc. Effects can themselves
831 /// cause effects, so we continue looping until all effects are processed.
832 fn flush_effects(&mut self) {
833 loop {
834 self.release_dropped_entities();
835 self.release_dropped_focus_handles();
836
837 if let Some(effect) = self.pending_effects.pop_front() {
838 match effect {
839 Effect::Notify { emitter } => {
840 self.apply_notify_effect(emitter);
841 }
842
843 Effect::Emit {
844 emitter,
845 event_type,
846 event,
847 } => self.apply_emit_effect(emitter, event_type, event),
848
849 Effect::RefreshWindows => {
850 self.apply_refresh_effect();
851 }
852
853 Effect::NotifyGlobalObservers { global_type } => {
854 self.apply_notify_global_observers_effect(global_type);
855 }
856
857 Effect::Defer { callback } => {
858 self.apply_defer_effect(callback);
859 }
860 Effect::EntityCreated {
861 entity,
862 tid,
863 window,
864 } => {
865 self.apply_entity_created_effect(entity, tid, window);
866 }
867 }
868 } else {
869 #[cfg(any(test, feature = "test-support"))]
870 for window in self
871 .windows
872 .values()
873 .filter_map(|window| {
874 let window = window.as_ref()?;
875 window.invalidator.is_dirty().then_some(window.handle)
876 })
877 .collect::<Vec<_>>()
878 {
879 self.update_window(window, |_, window, cx| window.draw(cx))
880 .unwrap();
881 }
882
883 if self.pending_effects.is_empty() {
884 break;
885 }
886 }
887 }
888 }
889
890 /// Repeatedly called during `flush_effects` to release any entities whose
891 /// reference count has become zero. We invoke any release observers before dropping
892 /// each entity.
893 fn release_dropped_entities(&mut self) {
894 loop {
895 let dropped = self.entities.take_dropped();
896 if dropped.is_empty() {
897 break;
898 }
899
900 for (entity_id, mut entity) in dropped {
901 self.observers.remove(&entity_id);
902 self.event_listeners.remove(&entity_id);
903 for release_callback in self.release_listeners.remove(&entity_id) {
904 release_callback(entity.as_mut(), self);
905 }
906 }
907 }
908 }
909
910 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
911 fn release_dropped_focus_handles(&mut self) {
912 self.focus_handles
913 .clone()
914 .write()
915 .retain(|handle_id, count| {
916 if count.load(SeqCst) == 0 {
917 for window_handle in self.windows() {
918 window_handle
919 .update(self, |_, window, _| {
920 if window.focus == Some(handle_id) {
921 window.blur();
922 }
923 })
924 .unwrap();
925 }
926 false
927 } else {
928 true
929 }
930 });
931 }
932
933 fn apply_notify_effect(&mut self, emitter: EntityId) {
934 self.pending_notifications.remove(&emitter);
935
936 self.observers
937 .clone()
938 .retain(&emitter, |handler| handler(self));
939 }
940
941 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
942 self.event_listeners
943 .clone()
944 .retain(&emitter, |(stored_type, handler)| {
945 if *stored_type == event_type {
946 handler(event.as_ref(), self)
947 } else {
948 true
949 }
950 });
951 }
952
953 fn apply_refresh_effect(&mut self) {
954 for window in self.windows.values_mut() {
955 if let Some(window) = window.as_mut() {
956 window.refreshing = true;
957 window.invalidator.set_dirty(true);
958 }
959 }
960 }
961
962 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
963 self.pending_global_notifications.remove(&type_id);
964 self.global_observers
965 .clone()
966 .retain(&type_id, |observer| observer(self));
967 }
968
969 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
970 callback(self);
971 }
972
973 fn apply_entity_created_effect(
974 &mut self,
975 entity: AnyEntity,
976 tid: TypeId,
977 window: Option<WindowId>,
978 ) {
979 self.new_entity_observers.clone().retain(&tid, |observer| {
980 if let Some(id) = window {
981 self.update_window_id(id, {
982 let entity = entity.clone();
983 |_, window, cx| (observer)(entity, &mut Some(window), cx)
984 })
985 .expect("All windows should be off the stack when flushing effects");
986 } else {
987 (observer)(entity.clone(), &mut None, self)
988 }
989 true
990 });
991 }
992
993 fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
994 where
995 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
996 {
997 self.update(|cx| {
998 let mut window = cx
999 .windows
1000 .get_mut(id)
1001 .ok_or_else(|| anyhow!("window not found"))?
1002 .take()
1003 .ok_or_else(|| anyhow!("window not found"))?;
1004
1005 let root_view = window.root.clone().unwrap();
1006
1007 cx.window_update_stack.push(window.handle.id);
1008 let result = update(root_view, &mut window, cx);
1009 cx.window_update_stack.pop();
1010
1011 if window.removed {
1012 cx.window_handles.remove(&id);
1013 cx.windows.remove(id);
1014
1015 cx.window_closed_observers.clone().retain(&(), |callback| {
1016 callback(cx);
1017 true
1018 });
1019 } else {
1020 cx.windows
1021 .get_mut(id)
1022 .ok_or_else(|| anyhow!("window not found"))?
1023 .replace(window);
1024 }
1025
1026 Ok(result)
1027 })
1028 }
1029 /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1030 /// so it can be held across `await` points.
1031 pub fn to_async(&self) -> AsyncApp {
1032 AsyncApp {
1033 app: self.this.clone(),
1034 background_executor: self.background_executor.clone(),
1035 foreground_executor: self.foreground_executor.clone(),
1036 }
1037 }
1038
1039 /// Obtains a reference to the executor, which can be used to spawn futures.
1040 pub fn background_executor(&self) -> &BackgroundExecutor {
1041 &self.background_executor
1042 }
1043
1044 /// Obtains a reference to the executor, which can be used to spawn futures.
1045 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1046 &self.foreground_executor
1047 }
1048
1049 /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1050 /// with [AsyncApp], which allows the application state to be accessed across await points.
1051 #[track_caller]
1052 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1053 where
1054 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1055 R: 'static,
1056 {
1057 let mut cx = self.to_async();
1058 self.foreground_executor
1059 .spawn(async move { f(&mut cx).await })
1060 }
1061
1062 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1063 /// that are currently on the stack to be returned to the app.
1064 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1065 self.push_effect(Effect::Defer {
1066 callback: Box::new(f),
1067 });
1068 }
1069
1070 /// Accessor for the application's asset source, which is provided when constructing the `App`.
1071 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1072 &self.asset_source
1073 }
1074
1075 /// Accessor for the text system.
1076 pub fn text_system(&self) -> &Arc<TextSystem> {
1077 &self.text_system
1078 }
1079
1080 /// Check whether a global of the given type has been assigned.
1081 pub fn has_global<G: Global>(&self) -> bool {
1082 self.globals_by_type.contains_key(&TypeId::of::<G>())
1083 }
1084
1085 /// Access the global of the given type. Panics if a global for that type has not been assigned.
1086 #[track_caller]
1087 pub fn global<G: Global>(&self) -> &G {
1088 self.globals_by_type
1089 .get(&TypeId::of::<G>())
1090 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1091 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
1092 .unwrap()
1093 }
1094
1095 /// Access the global of the given type if a value has been assigned.
1096 pub fn try_global<G: Global>(&self) -> Option<&G> {
1097 self.globals_by_type
1098 .get(&TypeId::of::<G>())
1099 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1100 }
1101
1102 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1103 #[track_caller]
1104 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1105 let global_type = TypeId::of::<G>();
1106 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1107 self.globals_by_type
1108 .get_mut(&global_type)
1109 .and_then(|any_state| any_state.downcast_mut::<G>())
1110 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
1111 .unwrap()
1112 }
1113
1114 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1115 /// yet been assigned.
1116 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1117 let global_type = TypeId::of::<G>();
1118 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1119 self.globals_by_type
1120 .entry(global_type)
1121 .or_insert_with(|| Box::<G>::default())
1122 .downcast_mut::<G>()
1123 .unwrap()
1124 }
1125
1126 /// Sets the value of the global of the given type.
1127 pub fn set_global<G: Global>(&mut self, global: G) {
1128 let global_type = TypeId::of::<G>();
1129 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1130 self.globals_by_type.insert(global_type, Box::new(global));
1131 }
1132
1133 /// Clear all stored globals. Does not notify global observers.
1134 #[cfg(any(test, feature = "test-support"))]
1135 pub fn clear_globals(&mut self) {
1136 self.globals_by_type.drain();
1137 }
1138
1139 /// Remove the global of the given type from the app context. Does not notify global observers.
1140 pub fn remove_global<G: Global>(&mut self) -> G {
1141 let global_type = TypeId::of::<G>();
1142 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1143 *self
1144 .globals_by_type
1145 .remove(&global_type)
1146 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1147 .downcast()
1148 .unwrap()
1149 }
1150
1151 /// Register a callback to be invoked when a global of the given type is updated.
1152 pub fn observe_global<G: Global>(
1153 &mut self,
1154 mut f: impl FnMut(&mut Self) + 'static,
1155 ) -> Subscription {
1156 let (subscription, activate) = self.global_observers.insert(
1157 TypeId::of::<G>(),
1158 Box::new(move |cx| {
1159 f(cx);
1160 true
1161 }),
1162 );
1163 self.defer(move |_| activate());
1164 subscription
1165 }
1166
1167 /// Move the global of the given type to the stack.
1168 #[track_caller]
1169 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1170 GlobalLease::new(
1171 self.globals_by_type
1172 .remove(&TypeId::of::<G>())
1173 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
1174 .unwrap(),
1175 )
1176 }
1177
1178 /// Restore the global of the given type after it is moved to the stack.
1179 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1180 let global_type = TypeId::of::<G>();
1181
1182 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1183 self.globals_by_type.insert(global_type, lease.global);
1184 }
1185
1186 pub(crate) fn new_entity_observer(
1187 &self,
1188 key: TypeId,
1189 value: NewEntityListener,
1190 ) -> Subscription {
1191 let (subscription, activate) = self.new_entity_observers.insert(key, value);
1192 activate();
1193 subscription
1194 }
1195
1196 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1197 /// The function will be passed a mutable reference to the view along with an appropriate context.
1198 pub fn observe_new<T: 'static>(
1199 &self,
1200 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1201 ) -> Subscription {
1202 self.new_entity_observer(
1203 TypeId::of::<T>(),
1204 Box::new(
1205 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1206 any_entity
1207 .downcast::<T>()
1208 .unwrap()
1209 .update(cx, |entity_state, cx| {
1210 if let Some(window) = window {
1211 on_new(entity_state, Some(window), cx);
1212 } else {
1213 on_new(entity_state, None, cx);
1214 }
1215 })
1216 },
1217 ),
1218 )
1219 }
1220
1221 /// Observe the release of a entity. The callback is invoked after the entity
1222 /// has no more strong references but before it has been dropped.
1223 pub fn observe_release<T>(
1224 &self,
1225 handle: &Entity<T>,
1226 on_release: impl FnOnce(&mut T, &mut App) + 'static,
1227 ) -> Subscription
1228 where
1229 T: 'static,
1230 {
1231 let (subscription, activate) = self.release_listeners.insert(
1232 handle.entity_id(),
1233 Box::new(move |entity, cx| {
1234 let entity = entity.downcast_mut().expect("invalid entity type");
1235 on_release(entity, cx)
1236 }),
1237 );
1238 activate();
1239 subscription
1240 }
1241
1242 /// Observe the release of a entity. The callback is invoked after the entity
1243 /// has no more strong references but before it has been dropped.
1244 pub fn observe_release_in<T>(
1245 &self,
1246 handle: &Entity<T>,
1247 window: &Window,
1248 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1249 ) -> Subscription
1250 where
1251 T: 'static,
1252 {
1253 let window_handle = window.handle;
1254 self.observe_release(&handle, move |entity, cx| {
1255 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1256 })
1257 }
1258
1259 /// Register a callback to be invoked when a keystroke is received by the application
1260 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1261 /// and that this API will not be invoked if the event's propagation is stopped.
1262 pub fn observe_keystrokes(
1263 &mut self,
1264 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1265 ) -> Subscription {
1266 fn inner(
1267 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1268 handler: KeystrokeObserver,
1269 ) -> Subscription {
1270 let (subscription, activate) = keystroke_observers.insert((), handler);
1271 activate();
1272 subscription
1273 }
1274
1275 inner(
1276 &mut self.keystroke_observers,
1277 Box::new(move |event, window, cx| {
1278 f(event, window, cx);
1279 true
1280 }),
1281 )
1282 }
1283
1284 /// Register key bindings.
1285 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1286 self.keymap.borrow_mut().add_bindings(bindings);
1287 self.pending_effects.push_back(Effect::RefreshWindows);
1288 }
1289
1290 /// Clear all key bindings in the app.
1291 pub fn clear_key_bindings(&mut self) {
1292 self.keymap.borrow_mut().clear();
1293 self.pending_effects.push_back(Effect::RefreshWindows);
1294 }
1295
1296 /// Register a global listener for actions invoked via the keyboard.
1297 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1298 self.global_action_listeners
1299 .entry(TypeId::of::<A>())
1300 .or_default()
1301 .push(Rc::new(move |action, phase, cx| {
1302 if phase == DispatchPhase::Bubble {
1303 let action = action.downcast_ref().unwrap();
1304 listener(action, cx)
1305 }
1306 }));
1307 }
1308
1309 /// Event handlers propagate events by default. Call this method to stop dispatching to
1310 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1311 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1312 /// calling this method before effects are flushed.
1313 pub fn stop_propagation(&mut self) {
1314 self.propagate_event = false;
1315 }
1316
1317 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1318 /// dispatching to action handlers higher in the element tree. This is the opposite of
1319 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1320 /// this method before effects are flushed.
1321 pub fn propagate(&mut self) {
1322 self.propagate_event = true;
1323 }
1324
1325 /// Build an action from some arbitrary data, typically a keymap entry.
1326 pub fn build_action(
1327 &self,
1328 name: &str,
1329 data: Option<serde_json::Value>,
1330 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1331 self.actions.build_action(name, data)
1332 }
1333
1334 /// Get all action names that have been registered. Note that registration only allows for
1335 /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1336 pub fn all_action_names(&self) -> &[SharedString] {
1337 self.actions.all_action_names()
1338 }
1339
1340 /// Returns key bindings that invoke the given action on the currently focused element, without
1341 /// checking context. Bindings are returned in the order they were added. For display, the last
1342 /// binding should take precedence.
1343 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1344 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1345 }
1346
1347 /// Get all non-internal actions that have been registered, along with their schemas.
1348 pub fn action_schemas(
1349 &self,
1350 generator: &mut schemars::r#gen::SchemaGenerator,
1351 ) -> Vec<(SharedString, Option<schemars::schema::Schema>)> {
1352 self.actions.action_schemas(generator)
1353 }
1354
1355 /// Get a list of all deprecated action aliases and their canonical names.
1356 pub fn action_deprecations(&self) -> &HashMap<SharedString, SharedString> {
1357 self.actions.action_deprecations()
1358 }
1359
1360 /// Register a callback to be invoked when the application is about to quit.
1361 /// It is not possible to cancel the quit event at this point.
1362 pub fn on_app_quit<Fut>(
1363 &self,
1364 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1365 ) -> Subscription
1366 where
1367 Fut: 'static + Future<Output = ()>,
1368 {
1369 let (subscription, activate) = self.quit_observers.insert(
1370 (),
1371 Box::new(move |cx| {
1372 let future = on_quit(cx);
1373 future.boxed_local()
1374 }),
1375 );
1376 activate();
1377 subscription
1378 }
1379
1380 /// Register a callback to be invoked when a window is closed
1381 /// The window is no longer accessible at the point this callback is invoked.
1382 pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1383 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1384 activate();
1385 subscription
1386 }
1387
1388 pub(crate) fn clear_pending_keystrokes(&mut self) {
1389 for window in self.windows() {
1390 window
1391 .update(self, |_, window, _| {
1392 window.clear_pending_keystrokes();
1393 })
1394 .ok();
1395 }
1396 }
1397
1398 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1399 /// the bindings in the element tree, and any global action listeners.
1400 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1401 let mut action_available = false;
1402 if let Some(window) = self.active_window() {
1403 if let Ok(window_action_available) =
1404 window.update(self, |_, window, cx| window.is_action_available(action, cx))
1405 {
1406 action_available = window_action_available;
1407 }
1408 }
1409
1410 action_available
1411 || self
1412 .global_action_listeners
1413 .contains_key(&action.as_any().type_id())
1414 }
1415
1416 /// Sets the menu bar for this application. This will replace any existing menu bar.
1417 pub fn set_menus(&self, menus: Vec<Menu>) {
1418 self.platform.set_menus(menus, &self.keymap.borrow());
1419 }
1420
1421 /// Gets the menu bar for this application.
1422 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1423 self.platform.get_menus()
1424 }
1425
1426 /// Sets the right click menu for the app icon in the dock
1427 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1428 self.platform.set_dock_menu(menus, &self.keymap.borrow());
1429 }
1430
1431 /// Performs the action associated with the given dock menu item, only used on Windows for now.
1432 pub fn perform_dock_menu_action(&self, action: usize) {
1433 self.platform.perform_dock_menu_action(action);
1434 }
1435
1436 /// Adds given path to the bottom of the list of recent paths for the application.
1437 /// The list is usually shown on the application icon's context menu in the dock,
1438 /// and allows to open the recent files via that context menu.
1439 /// If the path is already in the list, it will be moved to the bottom of the list.
1440 pub fn add_recent_document(&self, path: &Path) {
1441 self.platform.add_recent_document(path);
1442 }
1443
1444 /// Dispatch an action to the currently active window or global action handler
1445 /// See [`crate::Action`] for more information on how actions work
1446 pub fn dispatch_action(&mut self, action: &dyn Action) {
1447 if let Some(active_window) = self.active_window() {
1448 active_window
1449 .update(self, |_, window, cx| {
1450 window.dispatch_action(action.boxed_clone(), cx)
1451 })
1452 .log_err();
1453 } else {
1454 self.dispatch_global_action(action);
1455 }
1456 }
1457
1458 fn dispatch_global_action(&mut self, action: &dyn Action) {
1459 self.propagate_event = true;
1460
1461 if let Some(mut global_listeners) = self
1462 .global_action_listeners
1463 .remove(&action.as_any().type_id())
1464 {
1465 for listener in &global_listeners {
1466 listener(action.as_any(), DispatchPhase::Capture, self);
1467 if !self.propagate_event {
1468 break;
1469 }
1470 }
1471
1472 global_listeners.extend(
1473 self.global_action_listeners
1474 .remove(&action.as_any().type_id())
1475 .unwrap_or_default(),
1476 );
1477
1478 self.global_action_listeners
1479 .insert(action.as_any().type_id(), global_listeners);
1480 }
1481
1482 if self.propagate_event {
1483 if let Some(mut global_listeners) = self
1484 .global_action_listeners
1485 .remove(&action.as_any().type_id())
1486 {
1487 for listener in global_listeners.iter().rev() {
1488 listener(action.as_any(), DispatchPhase::Bubble, self);
1489 if !self.propagate_event {
1490 break;
1491 }
1492 }
1493
1494 global_listeners.extend(
1495 self.global_action_listeners
1496 .remove(&action.as_any().type_id())
1497 .unwrap_or_default(),
1498 );
1499
1500 self.global_action_listeners
1501 .insert(action.as_any().type_id(), global_listeners);
1502 }
1503 }
1504 }
1505
1506 /// Is there currently something being dragged?
1507 pub fn has_active_drag(&self) -> bool {
1508 self.active_drag.is_some()
1509 }
1510
1511 /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1512 /// prompts with this custom implementation.
1513 pub fn set_prompt_builder(
1514 &mut self,
1515 renderer: impl Fn(
1516 PromptLevel,
1517 &str,
1518 Option<&str>,
1519 &[&str],
1520 PromptHandle,
1521 &mut Window,
1522 &mut App,
1523 ) -> RenderablePromptHandle
1524 + 'static,
1525 ) {
1526 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1527 }
1528
1529 /// Reset the prompt builder to the default implementation.
1530 pub fn reset_prompt_builder(&mut self) {
1531 self.prompt_builder = Some(PromptBuilder::Default);
1532 }
1533
1534 /// Remove an asset from GPUI's cache
1535 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
1536 let asset_id = (TypeId::of::<A>(), hash(source));
1537 self.loading_assets.remove(&asset_id);
1538 }
1539
1540 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1541 ///
1542 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1543 /// time, and the results of this call will be cached
1544 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
1545 let asset_id = (TypeId::of::<A>(), hash(source));
1546 let mut is_first = false;
1547 let task = self
1548 .loading_assets
1549 .remove(&asset_id)
1550 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1551 .unwrap_or_else(|| {
1552 is_first = true;
1553 let future = A::load(source.clone(), self);
1554 let task = self.background_executor().spawn(future).shared();
1555 task
1556 });
1557
1558 self.loading_assets.insert(asset_id, Box::new(task.clone()));
1559
1560 (task, is_first)
1561 }
1562
1563 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
1564 /// for elements rendered within this window.
1565 #[track_caller]
1566 pub fn focus_handle(&self) -> FocusHandle {
1567 FocusHandle::new(&self.focus_handles)
1568 }
1569
1570 /// Tell GPUI that an entity has changed and observers of it should be notified.
1571 pub fn notify(&mut self, entity_id: EntityId) {
1572 let window_invalidators = mem::take(
1573 self.window_invalidators_by_entity
1574 .entry(entity_id)
1575 .or_default(),
1576 );
1577
1578 if window_invalidators.is_empty() {
1579 if self.pending_notifications.insert(entity_id) {
1580 self.pending_effects
1581 .push_back(Effect::Notify { emitter: entity_id });
1582 }
1583 } else {
1584 for invalidator in window_invalidators.values() {
1585 invalidator.invalidate_view(entity_id, self);
1586 }
1587 }
1588
1589 self.window_invalidators_by_entity
1590 .insert(entity_id, window_invalidators);
1591 }
1592
1593 /// Returns the name for this [`App`].
1594 #[cfg(any(test, feature = "test-support", debug_assertions))]
1595 pub fn get_name(&self) -> Option<&'static str> {
1596 self.name
1597 }
1598
1599 /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
1600 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
1601 self.platform.can_select_mixed_files_and_dirs()
1602 }
1603}
1604
1605impl AppContext for App {
1606 type Result<T> = T;
1607
1608 /// Builds an entity that is owned by the application.
1609 ///
1610 /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
1611 /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
1612 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
1613 self.update(|cx| {
1614 let slot = cx.entities.reserve();
1615 let handle = slot.clone();
1616 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1617
1618 cx.push_effect(Effect::EntityCreated {
1619 entity: handle.clone().into_any(),
1620 tid: TypeId::of::<T>(),
1621 window: cx.window_update_stack.last().cloned(),
1622 });
1623
1624 cx.entities.insert(slot, entity);
1625 handle
1626 })
1627 }
1628
1629 fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1630 Reservation(self.entities.reserve())
1631 }
1632
1633 fn insert_entity<T: 'static>(
1634 &mut self,
1635 reservation: Reservation<T>,
1636 build_entity: impl FnOnce(&mut Context<T>) -> T,
1637 ) -> Self::Result<Entity<T>> {
1638 self.update(|cx| {
1639 let slot = reservation.0;
1640 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1641 cx.entities.insert(slot, entity)
1642 })
1643 }
1644
1645 /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
1646 /// entity along with a `Context` for the entity.
1647 fn update_entity<T: 'static, R>(
1648 &mut self,
1649 handle: &Entity<T>,
1650 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
1651 ) -> R {
1652 self.update(|cx| {
1653 let mut entity = cx.entities.lease(handle);
1654 let result = update(
1655 &mut entity,
1656 &mut Context::new_context(cx, handle.downgrade()),
1657 );
1658 cx.entities.end_lease(entity);
1659 result
1660 })
1661 }
1662
1663 fn read_entity<T, R>(
1664 &self,
1665 handle: &Entity<T>,
1666 read: impl FnOnce(&T, &App) -> R,
1667 ) -> Self::Result<R>
1668 where
1669 T: 'static,
1670 {
1671 let entity = self.entities.read(handle);
1672 read(entity, self)
1673 }
1674
1675 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1676 where
1677 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1678 {
1679 self.update_window_id(handle.id, update)
1680 }
1681
1682 fn read_window<T, R>(
1683 &self,
1684 window: &WindowHandle<T>,
1685 read: impl FnOnce(Entity<T>, &App) -> R,
1686 ) -> Result<R>
1687 where
1688 T: 'static,
1689 {
1690 let window = self
1691 .windows
1692 .get(window.id)
1693 .ok_or_else(|| anyhow!("window not found"))?
1694 .as_ref()
1695 .expect("attempted to read a window that is already on the stack");
1696
1697 let root_view = window.root.clone().unwrap();
1698 let view = root_view
1699 .downcast::<T>()
1700 .map_err(|_| anyhow!("root view's type has changed"))?;
1701
1702 Ok(read(view, self))
1703 }
1704
1705 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
1706 where
1707 R: Send + 'static,
1708 {
1709 self.background_executor.spawn(future)
1710 }
1711
1712 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
1713 where
1714 G: Global,
1715 {
1716 let mut g = self.global::<G>();
1717 callback(&g, self)
1718 }
1719}
1720
1721/// These effects are processed at the end of each application update cycle.
1722pub(crate) enum Effect {
1723 Notify {
1724 emitter: EntityId,
1725 },
1726 Emit {
1727 emitter: EntityId,
1728 event_type: TypeId,
1729 event: Box<dyn Any>,
1730 },
1731 RefreshWindows,
1732 NotifyGlobalObservers {
1733 global_type: TypeId,
1734 },
1735 Defer {
1736 callback: Box<dyn FnOnce(&mut App) + 'static>,
1737 },
1738 EntityCreated {
1739 entity: AnyEntity,
1740 tid: TypeId,
1741 window: Option<WindowId>,
1742 },
1743}
1744
1745impl std::fmt::Debug for Effect {
1746 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1747 match self {
1748 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
1749 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
1750 Effect::RefreshWindows => write!(f, "RefreshWindows"),
1751 Effect::NotifyGlobalObservers { global_type } => {
1752 write!(f, "NotifyGlobalObservers({:?})", global_type)
1753 }
1754 Effect::Defer { .. } => write!(f, "Defer(..)"),
1755 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
1756 }
1757 }
1758}
1759
1760/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1761pub(crate) struct GlobalLease<G: Global> {
1762 global: Box<dyn Any>,
1763 global_type: PhantomData<G>,
1764}
1765
1766impl<G: Global> GlobalLease<G> {
1767 fn new(global: Box<dyn Any>) -> Self {
1768 GlobalLease {
1769 global,
1770 global_type: PhantomData,
1771 }
1772 }
1773}
1774
1775impl<G: Global> Deref for GlobalLease<G> {
1776 type Target = G;
1777
1778 fn deref(&self) -> &Self::Target {
1779 self.global.downcast_ref().unwrap()
1780 }
1781}
1782
1783impl<G: Global> DerefMut for GlobalLease<G> {
1784 fn deref_mut(&mut self) -> &mut Self::Target {
1785 self.global.downcast_mut().unwrap()
1786 }
1787}
1788
1789/// Contains state associated with an active drag operation, started by dragging an element
1790/// within the window or by dragging into the app from the underlying platform.
1791pub struct AnyDrag {
1792 /// The view used to render this drag
1793 pub view: AnyView,
1794
1795 /// The value of the dragged item, to be dropped
1796 pub value: Arc<dyn Any>,
1797
1798 /// This is used to render the dragged item in the same place
1799 /// on the original element that the drag was initiated
1800 pub cursor_offset: Point<Pixels>,
1801}
1802
1803/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1804/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1805#[derive(Clone)]
1806pub struct AnyTooltip {
1807 /// The view used to display the tooltip
1808 pub view: AnyView,
1809
1810 /// The absolute position of the mouse when the tooltip was deployed.
1811 pub mouse_position: Point<Pixels>,
1812
1813 /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
1814 /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
1815 /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
1816 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
1817}
1818
1819/// A keystroke event, and potentially the associated action
1820#[derive(Debug)]
1821pub struct KeystrokeEvent {
1822 /// The keystroke that occurred
1823 pub keystroke: Keystroke,
1824
1825 /// The action that was resolved for the keystroke, if any
1826 pub action: Option<Box<dyn Action>>,
1827}
1828
1829struct NullHttpClient;
1830
1831impl HttpClient for NullHttpClient {
1832 fn send(
1833 &self,
1834 _req: http_client::Request<http_client::AsyncBody>,
1835 ) -> futures::future::BoxFuture<
1836 'static,
1837 Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>,
1838 > {
1839 async move { Err(anyhow!("No HttpClient available")) }.boxed()
1840 }
1841
1842 fn proxy(&self) -> Option<&http_client::Uri> {
1843 None
1844 }
1845
1846 fn type_name(&self) -> &'static str {
1847 type_name::<Self>()
1848 }
1849}