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