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