1use scheduler::Instant;
3use std::{
4 any::{TypeId, type_name},
5 cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
6 ffi::OsString,
7 marker::PhantomData,
8 mem,
9 ops::{Deref, DerefMut},
10 path::{Path, PathBuf},
11 rc::{Rc, Weak},
12 sync::{Arc, atomic::Ordering::SeqCst},
13 time::Duration,
14};
15
16use anyhow::{Context as _, Result, anyhow};
17use derive_more::{Deref, DerefMut};
18use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
19use itertools::Itertools;
20use parking_lot::RwLock;
21use slotmap::SlotMap;
22
23pub use async_context::*;
24#[cfg(feature = "bench-support")]
25pub use bench_context::{
26 BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
27 MetricReport, bench_platform,
28};
29use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
30pub use context::*;
31pub use entity_map::*;
32use gpui_util::{ResultExt, debug_panic};
33#[cfg(any(test, feature = "test-support"))]
34pub use headless_app_context::*;
35use http_client::{HttpClient, Url};
36use smallvec::SmallVec;
37#[cfg(any(test, feature = "test-support"))]
38pub use test_app::*;
39#[cfg(any(test, feature = "test-support"))]
40pub use test_context::*;
41#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
42pub use visual_test_context::*;
43
44#[cfg(any(feature = "inspector", debug_assertions))]
45use crate::InspectorElementRegistry;
46use crate::asset_cache::CachedLoad;
47use crate::{
48 Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
49 AnyWindowHandle, AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds,
50 ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase, DisplayId, EventEmitter,
51 ExternalDragPayload, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext,
52 Keymap, Keystroke, LayoutId, Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions,
53 Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point,
54 Priority, PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
55 RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
56 Subscription, SvgRenderer, SystemNotification, SystemNotificationResponse, Task,
57 TextRenderingMode, TextSystem, ThermalState, Window, WindowAppearance, WindowButtonLayout,
58 WindowHandle, WindowId, WindowInvalidator, WindowingRequest,
59 colors::{Colors, GlobalColors},
60 hash, init_app_menus,
61};
62
63mod async_context;
64#[cfg(feature = "bench-support")]
65mod bench_context;
66mod context;
67mod entity_map;
68#[cfg(any(test, feature = "test-support"))]
69mod headless_app_context;
70#[cfg(any(test, feature = "test-support"))]
71mod test_app;
72#[cfg(any(test, feature = "test-support"))]
73mod test_context;
74#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
75mod visual_test_context;
76
77pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
80
81#[doc(hidden)]
84pub struct AppCell {
85 app: RefCell<App>,
86}
87
88impl AppCell {
89 #[doc(hidden)]
90 #[track_caller]
91 pub fn borrow(&self) -> AppRef<'_> {
92 if option_env!("TRACK_THREAD_BORROWS").is_some() {
93 let thread_id = std::thread::current().id();
94 eprintln!("borrowed {thread_id:?}");
95 }
96 AppRef(self.app.borrow())
97 }
98
99 #[doc(hidden)]
100 #[track_caller]
101 pub fn borrow_mut(&self) -> AppRefMut<'_> {
102 if option_env!("TRACK_THREAD_BORROWS").is_some() {
103 let thread_id = std::thread::current().id();
104 eprintln!("borrowed {thread_id:?}");
105 }
106 AppRefMut(self.app.borrow_mut())
107 }
108
109 #[doc(hidden)]
110 #[track_caller]
111 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
112 if option_env!("TRACK_THREAD_BORROWS").is_some() {
113 let thread_id = std::thread::current().id();
114 eprintln!("borrowed {thread_id:?}");
115 }
116 Ok(AppRefMut(self.app.try_borrow_mut()?))
117 }
118}
119
120#[doc(hidden)]
121#[derive(Deref, DerefMut)]
122pub struct AppRef<'a>(Ref<'a, App>);
123
124impl Drop for AppRef<'_> {
125 fn drop(&mut self) {
126 if option_env!("TRACK_THREAD_BORROWS").is_some() {
127 let thread_id = std::thread::current().id();
128 eprintln!("dropped borrow from {thread_id:?}");
129 }
130 }
131}
132
133#[doc(hidden)]
134#[derive(Deref, DerefMut)]
135pub struct AppRefMut<'a>(RefMut<'a, App>);
136
137impl Drop for AppRefMut<'_> {
138 fn drop(&mut self) {
139 if option_env!("TRACK_THREAD_BORROWS").is_some() {
140 let thread_id = std::thread::current().id();
141 eprintln!("dropped {thread_id:?}");
142 }
143 }
144}
145
146pub struct Application(Rc<AppCell>);
149
150pub struct ApplicationHandle {
156 app: Rc<AppCell>,
157}
158
159impl ApplicationHandle {
160 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
164 let cx = &mut *self.app.borrow_mut();
165 f(cx)
166 }
167
168 pub fn to_async(&self) -> AsyncApp {
171 self.update(|cx| cx.to_async())
172 }
173}
174
175impl Application {
178 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
180 Self(App::new_app(
181 platform,
182 Arc::new(()),
183 Arc::new(NullHttpClient),
184 ))
185 }
186
187 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
197 let this = Self::with_platform(platform);
198 this.0.borrow_mut().accessibility_force_disabled = true;
199 this
200 }
201
202 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
204 let mut context_lock = self.0.borrow_mut();
205 let asset_source = Arc::new(asset_source);
206 context_lock.asset_source = asset_source.clone();
207 context_lock.svg_renderer = SvgRenderer::new(asset_source);
208 drop(context_lock);
209 self
210 }
211
212 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
214 self.0.borrow_mut().restart_arguments = arguments;
215 self
216 }
217
218 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
220 let mut context_lock = self.0.borrow_mut();
221 context_lock.http_client = http_client;
222 drop(context_lock);
223 self
224 }
225
226 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
229 self.0.borrow_mut().quit_mode = mode;
230 self
231 }
232
233 pub fn with_windowing(self, request: WindowingRequest) -> Self {
240 self.0.borrow().platform.set_initial_windowing(request);
241 self
242 }
243
244 pub fn run<F>(self, on_finish_launching: F)
250 where
251 F: 'static + FnOnce(&mut App),
252 {
253 let this = self.0.clone();
254 let platform = self.0.borrow().platform.clone();
255 platform.run(Box::new(move || {
256 let cx = &mut *this.borrow_mut();
257 on_finish_launching(cx);
258 }));
259
260 #[cfg(target_family = "wasm")]
261 std::mem::forget(self);
262 }
263
264 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
274 where
275 F: 'static + FnOnce(&mut App),
276 {
277 let this = self.0.clone();
278 let platform = self.0.borrow().platform.clone();
279 platform.run(Box::new(move || {
280 let cx = &mut *this.borrow_mut();
281 on_finish_launching(cx);
282 }));
283 ApplicationHandle { app: self.0 }
284 }
285
286 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
289 where
290 F: 'static + FnMut(Vec<String>),
291 {
292 self.0.borrow().platform.on_open_urls(Box::new(callback));
293 self
294 }
295
296 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
299 where
300 F: 'static + FnMut(&mut App),
301 {
302 let this = Rc::downgrade(&self.0);
303 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
304 if let Some(app) = this.upgrade() {
305 callback(&mut app.borrow_mut());
306 }
307 }));
308 self
309 }
310
311 pub fn background_executor(&self) -> BackgroundExecutor {
313 self.0.borrow().background_executor.clone()
314 }
315
316 pub fn foreground_executor(&self) -> ForegroundExecutor {
318 self.0.borrow().foreground_executor.clone()
319 }
320
321 pub fn text_system(&self) -> Arc<TextSystem> {
323 self.0.borrow().text_system.clone()
324 }
325
326 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
328 self.0.borrow().path_for_auxiliary_executable(name)
329 }
330}
331
332type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
333type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
334type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
335pub(crate) type KeystrokeObserver =
336 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
337type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
338type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
339type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
340type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
341
342struct MissingGlyphCallbackEntry {
343 registration: Rc<()>,
344 callback: Option<MissingGlyphCallback>,
345}
346
347#[derive(Default)]
348struct MissingGlyphCallbackSlot {
349 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
350}
351
352impl MissingGlyphCallbackSlot {
353 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
354 let registration = Rc::new(());
355 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
356 registration: registration.clone(),
357 callback: Some(callback),
358 });
359 registration
360 }
361
362 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
363 let Some((registration, mut callback)) =
364 self.entry.borrow_mut().as_mut().and_then(|entry| {
365 entry
366 .callback
367 .take()
368 .map(|callback| (entry.registration.clone(), callback))
369 })
370 else {
371 return;
372 };
373 callback(missing_glyphs, cx);
374
375 let mut entry = self.entry.borrow_mut();
376 let is_current = entry
377 .as_ref()
378 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
379 if is_current {
380 let Some(entry) = entry.as_mut() else {
381 return;
382 };
383 entry.callback = Some(callback);
384 }
385 }
386
387 fn remove(&self, registration: &Rc<()>) -> bool {
388 let mut entry = self.entry.borrow_mut();
389 let is_current = entry
390 .as_ref()
391 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
392 if is_current {
393 entry.take();
394 }
395 is_current
396 }
397}
398
399#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
401pub enum QuitMode {
402 #[default]
404 Default,
405 LastWindowClosed,
407 Explicit,
409}
410
411#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
416pub enum CursorHideMode {
417 Never,
419 OnTyping,
421 #[default]
424 OnTypingAndAction,
425}
426
427#[doc(hidden)]
428#[derive(Clone, PartialEq, Eq)]
429pub struct SystemWindowTab {
430 pub id: WindowId,
431 pub title: SharedString,
432 pub handle: AnyWindowHandle,
433 pub last_active_at: Instant,
434}
435
436impl SystemWindowTab {
437 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
439 Self {
440 id: handle.id,
441 title,
442 handle,
443 last_active_at: Instant::now(),
444 }
445 }
446}
447
448#[derive(Default)]
450pub struct SystemWindowTabController {
451 visible: Option<bool>,
452 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
453}
454
455impl Global for SystemWindowTabController {}
456
457impl SystemWindowTabController {
458 pub fn new() -> Self {
460 Self {
461 visible: None,
462 tab_groups: FxHashMap::default(),
463 }
464 }
465
466 pub fn init(cx: &mut App) {
468 cx.set_global(SystemWindowTabController::new());
469 }
470
471 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
473 &self.tab_groups
474 }
475
476 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
478 let controller = cx.global::<SystemWindowTabController>();
479 let current_group = controller
480 .tab_groups
481 .iter()
482 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
483
484 let current_group = current_group?;
485 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
487 let idx = group_ids.iter().position(|g| *g == current_group)?;
488 let next_idx = (idx + 1) % group_ids.len();
489
490 controller
491 .tab_groups
492 .get(group_ids[next_idx])
493 .and_then(|tabs| {
494 tabs.iter()
495 .max_by_key(|tab| tab.last_active_at)
496 .or_else(|| tabs.first())
497 .map(|tab| &tab.handle)
498 })
499 }
500
501 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
503 let controller = cx.global::<SystemWindowTabController>();
504 let current_group = controller
505 .tab_groups
506 .iter()
507 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
508
509 let current_group = current_group?;
510 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
512 let idx = group_ids.iter().position(|g| *g == current_group)?;
513 let prev_idx = if idx == 0 {
514 group_ids.len() - 1
515 } else {
516 idx - 1
517 };
518
519 controller
520 .tab_groups
521 .get(group_ids[prev_idx])
522 .and_then(|tabs| {
523 tabs.iter()
524 .max_by_key(|tab| tab.last_active_at)
525 .or_else(|| tabs.first())
526 .map(|tab| &tab.handle)
527 })
528 }
529
530 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
532 self.tab_groups
533 .values()
534 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
535 }
536
537 pub fn init_visible(cx: &mut App, visible: bool) {
539 let mut controller = cx.global_mut::<SystemWindowTabController>();
540 if controller.visible.is_none() {
541 controller.visible = Some(visible);
542 }
543 }
544
545 pub fn is_visible(&self) -> bool {
547 self.visible.unwrap_or(false)
548 }
549
550 pub fn set_visible(cx: &mut App, visible: bool) {
552 let mut controller = cx.global_mut::<SystemWindowTabController>();
553 controller.visible = Some(visible);
554 }
555
556 pub fn update_last_active(cx: &mut App, id: WindowId) {
558 let mut controller = cx.global_mut::<SystemWindowTabController>();
559 for windows in controller.tab_groups.values_mut() {
560 for tab in windows.iter_mut() {
561 if tab.id == id {
562 tab.last_active_at = Instant::now();
563 }
564 }
565 }
566 }
567
568 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
570 let mut controller = cx.global_mut::<SystemWindowTabController>();
571 for (_, windows) in controller.tab_groups.iter_mut() {
572 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
573 if ix < windows.len() && current_pos != ix {
574 let window_tab = windows.remove(current_pos);
575 windows.insert(ix, window_tab);
576 }
577 break;
578 }
579 }
580 }
581
582 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
584 let controller = cx.global::<SystemWindowTabController>();
585 let tab = controller
586 .tab_groups
587 .values()
588 .flat_map(|windows| windows.iter())
589 .find(|tab| tab.id == id);
590
591 if tab.map_or(true, |t| t.title == title) {
592 return;
593 }
594
595 let mut controller = cx.global_mut::<SystemWindowTabController>();
596 for windows in controller.tab_groups.values_mut() {
597 for tab in windows.iter_mut() {
598 if tab.id == id {
599 tab.title = title;
600 return;
601 }
602 }
603 }
604 }
605
606 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
608 let mut controller = cx.global_mut::<SystemWindowTabController>();
609 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
610 return;
611 };
612
613 let mut expected_tab_ids: Vec<_> = tabs
614 .iter()
615 .filter(|tab| tab.id != id)
616 .map(|tab| tab.id)
617 .sorted()
618 .collect();
619
620 let mut tab_group_id = None;
621 for (group_id, group_tabs) in &controller.tab_groups {
622 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
623 if tab_ids == expected_tab_ids {
624 tab_group_id = Some(*group_id);
625 break;
626 }
627 }
628
629 if let Some(tab_group_id) = tab_group_id {
630 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
631 tabs.push(tab);
632 }
633 } else {
634 let new_group_id = controller.tab_groups.len();
635 controller.tab_groups.insert(new_group_id, tabs);
636 }
637 }
638
639 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
641 let mut controller = cx.global_mut::<SystemWindowTabController>();
642 let mut removed_tab = None;
643
644 controller.tab_groups.retain(|_, tabs| {
645 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
646 removed_tab = Some(tabs.remove(pos));
647 }
648 !tabs.is_empty()
649 });
650
651 removed_tab
652 }
653
654 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
656 let mut removed_tab = Self::remove_tab(cx, id);
657 let mut controller = cx.global_mut::<SystemWindowTabController>();
658
659 if let Some(tab) = removed_tab {
660 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
661 controller.tab_groups.insert(new_group_id, vec![tab]);
662 }
663 }
664
665 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
667 let mut controller = cx.global_mut::<SystemWindowTabController>();
668 let Some(initial_tabs) = controller.tabs(id) else {
669 return;
670 };
671
672 let initial_tabs_len = initial_tabs.len();
673 let mut all_tabs = initial_tabs.clone();
674
675 for (_, mut tabs) in controller.tab_groups.drain() {
676 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
677 all_tabs.extend(tabs);
678 }
679
680 controller.tab_groups.insert(0, all_tabs);
681 }
682
683 pub fn select_next_tab(cx: &mut App, id: WindowId) {
685 let mut controller = cx.global_mut::<SystemWindowTabController>();
686 let Some(tabs) = controller.tabs(id) else {
687 return;
688 };
689
690 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
691 let next_index = (current_index + 1) % tabs.len();
692
693 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
694 window.activate_window();
695 });
696 }
697
698 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
700 let mut controller = cx.global_mut::<SystemWindowTabController>();
701 let Some(tabs) = controller.tabs(id) else {
702 return;
703 };
704
705 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
706 let previous_index = if current_index == 0 {
707 tabs.len() - 1
708 } else {
709 current_index - 1
710 };
711
712 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
713 window.activate_window();
714 });
715 }
716}
717
718pub(crate) enum GpuiMode {
719 #[cfg(any(test, feature = "test-support"))]
720 Test {
721 skip_drawing: bool,
722 },
723 Production,
724}
725
726impl GpuiMode {
727 #[cfg(any(test, feature = "test-support"))]
728 pub fn test() -> Self {
729 GpuiMode::Test {
730 skip_drawing: false,
731 }
732 }
733
734 #[inline]
735 pub(crate) fn skip_drawing(&self) -> bool {
736 match self {
737 #[cfg(any(test, feature = "test-support"))]
738 GpuiMode::Test { skip_drawing } => *skip_drawing,
739 GpuiMode::Production => false,
740 }
741 }
742}
743
744struct PlatformOwnedDrag {
745 source_window: WindowId,
746 state: PlatformOwnedDragState,
747}
748
749enum PlatformOwnedDragState {
750 Suspended(AnyDrag),
751 RestoredInSourceWindow,
754}
755
756pub struct App {
760 pub(crate) this: Weak<AppCell>,
761 pub(crate) platform: Rc<dyn Platform>,
762 text_system: Arc<TextSystem>,
763
764 pub(crate) actions: Rc<ActionRegistry>,
765 pub(crate) active_drag: Option<AnyDrag>,
766 platform_owned_drag: Option<PlatformOwnedDrag>,
767 pub(crate) background_executor: BackgroundExecutor,
768 pub(crate) foreground_executor: ForegroundExecutor,
769 #[cfg(feature = "profiler")]
770 foreground_journal: crate::profiler::journal::ForegroundJournal,
771 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
772 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
773 pub(crate) entities: EntityMap,
774 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
775 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
776 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
777 pub(crate) focus_handles: Arc<FocusMap>,
778 pub(crate) keymap: Rc<RefCell<Keymap>>,
779 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
780 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
781 pub(crate) global_action_listeners:
782 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
783 pending_effects: VecDeque<Effect>,
784
785 pub(crate) observers: SubscriberSet<EntityId, Handler>,
786 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
787 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
788 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
789 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
790 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
791 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
792 pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
793 pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
794 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
795 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
796 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
797 pub(crate) restart_observers: SubscriberSet<(), Handler>,
798 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
799
800 pub(crate) element_arena: RefCell<Arena>,
803 pub(crate) event_arena: Arena,
805
806 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
811
812 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
814 asset_source: Arc<dyn AssetSource>,
815 pub(crate) svg_renderer: SvgRenderer,
816 http_client: Arc<dyn HttpClient>,
817
818 pub(crate) pending_notifications: FxHashSet<EntityId>,
820 pub(crate) pending_global_notifications: TypeIdHashSet,
821 pub(crate) dependencies: crate::fast::dependencies::AppDependencies,
822 pub(crate) restart_path: Option<PathBuf>,
823 pub(crate) restart_arguments: Vec<OsString>,
824 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
826 pub(crate) prompt_builder: Option<PromptBuilder>,
827 pub(crate) window_invalidators_by_entity:
828 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
829 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
830 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
831 #[cfg(any(feature = "inspector", debug_assertions))]
832 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
833 #[cfg(any(feature = "inspector", debug_assertions))]
834 pub(crate) inspector_element_registry: InspectorElementRegistry,
835 #[cfg(any(test, feature = "test-support", debug_assertions))]
836 pub(crate) name: Option<&'static str>,
837 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
838
839 pub(crate) window_update_stack: Vec<WindowId>,
840 pub(crate) mode: GpuiMode,
841 pub(crate) cursor_hide_mode: CursorHideMode,
842 pub(crate) reduce_motion: bool,
843 pub(crate) synced_animation_epoch: Instant,
845 pub(crate) accessibility_force_disabled: bool,
848 pending_updates: usize,
849 quit_mode: QuitMode,
850 quitting: bool,
851
852 #[cfg(any(test, gpui_leak_detection))]
855 _ref_counts: Arc<RwLock<EntityRefCounts>>,
856}
857
858impl App {
859 #[allow(clippy::new_ret_no_self)]
860 pub(crate) fn new_app(
861 platform: Rc<dyn Platform>,
862 asset_source: Arc<dyn AssetSource>,
863 http_client: Arc<dyn HttpClient>,
864 ) -> Rc<AppCell> {
865 let background_executor = platform.background_executor();
866 let foreground_executor = platform.foreground_executor();
867 assert!(
868 background_executor.is_main_thread(),
869 "must construct App on main thread"
870 );
871 #[cfg(feature = "profiler")]
872 let foreground_journal = crate::profiler::journal::install_foreground_journal();
873 let synced_animation_epoch = background_executor.now();
874
875 let text_system = Arc::new(TextSystem::new(platform.text_system()));
876 let entities = EntityMap::new();
877 let keyboard_layout = platform.keyboard_layout();
878 let keyboard_mapper = platform.keyboard_mapper();
879
880 #[cfg(any(test, gpui_leak_detection))]
881 let _ref_counts = entities.ref_counts_drop_handle();
882
883 let app = Rc::new_cyclic(|this| AppCell {
884 app: RefCell::new(App {
885 this: this.clone(),
886 platform: platform.clone(),
887 text_system,
888 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
889 mode: GpuiMode::Production,
890 actions: Rc::new(ActionRegistry::default()),
891 pending_updates: 0,
892 active_drag: None,
893 platform_owned_drag: None,
894 background_executor,
895 foreground_executor,
896 #[cfg(feature = "profiler")]
897 foreground_journal,
898 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
899 hang_monitor: None,
900 svg_renderer: SvgRenderer::new(asset_source.clone()),
901 loading_assets: Default::default(),
902 asset_source,
903 http_client,
904 globals_by_type: Default::default(),
905 entities,
906 new_entity_observers: SubscriberSet::new(),
907 windows: SlotMap::with_key(),
908 window_update_stack: Vec::new(),
909 window_handles: FxHashMap::default(),
910 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
911 keymap: Rc::new(RefCell::new(Keymap::default())),
912 keyboard_layout,
913 keyboard_mapper,
914 global_action_listeners: Default::default(),
915 pending_effects: VecDeque::new(),
916 pending_notifications: FxHashSet::default(),
917 pending_global_notifications: Default::default(),
918 dependencies: crate::fast::dependencies::AppDependencies::default(),
919 observers: SubscriberSet::new(),
920 tracked_entities: FxHashMap::default(),
921 window_invalidators_by_entity: FxHashMap::default(),
922 current_window_by_entity: FxHashMap::default(),
923 event_listeners: SubscriberSet::new(),
924 release_listeners: SubscriberSet::new(),
925 keystroke_observers: SubscriberSet::new(),
926 keystroke_interceptors: SubscriberSet::new(),
927 keyboard_layout_observers: SubscriberSet::new(),
928 missing_glyph_callback: Rc::default(),
929 thermal_state_observers: SubscriberSet::new(),
930 system_sleep_observers: SubscriberSet::new(),
931 system_wake_observers: SubscriberSet::new(),
932 global_observers: SubscriberSet::new(),
933 quit_observers: SubscriberSet::new(),
934 restart_observers: SubscriberSet::new(),
935 restart_path: None,
936 restart_arguments: Vec::new(),
937 window_closed_observers: SubscriberSet::new(),
938 layout_id_buffer: Default::default(),
939 propagate_event: true,
940 prompt_builder: Some(PromptBuilder::Default),
941 #[cfg(any(feature = "inspector", debug_assertions))]
942 inspector_renderer: None,
943 #[cfg(any(feature = "inspector", debug_assertions))]
944 inspector_element_registry: InspectorElementRegistry::default(),
945 quit_mode: QuitMode::default(),
946 quitting: false,
947 cursor_hide_mode: CursorHideMode::default(),
948 reduce_motion: false,
949 synced_animation_epoch,
950 accessibility_force_disabled: false,
951
952 #[cfg(any(test, feature = "test-support", debug_assertions))]
953 name: None,
954 element_arena: RefCell::new(Arena::new(1024 * 1024)),
955 event_arena: Arena::new(1024 * 1024),
956
957 #[cfg(any(test, gpui_leak_detection))]
958 _ref_counts,
959 }),
960 });
961
962 init_app_menus(platform.as_ref(), &app.borrow());
963 SystemWindowTabController::init(&mut app.borrow_mut());
964 #[cfg(feature = "profiler")]
965 crate::profiler::journal::observe_power(&app.borrow());
966
967 platform.on_keyboard_layout_change(Box::new({
968 let app = Rc::downgrade(&app);
969 move || {
970 if let Some(app) = app.upgrade() {
971 let cx = &mut app.borrow_mut();
972 cx.keyboard_layout = cx.platform.keyboard_layout();
973 cx.keyboard_mapper = cx.platform.keyboard_mapper();
974 cx.keyboard_layout_observers
975 .clone()
976 .retain(&(), move |callback| (callback)(cx));
977 }
978 }
979 }));
980
981 platform.on_thermal_state_change(Box::new({
982 let app = Rc::downgrade(&app);
983 move || {
984 if let Some(app) = app.upgrade() {
985 let cx = &mut app.borrow_mut();
986 cx.thermal_state_observers
987 .clone()
988 .retain(&(), move |callback| (callback)(cx));
989 }
990 }
991 }));
992
993 platform.on_system_sleep(Box::new({
994 let app = Rc::downgrade(&app);
995 move || {
996 if let Some(app) = app.upgrade() {
997 let cx = &mut app.borrow_mut();
998 cx.system_sleep_observers
999 .clone()
1000 .retain(&(), move |callback| (callback)(cx));
1001 }
1002 }
1003 }));
1004
1005 platform.on_system_wake(Box::new({
1006 let app = Rc::downgrade(&app);
1007 move || {
1008 if let Some(app) = app.upgrade() {
1009 let cx = &mut app.borrow_mut();
1010 cx.system_wake_observers
1011 .clone()
1012 .retain(&(), move |callback| (callback)(cx));
1013 }
1014 }
1015 }));
1016
1017 platform.on_quit(Box::new({
1018 let cx = Rc::downgrade(&app);
1019 move || {
1020 let Some(cx) = cx.upgrade() else {
1021 return true;
1022 };
1023 match cx.try_borrow_mut() {
1024 Ok(mut cx) => {
1025 cx.shutdown();
1026 true
1027 }
1028 Err(_) => {
1029 false
1032 }
1033 }
1034 }
1035 }));
1036
1037 app
1038 }
1039
1040 #[doc(hidden)]
1041 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1042 self.entities.ref_counts_drop_handle()
1043 }
1044
1045 #[cfg(any(test, gpui_leak_detection))]
1051 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1052 self.entities.leak_detector_snapshot()
1053 }
1054
1055 #[cfg(any(test, gpui_leak_detection))]
1067 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1068 self.entities.assert_no_new_leaks(snapshot)
1069 }
1070
1071 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1073 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1074 LeakDetectorSnapshot::default()
1075 }
1076
1077 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1080 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1081
1082 pub fn shutdown(&mut self) {
1088 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1091 let hang_monitor_flush = self
1092 .hang_monitor
1093 .as_ref()
1094 .and_then(|hang_monitor| hang_monitor.request_flush());
1095
1096 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1097
1098 for observer in self.quit_observers.remove(&()) {
1099 futures.push(observer(self));
1100 }
1101
1102 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1103 if let Some(flushed) = hang_monitor_flush {
1104 futures.push(
1105 async move {
1106 if flushed.await.is_err() {
1107 log::warn!("hang monitor exited before flushing");
1108 }
1109 }
1110 .boxed_local(),
1111 );
1112 }
1113
1114 self.windows.clear();
1115 self.window_handles.clear();
1116 self.flush_effects();
1117 self.quitting = true;
1118
1119 let futures = futures::future::join_all(futures);
1120 #[cfg(not(target_family = "wasm"))]
1121 if self
1122 .foreground_executor
1123 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1124 .is_err()
1125 {
1126 log::error!("timed out waiting on app_will_quit");
1127 }
1128 #[cfg(target_family = "wasm")]
1129 self.foreground_executor.spawn(futures).detach();
1130
1131 self.quitting = false;
1132 }
1133
1134 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1136 self.keyboard_layout.as_ref()
1137 }
1138
1139 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1141 &self.keyboard_mapper
1142 }
1143
1144 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1146 where
1147 F: 'static + FnMut(&mut App),
1148 {
1149 let (subscription, activate) = self.keyboard_layout_observers.insert(
1150 (),
1151 Box::new(move |cx| {
1152 callback(cx);
1153 true
1154 }),
1155 );
1156 activate();
1157 subscription
1158 }
1159
1160 pub fn quit(&self) {
1162 self.platform.quit();
1163 }
1164
1165 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1179 if !self.windows.is_empty() {
1180 return Task::ready(Err(anyhow::anyhow!(
1181 "cannot switch windowing modes while windows are open"
1182 )));
1183 }
1184 self.platform.request_windowing(request)
1185 }
1186
1187 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1197 self.platform.graphical_environment()
1198 }
1199
1200 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1203 self.cursor_hide_mode
1204 }
1205
1206 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1209 self.cursor_hide_mode = mode;
1210 }
1211
1212 pub fn is_cursor_visible(&self) -> bool {
1218 self.platform.is_cursor_visible()
1219 }
1220
1221 pub fn reduce_motion(&self) -> bool {
1224 self.reduce_motion
1225 }
1226
1227 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1230 if self.reduce_motion != reduce_motion {
1231 self.reduce_motion = reduce_motion;
1232 self.refresh_windows();
1233 }
1234 }
1235
1236 pub fn refresh_windows(&mut self) {
1239 self.pending_effects.push_back(Effect::RefreshWindows);
1240 }
1241
1242 #[inline(always)]
1243 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1244 self.start_update();
1245 let result = update(self);
1246 self.finish_update();
1247 result
1248 }
1249
1250 pub(crate) fn start_update(&mut self) {
1251 self.pending_updates += 1;
1252 }
1253
1254 #[inline(never)]
1255 pub(crate) fn finish_update(&mut self) {
1256 if self.pending_updates == 1 {
1257 self.flush_effects();
1258 }
1259 self.pending_updates -= 1;
1260 }
1261
1262 pub fn observe<W>(
1264 &mut self,
1265 entity: &Entity<W>,
1266 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1267 ) -> Subscription
1268 where
1269 W: 'static,
1270 {
1271 self.observe_internal(entity, move |e, cx| {
1272 on_notify(e, cx);
1273 true
1274 })
1275 }
1276
1277 pub(crate) fn record_entities_accessed(
1278 &mut self,
1279 window_handle: AnyWindowHandle,
1280 invalidator: WindowInvalidator,
1281 entities: &FxHashSet<EntityId>,
1282 ) {
1283 let mut tracked_entities =
1284 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1285 for entity in tracked_entities.iter() {
1286 self.window_invalidators_by_entity
1287 .entry(*entity)
1288 .and_modify(|windows| {
1289 windows.remove(&window_handle.id);
1290 });
1291 }
1292 for entity in entities.iter() {
1293 self.window_invalidators_by_entity
1294 .entry(*entity)
1295 .or_default()
1296 .insert(window_handle.id, invalidator.clone());
1297 self.current_window_by_entity
1298 .insert(*entity, window_handle.id);
1299 }
1300 tracked_entities.clear();
1301 tracked_entities.extend(entities.iter().copied());
1302 self.tracked_entities
1303 .insert(window_handle.id, tracked_entities);
1304 }
1305
1306 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1307 let (subscription, activate) = self.observers.insert(key, value);
1308 self.defer(move |_| activate());
1309 subscription
1310 }
1311
1312 pub(crate) fn observe_internal<W>(
1313 &mut self,
1314 entity: &Entity<W>,
1315 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1316 ) -> Subscription
1317 where
1318 W: 'static,
1319 {
1320 let entity_id = entity.entity_id();
1321 let handle = entity.downgrade();
1322 self.new_observer(
1323 entity_id,
1324 Box::new(move |cx| {
1325 if let Some(entity) = handle.upgrade() {
1326 on_notify(entity, cx)
1327 } else {
1328 false
1329 }
1330 }),
1331 )
1332 }
1333
1334 pub fn subscribe<T, Event>(
1337 &mut self,
1338 entity: &Entity<T>,
1339 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1340 ) -> Subscription
1341 where
1342 T: 'static + EventEmitter<Event>,
1343 Event: 'static,
1344 {
1345 self.subscribe_internal(entity, move |entity, event, cx| {
1346 on_event(entity, event, cx);
1347 true
1348 })
1349 }
1350
1351 pub(crate) fn new_subscription(
1352 &mut self,
1353 key: EntityId,
1354 value: (TypeId, Listener),
1355 ) -> Subscription {
1356 let (subscription, activate) = self.event_listeners.insert(key, value);
1357 self.defer(move |_| activate());
1358 subscription
1359 }
1360 pub(crate) fn subscribe_internal<T, Evt>(
1361 &mut self,
1362 entity: &Entity<T>,
1363 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1364 ) -> Subscription
1365 where
1366 T: 'static + EventEmitter<Evt>,
1367 Evt: 'static,
1368 {
1369 let entity_id = entity.entity_id();
1370 let handle = entity.downgrade();
1371 self.new_subscription(
1372 entity_id,
1373 (
1374 TypeId::of::<Evt>(),
1375 Box::new(move |event, cx| {
1376 let event: &Evt = event.downcast_ref().expect("invalid event type");
1377 if let Some(entity) = handle.upgrade() {
1378 on_event(entity, event, cx)
1379 } else {
1380 false
1381 }
1382 }),
1383 ),
1384 )
1385 }
1386
1387 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1391 self.windows
1392 .keys()
1393 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1394 .collect()
1395 }
1396
1397 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1403 self.platform.window_stack()
1404 }
1405
1406 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1408 self.platform.active_window()
1409 }
1410
1411 pub fn open_window<V: 'static + Render>(
1415 &mut self,
1416 options: crate::WindowOptions,
1417 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1418 ) -> anyhow::Result<WindowHandle<V>> {
1419 self.update(|cx| {
1420 let id = cx.windows.insert(None);
1421 let handle = WindowHandle::new(id);
1422 match Window::new(handle.into(), options, cx) {
1423 Ok(mut window) => {
1424 cx.window_update_stack.push(id);
1425 let root_view = build_root_view(&mut window, cx);
1426 cx.window_update_stack.pop();
1427 window.root.replace(root_view.into());
1428 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1429
1430 let clear = window.draw(cx);
1435 clear.clear(cx);
1436
1437 cx.window_handles.insert(id, window.handle);
1438 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1439 Ok(handle)
1440 }
1441 Err(e) => {
1442 cx.windows.remove(id);
1443 Err(e)
1444 }
1445 }
1446 })
1447 }
1448
1449 pub fn activate(&self, ignoring_other_apps: bool) {
1451 self.platform.activate(ignoring_other_apps);
1452 }
1453
1454 pub fn hide(&self) {
1456 self.platform.hide();
1457 }
1458
1459 pub fn hide_other_apps(&self) {
1461 self.platform.hide_other_apps();
1462 }
1463
1464 pub fn unhide_other_apps(&self) {
1466 self.platform.unhide_other_apps();
1467 }
1468
1469 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1471 self.platform.displays()
1472 }
1473
1474 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1476 self.platform.primary_display()
1477 }
1478
1479 pub fn is_screen_capture_supported(&self) -> bool {
1481 self.platform.is_screen_capture_supported()
1482 }
1483
1484 pub fn screen_capture_sources(
1486 &self,
1487 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1488 self.platform.screen_capture_sources()
1489 }
1490
1491 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1493 self.displays()
1494 .iter()
1495 .find(|display| display.id() == id)
1496 .cloned()
1497 }
1498
1499 pub fn thermal_state(&self) -> ThermalState {
1501 self.platform.thermal_state()
1502 }
1503
1504 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1506 self.platform.prevent_idle_sleep(reason)
1507 }
1508
1509 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1511 where
1512 F: 'static + FnMut(&mut App),
1513 {
1514 let (subscription, activate) = self.thermal_state_observers.insert(
1515 (),
1516 Box::new(move |cx| {
1517 callback(cx);
1518 true
1519 }),
1520 );
1521 activate();
1522 subscription
1523 }
1524
1525 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1530 where
1531 F: 'static + FnMut(&mut App),
1532 {
1533 let (subscription, activate) = self.system_sleep_observers.insert(
1534 (),
1535 Box::new(move |cx| {
1536 callback(cx);
1537 true
1538 }),
1539 );
1540 activate();
1541 subscription
1542 }
1543
1544 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1546 where
1547 F: 'static + FnMut(&mut App),
1548 {
1549 let (subscription, activate) = self.system_wake_observers.insert(
1550 (),
1551 Box::new(move |cx| {
1552 callback(cx);
1553 true
1554 }),
1555 );
1556 activate();
1557 subscription
1558 }
1559
1560 pub fn window_appearance(&self) -> WindowAppearance {
1562 self.platform.window_appearance()
1563 }
1564
1565 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1576 self.platform.set_window_appearance(appearance);
1577 }
1578
1579 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1581 self.platform.button_layout()
1582 }
1583
1584 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1586 self.platform.read_from_clipboard()
1587 }
1588
1589 pub fn read_from_clipboard_async(
1597 &self,
1598 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1599 self.platform.read_from_clipboard_async()
1600 }
1601
1602 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1604 self.text_rendering_mode.set(mode);
1605 }
1606
1607 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1609 self.text_rendering_mode.get()
1610 }
1611
1612 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1614 self.platform.write_to_clipboard(item)
1615 }
1616
1617 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1620 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1621 self.platform.read_from_primary()
1622 }
1623
1624 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1627 pub fn write_to_primary(&self, item: ClipboardItem) {
1628 self.platform.write_to_primary(item)
1629 }
1630
1631 #[cfg(target_os = "macos")]
1637 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1638 self.platform.read_from_find_pasteboard()
1639 }
1640
1641 #[cfg(target_os = "macos")]
1647 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1648 self.platform.write_to_find_pasteboard(item)
1649 }
1650
1651 pub fn write_credentials(
1653 &self,
1654 url: &str,
1655 username: &str,
1656 password: &[u8],
1657 ) -> Task<Result<()>> {
1658 self.platform.write_credentials(url, username, password)
1659 }
1660
1661 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1663 self.platform.read_credentials(url)
1664 }
1665
1666 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1668 self.platform.delete_credentials(url)
1669 }
1670
1671 pub fn open_url(&self, url: &str) {
1673 self.platform.open_url(url);
1674 }
1675
1676 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1683 self.platform.register_url_scheme(scheme)
1684 }
1685
1686 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1693 self.platform.set_app_identity(identifier, name);
1694 }
1695
1696 pub fn show_system_notification(&self, notification: SystemNotification) {
1703 self.platform.show_system_notification(notification);
1704 }
1705
1706 pub fn dismiss_system_notification(&self, tag: &str) {
1711 self.platform.dismiss_system_notification(tag);
1712 }
1713
1714 pub fn on_system_notification_response<F>(&self, mut callback: F)
1718 where
1719 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1720 {
1721 let this = self.this.clone();
1722 self.platform
1723 .on_system_notification_response(Box::new(move |response| {
1724 if let Some(app) = this.upgrade() {
1725 callback(response, &mut app.borrow_mut());
1726 }
1727 }));
1728 }
1729
1730 pub fn app_path(&self) -> Result<PathBuf> {
1734 self.platform.app_path()
1735 }
1736
1737 pub fn compositor_name(&self) -> &'static str {
1741 self.platform.compositor_name()
1742 }
1743
1744 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1746 self.platform.path_for_auxiliary_executable(name)
1747 }
1748
1749 pub fn prompt_for_paths(
1755 &self,
1756 options: PathPromptOptions,
1757 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1758 self.platform.prompt_for_paths(options)
1759 }
1760
1761 pub fn prompt_for_new_path(
1768 &self,
1769 directory: &Path,
1770 suggested_name: Option<&str>,
1771 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1772 self.platform.prompt_for_new_path(directory, suggested_name)
1773 }
1774
1775 pub fn reveal_path(&self, path: &Path) {
1777 self.platform.reveal_path(path)
1778 }
1779
1780 pub fn open_with_system(&self, path: &Path) {
1782 self.platform.open_with_system(path)
1783 }
1784
1785 pub fn should_auto_hide_scrollbars(&self) -> bool {
1787 self.platform.should_auto_hide_scrollbars()
1788 }
1789
1790 pub fn restart(&mut self) {
1792 self.restart_observers
1793 .clone()
1794 .retain(&(), |observer| observer(self));
1795 self.platform.restart(
1796 self.restart_path.take(),
1797 std::mem::take(&mut self.restart_arguments),
1798 )
1799 }
1800
1801 pub fn set_restart_path(&mut self, path: PathBuf) {
1803 self.restart_path = Some(path);
1804 }
1805
1806 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1808 self.http_client.clone()
1809 }
1810
1811 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1813 self.http_client = new_client;
1814 }
1815
1816 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1819 self.quit_mode = mode;
1820 }
1821
1822 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
1831 self.platform.set_activation_policy(policy);
1832 }
1833
1834 pub fn svg_renderer(&self) -> SvgRenderer {
1836 self.svg_renderer.clone()
1837 }
1838
1839 pub(crate) fn push_effect(&mut self, effect: Effect) {
1840 match &effect {
1841 Effect::Notify { emitter } => {
1842 if !self.pending_notifications.insert(*emitter) {
1843 return;
1844 }
1845 }
1846 Effect::NotifyGlobalObservers { global_type } => {
1847 crate::fast::dependencies::global_changed(self, *global_type);
1848 if !self.pending_global_notifications.insert(*global_type) {
1849 return;
1850 }
1851 }
1852 _ => {}
1853 };
1854
1855 self.pending_effects.push_back(effect);
1856 }
1857
1858 fn flush_effects(&mut self) {
1862 loop {
1863 self.release_dropped_entities();
1864 self.release_dropped_focus_handles();
1865 if let Some(effect) = self.pending_effects.pop_front() {
1866 match effect {
1867 Effect::Notify { emitter } => {
1868 self.apply_notify_effect(emitter);
1869 }
1870
1871 Effect::Emit {
1872 emitter,
1873 event_type,
1874 event,
1875 } => self.apply_emit_effect(emitter, event_type, &*event),
1876
1877 Effect::RefreshWindows => {
1878 self.apply_refresh_effect();
1879 }
1880
1881 Effect::NotifyGlobalObservers { global_type } => {
1882 self.apply_notify_global_observers_effect(global_type);
1883 }
1884
1885 Effect::Defer { callback } => {
1886 self.apply_defer_effect(callback);
1887 }
1888 Effect::EntityCreated {
1889 entity,
1890 tid,
1891 window,
1892 } => {
1893 self.apply_entity_created_effect(entity, tid, window);
1894 }
1895 }
1896 } else {
1897 #[cfg(any(test, feature = "test-support"))]
1898 if matches!(self.mode, GpuiMode::Test { .. }) {
1899 for window in self
1900 .windows
1901 .values()
1902 .filter_map(|window| {
1903 let window = window.as_deref()?;
1904 window.invalidator.is_dirty().then_some(window.handle)
1905 })
1906 .collect::<Vec<_>>()
1907 {
1908 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1909 .unwrap();
1910 }
1911 }
1912
1913 if self.pending_effects.is_empty() {
1914 for window in self.windows.values().filter_map(|window| window.as_deref()) {
1915 if window.invalidator.is_dirty()
1916 || window.needs_present.get()
1917 || !window.next_frame_callbacks.borrow().is_empty()
1918 {
1919 window.platform_window.schedule_frame();
1920 }
1921 }
1922
1923 self.event_arena.clear();
1924 break;
1925 }
1926 }
1927 }
1928 }
1929
1930 fn release_dropped_entities(&mut self) {
1934 loop {
1935 let dropped = self.entities.take_dropped();
1936 if dropped.is_empty() {
1937 break;
1938 }
1939
1940 for (entity_id, mut entity) in dropped {
1941 self.observers.remove(&entity_id);
1942 self.event_listeners.remove(&entity_id);
1943 self.window_invalidators_by_entity.remove(&entity_id);
1944 self.current_window_by_entity.remove(&entity_id);
1945 for release_callback in self.release_listeners.remove(&entity_id) {
1946 release_callback(entity.as_mut(), self);
1947 }
1948 }
1949 }
1950 }
1951
1952 fn release_dropped_focus_handles(&mut self) {
1954 self.focus_handles
1955 .clone()
1956 .write()
1957 .retain(|handle_id, focus| {
1958 if focus.ref_count.load(SeqCst) == 0 {
1959 for window_handle in self.windows() {
1960 window_handle
1961 .update(self, |_, window, cx| {
1962 if window.focus == Some(handle_id) {
1963 window.blur(cx);
1964 }
1965 })
1966 .unwrap();
1967 }
1968 false
1969 } else {
1970 true
1971 }
1972 });
1973 }
1974
1975 fn apply_notify_effect(&mut self, emitter: EntityId) {
1976 self.pending_notifications.remove(&emitter);
1977
1978 self.observers
1979 .clone()
1980 .retain(&emitter, |handler| handler(self));
1981 }
1982
1983 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1984 self.event_listeners
1985 .clone()
1986 .retain(&emitter, |(stored_type, handler)| {
1987 if *stored_type == event_type {
1988 handler(event, self)
1989 } else {
1990 true
1991 }
1992 });
1993 }
1994
1995 fn apply_refresh_effect(&mut self) {
1996 for window in self.windows.values_mut() {
1997 if let Some(window) = window.as_deref_mut() {
1998 window.refreshing = true;
1999 window.invalidator.set_dirty(true);
2000 }
2001 }
2002 }
2003
2004 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2005 self.pending_global_notifications.remove(&type_id);
2006 self.global_observers
2007 .clone()
2008 .retain(&type_id, |observer| observer(self));
2009 }
2010
2011 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2012 callback(self);
2013 }
2014
2015 fn apply_entity_created_effect(
2016 &mut self,
2017 entity: AnyEntity,
2018 tid: TypeId,
2019 window: Option<WindowId>,
2020 ) {
2021 if let Some(id) = window {
2025 self.current_window_by_entity.insert(entity.entity_id(), id);
2026 }
2027
2028 self.new_entity_observers.clone().retain(&tid, |observer| {
2029 if let Some(id) = window {
2030 self.update_window_id(id, {
2031 let entity = entity.clone();
2032 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2033 })
2034 .expect("All windows should be off the stack when flushing effects");
2035 } else {
2036 (observer)(entity.clone(), &mut None, self)
2037 }
2038 true
2039 });
2040 }
2041
2042 #[inline(always)]
2048 pub fn with_window<R>(
2049 &mut self,
2050 entity_id: EntityId,
2051 f: impl FnOnce(&mut Window, &mut App) -> R,
2052 ) -> Option<R> {
2053 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2054 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2055 .ok()
2056 }
2057
2058 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2059 self.current_window_by_entity
2060 .entry(entity_id)
2061 .or_insert(window);
2062 }
2063
2064 #[inline(always)]
2065 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2066 where
2067 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2068 {
2069 let mut update = Some(update);
2070 let mut result = None;
2071 self.update_window_erased(id, &mut |arguments| {
2072 if let Some((root_view, window, cx)) = arguments {
2073 result = Some(update.take().unwrap()(root_view, window, cx));
2074 } else {
2075 drop(update.take());
2076 drop(result.take());
2077 }
2078 });
2079 result.context("window not found")
2080 }
2081
2082 pub fn to_async(&self) -> AsyncApp {
2085 AsyncApp {
2086 app: self.this.clone(),
2087 background_executor: self.background_executor.clone(),
2088 foreground_executor: self.foreground_executor.clone(),
2089 }
2090 }
2091
2092 pub fn background_executor(&self) -> &BackgroundExecutor {
2094 &self.background_executor
2095 }
2096
2097 pub fn is_test(&self) -> bool {
2100 self.background_executor.is_test()
2101 }
2102
2103 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2105 if self.quitting {
2106 panic!("Can't spawn on main thread after on_app_quit")
2107 };
2108 &self.foreground_executor
2109 }
2110
2111 #[cfg(feature = "profiler")]
2114 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2115 self.foreground_journal.clone()
2116 }
2117
2118 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2135 pub fn start_hang_monitor(
2136 &mut self,
2137 config: crate::profiler::hang::HangMonitorConfig,
2138 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2139 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2140 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2141
2142 if self.hang_monitor.is_some() {
2143 debug_assert!(false, "the hang monitor was started twice");
2144 return Err(HangMonitorError::AlreadyStarted);
2145 }
2146 let detector = HangDetector::new(
2147 self.foreground_journal(),
2148 config.threshold,
2149 config.frame_budget,
2150 );
2151 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2152 .map_err(HangMonitorError::Spawn)?;
2153 self.hang_monitor = Some(monitor);
2154 Ok(())
2155 }
2156
2157 #[track_caller]
2160 #[inline(always)]
2161 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2162 where
2163 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2164 R: 'static,
2165 {
2166 let mut cx = self.prepare_spawn();
2167
2168 self.foreground_executor
2169 .spawn(async move { f(&mut cx).await }.boxed_local())
2170 }
2171
2172 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2176 where
2177 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2178 R: 'static,
2179 {
2180 if self.quitting {
2181 debug_panic!("Can't spawn on main thread after on_app_quit")
2182 };
2183
2184 let mut cx = self.to_async();
2185
2186 self.foreground_executor
2187 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2188 }
2189
2190 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2193 self.push_effect(Effect::Defer {
2194 callback: Box::new(f),
2195 });
2196 }
2197
2198 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2200 &self.asset_source
2201 }
2202
2203 pub fn text_system(&self) -> &Arc<TextSystem> {
2205 &self.text_system
2206 }
2207
2208 pub fn on_missing_glyphs(
2219 &self,
2220 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2221 ) -> Subscription {
2222 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2223
2224 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2225 let callback = self.missing_glyph_callback.clone();
2226 self.spawn(async move |cx| {
2227 while let Ok(missing_glyphs) = receiver.recv().await {
2228 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2229 }
2230 })
2231 .detach();
2232 }
2233 self.text_system.enable_missing_glyph_reporting();
2234
2235 let callback = self.missing_glyph_callback.clone();
2236 let text_system = self.text_system.clone();
2237 Subscription::new(move || {
2238 if callback.remove(®istration) {
2239 text_system.disable_missing_glyph_reporting();
2240 }
2241 })
2242 }
2243
2244 pub fn has_global<G: Global>(&self) -> bool {
2246 crate::fast::dependencies::note_global_presence_read::<G>(self);
2247 self.globals_by_type.contains_key(&TypeId::of::<G>())
2248 }
2249
2250 #[track_caller]
2252 pub fn global<G: Global>(&self) -> &G {
2253 crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2254 self.globals_by_type
2255 .get(&TypeId::of::<G>())
2256 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2257 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2258 }
2259
2260 pub fn try_global<G: Global>(&self) -> Option<&G> {
2262 crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2263 self.globals_by_type
2264 .get(&TypeId::of::<G>())
2265 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2266 }
2267
2268 #[track_caller]
2270 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2271 let global_type = TypeId::of::<G>();
2272 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2273 self.globals_by_type
2274 .get_mut(&global_type)
2275 .and_then(|any_state| any_state.downcast_mut::<G>())
2276 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2277 }
2278
2279 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2282 let global_type = TypeId::of::<G>();
2283 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2284 crate::fast::dependencies::note_global_inserted::<G>(self);
2285 self.globals_by_type
2286 .entry(global_type)
2287 .or_insert_with(|| Box::<G>::default())
2288 .downcast_mut::<G>()
2289 .unwrap()
2290 }
2291
2292 pub fn set_global<G: Global>(&mut self, global: G) {
2294 let global_type = TypeId::of::<G>();
2295 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2296 crate::fast::dependencies::note_global_inserted::<G>(self);
2297 self.globals_by_type.insert(global_type, Box::new(global));
2298 }
2299
2300 #[cfg(any(test, feature = "test-support"))]
2302 pub fn clear_globals(&mut self) {
2303 self.globals_by_type.drain();
2304 }
2305
2306 pub fn remove_global<G: Global>(&mut self) -> G {
2308 crate::fast::dependencies::note_global_removed::<G>(self);
2309 let global_type = TypeId::of::<G>();
2310 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2311 *self
2312 .globals_by_type
2313 .remove(&global_type)
2314 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2315 .downcast()
2316 .unwrap()
2317 }
2318
2319 pub fn observe_global<G: Global>(
2321 &mut self,
2322 mut f: impl FnMut(&mut Self) + 'static,
2323 ) -> Subscription {
2324 let (subscription, activate) = self.global_observers.insert(
2325 TypeId::of::<G>(),
2326 Box::new(move |cx| {
2327 f(cx);
2328 true
2329 }),
2330 );
2331 self.defer(move |_| activate());
2332 subscription
2333 }
2334
2335 #[track_caller]
2337 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2338 GlobalLease::new(
2339 self.globals_by_type
2340 .remove(&TypeId::of::<G>())
2341 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2342 .unwrap(),
2343 )
2344 }
2345
2346 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2348 let global_type = TypeId::of::<G>();
2349
2350 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2351 self.globals_by_type.insert(global_type, lease.global);
2352 }
2353
2354 pub(crate) fn new_entity_observer(
2355 &self,
2356 key: TypeId,
2357 value: NewEntityListener,
2358 ) -> Subscription {
2359 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2360 activate();
2361 subscription
2362 }
2363
2364 pub fn observe_new<T: 'static>(
2367 &self,
2368 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2369 ) -> Subscription {
2370 self.new_entity_observer(
2371 TypeId::of::<T>(),
2372 Box::new(
2373 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2374 any_entity
2375 .downcast::<T>()
2376 .unwrap()
2377 .update(cx, |entity_state, cx| {
2378 on_new(entity_state, window.as_deref_mut(), cx)
2379 })
2380 },
2381 ),
2382 )
2383 }
2384
2385 pub fn observe_release<T>(
2388 &self,
2389 handle: &Entity<T>,
2390 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2391 ) -> Subscription
2392 where
2393 T: 'static,
2394 {
2395 let (subscription, activate) = self.release_listeners.insert(
2396 handle.entity_id(),
2397 Box::new(move |entity, cx| {
2398 let entity = entity.downcast_mut().expect("invalid entity type");
2399 on_release(entity, cx)
2400 }),
2401 );
2402 activate();
2403 subscription
2404 }
2405
2406 pub fn observe_release_in<T>(
2409 &self,
2410 handle: &Entity<T>,
2411 window: &Window,
2412 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2413 ) -> Subscription
2414 where
2415 T: 'static,
2416 {
2417 let window_handle = window.handle;
2418 self.observe_release(handle, move |entity, cx| {
2419 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2420 })
2421 }
2422
2423 pub fn observe_keystrokes(
2428 &mut self,
2429 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2430 ) -> Subscription {
2431 fn inner(
2432 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2433 handler: KeystrokeObserver,
2434 ) -> Subscription {
2435 let (subscription, activate) = keystroke_observers.insert((), handler);
2436 activate();
2437 subscription
2438 }
2439
2440 inner(
2441 &self.keystroke_observers,
2442 Box::new(move |event, window, cx| {
2443 f(event, window, cx);
2444 true
2445 }),
2446 )
2447 }
2448
2449 pub fn intercept_keystrokes(
2454 &mut self,
2455 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2456 ) -> Subscription {
2457 fn inner(
2458 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2459 handler: KeystrokeObserver,
2460 ) -> Subscription {
2461 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2462 activate();
2463 subscription
2464 }
2465
2466 inner(
2467 &self.keystroke_interceptors,
2468 Box::new(move |event, window, cx| {
2469 f(event, window, cx);
2470 true
2471 }),
2472 )
2473 }
2474
2475 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2477 self.keymap.borrow_mut().add_bindings(bindings);
2478 self.pending_effects.push_back(Effect::RefreshWindows);
2479 }
2480
2481 pub fn clear_key_bindings(&mut self) {
2483 self.keymap.borrow_mut().clear();
2484 self.pending_effects.push_back(Effect::RefreshWindows);
2485 }
2486
2487 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2489 self.keymap.clone()
2490 }
2491
2492 pub fn on_action<A: Action>(
2496 &mut self,
2497 listener: impl Fn(&A, &mut Self) + 'static,
2498 ) -> &mut Self {
2499 self.global_action_listeners
2500 .entry(TypeId::of::<A>())
2501 .or_default()
2502 .push(Rc::new(move |action, phase, cx| {
2503 if phase == DispatchPhase::Bubble {
2504 let action = action.downcast_ref().unwrap();
2505 listener(action, cx)
2506 }
2507 }));
2508 self
2509 }
2510
2511 pub fn stop_propagation(&mut self) {
2516 self.propagate_event = false;
2517 }
2518
2519 pub fn propagate(&mut self) {
2524 self.propagate_event = true;
2525 }
2526
2527 pub fn build_action(
2529 &self,
2530 name: &str,
2531 data: Option<serde_json::Value>,
2532 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2533 self.actions.build_action(name, data)
2534 }
2535
2536 pub fn all_action_names(&self) -> &[&'static str] {
2539 self.actions.all_action_names()
2540 }
2541
2542 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2546 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2547 }
2548
2549 pub fn action_schemas(
2551 &self,
2552 generator: &mut schemars::SchemaGenerator,
2553 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2554 self.actions.action_schemas(generator)
2555 }
2556
2557 pub fn action_schema_by_name(
2562 &self,
2563 name: &str,
2564 generator: &mut schemars::SchemaGenerator,
2565 ) -> Option<Option<schemars::Schema>> {
2566 self.actions.action_schema_by_name(name, generator)
2567 }
2568
2569 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2571 self.actions.deprecated_aliases()
2572 }
2573
2574 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2576 self.actions.deprecation_messages()
2577 }
2578
2579 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2581 self.actions.documentation()
2582 }
2583
2584 pub fn on_app_quit<Fut>(
2587 &self,
2588 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2589 ) -> Subscription
2590 where
2591 Fut: 'static + Future<Output = ()>,
2592 {
2593 let (subscription, activate) = self.quit_observers.insert(
2594 (),
2595 Box::new(move |cx| {
2596 let future = on_quit(cx);
2597 future.boxed_local()
2598 }),
2599 );
2600 activate();
2601 subscription
2602 }
2603
2604 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2608 let (subscription, activate) = self.restart_observers.insert(
2609 (),
2610 Box::new(move |cx| {
2611 on_restart(cx);
2612 true
2613 }),
2614 );
2615 activate();
2616 subscription
2617 }
2618
2619 pub fn on_window_closed(
2622 &self,
2623 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2624 ) -> Subscription {
2625 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2626 activate();
2627 subscription
2628 }
2629
2630 pub(crate) fn clear_pending_keystrokes(&mut self) {
2631 for window in self.windows() {
2632 window
2633 .update(self, |_, window, cx| {
2634 window.clear_pending_keystrokes(cx);
2635 })
2636 .ok();
2637 }
2638 }
2639
2640 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2643 let mut action_available = false;
2644 if let Some(window) = self.active_window()
2645 && let Ok(window_action_available) =
2646 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2647 {
2648 action_available = window_action_available;
2649 }
2650
2651 action_available
2652 || self
2653 .global_action_listeners
2654 .contains_key(&action.as_any().type_id())
2655 }
2656
2657 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2659 let menus: Vec<Menu> = menus.into_iter().collect();
2660 self.platform.set_menus(menus, &self.keymap.borrow());
2661 }
2662
2663 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2665 self.platform.get_menus()
2666 }
2667
2668 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2670 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2671 }
2672
2673 pub fn perform_dock_menu_action(&self, action: usize) {
2675 self.platform.perform_dock_menu_action(action);
2676 }
2677
2678 pub fn add_recent_document(&self, path: &Path) {
2683 self.platform.add_recent_document(path);
2684 }
2685
2686 pub fn update_jump_list(
2689 &self,
2690 menus: Vec<MenuItem>,
2691 entries: Vec<SmallVec<[PathBuf; 2]>>,
2692 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2693 self.platform.update_jump_list(menus, entries)
2694 }
2695
2696 pub fn dispatch_action(&mut self, action: &dyn Action) {
2699 if let Some(active_window) = self.active_window() {
2700 active_window
2701 .update(self, |_, window, cx| {
2702 window.dispatch_action(action.boxed_clone(), cx)
2703 })
2704 .log_err();
2705 } else {
2706 self.dispatch_global_action(action);
2707 }
2708 }
2709
2710 fn dispatch_global_action(&mut self, action: &dyn Action) {
2711 self.propagate_event = true;
2712
2713 if let Some(mut global_listeners) = self
2714 .global_action_listeners
2715 .remove(&action.as_any().type_id())
2716 {
2717 for listener in &global_listeners {
2718 listener(action.as_any(), DispatchPhase::Capture, self);
2719 if !self.propagate_event {
2720 break;
2721 }
2722 }
2723
2724 global_listeners.extend(
2725 self.global_action_listeners
2726 .remove(&action.as_any().type_id())
2727 .unwrap_or_default(),
2728 );
2729
2730 self.global_action_listeners
2731 .insert(action.as_any().type_id(), global_listeners);
2732 }
2733
2734 if self.propagate_event
2735 && let Some(mut global_listeners) = self
2736 .global_action_listeners
2737 .remove(&action.as_any().type_id())
2738 {
2739 for listener in global_listeners.iter().rev() {
2740 listener(action.as_any(), DispatchPhase::Bubble, self);
2741 if !self.propagate_event {
2742 break;
2743 }
2744 }
2745
2746 global_listeners.extend(
2747 self.global_action_listeners
2748 .remove(&action.as_any().type_id())
2749 .unwrap_or_default(),
2750 );
2751
2752 self.global_action_listeners
2753 .insert(action.as_any().type_id(), global_listeners);
2754 }
2755 }
2756
2757 pub fn has_active_drag(&self) -> bool {
2759 self.active_drag.is_some()
2760 }
2761
2762 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2764 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2765 }
2766
2767 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2769 if self.active_drag.is_some() {
2770 self.active_drag = None;
2771 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2772 drag.source_window == window.window_handle().window_id()
2773 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2774 }) {
2775 self.platform_owned_drag = None;
2776 }
2777 window.refresh();
2778 true
2779 } else {
2780 false
2781 }
2782 }
2783
2784 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2785 let Some(drag) = self.active_drag.take() else {
2786 return false;
2787 };
2788 self.platform_owned_drag = Some(PlatformOwnedDrag {
2789 source_window,
2790 state: PlatformOwnedDragState::Suspended(drag),
2791 });
2792 true
2793 }
2794
2795 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2796 let Some(platform_drag) = self
2797 .platform_owned_drag
2798 .as_mut()
2799 .filter(|drag| drag.source_window == source_window)
2800 else {
2801 return false;
2802 };
2803 let state = std::mem::replace(
2804 &mut platform_drag.state,
2805 PlatformOwnedDragState::RestoredInSourceWindow,
2806 );
2807 let PlatformOwnedDragState::Suspended(drag) = state else {
2808 return false;
2809 };
2810 self.active_drag = Some(drag);
2811 true
2812 }
2813
2814 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2815 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2816 drag.source_window == source_window
2817 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2818 }) else {
2819 return false;
2820 };
2821 let Some(drag) = self.active_drag.take() else {
2822 return false;
2823 };
2824 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2825 true
2826 }
2827
2828 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2829 if !self
2830 .platform_owned_drag
2831 .as_ref()
2832 .is_some_and(|drag| drag.source_window == source_window)
2833 {
2834 return false;
2835 }
2836 self.platform_owned_drag = None;
2837 self.active_drag = None;
2838 true
2839 }
2840
2841 pub fn set_active_drag_cursor_style(
2843 &mut self,
2844 cursor_style: CursorStyle,
2845 window: &mut Window,
2846 ) -> bool {
2847 if let Some(ref mut drag) = self.active_drag {
2848 drag.cursor_style = Some(cursor_style);
2849 window.refresh();
2850 true
2851 } else {
2852 false
2853 }
2854 }
2855
2856 pub fn set_prompt_builder(
2859 &mut self,
2860 renderer: impl Fn(
2861 PromptLevel,
2862 &str,
2863 Option<&str>,
2864 &[PromptButton],
2865 PromptHandle,
2866 &mut Window,
2867 &mut App,
2868 ) -> RenderablePromptHandle
2869 + 'static,
2870 ) {
2871 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2872 }
2873
2874 pub fn reset_prompt_builder(&mut self) {
2876 self.prompt_builder = Some(PromptBuilder::Default);
2877 }
2878
2879 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2881 let asset_id = (TypeId::of::<A>(), hash(source));
2882 self.loading_assets.remove(&asset_id);
2883 }
2884
2885 #[cfg(any(test, feature = "test-support"))]
2888 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
2889 let asset_id = (TypeId::of::<A>(), hash(source));
2890 self.loading_assets.contains_key(&asset_id)
2891 }
2892
2893 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
2898 self.asset_entry::<A>(source).get()
2899 }
2900
2901 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
2902 let asset_id = (TypeId::of::<A>(), hash(source));
2903 if !self.loading_assets.contains_key(&asset_id) {
2904 let future = A::load(source.clone(), self);
2905 let entry = CachedLoad::new(future, self);
2906 self.loading_assets.insert(asset_id, Box::new(entry));
2907 }
2908 self.loading_assets
2909 .get(&asset_id)
2910 .and_then(|entry| entry.downcast_ref())
2911 .expect("asset cache entries are keyed by their asset type")
2912 }
2913
2914 #[track_caller]
2917 pub fn focus_handle(&self) -> FocusHandle {
2918 FocusHandle::new(&self.focus_handles)
2919 }
2920
2921 pub fn notify(&mut self, entity_id: EntityId) {
2923 crate::fast::dependencies::note_notify(&mut self.entities, entity_id);
2924 let window_invalidators = mem::take(
2925 self.window_invalidators_by_entity
2926 .entry(entity_id)
2927 .or_default(),
2928 );
2929
2930 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2935 .iter()
2936 .filter(|(window_id, _)| {
2937 self.tracked_entities
2938 .get(window_id)
2939 .is_some_and(|set| set.contains(&entity_id))
2940 })
2941 .map(|(_, invalidator)| invalidator.clone())
2942 .collect();
2943
2944 if live_invalidators.is_empty() {
2945 if self.pending_notifications.insert(entity_id) {
2946 self.pending_effects
2947 .push_back(Effect::Notify { emitter: entity_id });
2948 }
2949 } else {
2950 for invalidator in &live_invalidators {
2951 invalidator.invalidate_view(entity_id, self);
2952 }
2953 }
2954
2955 self.window_invalidators_by_entity
2956 .insert(entity_id, window_invalidators);
2957 }
2958
2959 #[cfg(any(test, feature = "test-support", debug_assertions))]
2961 pub fn get_name(&self) -> Option<&'static str> {
2962 self.name
2963 }
2964
2965 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2967 self.platform.can_select_mixed_files_and_dirs()
2968 }
2969
2970 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2975 for window in self.windows.values_mut().flatten() {
2977 _ = window.drop_image(image.clone());
2978 }
2979
2980 if let Some(window) = current_window {
2982 _ = window.drop_image(image);
2983 }
2984 }
2985
2986 #[cfg(any(feature = "inspector", debug_assertions))]
2988 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2989 self.inspector_renderer = Some(f);
2990 }
2991
2992 #[cfg(any(feature = "inspector", debug_assertions))]
2994 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
2995 &mut self,
2996 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
2997 ) where
2998 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2999 {
3000 self.inspector_element_registry.register(factory);
3001 }
3002
3003 pub fn init_colors(&mut self) {
3007 self.set_global(GlobalColors(Arc::new(Colors::default())));
3008 }
3009
3010 #[inline(never)]
3011 fn update_window_erased(
3012 &mut self,
3013 window_id: WindowId,
3014 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3015 ) {
3016 self.update(|cx| {
3017 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3018 update(None);
3019 return;
3020 };
3021
3022 let root_view = window.root.clone().unwrap();
3023
3024 cx.window_update_stack.push(window.handle.id);
3025 update(Some((root_view, &mut window, cx)));
3026 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3027 cx.window_update_stack.pop();
3028
3029 if window.removed {
3030 cx.end_platform_drag(window_id);
3031 cx.window_handles.remove(&window_id);
3032 cx.windows.remove(window_id);
3033 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3034 for entity_id in tracked {
3035 if let Some(windows) =
3036 cx.window_invalidators_by_entity.get_mut(&entity_id)
3037 {
3038 windows.remove(&window_id);
3039 }
3040 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3041 cx.current_window_by_entity.remove(&entity_id);
3042 }
3043 }
3044 }
3045
3046 cx.window_closed_observers.clone().retain(&(), |callback| {
3047 callback(cx, window_id);
3048 true
3049 });
3050
3051 let quit_on_empty = match cx.quit_mode {
3052 QuitMode::Explicit => false,
3053 QuitMode::LastWindowClosed => true,
3054 QuitMode::Default => cfg!(not(target_os = "macos")),
3055 };
3056
3057 if quit_on_empty && cx.windows.is_empty() {
3058 cx.quit();
3059 }
3060 } else {
3061 cx.windows.get_mut(window_id)?.replace(window);
3062 }
3063 Some(())
3064 }
3065 if trail(window_id, window, cx).is_none() {
3066 update(None);
3067 }
3068 });
3069 }
3070
3071 #[inline(never)]
3072 fn update_entity_erased(
3073 &mut self,
3074 handle: &AnyEntity,
3075 entity_type: &str,
3076 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3077 ) {
3078 self.update(|cx| {
3079 let mut lease = cx.entities.lease_erased(handle, entity_type);
3080 update(lease.entity.as_deref_mut().unwrap(), cx);
3081 cx.entities.end_lease_erased(handle.entity_id, lease);
3082 });
3083 }
3084
3085 #[inline(never)]
3086 #[track_caller]
3087 fn prepare_spawn(&self) -> AsyncApp {
3088 if self.quitting {
3089 debug_panic!("Can't spawn on main thread after on_app_quit")
3090 };
3091 self.to_async()
3092 }
3093}
3094
3095impl AppContext for App {
3096 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3101 self.update(|cx| {
3102 let slot = cx.entities.reserve();
3103 let handle = slot.clone();
3104 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3105
3106 cx.push_effect(Effect::EntityCreated {
3107 entity: handle.into_any(),
3108 tid: TypeId::of::<T>(),
3109 window: cx.window_update_stack.last().cloned(),
3110 });
3111
3112 cx.entities.insert(slot, entity)
3113 })
3114 }
3115
3116 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3117 Reservation(self.entities.reserve())
3118 }
3119
3120 fn insert_entity<T: 'static>(
3121 &mut self,
3122 reservation: Reservation<T>,
3123 build_entity: impl FnOnce(&mut Context<T>) -> T,
3124 ) -> Entity<T> {
3125 self.update(|cx| {
3126 let slot = reservation.0;
3127 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3128 cx.entities.insert(slot, entity)
3129 })
3130 }
3131
3132 #[inline(always)]
3135 fn update_entity<T: 'static, R>(
3136 &mut self,
3137 handle: &Entity<T>,
3138 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3139 ) -> R {
3140 let mut update = Some(update);
3141 let mut result = None;
3142 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3143 let value = update.take().unwrap()(
3144 entity.downcast_mut::<T>().unwrap(),
3145 &mut Context::new_context(cx, handle.downgrade()),
3146 );
3147 result = Some(value);
3148 });
3149 result.unwrap()
3150 }
3151
3152 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3153 where
3154 T: 'static,
3155 {
3156 GpuiBorrow::new(handle.clone(), self)
3157 }
3158
3159 #[inline(always)]
3160 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3161 where
3162 T: 'static,
3163 {
3164 let entity = self.entities.read(handle);
3165 read(entity, self)
3166 }
3167
3168 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3169 where
3170 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3171 {
3172 self.update_window_id(handle.id, update)
3173 }
3174
3175 fn with_window<R>(
3176 &mut self,
3177 entity_id: EntityId,
3178 f: impl FnOnce(&mut Window, &mut App) -> R,
3179 ) -> Option<R> {
3180 App::with_window(self, entity_id, f)
3181 }
3182
3183 fn read_window<T, R>(
3184 &self,
3185 window: &WindowHandle<T>,
3186 read: impl FnOnce(Entity<T>, &App) -> R,
3187 ) -> Result<R>
3188 where
3189 T: 'static,
3190 {
3191 let window = self
3192 .windows
3193 .get(window.id)
3194 .context("window not found")?
3195 .as_deref()
3196 .expect("attempted to read a window that is already on the stack");
3197
3198 let root_view = window.root.clone().unwrap();
3199 let view = root_view
3200 .downcast::<T>()
3201 .map_err(|_| anyhow!("root view's type has changed"))?;
3202
3203 Ok(read(view, self))
3204 }
3205
3206 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3207 where
3208 R: Send + 'static,
3209 {
3210 self.background_executor.spawn(future)
3211 }
3212
3213 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3214 where
3215 G: Global,
3216 {
3217 let mut g = self.global::<G>();
3218 callback(g, self)
3219 }
3220}
3221
3222pub(crate) enum Effect {
3224 Notify {
3225 emitter: EntityId,
3226 },
3227 Emit {
3228 emitter: EntityId,
3229 event_type: TypeId,
3230 event: ArenaBox<dyn Any>,
3231 },
3232 RefreshWindows,
3233 NotifyGlobalObservers {
3234 global_type: TypeId,
3235 },
3236 Defer {
3237 callback: Box<dyn FnOnce(&mut App) + 'static>,
3238 },
3239 EntityCreated {
3240 entity: AnyEntity,
3241 tid: TypeId,
3242 window: Option<WindowId>,
3243 },
3244}
3245
3246impl std::fmt::Debug for Effect {
3247 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3248 match self {
3249 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3250 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3251 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3252 Effect::NotifyGlobalObservers { global_type } => {
3253 write!(f, "NotifyGlobalObservers({:?})", global_type)
3254 }
3255 Effect::Defer { .. } => write!(f, "Defer(..)"),
3256 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3257 }
3258 }
3259}
3260
3261pub(crate) struct GlobalLease<G: Global> {
3263 global: Box<dyn Any>,
3264 global_type: PhantomData<G>,
3265}
3266
3267impl<G: Global> GlobalLease<G> {
3268 fn new(global: Box<dyn Any>) -> Self {
3269 GlobalLease {
3270 global,
3271 global_type: PhantomData,
3272 }
3273 }
3274}
3275
3276impl<G: Global> Deref for GlobalLease<G> {
3277 type Target = G;
3278
3279 fn deref(&self) -> &Self::Target {
3280 self.global.downcast_ref().unwrap()
3281 }
3282}
3283
3284impl<G: Global> DerefMut for GlobalLease<G> {
3285 fn deref_mut(&mut self) -> &mut Self::Target {
3286 self.global.downcast_mut().unwrap()
3287 }
3288}
3289
3290pub struct AnyDrag {
3293 pub view: AnyView,
3295
3296 pub value: Arc<dyn Any>,
3298
3299 pub cursor_offset: Point<Pixels>,
3302
3303 pub cursor_style: Option<CursorStyle>,
3305
3306 pub external_payload_source: Option<ExternalDragPayloadSource>,
3309}
3310
3311pub type ExternalDragPayloadSource =
3314 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3315
3316#[derive(Clone)]
3319pub struct AnyTooltip {
3320 pub view: AnyView,
3322
3323 pub mouse_position: Point<Pixels>,
3325
3326 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3330}
3331
3332#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3334pub enum InputPreference {
3335 CharacterInput,
3337 KeyBindings,
3339}
3340
3341#[derive(Debug)]
3343pub struct KeystrokeEvent {
3344 pub keystroke: Keystroke,
3346
3347 pub input_preference: InputPreference,
3355
3356 pub action: Option<Box<dyn Action>>,
3358
3359 pub context_stack: Vec<KeyContext>,
3361}
3362
3363struct NullHttpClient;
3364
3365impl HttpClient for NullHttpClient {
3366 fn send(
3367 &self,
3368 _req: http_client::Request<http_client::AsyncBody>,
3369 ) -> futures::future::BoxFuture<
3370 'static,
3371 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3372 > {
3373 async move {
3374 anyhow::bail!("No HttpClient available");
3375 }
3376 .boxed()
3377 }
3378
3379 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3380 None
3381 }
3382
3383 fn proxy(&self) -> Option<&Url> {
3384 None
3385 }
3386}
3387
3388pub struct GpuiBorrow<'a, T> {
3390 inner: Option<Lease<T>>,
3391 app: &'a mut App,
3392}
3393
3394impl<'a, T: 'static> GpuiBorrow<'a, T> {
3395 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3396 app.start_update();
3397 let lease = app.entities.lease(&inner);
3398 Self {
3399 inner: Some(lease),
3400 app,
3401 }
3402 }
3403}
3404
3405impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3406 fn borrow(&self) -> &T {
3407 self.inner.as_ref().unwrap().borrow()
3408 }
3409}
3410
3411impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3412 fn borrow_mut(&mut self) -> &mut T {
3413 self.inner.as_mut().unwrap().borrow_mut()
3414 }
3415}
3416
3417impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3418 type Target = T;
3419
3420 fn deref(&self) -> &Self::Target {
3421 self.inner.as_ref().unwrap()
3422 }
3423}
3424
3425impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3426 fn deref_mut(&mut self) -> &mut T {
3427 self.inner.as_mut().unwrap()
3428 }
3429}
3430
3431impl<'a, T> Drop for GpuiBorrow<'a, T> {
3432 fn drop(&mut self) {
3433 let lease = self.inner.take().unwrap();
3434 self.app.notify(lease.id);
3435 self.app.entities.end_lease(lease);
3436 self.app.finish_update();
3437 }
3438}
3439
3440#[cfg(test)]
3441mod test {
3442 use std::{
3443 cell::{Cell, RefCell},
3444 ffi::OsString,
3445 path::PathBuf,
3446 rc::Rc,
3447 };
3448
3449 #[cfg(unix)]
3450 use std::os::unix::ffi::OsStringExt;
3451
3452 use crate::{
3453 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3454 TestAppContext, Window,
3455 };
3456
3457 struct RenderCounter(Rc<Cell<usize>>);
3458
3459 impl Render for RenderCounter {
3460 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3461 self.0.set(self.0.get() + 1);
3462 Empty
3463 }
3464 }
3465
3466 #[gpui::test]
3467 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3468 let render_count = Rc::new(Cell::new(0));
3469
3470 let _window = cx.add_window({
3471 let render_count = render_count.clone();
3472 move |_, _| RenderCounter(render_count)
3473 });
3474
3475 cx.run_until_parked();
3476 let render_count_before_refresh = render_count.get();
3477
3478 cx.to_async().refresh();
3479
3480 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3481 }
3482
3483 #[gpui::test]
3484 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3485 let observed = Rc::new(RefCell::new(Vec::new()));
3486 let subscription = cx.update(|cx| {
3487 let observed = observed.clone();
3488 cx.on_missing_glyphs(move |missing_glyphs, _| {
3489 observed.borrow_mut().extend_from_slice(missing_glyphs);
3490 })
3491 });
3492 cx.update(|cx| {
3493 cx.text_system()
3494 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3495 });
3496 cx.run_until_parked();
3497 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3498
3499 let second_observed = Rc::new(RefCell::new(Vec::new()));
3500 let second_subscription = cx.update(|cx| {
3501 let second_observed = second_observed.clone();
3502 cx.on_missing_glyphs(move |missing_glyphs, _| {
3503 second_observed
3504 .borrow_mut()
3505 .extend_from_slice(missing_glyphs);
3506 })
3507 });
3508 cx.update(|cx| {
3509 cx.text_system()
3510 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3511 });
3512 cx.run_until_parked();
3513 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3514 assert_eq!(
3515 second_observed.borrow().as_slice(),
3516 &[missing_glyph("replacement")]
3517 );
3518
3519 drop(subscription);
3520 cx.update(|cx| {
3521 cx.text_system()
3522 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3523 });
3524 cx.run_until_parked();
3525 assert_eq!(
3526 second_observed.borrow().as_slice(),
3527 &[
3528 missing_glyph("replacement"),
3529 missing_glyph("after old drop")
3530 ]
3531 );
3532
3533 drop(second_subscription);
3534 cx.update(|cx| {
3535 cx.text_system()
3536 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3537 });
3538 cx.run_until_parked();
3539 assert_eq!(second_observed.borrow().len(), 2);
3540 }
3541
3542 #[test]
3543 fn test_gpui_borrow() {
3544 let cx = TestAppContext::single();
3545 let observation_count = Rc::new(RefCell::new(0));
3546
3547 let state = cx.update(|cx| {
3548 let state = cx.new(|_| false);
3549 cx.observe(&state, {
3550 let observation_count = observation_count.clone();
3551 move |_, _| {
3552 let mut count = observation_count.borrow_mut();
3553 *count += 1;
3554 }
3555 })
3556 .detach();
3557
3558 state
3559 });
3560
3561 cx.update(|cx| {
3562 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3564 });
3565
3566 cx.update(|cx| {
3567 state.write(cx, false);
3568 });
3569
3570 assert_eq!(*observation_count.borrow(), 2);
3571 }
3572
3573 #[gpui::test]
3574 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3575 #[cfg(unix)]
3576 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3577 #[cfg(not(unix))]
3578 let user_data_dir = OsString::from("C:\\zed data");
3579 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3580 let restart_path = PathBuf::from("updated-zed");
3581 let _application =
3582 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3583 let restart = cx.expect_restart();
3584
3585 cx.update(|cx| {
3586 cx.set_restart_path(restart_path.clone());
3587 cx.restart();
3588 });
3589
3590 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3591 assert_eq!(path, Some(restart_path));
3592 assert_eq!(restart_arguments, arguments);
3593 }
3594
3595 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3596 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3597 }
3598}