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