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