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