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