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<Fut, R>(&self, f: impl FnOnce(AsyncApp) -> Fut) -> Task<R>
1053 where
1054 Fut: Future<Output = R> + 'static,
1055 R: 'static,
1056 {
1057 self.foreground_executor.spawn(f(self.to_async()))
1058 }
1059
1060 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1061 /// that are currently on the stack to be returned to the app.
1062 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1063 self.push_effect(Effect::Defer {
1064 callback: Box::new(f),
1065 });
1066 }
1067
1068 /// Accessor for the application's asset source, which is provided when constructing the `App`.
1069 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1070 &self.asset_source
1071 }
1072
1073 /// Accessor for the text system.
1074 pub fn text_system(&self) -> &Arc<TextSystem> {
1075 &self.text_system
1076 }
1077
1078 /// Check whether a global of the given type has been assigned.
1079 pub fn has_global<G: Global>(&self) -> bool {
1080 self.globals_by_type.contains_key(&TypeId::of::<G>())
1081 }
1082
1083 /// Access the global of the given type. Panics if a global for that type has not been assigned.
1084 #[track_caller]
1085 pub fn global<G: Global>(&self) -> &G {
1086 self.globals_by_type
1087 .get(&TypeId::of::<G>())
1088 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1089 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
1090 .unwrap()
1091 }
1092
1093 /// Access the global of the given type if a value has been assigned.
1094 pub fn try_global<G: Global>(&self) -> Option<&G> {
1095 self.globals_by_type
1096 .get(&TypeId::of::<G>())
1097 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1098 }
1099
1100 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1101 #[track_caller]
1102 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1103 let global_type = TypeId::of::<G>();
1104 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1105 self.globals_by_type
1106 .get_mut(&global_type)
1107 .and_then(|any_state| any_state.downcast_mut::<G>())
1108 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
1109 .unwrap()
1110 }
1111
1112 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1113 /// yet been assigned.
1114 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1115 let global_type = TypeId::of::<G>();
1116 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1117 self.globals_by_type
1118 .entry(global_type)
1119 .or_insert_with(|| Box::<G>::default())
1120 .downcast_mut::<G>()
1121 .unwrap()
1122 }
1123
1124 /// Sets the value of the global of the given type.
1125 pub fn set_global<G: Global>(&mut self, global: G) {
1126 let global_type = TypeId::of::<G>();
1127 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1128 self.globals_by_type.insert(global_type, Box::new(global));
1129 }
1130
1131 /// Clear all stored globals. Does not notify global observers.
1132 #[cfg(any(test, feature = "test-support"))]
1133 pub fn clear_globals(&mut self) {
1134 self.globals_by_type.drain();
1135 }
1136
1137 /// Remove the global of the given type from the app context. Does not notify global observers.
1138 pub fn remove_global<G: Global>(&mut self) -> G {
1139 let global_type = TypeId::of::<G>();
1140 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1141 *self
1142 .globals_by_type
1143 .remove(&global_type)
1144 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1145 .downcast()
1146 .unwrap()
1147 }
1148
1149 /// Register a callback to be invoked when a global of the given type is updated.
1150 pub fn observe_global<G: Global>(
1151 &mut self,
1152 mut f: impl FnMut(&mut Self) + 'static,
1153 ) -> Subscription {
1154 let (subscription, activate) = self.global_observers.insert(
1155 TypeId::of::<G>(),
1156 Box::new(move |cx| {
1157 f(cx);
1158 true
1159 }),
1160 );
1161 self.defer(move |_| activate());
1162 subscription
1163 }
1164
1165 /// Move the global of the given type to the stack.
1166 #[track_caller]
1167 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1168 GlobalLease::new(
1169 self.globals_by_type
1170 .remove(&TypeId::of::<G>())
1171 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
1172 .unwrap(),
1173 )
1174 }
1175
1176 /// Restore the global of the given type after it is moved to the stack.
1177 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1178 let global_type = TypeId::of::<G>();
1179
1180 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1181 self.globals_by_type.insert(global_type, lease.global);
1182 }
1183
1184 pub(crate) fn new_entity_observer(
1185 &self,
1186 key: TypeId,
1187 value: NewEntityListener,
1188 ) -> Subscription {
1189 let (subscription, activate) = self.new_entity_observers.insert(key, value);
1190 activate();
1191 subscription
1192 }
1193
1194 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1195 /// The function will be passed a mutable reference to the view along with an appropriate context.
1196 pub fn observe_new<T: 'static>(
1197 &self,
1198 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1199 ) -> Subscription {
1200 self.new_entity_observer(
1201 TypeId::of::<T>(),
1202 Box::new(
1203 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1204 any_entity
1205 .downcast::<T>()
1206 .unwrap()
1207 .update(cx, |entity_state, cx| {
1208 if let Some(window) = window {
1209 on_new(entity_state, Some(window), cx);
1210 } else {
1211 on_new(entity_state, None, cx);
1212 }
1213 })
1214 },
1215 ),
1216 )
1217 }
1218
1219 /// Observe the release of a entity. The callback is invoked after the entity
1220 /// has no more strong references but before it has been dropped.
1221 pub fn observe_release<T>(
1222 &self,
1223 handle: &Entity<T>,
1224 on_release: impl FnOnce(&mut T, &mut App) + 'static,
1225 ) -> Subscription
1226 where
1227 T: 'static,
1228 {
1229 let (subscription, activate) = self.release_listeners.insert(
1230 handle.entity_id(),
1231 Box::new(move |entity, cx| {
1232 let entity = entity.downcast_mut().expect("invalid entity type");
1233 on_release(entity, cx)
1234 }),
1235 );
1236 activate();
1237 subscription
1238 }
1239
1240 /// Observe the release of a entity. The callback is invoked after the entity
1241 /// has no more strong references but before it has been dropped.
1242 pub fn observe_release_in<T>(
1243 &self,
1244 handle: &Entity<T>,
1245 window: &Window,
1246 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1247 ) -> Subscription
1248 where
1249 T: 'static,
1250 {
1251 let window_handle = window.handle;
1252 self.observe_release(&handle, move |entity, cx| {
1253 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1254 })
1255 }
1256
1257 /// Register a callback to be invoked when a keystroke is received by the application
1258 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1259 /// and that this API will not be invoked if the event's propagation is stopped.
1260 pub fn observe_keystrokes(
1261 &mut self,
1262 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1263 ) -> Subscription {
1264 fn inner(
1265 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1266 handler: KeystrokeObserver,
1267 ) -> Subscription {
1268 let (subscription, activate) = keystroke_observers.insert((), handler);
1269 activate();
1270 subscription
1271 }
1272
1273 inner(
1274 &mut self.keystroke_observers,
1275 Box::new(move |event, window, cx| {
1276 f(event, window, cx);
1277 true
1278 }),
1279 )
1280 }
1281
1282 /// Register key bindings.
1283 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1284 self.keymap.borrow_mut().add_bindings(bindings);
1285 self.pending_effects.push_back(Effect::RefreshWindows);
1286 }
1287
1288 /// Clear all key bindings in the app.
1289 pub fn clear_key_bindings(&mut self) {
1290 self.keymap.borrow_mut().clear();
1291 self.pending_effects.push_back(Effect::RefreshWindows);
1292 }
1293
1294 /// Register a global listener for actions invoked via the keyboard.
1295 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1296 self.global_action_listeners
1297 .entry(TypeId::of::<A>())
1298 .or_default()
1299 .push(Rc::new(move |action, phase, cx| {
1300 if phase == DispatchPhase::Bubble {
1301 let action = action.downcast_ref().unwrap();
1302 listener(action, cx)
1303 }
1304 }));
1305 }
1306
1307 /// Event handlers propagate events by default. Call this method to stop dispatching to
1308 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1309 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1310 /// calling this method before effects are flushed.
1311 pub fn stop_propagation(&mut self) {
1312 self.propagate_event = false;
1313 }
1314
1315 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1316 /// dispatching to action handlers higher in the element tree. This is the opposite of
1317 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1318 /// this method before effects are flushed.
1319 pub fn propagate(&mut self) {
1320 self.propagate_event = true;
1321 }
1322
1323 /// Build an action from some arbitrary data, typically a keymap entry.
1324 pub fn build_action(
1325 &self,
1326 name: &str,
1327 data: Option<serde_json::Value>,
1328 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1329 self.actions.build_action(name, data)
1330 }
1331
1332 /// Get all action names that have been registered. Note that registration only allows for
1333 /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1334 pub fn all_action_names(&self) -> &[SharedString] {
1335 self.actions.all_action_names()
1336 }
1337
1338 /// Returns key bindings that invoke the given action on the currently focused element, without
1339 /// checking context. Bindings are returned in the order they were added. For display, the last
1340 /// binding should take precedence.
1341 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1342 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1343 }
1344
1345 /// Get all non-internal actions that have been registered, along with their schemas.
1346 pub fn action_schemas(
1347 &self,
1348 generator: &mut schemars::gen::SchemaGenerator,
1349 ) -> Vec<(SharedString, Option<schemars::schema::Schema>)> {
1350 self.actions.action_schemas(generator)
1351 }
1352
1353 /// Get a list of all deprecated action aliases and their canonical names.
1354 pub fn action_deprecations(&self) -> &HashMap<SharedString, SharedString> {
1355 self.actions.action_deprecations()
1356 }
1357
1358 /// Register a callback to be invoked when the application is about to quit.
1359 /// It is not possible to cancel the quit event at this point.
1360 pub fn on_app_quit<Fut>(
1361 &self,
1362 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1363 ) -> Subscription
1364 where
1365 Fut: 'static + Future<Output = ()>,
1366 {
1367 let (subscription, activate) = self.quit_observers.insert(
1368 (),
1369 Box::new(move |cx| {
1370 let future = on_quit(cx);
1371 future.boxed_local()
1372 }),
1373 );
1374 activate();
1375 subscription
1376 }
1377
1378 /// Register a callback to be invoked when a window is closed
1379 /// The window is no longer accessible at the point this callback is invoked.
1380 pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1381 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1382 activate();
1383 subscription
1384 }
1385
1386 pub(crate) fn clear_pending_keystrokes(&mut self) {
1387 for window in self.windows() {
1388 window
1389 .update(self, |_, window, _| {
1390 window.clear_pending_keystrokes();
1391 })
1392 .ok();
1393 }
1394 }
1395
1396 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1397 /// the bindings in the element tree, and any global action listeners.
1398 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1399 let mut action_available = false;
1400 if let Some(window) = self.active_window() {
1401 if let Ok(window_action_available) =
1402 window.update(self, |_, window, cx| window.is_action_available(action, cx))
1403 {
1404 action_available = window_action_available;
1405 }
1406 }
1407
1408 action_available
1409 || self
1410 .global_action_listeners
1411 .contains_key(&action.as_any().type_id())
1412 }
1413
1414 /// Sets the menu bar for this application. This will replace any existing menu bar.
1415 pub fn set_menus(&self, menus: Vec<Menu>) {
1416 self.platform.set_menus(menus, &self.keymap.borrow());
1417 }
1418
1419 /// Gets the menu bar for this application.
1420 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1421 self.platform.get_menus()
1422 }
1423
1424 /// Sets the right click menu for the app icon in the dock
1425 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1426 self.platform.set_dock_menu(menus, &self.keymap.borrow());
1427 }
1428
1429 /// Performs the action associated with the given dock menu item, only used on Windows for now.
1430 pub fn perform_dock_menu_action(&self, action: usize) {
1431 self.platform.perform_dock_menu_action(action);
1432 }
1433
1434 /// Adds given path to the bottom of the list of recent paths for the application.
1435 /// The list is usually shown on the application icon's context menu in the dock,
1436 /// and allows to open the recent files via that context menu.
1437 /// If the path is already in the list, it will be moved to the bottom of the list.
1438 pub fn add_recent_document(&self, path: &Path) {
1439 self.platform.add_recent_document(path);
1440 }
1441
1442 /// Dispatch an action to the currently active window or global action handler
1443 /// See [`crate::Action`] for more information on how actions work
1444 pub fn dispatch_action(&mut self, action: &dyn Action) {
1445 if let Some(active_window) = self.active_window() {
1446 active_window
1447 .update(self, |_, window, cx| {
1448 window.dispatch_action(action.boxed_clone(), cx)
1449 })
1450 .log_err();
1451 } else {
1452 self.dispatch_global_action(action);
1453 }
1454 }
1455
1456 fn dispatch_global_action(&mut self, action: &dyn Action) {
1457 self.propagate_event = true;
1458
1459 if let Some(mut global_listeners) = self
1460 .global_action_listeners
1461 .remove(&action.as_any().type_id())
1462 {
1463 for listener in &global_listeners {
1464 listener(action.as_any(), DispatchPhase::Capture, self);
1465 if !self.propagate_event {
1466 break;
1467 }
1468 }
1469
1470 global_listeners.extend(
1471 self.global_action_listeners
1472 .remove(&action.as_any().type_id())
1473 .unwrap_or_default(),
1474 );
1475
1476 self.global_action_listeners
1477 .insert(action.as_any().type_id(), global_listeners);
1478 }
1479
1480 if self.propagate_event {
1481 if let Some(mut global_listeners) = self
1482 .global_action_listeners
1483 .remove(&action.as_any().type_id())
1484 {
1485 for listener in global_listeners.iter().rev() {
1486 listener(action.as_any(), DispatchPhase::Bubble, self);
1487 if !self.propagate_event {
1488 break;
1489 }
1490 }
1491
1492 global_listeners.extend(
1493 self.global_action_listeners
1494 .remove(&action.as_any().type_id())
1495 .unwrap_or_default(),
1496 );
1497
1498 self.global_action_listeners
1499 .insert(action.as_any().type_id(), global_listeners);
1500 }
1501 }
1502 }
1503
1504 /// Is there currently something being dragged?
1505 pub fn has_active_drag(&self) -> bool {
1506 self.active_drag.is_some()
1507 }
1508
1509 /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1510 /// prompts with this custom implementation.
1511 pub fn set_prompt_builder(
1512 &mut self,
1513 renderer: impl Fn(
1514 PromptLevel,
1515 &str,
1516 Option<&str>,
1517 &[&str],
1518 PromptHandle,
1519 &mut Window,
1520 &mut App,
1521 ) -> RenderablePromptHandle
1522 + 'static,
1523 ) {
1524 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1525 }
1526
1527 /// Remove an asset from GPUI's cache
1528 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
1529 let asset_id = (TypeId::of::<A>(), hash(source));
1530 self.loading_assets.remove(&asset_id);
1531 }
1532
1533 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1534 ///
1535 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1536 /// time, and the results of this call will be cached
1537 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
1538 let asset_id = (TypeId::of::<A>(), hash(source));
1539 let mut is_first = false;
1540 let task = self
1541 .loading_assets
1542 .remove(&asset_id)
1543 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1544 .unwrap_or_else(|| {
1545 is_first = true;
1546 let future = A::load(source.clone(), self);
1547 let task = self.background_executor().spawn(future).shared();
1548 task
1549 });
1550
1551 self.loading_assets.insert(asset_id, Box::new(task.clone()));
1552
1553 (task, is_first)
1554 }
1555
1556 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
1557 /// for elements rendered within this window.
1558 #[track_caller]
1559 pub fn focus_handle(&self) -> FocusHandle {
1560 FocusHandle::new(&self.focus_handles)
1561 }
1562
1563 /// Tell GPUI that an entity has changed and observers of it should be notified.
1564 pub fn notify(&mut self, entity_id: EntityId) {
1565 let window_invalidators = mem::take(
1566 self.window_invalidators_by_entity
1567 .entry(entity_id)
1568 .or_default(),
1569 );
1570
1571 if window_invalidators.is_empty() {
1572 if self.pending_notifications.insert(entity_id) {
1573 self.pending_effects
1574 .push_back(Effect::Notify { emitter: entity_id });
1575 }
1576 } else {
1577 for invalidator in window_invalidators.values() {
1578 invalidator.invalidate_view(entity_id, self);
1579 }
1580 }
1581
1582 self.window_invalidators_by_entity
1583 .insert(entity_id, window_invalidators);
1584 }
1585
1586 /// Get the name for this App.
1587 #[cfg(any(test, feature = "test-support", debug_assertions))]
1588 pub fn get_name(&self) -> &'static str {
1589 self.name.as_ref().unwrap()
1590 }
1591
1592 /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
1593 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
1594 self.platform.can_select_mixed_files_and_dirs()
1595 }
1596}
1597
1598impl AppContext for App {
1599 type Result<T> = T;
1600
1601 /// Build an entity that is owned by the application. The given function will be invoked with
1602 /// a `Context` and must return an object representing the entity. A `Entity` handle will be returned,
1603 /// which can be used to access the entity in a context.
1604 fn new<T: 'static>(
1605 &mut self,
1606 build_entity: impl FnOnce(&mut Context<'_, T>) -> T,
1607 ) -> Entity<T> {
1608 self.update(|cx| {
1609 let slot = cx.entities.reserve();
1610 let handle = slot.clone();
1611 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1612
1613 cx.push_effect(Effect::EntityCreated {
1614 entity: handle.clone().into_any(),
1615 tid: TypeId::of::<T>(),
1616 window: cx.window_update_stack.last().cloned(),
1617 });
1618
1619 cx.entities.insert(slot, entity);
1620 handle
1621 })
1622 }
1623
1624 fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1625 Reservation(self.entities.reserve())
1626 }
1627
1628 fn insert_entity<T: 'static>(
1629 &mut self,
1630 reservation: Reservation<T>,
1631 build_entity: impl FnOnce(&mut Context<'_, T>) -> T,
1632 ) -> Self::Result<Entity<T>> {
1633 self.update(|cx| {
1634 let slot = reservation.0;
1635 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1636 cx.entities.insert(slot, entity)
1637 })
1638 }
1639
1640 /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
1641 /// entity along with a `Context` for the entity.
1642 fn update_entity<T: 'static, R>(
1643 &mut self,
1644 handle: &Entity<T>,
1645 update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
1646 ) -> R {
1647 self.update(|cx| {
1648 let mut entity = cx.entities.lease(handle);
1649 let result = update(
1650 &mut entity,
1651 &mut Context::new_context(cx, handle.downgrade()),
1652 );
1653 cx.entities.end_lease(entity);
1654 result
1655 })
1656 }
1657
1658 fn read_entity<T, R>(
1659 &self,
1660 handle: &Entity<T>,
1661 read: impl FnOnce(&T, &App) -> R,
1662 ) -> Self::Result<R>
1663 where
1664 T: 'static,
1665 {
1666 let entity = self.entities.read(handle);
1667 read(entity, self)
1668 }
1669
1670 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1671 where
1672 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1673 {
1674 self.update_window_id(handle.id, update)
1675 }
1676
1677 fn read_window<T, R>(
1678 &self,
1679 window: &WindowHandle<T>,
1680 read: impl FnOnce(Entity<T>, &App) -> R,
1681 ) -> Result<R>
1682 where
1683 T: 'static,
1684 {
1685 let window = self
1686 .windows
1687 .get(window.id)
1688 .ok_or_else(|| anyhow!("window not found"))?
1689 .as_ref()
1690 .expect("attempted to read a window that is already on the stack");
1691
1692 let root_view = window.root.clone().unwrap();
1693 let view = root_view
1694 .downcast::<T>()
1695 .map_err(|_| anyhow!("root view's type has changed"))?;
1696
1697 Ok(read(view, self))
1698 }
1699
1700 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
1701 where
1702 R: Send + 'static,
1703 {
1704 self.background_executor.spawn(future)
1705 }
1706
1707 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
1708 where
1709 G: Global,
1710 {
1711 let mut g = self.global::<G>();
1712 callback(&g, self)
1713 }
1714}
1715
1716/// These effects are processed at the end of each application update cycle.
1717pub(crate) enum Effect {
1718 Notify {
1719 emitter: EntityId,
1720 },
1721 Emit {
1722 emitter: EntityId,
1723 event_type: TypeId,
1724 event: Box<dyn Any>,
1725 },
1726 RefreshWindows,
1727 NotifyGlobalObservers {
1728 global_type: TypeId,
1729 },
1730 Defer {
1731 callback: Box<dyn FnOnce(&mut App) + 'static>,
1732 },
1733 EntityCreated {
1734 entity: AnyEntity,
1735 tid: TypeId,
1736 window: Option<WindowId>,
1737 },
1738}
1739
1740impl std::fmt::Debug for Effect {
1741 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1742 match self {
1743 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
1744 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
1745 Effect::RefreshWindows => write!(f, "RefreshWindows"),
1746 Effect::NotifyGlobalObservers { global_type } => {
1747 write!(f, "NotifyGlobalObservers({:?})", global_type)
1748 }
1749 Effect::Defer { .. } => write!(f, "Defer(..)"),
1750 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
1751 }
1752 }
1753}
1754
1755/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1756pub(crate) struct GlobalLease<G: Global> {
1757 global: Box<dyn Any>,
1758 global_type: PhantomData<G>,
1759}
1760
1761impl<G: Global> GlobalLease<G> {
1762 fn new(global: Box<dyn Any>) -> Self {
1763 GlobalLease {
1764 global,
1765 global_type: PhantomData,
1766 }
1767 }
1768}
1769
1770impl<G: Global> Deref for GlobalLease<G> {
1771 type Target = G;
1772
1773 fn deref(&self) -> &Self::Target {
1774 self.global.downcast_ref().unwrap()
1775 }
1776}
1777
1778impl<G: Global> DerefMut for GlobalLease<G> {
1779 fn deref_mut(&mut self) -> &mut Self::Target {
1780 self.global.downcast_mut().unwrap()
1781 }
1782}
1783
1784/// Contains state associated with an active drag operation, started by dragging an element
1785/// within the window or by dragging into the app from the underlying platform.
1786pub struct AnyDrag {
1787 /// The view used to render this drag
1788 pub view: AnyView,
1789
1790 /// The value of the dragged item, to be dropped
1791 pub value: Arc<dyn Any>,
1792
1793 /// This is used to render the dragged item in the same place
1794 /// on the original element that the drag was initiated
1795 pub cursor_offset: Point<Pixels>,
1796}
1797
1798/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1799/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1800#[derive(Clone)]
1801pub struct AnyTooltip {
1802 /// The view used to display the tooltip
1803 pub view: AnyView,
1804
1805 /// The absolute position of the mouse when the tooltip was deployed.
1806 pub mouse_position: Point<Pixels>,
1807
1808 /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
1809 /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
1810 /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
1811 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
1812}
1813
1814/// A keystroke event, and potentially the associated action
1815#[derive(Debug)]
1816pub struct KeystrokeEvent {
1817 /// The keystroke that occurred
1818 pub keystroke: Keystroke,
1819
1820 /// The action that was resolved for the keystroke, if any
1821 pub action: Option<Box<dyn Action>>,
1822}
1823
1824struct NullHttpClient;
1825
1826impl HttpClient for NullHttpClient {
1827 fn send(
1828 &self,
1829 _req: http_client::Request<http_client::AsyncBody>,
1830 ) -> futures::future::BoxFuture<
1831 'static,
1832 Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>,
1833 > {
1834 async move { Err(anyhow!("No HttpClient available")) }.boxed()
1835 }
1836
1837 fn proxy(&self) -> Option<&http_client::Uri> {
1838 None
1839 }
1840
1841 fn type_name(&self) -> &'static str {
1842 type_name::<Self>()
1843 }
1844}