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