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