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