1use scheduler::Instant;
2use std::{
3 any::{TypeId, type_name},
4 cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
5 ffi::OsString,
6 marker::PhantomData,
7 mem,
8 ops::{Deref, DerefMut},
9 path::{Path, PathBuf},
10 rc::{Rc, Weak},
11 sync::{Arc, atomic::Ordering::SeqCst},
12 time::Duration,
13};
14
15use anyhow::{Context as _, Result, anyhow};
16use derive_more::{Deref, DerefMut};
17use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
18use itertools::Itertools;
19use parking_lot::RwLock;
20use slotmap::SlotMap;
21
22pub use async_context::*;
23#[cfg(feature = "bench-support")]
24pub use bench_context::{
25 BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
26 MetricReport, bench_platform,
27};
28use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
29pub use context::*;
30pub use entity_map::*;
31use gpui_util::{ResultExt, debug_panic};
32#[cfg(any(test, feature = "test-support"))]
33pub use headless_app_context::*;
34use http_client::{HttpClient, Url};
35use smallvec::SmallVec;
36#[cfg(any(test, feature = "test-support"))]
37pub use test_app::*;
38#[cfg(any(test, feature = "test-support"))]
39pub use test_context::*;
40#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
41pub use visual_test_context::*;
42
43#[cfg(debug_assertions)]
44use crate::InspectorElementRegistry;
45use crate::asset_cache::CachedLoad;
46use crate::{
47 Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
48 AnyWindowHandle, AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds,
49 ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase, DisplayChanges, DisplayEvent,
50 DisplayId, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap, ForegroundExecutor,
51 Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu, MenuItem, MissingGlyph,
52 OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
53 PlatformKeyboardMapper, PlatformTextSystem, Point, Priority, PromptBuilder, PromptButton,
54 PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
55 ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
56 SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
57 ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
58 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 with_platform_and_text_system(
192 platform: Rc<dyn Platform>,
193 text_system: Arc<dyn PlatformTextSystem>,
194 ) -> Self {
195 Self(App::new_app_with_text_system(
196 platform,
197 Arc::new(()),
198 Arc::new(NullHttpClient),
199 Some(text_system),
200 ))
201 }
202
203 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
213 let this = Self::with_platform(platform);
214 this.0.borrow_mut().accessibility_force_disabled = true;
215 this
216 }
217
218 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
220 let mut context_lock = self.0.borrow_mut();
221 let asset_source = Arc::new(asset_source);
222 context_lock.asset_source = asset_source.clone();
223 context_lock.svg_renderer = SvgRenderer::new(asset_source);
224 drop(context_lock);
225 self
226 }
227
228 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
230 self.0.borrow_mut().restart_arguments = arguments;
231 self
232 }
233
234 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
236 let mut context_lock = self.0.borrow_mut();
237 context_lock.http_client = http_client;
238 drop(context_lock);
239 self
240 }
241
242 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
245 self.0.borrow_mut().quit_mode = mode;
246 self
247 }
248
249 pub fn with_windowing(self, request: WindowingRequest) -> Self {
256 self.0.borrow().platform.set_initial_windowing(request);
257 self
258 }
259
260 pub fn run<F>(self, on_finish_launching: F)
266 where
267 F: 'static + FnOnce(&mut App),
268 {
269 let this = self.0.clone();
270 let platform = self.0.borrow().platform.clone();
271 platform.run(Box::new(move || {
272 let cx = &mut *this.borrow_mut();
273 cx.displays_changed();
275 on_finish_launching(cx);
276 }));
277
278 #[cfg(target_family = "wasm")]
279 std::mem::forget(self);
280 }
281
282 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
292 where
293 F: 'static + FnOnce(&mut App),
294 {
295 let this = self.0.clone();
296 let platform = self.0.borrow().platform.clone();
297 platform.run(Box::new(move || {
298 let cx = &mut *this.borrow_mut();
299 cx.displays_changed();
301 on_finish_launching(cx);
302 }));
303 ApplicationHandle { app: self.0 }
304 }
305
306 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
309 where
310 F: 'static + FnMut(Vec<String>),
311 {
312 self.0.borrow().platform.on_open_urls(Box::new(callback));
313 self
314 }
315
316 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
319 where
320 F: 'static + FnMut(&mut App),
321 {
322 let this = Rc::downgrade(&self.0);
323 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
324 if let Some(app) = this.upgrade() {
325 callback(&mut app.borrow_mut());
326 }
327 }));
328 self
329 }
330
331 pub fn background_executor(&self) -> BackgroundExecutor {
333 self.0.borrow().background_executor.clone()
334 }
335
336 pub fn foreground_executor(&self) -> ForegroundExecutor {
338 self.0.borrow().foreground_executor.clone()
339 }
340
341 pub fn text_system(&self) -> Arc<TextSystem> {
343 self.0.borrow().text_system.clone()
344 }
345
346 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
348 self.0.borrow().path_for_auxiliary_executable(name)
349 }
350}
351
352type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
353type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
354
355#[derive(Clone, Copy, PartialEq)]
357struct DisplayState {
358 bounds: Bounds<Pixels>,
359 refresh_interval: Option<Duration>,
360}
361
362impl DisplayState {
363 fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
364 let mut changes = DisplayChanges::empty();
365 changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
366 changes.set(
367 DisplayChanges::REFRESH_INTERVAL,
368 self.refresh_interval != previous.refresh_interval,
369 );
370 changes
371 }
372}
373
374fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
375 platform
376 .displays()
377 .into_iter()
378 .map(|display| {
379 let state = DisplayState {
380 bounds: display.bounds(),
381 refresh_interval: display.refresh_interval(),
382 };
383 (display.id(), state)
384 })
385 .collect()
386}
387
388fn display_events(
390 previous: &HashMap<DisplayId, DisplayState>,
391 current: &HashMap<DisplayId, DisplayState>,
392) -> Vec<DisplayEvent> {
393 let removed = previous
394 .keys()
395 .filter(|id| !current.contains_key(id))
396 .map(|id| DisplayEvent::Removed(*id));
397 let added_or_changed = current.iter().filter_map(|(id, state)| {
398 let Some(previous_state) = previous.get(id) else {
399 return Some(DisplayEvent::Added(*id));
400 };
401 let changes = state.changes_from(previous_state);
402 (!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
403 });
404 removed.chain(added_or_changed).collect()
405}
406type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
407type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
408pub(crate) type KeystrokeObserver =
409 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
410type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
411type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
412type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
413type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
414
415struct MissingGlyphCallbackEntry {
416 registration: Rc<()>,
417 callback: Option<MissingGlyphCallback>,
418}
419
420#[derive(Default)]
421struct MissingGlyphCallbackSlot {
422 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
423}
424
425impl MissingGlyphCallbackSlot {
426 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
427 let registration = Rc::new(());
428 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
429 registration: registration.clone(),
430 callback: Some(callback),
431 });
432 registration
433 }
434
435 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
436 let Some((registration, mut callback)) =
437 self.entry.borrow_mut().as_mut().and_then(|entry| {
438 entry
439 .callback
440 .take()
441 .map(|callback| (entry.registration.clone(), callback))
442 })
443 else {
444 return;
445 };
446 callback(missing_glyphs, cx);
447
448 let mut entry = self.entry.borrow_mut();
449 let is_current = entry
450 .as_ref()
451 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
452 if is_current {
453 let Some(entry) = entry.as_mut() else {
454 return;
455 };
456 entry.callback = Some(callback);
457 }
458 }
459
460 fn remove(&self, registration: &Rc<()>) -> bool {
461 let mut entry = self.entry.borrow_mut();
462 let is_current = entry
463 .as_ref()
464 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
465 if is_current {
466 entry.take();
467 }
468 is_current
469 }
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
474pub enum QuitMode {
475 #[default]
477 Default,
478 LastWindowClosed,
480 Explicit,
482}
483
484#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
489pub enum CursorHideMode {
490 Never,
492 OnTyping,
494 #[default]
497 OnTypingAndAction,
498}
499
500#[doc(hidden)]
501#[derive(Clone, PartialEq, Eq)]
502pub struct SystemWindowTab {
503 pub id: WindowId,
504 pub title: SharedString,
505 pub handle: AnyWindowHandle,
506 pub last_active_at: Instant,
507}
508
509impl SystemWindowTab {
510 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
512 Self {
513 id: handle.id,
514 title,
515 handle,
516 last_active_at: Instant::now(),
517 }
518 }
519}
520
521#[derive(Default)]
523pub struct SystemWindowTabController {
524 visible: Option<bool>,
525 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
526}
527
528impl Global for SystemWindowTabController {}
529
530impl SystemWindowTabController {
531 pub fn new() -> Self {
533 Self {
534 visible: None,
535 tab_groups: FxHashMap::default(),
536 }
537 }
538
539 pub fn init(cx: &mut App) {
541 cx.set_global(SystemWindowTabController::new());
542 }
543
544 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
546 &self.tab_groups
547 }
548
549 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
551 let controller = cx.global::<SystemWindowTabController>();
552 let current_group = controller
553 .tab_groups
554 .iter()
555 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
556
557 let current_group = current_group?;
558 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
560 let idx = group_ids.iter().position(|g| *g == current_group)?;
561 let next_idx = (idx + 1) % group_ids.len();
562
563 controller
564 .tab_groups
565 .get(group_ids[next_idx])
566 .and_then(|tabs| {
567 tabs.iter()
568 .max_by_key(|tab| tab.last_active_at)
569 .or_else(|| tabs.first())
570 .map(|tab| &tab.handle)
571 })
572 }
573
574 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
576 let controller = cx.global::<SystemWindowTabController>();
577 let current_group = controller
578 .tab_groups
579 .iter()
580 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
581
582 let current_group = current_group?;
583 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
585 let idx = group_ids.iter().position(|g| *g == current_group)?;
586 let prev_idx = if idx == 0 {
587 group_ids.len() - 1
588 } else {
589 idx - 1
590 };
591
592 controller
593 .tab_groups
594 .get(group_ids[prev_idx])
595 .and_then(|tabs| {
596 tabs.iter()
597 .max_by_key(|tab| tab.last_active_at)
598 .or_else(|| tabs.first())
599 .map(|tab| &tab.handle)
600 })
601 }
602
603 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
605 self.tab_groups
606 .values()
607 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
608 }
609
610 pub fn init_visible(cx: &mut App, visible: bool) {
612 let mut controller = cx.global_mut::<SystemWindowTabController>();
613 if controller.visible.is_none() {
614 controller.visible = Some(visible);
615 }
616 }
617
618 pub fn is_visible(&self) -> bool {
620 self.visible.unwrap_or(false)
621 }
622
623 pub fn set_visible(cx: &mut App, visible: bool) {
625 let mut controller = cx.global_mut::<SystemWindowTabController>();
626 controller.visible = Some(visible);
627 }
628
629 pub fn update_last_active(cx: &mut App, id: WindowId) {
631 let mut controller = cx.global_mut::<SystemWindowTabController>();
632 for windows in controller.tab_groups.values_mut() {
633 for tab in windows.iter_mut() {
634 if tab.id == id {
635 tab.last_active_at = Instant::now();
636 }
637 }
638 }
639 }
640
641 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
643 let mut controller = cx.global_mut::<SystemWindowTabController>();
644 for (_, windows) in controller.tab_groups.iter_mut() {
645 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
646 if ix < windows.len() && current_pos != ix {
647 let window_tab = windows.remove(current_pos);
648 windows.insert(ix, window_tab);
649 }
650 break;
651 }
652 }
653 }
654
655 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
657 let controller = cx.global::<SystemWindowTabController>();
658 let tab = controller
659 .tab_groups
660 .values()
661 .flat_map(|windows| windows.iter())
662 .find(|tab| tab.id == id);
663
664 if tab.map_or(true, |t| t.title == title) {
665 return;
666 }
667
668 let mut controller = cx.global_mut::<SystemWindowTabController>();
669 for windows in controller.tab_groups.values_mut() {
670 for tab in windows.iter_mut() {
671 if tab.id == id {
672 tab.title = title;
673 return;
674 }
675 }
676 }
677 }
678
679 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
681 let mut controller = cx.global_mut::<SystemWindowTabController>();
682 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
683 return;
684 };
685
686 let mut expected_tab_ids: Vec<_> = tabs
687 .iter()
688 .filter(|tab| tab.id != id)
689 .map(|tab| tab.id)
690 .sorted()
691 .collect();
692
693 let mut tab_group_id = None;
694 for (group_id, group_tabs) in &controller.tab_groups {
695 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
696 if tab_ids == expected_tab_ids {
697 tab_group_id = Some(*group_id);
698 break;
699 }
700 }
701
702 if let Some(tab_group_id) = tab_group_id {
703 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
704 tabs.push(tab);
705 }
706 } else {
707 let new_group_id = controller.tab_groups.len();
708 controller.tab_groups.insert(new_group_id, tabs);
709 }
710 }
711
712 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
714 let mut controller = cx.global_mut::<SystemWindowTabController>();
715 let mut removed_tab = None;
716
717 controller.tab_groups.retain(|_, tabs| {
718 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
719 removed_tab = Some(tabs.remove(pos));
720 }
721 !tabs.is_empty()
722 });
723
724 removed_tab
725 }
726
727 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
729 let mut removed_tab = Self::remove_tab(cx, id);
730 let mut controller = cx.global_mut::<SystemWindowTabController>();
731
732 if let Some(tab) = removed_tab {
733 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
734 controller.tab_groups.insert(new_group_id, vec![tab]);
735 }
736 }
737
738 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
740 let mut controller = cx.global_mut::<SystemWindowTabController>();
741 let Some(initial_tabs) = controller.tabs(id) else {
742 return;
743 };
744
745 let initial_tabs_len = initial_tabs.len();
746 let mut all_tabs = initial_tabs.clone();
747
748 for (_, mut tabs) in controller.tab_groups.drain() {
749 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
750 all_tabs.extend(tabs);
751 }
752
753 controller.tab_groups.insert(0, all_tabs);
754 }
755
756 pub fn select_next_tab(cx: &mut App, id: WindowId) {
758 let mut controller = cx.global_mut::<SystemWindowTabController>();
759 let Some(tabs) = controller.tabs(id) else {
760 return;
761 };
762
763 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
764 let next_index = (current_index + 1) % tabs.len();
765
766 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
767 window.activate_window();
768 });
769 }
770
771 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
773 let mut controller = cx.global_mut::<SystemWindowTabController>();
774 let Some(tabs) = controller.tabs(id) else {
775 return;
776 };
777
778 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
779 let previous_index = if current_index == 0 {
780 tabs.len() - 1
781 } else {
782 current_index - 1
783 };
784
785 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
786 window.activate_window();
787 });
788 }
789}
790
791pub(crate) enum GpuiMode {
792 #[cfg(any(test, feature = "test-support"))]
793 Test {
794 skip_drawing: bool,
795 },
796 Production,
797}
798
799impl GpuiMode {
800 #[cfg(any(test, feature = "test-support"))]
801 pub fn test() -> Self {
802 GpuiMode::Test {
803 skip_drawing: false,
804 }
805 }
806
807 #[inline]
808 pub(crate) fn skip_drawing(&self) -> bool {
809 match self {
810 #[cfg(any(test, feature = "test-support"))]
811 GpuiMode::Test { skip_drawing } => *skip_drawing,
812 GpuiMode::Production => false,
813 }
814 }
815}
816
817struct PlatformOwnedDrag {
818 source_window: WindowId,
819 state: PlatformOwnedDragState,
820}
821
822enum PlatformOwnedDragState {
823 Suspended(AnyDrag),
824 RestoredInSourceWindow,
827}
828
829pub struct App {
833 pub(crate) this: Weak<AppCell>,
834 pub(crate) platform: Rc<dyn Platform>,
835 text_system: Arc<TextSystem>,
836
837 pub(crate) actions: Rc<ActionRegistry>,
838 pub(crate) active_drag: Option<AnyDrag>,
839 platform_owned_drag: Option<PlatformOwnedDrag>,
840 pub(crate) background_executor: BackgroundExecutor,
841 pub(crate) foreground_executor: ForegroundExecutor,
842 #[cfg(feature = "profiler")]
843 foreground_journal: crate::profiler::journal::ForegroundJournal,
844 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
845 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
846 pub(crate) entities: EntityMap,
847 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
848 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
849 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
850 pub(crate) focus_handles: Arc<FocusMap>,
851 pub(crate) keymap: Rc<RefCell<Keymap>>,
852 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
853 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
854 pub(crate) global_action_listeners:
855 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
856 pending_effects: VecDeque<Effect>,
857
858 pub(crate) observers: SubscriberSet<EntityId, Handler>,
859 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
860 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
861 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
862 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
863 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
864 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
865 pub(crate) display_observers: SubscriberSet<(), DisplayHandler>,
866 displays: HashMap<DisplayId, DisplayState>,
869 pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
870 pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
871 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
872 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
873 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
874 pub(crate) restart_observers: SubscriberSet<(), Handler>,
875 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
876
877 pub(crate) element_arena: RefCell<Arena>,
880 pub(crate) event_arena: Arena,
882
883 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
888
889 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
891 asset_source: Arc<dyn AssetSource>,
892 pub(crate) svg_renderer: SvgRenderer,
893 http_client: Arc<dyn HttpClient>,
894
895 pub(crate) pending_notifications: FxHashSet<EntityId>,
897 pub(crate) pending_global_notifications: TypeIdHashSet,
898 pub(crate) restart_path: Option<PathBuf>,
899 pub(crate) restart_arguments: Vec<OsString>,
900 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
902 pub(crate) prompt_builder: Option<PromptBuilder>,
903 pub(crate) window_invalidators_by_entity:
904 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
905 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
906 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
907 #[cfg(debug_assertions)]
908 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
909 #[cfg(debug_assertions)]
910 pub(crate) inspector_element_registry: InspectorElementRegistry,
911 #[cfg(any(test, feature = "test-support", debug_assertions))]
912 pub(crate) name: Option<&'static str>,
913 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
914
915 pub(crate) window_update_stack: Vec<WindowId>,
916 pub(crate) mode: GpuiMode,
917 pub(crate) cursor_hide_mode: CursorHideMode,
918 pub(crate) reduce_motion: bool,
919 pub(crate) synced_animation_epoch: Instant,
921 pub(crate) accessibility_force_disabled: bool,
924 pending_updates: usize,
925 quit_mode: QuitMode,
926 quitting: bool,
927
928 #[cfg(any(test, gpui_leak_detection))]
931 _ref_counts: Arc<RwLock<EntityRefCounts>>,
932}
933
934impl App {
935 #[allow(clippy::new_ret_no_self)]
936 pub(crate) fn new_app(
937 platform: Rc<dyn Platform>,
938 asset_source: Arc<dyn AssetSource>,
939 http_client: Arc<dyn HttpClient>,
940 ) -> Rc<AppCell> {
941 Self::new_app_with_text_system(platform, asset_source, http_client, None)
942 }
943
944 fn new_app_with_text_system(
945 platform: Rc<dyn Platform>,
946 asset_source: Arc<dyn AssetSource>,
947 http_client: Arc<dyn HttpClient>,
948 text_override: Option<Arc<dyn PlatformTextSystem>>,
949 ) -> Rc<AppCell> {
950 let background_executor = platform.background_executor();
951 let foreground_executor = platform.foreground_executor();
952 assert!(
953 background_executor.is_main_thread(),
954 "must construct App on main thread"
955 );
956 #[cfg(feature = "profiler")]
957 let foreground_journal = crate::profiler::journal::install_foreground_journal();
958 let synced_animation_epoch = background_executor.now();
959
960 let backend = text_override.unwrap_or_else(|| platform.text_system());
961 let text_system = Arc::new(TextSystem::new(backend));
962 let entities = EntityMap::new();
963 let keyboard_layout = platform.keyboard_layout();
964 let keyboard_mapper = platform.keyboard_mapper();
965
966 #[cfg(any(test, gpui_leak_detection))]
967 let _ref_counts = entities.ref_counts_drop_handle();
968
969 let app = Rc::new_cyclic(|this| AppCell {
970 app: RefCell::new(App {
971 this: this.clone(),
972 platform: platform.clone(),
973 text_system,
974 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
975 mode: GpuiMode::Production,
976 actions: Rc::new(ActionRegistry::default()),
977 pending_updates: 0,
978 active_drag: None,
979 platform_owned_drag: None,
980 background_executor,
981 foreground_executor,
982 #[cfg(feature = "profiler")]
983 foreground_journal,
984 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
985 hang_monitor: None,
986 svg_renderer: SvgRenderer::new(asset_source.clone()),
987 loading_assets: Default::default(),
988 asset_source,
989 http_client,
990 globals_by_type: Default::default(),
991 entities,
992 new_entity_observers: SubscriberSet::new(),
993 windows: SlotMap::with_key(),
994 window_update_stack: Vec::new(),
995 window_handles: FxHashMap::default(),
996 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
997 keymap: Rc::new(RefCell::new(Keymap::default())),
998 keyboard_layout,
999 keyboard_mapper,
1000 global_action_listeners: Default::default(),
1001 pending_effects: VecDeque::new(),
1002 pending_notifications: FxHashSet::default(),
1003 pending_global_notifications: Default::default(),
1004 observers: SubscriberSet::new(),
1005 tracked_entities: FxHashMap::default(),
1006 window_invalidators_by_entity: FxHashMap::default(),
1007 current_window_by_entity: FxHashMap::default(),
1008 event_listeners: SubscriberSet::new(),
1009 release_listeners: SubscriberSet::new(),
1010 keystroke_observers: SubscriberSet::new(),
1011 keystroke_interceptors: SubscriberSet::new(),
1012 keyboard_layout_observers: SubscriberSet::new(),
1013 missing_glyph_callback: Rc::default(),
1014 thermal_state_observers: SubscriberSet::new(),
1015 display_observers: SubscriberSet::new(),
1016 displays: read_displays(platform.as_ref()),
1017 system_sleep_observers: SubscriberSet::new(),
1018 system_wake_observers: SubscriberSet::new(),
1019 global_observers: SubscriberSet::new(),
1020 quit_observers: SubscriberSet::new(),
1021 restart_observers: SubscriberSet::new(),
1022 restart_path: None,
1023 restart_arguments: Vec::new(),
1024 window_closed_observers: SubscriberSet::new(),
1025 layout_id_buffer: Default::default(),
1026 propagate_event: true,
1027 prompt_builder: Some(PromptBuilder::Default),
1028 #[cfg(debug_assertions)]
1029 inspector_renderer: None,
1030 #[cfg(debug_assertions)]
1031 inspector_element_registry: InspectorElementRegistry::default(),
1032 quit_mode: QuitMode::default(),
1033 quitting: false,
1034 cursor_hide_mode: CursorHideMode::default(),
1035 reduce_motion: false,
1036 synced_animation_epoch,
1037 accessibility_force_disabled: false,
1038
1039 #[cfg(any(test, feature = "test-support", debug_assertions))]
1040 name: None,
1041 element_arena: RefCell::new(Arena::new(1024 * 1024)),
1042 event_arena: Arena::new(1024 * 1024),
1043
1044 #[cfg(any(test, gpui_leak_detection))]
1045 _ref_counts,
1046 }),
1047 });
1048
1049 init_app_menus(platform.as_ref(), &app.borrow());
1050 SystemWindowTabController::init(&mut app.borrow_mut());
1051 #[cfg(feature = "profiler")]
1052 crate::profiler::journal::observe_power(&app.borrow());
1053
1054 platform.on_keyboard_layout_change(Box::new({
1055 let app = Rc::downgrade(&app);
1056 move || {
1057 if let Some(app) = app.upgrade() {
1058 let cx = &mut app.borrow_mut();
1059 cx.keyboard_layout = cx.platform.keyboard_layout();
1060 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1061 cx.keyboard_layout_observers
1062 .clone()
1063 .retain(&(), move |callback| (callback)(cx));
1064 }
1065 }
1066 }));
1067
1068 platform.on_thermal_state_change(Box::new({
1069 let app = Rc::downgrade(&app);
1070 move || {
1071 if let Some(app) = app.upgrade() {
1072 let cx = &mut app.borrow_mut();
1073 cx.thermal_state_observers
1074 .clone()
1075 .retain(&(), move |callback| (callback)(cx));
1076 }
1077 }
1078 }));
1079
1080 platform.on_displays_changed(Box::new({
1081 let app = Rc::downgrade(&app);
1082 move || {
1083 if let Some(app) = app.upgrade() {
1084 app.borrow_mut().displays_changed();
1085 }
1086 }
1087 }));
1088
1089 platform.on_system_sleep(Box::new({
1090 let app = Rc::downgrade(&app);
1091 move || {
1092 if let Some(app) = app.upgrade() {
1093 let cx = &mut app.borrow_mut();
1094 cx.system_sleep_observers
1095 .clone()
1096 .retain(&(), move |callback| (callback)(cx));
1097 }
1098 }
1099 }));
1100
1101 platform.on_system_wake(Box::new({
1102 let app = Rc::downgrade(&app);
1103 move || {
1104 if let Some(app) = app.upgrade() {
1105 let cx = &mut app.borrow_mut();
1106 cx.system_wake_observers
1107 .clone()
1108 .retain(&(), move |callback| (callback)(cx));
1109 }
1110 }
1111 }));
1112
1113 platform.on_quit(Box::new({
1114 let cx = Rc::downgrade(&app);
1115 move || {
1116 let Some(cx) = cx.upgrade() else {
1117 return true;
1118 };
1119 match cx.try_borrow_mut() {
1120 Ok(mut cx) => {
1121 cx.shutdown();
1122 true
1123 }
1124 Err(_) => {
1125 false
1128 }
1129 }
1130 }
1131 }));
1132
1133 app
1134 }
1135
1136 #[doc(hidden)]
1137 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1138 self.entities.ref_counts_drop_handle()
1139 }
1140
1141 #[cfg(any(test, gpui_leak_detection))]
1147 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1148 self.entities.leak_detector_snapshot()
1149 }
1150
1151 #[cfg(any(test, gpui_leak_detection))]
1163 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1164 self.entities.assert_no_new_leaks(snapshot)
1165 }
1166
1167 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1169 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1170 LeakDetectorSnapshot::default()
1171 }
1172
1173 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1176 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1177
1178 pub fn shutdown(&mut self) {
1184 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1187 let hang_monitor_flush = self
1188 .hang_monitor
1189 .as_ref()
1190 .and_then(|hang_monitor| hang_monitor.request_flush());
1191
1192 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1193
1194 for observer in self.quit_observers.remove(&()) {
1195 futures.push(observer(self));
1196 }
1197
1198 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1199 if let Some(flushed) = hang_monitor_flush {
1200 futures.push(
1201 async move {
1202 if flushed.await.is_err() {
1203 log::warn!("hang monitor exited before flushing");
1204 }
1205 }
1206 .boxed_local(),
1207 );
1208 }
1209
1210 self.windows.clear();
1211 self.window_handles.clear();
1212 self.flush_effects();
1213 self.quitting = true;
1214
1215 let futures = futures::future::join_all(futures);
1216 #[cfg(not(target_family = "wasm"))]
1217 if self
1218 .foreground_executor
1219 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1220 .is_err()
1221 {
1222 log::error!("timed out waiting on app_will_quit");
1223 }
1224 #[cfg(target_family = "wasm")]
1225 self.foreground_executor.spawn(futures).detach();
1226
1227 self.quitting = false;
1228 }
1229
1230 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1232 self.keyboard_layout.as_ref()
1233 }
1234
1235 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1237 &self.keyboard_mapper
1238 }
1239
1240 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1242 where
1243 F: 'static + FnMut(&mut App),
1244 {
1245 let (subscription, activate) = self.keyboard_layout_observers.insert(
1246 (),
1247 Box::new(move |cx| {
1248 callback(cx);
1249 true
1250 }),
1251 );
1252 activate();
1253 subscription
1254 }
1255
1256 pub fn quit(&self) {
1258 self.platform.quit();
1259 }
1260
1261 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1275 if !self.windows.is_empty() {
1276 return Task::ready(Err(anyhow::anyhow!(
1277 "cannot switch windowing modes while windows are open"
1278 )));
1279 }
1280 self.platform.request_windowing(request)
1281 }
1282
1283 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1293 self.platform.graphical_environment()
1294 }
1295
1296 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1299 self.cursor_hide_mode
1300 }
1301
1302 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1305 self.cursor_hide_mode = mode;
1306 }
1307
1308 pub fn is_cursor_visible(&self) -> bool {
1314 self.platform.is_cursor_visible()
1315 }
1316
1317 pub fn reduce_motion(&self) -> bool {
1320 self.reduce_motion
1321 }
1322
1323 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1326 if self.reduce_motion != reduce_motion {
1327 self.reduce_motion = reduce_motion;
1328 self.refresh_windows();
1329 }
1330 }
1331
1332 pub fn refresh_windows(&mut self) {
1335 self.pending_effects.push_back(Effect::RefreshWindows);
1336 }
1337
1338 #[inline(always)]
1339 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1340 self.start_update();
1341 let result = update(self);
1342 self.finish_update();
1343 result
1344 }
1345
1346 pub(crate) fn start_update(&mut self) {
1347 self.pending_updates += 1;
1348 }
1349
1350 #[inline(never)]
1351 pub(crate) fn finish_update(&mut self) {
1352 if self.pending_updates == 1 {
1353 self.flush_effects();
1354 }
1355 self.pending_updates -= 1;
1356 }
1357
1358 pub fn observe<W>(
1360 &mut self,
1361 entity: &Entity<W>,
1362 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1363 ) -> Subscription
1364 where
1365 W: 'static,
1366 {
1367 self.observe_internal(entity, move |e, cx| {
1368 on_notify(e, cx);
1369 true
1370 })
1371 }
1372
1373 pub(crate) fn detect_accessed_entities<R>(
1374 &mut self,
1375 callback: impl FnOnce(&mut App) -> R,
1376 ) -> (R, FxHashSet<EntityId>) {
1377 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1378 let result = callback(self);
1379 let entities_accessed_in_callback = self
1380 .entities
1381 .accessed_entities
1382 .get_mut()
1383 .difference(&accessed_entities_start)
1384 .copied()
1385 .collect::<FxHashSet<EntityId>>();
1386 (result, entities_accessed_in_callback)
1387 }
1388
1389 pub(crate) fn record_entities_accessed(
1390 &mut self,
1391 window_handle: AnyWindowHandle,
1392 invalidator: WindowInvalidator,
1393 entities: &FxHashSet<EntityId>,
1394 ) {
1395 let mut tracked_entities =
1396 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1397 for entity in tracked_entities.iter() {
1398 self.window_invalidators_by_entity
1399 .entry(*entity)
1400 .and_modify(|windows| {
1401 windows.remove(&window_handle.id);
1402 });
1403 }
1404 for entity in entities.iter() {
1405 self.window_invalidators_by_entity
1406 .entry(*entity)
1407 .or_default()
1408 .insert(window_handle.id, invalidator.clone());
1409 self.current_window_by_entity
1410 .insert(*entity, window_handle.id);
1411 }
1412 tracked_entities.clear();
1413 tracked_entities.extend(entities.iter().copied());
1414 self.tracked_entities
1415 .insert(window_handle.id, tracked_entities);
1416 }
1417
1418 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1419 let (subscription, activate) = self.observers.insert(key, value);
1420 self.defer(move |_| activate());
1421 subscription
1422 }
1423
1424 pub(crate) fn observe_internal<W>(
1425 &mut self,
1426 entity: &Entity<W>,
1427 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1428 ) -> Subscription
1429 where
1430 W: 'static,
1431 {
1432 let entity_id = entity.entity_id();
1433 let handle = entity.downgrade();
1434 self.new_observer(
1435 entity_id,
1436 Box::new(move |cx| {
1437 if let Some(entity) = handle.upgrade() {
1438 on_notify(entity, cx)
1439 } else {
1440 false
1441 }
1442 }),
1443 )
1444 }
1445
1446 pub fn subscribe<T, Event>(
1449 &mut self,
1450 entity: &Entity<T>,
1451 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1452 ) -> Subscription
1453 where
1454 T: 'static + EventEmitter<Event>,
1455 Event: 'static,
1456 {
1457 self.subscribe_internal(entity, move |entity, event, cx| {
1458 on_event(entity, event, cx);
1459 true
1460 })
1461 }
1462
1463 pub(crate) fn new_subscription(
1464 &mut self,
1465 key: EntityId,
1466 value: (TypeId, Listener),
1467 ) -> Subscription {
1468 let (subscription, activate) = self.event_listeners.insert(key, value);
1469 self.defer(move |_| activate());
1470 subscription
1471 }
1472 pub(crate) fn subscribe_internal<T, Evt>(
1473 &mut self,
1474 entity: &Entity<T>,
1475 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1476 ) -> Subscription
1477 where
1478 T: 'static + EventEmitter<Evt>,
1479 Evt: 'static,
1480 {
1481 let entity_id = entity.entity_id();
1482 let handle = entity.downgrade();
1483 self.new_subscription(
1484 entity_id,
1485 (
1486 TypeId::of::<Evt>(),
1487 Box::new(move |event, cx| {
1488 let event: &Evt = event.downcast_ref().expect("invalid event type");
1489 if let Some(entity) = handle.upgrade() {
1490 on_event(entity, event, cx)
1491 } else {
1492 false
1493 }
1494 }),
1495 ),
1496 )
1497 }
1498
1499 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1503 self.windows
1504 .keys()
1505 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1506 .collect()
1507 }
1508
1509 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1515 self.platform.window_stack()
1516 }
1517
1518 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1520 self.platform.active_window()
1521 }
1522
1523 pub fn open_window<V: 'static + Render>(
1527 &mut self,
1528 options: crate::WindowOptions,
1529 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1530 ) -> anyhow::Result<WindowHandle<V>> {
1531 self.update(|cx| {
1532 let id = cx.windows.insert(None);
1533 let handle = WindowHandle::new(id);
1534 match Window::new(handle.into(), options, cx) {
1535 Ok(mut window) => {
1536 cx.window_update_stack.push(id);
1537 let root_view = build_root_view(&mut window, cx);
1538 cx.window_update_stack.pop();
1539 window.root.replace(root_view.into());
1540 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1541
1542 let clear = window.draw(cx);
1547 clear.clear(cx);
1548
1549 cx.window_handles.insert(id, window.handle);
1550 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1551 Ok(handle)
1552 }
1553 Err(e) => {
1554 cx.windows.remove(id);
1555 Err(e)
1556 }
1557 }
1558 })
1559 }
1560
1561 pub fn activate(&self, ignoring_other_apps: bool) {
1563 self.platform.activate(ignoring_other_apps);
1564 }
1565
1566 pub fn hide(&self) {
1568 self.platform.hide();
1569 }
1570
1571 pub fn hide_other_apps(&self) {
1573 self.platform.hide_other_apps();
1574 }
1575
1576 pub fn unhide_other_apps(&self) {
1578 self.platform.unhide_other_apps();
1579 }
1580
1581 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1583 self.platform.displays()
1584 }
1585
1586 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1588 self.platform.primary_display()
1589 }
1590
1591 pub fn is_screen_capture_supported(&self) -> bool {
1593 self.platform.is_screen_capture_supported()
1594 }
1595
1596 pub fn screen_capture_sources(
1598 &self,
1599 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1600 self.platform.screen_capture_sources()
1601 }
1602
1603 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1605 self.displays()
1606 .iter()
1607 .find(|display| display.id() == id)
1608 .cloned()
1609 }
1610
1611 pub fn thermal_state(&self) -> ThermalState {
1613 self.platform.thermal_state()
1614 }
1615
1616 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1618 self.platform.prevent_idle_sleep(reason)
1619 }
1620
1621 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1623 where
1624 F: 'static + FnMut(&mut App),
1625 {
1626 let (subscription, activate) = self.thermal_state_observers.insert(
1627 (),
1628 Box::new(move |cx| {
1629 callback(cx);
1630 true
1631 }),
1632 );
1633 activate();
1634 subscription
1635 }
1636
1637 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1642 where
1643 F: 'static + FnMut(&mut App),
1644 {
1645 let (subscription, activate) = self.system_sleep_observers.insert(
1646 (),
1647 Box::new(move |cx| {
1648 callback(cx);
1649 true
1650 }),
1651 );
1652 activate();
1653 subscription
1654 }
1655
1656 pub(crate) fn displays_changed(&mut self) {
1657 let current = read_displays(self.platform.as_ref());
1658 let events = display_events(&self.displays, ¤t);
1659 self.displays = current;
1660 for event in &events {
1661 let DisplayEvent::Changed { id, .. } = *event else {
1662 continue;
1663 };
1664 for handle in self.windows() {
1665 self.update_window(handle, |_, window, cx| {
1666 if window.display_id == Some(id) {
1667 window.notify_display_observers(cx);
1668 }
1669 })
1670 .log_err();
1671 }
1672 }
1673 for event in events {
1674 self.display_observers
1675 .clone()
1676 .retain(&(), |callback| (callback)(event, self));
1677 }
1678 }
1679
1680 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1681 self.displays.contains_key(&id)
1682 }
1683
1684 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1687 self.displays.get(&id)?.refresh_interval
1688 }
1689
1690 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1693 where
1694 F: 'static + FnMut(DisplayEvent, &mut App),
1695 {
1696 let (subscription, activate) = self.display_observers.insert(
1697 (),
1698 Box::new(move |event, cx| {
1699 callback(event, cx);
1700 true
1701 }),
1702 );
1703 activate();
1704 subscription
1705 }
1706
1707 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1709 where
1710 F: 'static + FnMut(&mut App),
1711 {
1712 let (subscription, activate) = self.system_wake_observers.insert(
1713 (),
1714 Box::new(move |cx| {
1715 callback(cx);
1716 true
1717 }),
1718 );
1719 activate();
1720 subscription
1721 }
1722
1723 pub fn window_appearance(&self) -> WindowAppearance {
1725 self.platform.window_appearance()
1726 }
1727
1728 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1739 self.platform.set_window_appearance(appearance);
1740 }
1741
1742 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1744 self.platform.button_layout()
1745 }
1746
1747 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1749 self.platform.read_from_clipboard()
1750 }
1751
1752 pub fn read_from_clipboard_async(
1760 &self,
1761 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1762 self.platform.read_from_clipboard_async()
1763 }
1764
1765 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1767 self.text_rendering_mode.set(mode);
1768 }
1769
1770 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1772 self.text_rendering_mode.get()
1773 }
1774
1775 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1777 self.platform.write_to_clipboard(item)
1778 }
1779
1780 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1783 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1784 self.platform.read_from_primary()
1785 }
1786
1787 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1790 pub fn write_to_primary(&self, item: ClipboardItem) {
1791 self.platform.write_to_primary(item)
1792 }
1793
1794 #[cfg(target_os = "macos")]
1800 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1801 self.platform.read_from_find_pasteboard()
1802 }
1803
1804 #[cfg(target_os = "macos")]
1810 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1811 self.platform.write_to_find_pasteboard(item)
1812 }
1813
1814 pub fn write_credentials(
1816 &self,
1817 url: &str,
1818 username: &str,
1819 password: &[u8],
1820 ) -> Task<Result<()>> {
1821 self.platform.write_credentials(url, username, password)
1822 }
1823
1824 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1826 self.platform.read_credentials(url)
1827 }
1828
1829 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1831 self.platform.delete_credentials(url)
1832 }
1833
1834 pub fn open_url(&self, url: &str) {
1836 self.platform.open_url(url);
1837 }
1838
1839 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1846 self.platform.register_url_scheme(scheme)
1847 }
1848
1849 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1856 self.platform.set_app_identity(identifier, name);
1857 }
1858
1859 pub fn show_system_notification(&self, notification: SystemNotification) {
1866 self.platform.show_system_notification(notification);
1867 }
1868
1869 pub fn dismiss_system_notification(&self, tag: &str) {
1874 self.platform.dismiss_system_notification(tag);
1875 }
1876
1877 pub fn on_system_notification_response<F>(&self, mut callback: F)
1881 where
1882 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1883 {
1884 let this = self.this.clone();
1885 self.platform
1886 .on_system_notification_response(Box::new(move |response| {
1887 if let Some(app) = this.upgrade() {
1888 callback(response, &mut app.borrow_mut());
1889 }
1890 }));
1891 }
1892
1893 pub fn app_path(&self) -> Result<PathBuf> {
1897 self.platform.app_path()
1898 }
1899
1900 pub fn compositor_name(&self) -> &'static str {
1904 self.platform.compositor_name()
1905 }
1906
1907 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1909 self.platform.path_for_auxiliary_executable(name)
1910 }
1911
1912 pub fn prompt_for_paths(
1918 &self,
1919 options: PathPromptOptions,
1920 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1921 self.platform.prompt_for_paths(options)
1922 }
1923
1924 pub fn prompt_for_new_path(
1931 &self,
1932 directory: &Path,
1933 suggested_name: Option<&str>,
1934 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1935 self.platform.prompt_for_new_path(directory, suggested_name)
1936 }
1937
1938 pub fn reveal_path(&self, path: &Path) {
1940 self.platform.reveal_path(path)
1941 }
1942
1943 pub fn open_with_system(&self, path: &Path) {
1945 self.platform.open_with_system(path)
1946 }
1947
1948 pub fn should_auto_hide_scrollbars(&self) -> bool {
1950 self.platform.should_auto_hide_scrollbars()
1951 }
1952
1953 pub fn restart(&mut self) {
1955 self.restart_observers
1956 .clone()
1957 .retain(&(), |observer| observer(self));
1958 self.platform.restart(
1959 self.restart_path.take(),
1960 std::mem::take(&mut self.restart_arguments),
1961 )
1962 }
1963
1964 pub fn set_restart_path(&mut self, path: PathBuf) {
1966 self.restart_path = Some(path);
1967 }
1968
1969 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1971 self.http_client.clone()
1972 }
1973
1974 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1976 self.http_client = new_client;
1977 }
1978
1979 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1982 self.quit_mode = mode;
1983 }
1984
1985 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
1994 self.platform.set_activation_policy(policy);
1995 }
1996
1997 pub fn svg_renderer(&self) -> SvgRenderer {
1999 self.svg_renderer.clone()
2000 }
2001
2002 pub(crate) fn push_effect(&mut self, effect: Effect) {
2003 match &effect {
2004 Effect::Notify { emitter } => {
2005 if !self.pending_notifications.insert(*emitter) {
2006 return;
2007 }
2008 }
2009 Effect::NotifyGlobalObservers { global_type } => {
2010 if !self.pending_global_notifications.insert(*global_type) {
2011 return;
2012 }
2013 }
2014 _ => {}
2015 };
2016
2017 self.pending_effects.push_back(effect);
2018 }
2019
2020 fn flush_effects(&mut self) {
2024 loop {
2025 self.release_dropped_entities();
2026 self.release_dropped_focus_handles();
2027 if let Some(effect) = self.pending_effects.pop_front() {
2028 match effect {
2029 Effect::Notify { emitter } => {
2030 self.apply_notify_effect(emitter);
2031 }
2032
2033 Effect::Emit {
2034 emitter,
2035 event_type,
2036 event,
2037 } => self.apply_emit_effect(emitter, event_type, &*event),
2038
2039 Effect::RefreshWindows => {
2040 self.apply_refresh_effect();
2041 }
2042
2043 Effect::NotifyGlobalObservers { global_type } => {
2044 self.apply_notify_global_observers_effect(global_type);
2045 }
2046
2047 Effect::Defer { callback } => {
2048 self.apply_defer_effect(callback);
2049 }
2050 Effect::EntityCreated {
2051 entity,
2052 tid,
2053 window,
2054 } => {
2055 self.apply_entity_created_effect(entity, tid, window);
2056 }
2057 }
2058 } else {
2059 #[cfg(any(test, feature = "test-support"))]
2060 if matches!(self.mode, GpuiMode::Test { .. }) {
2061 for window in self
2062 .windows
2063 .values()
2064 .filter_map(|window| {
2065 let window = window.as_deref()?;
2066 window.invalidator.is_dirty().then_some(window.handle)
2067 })
2068 .collect::<Vec<_>>()
2069 {
2070 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2071 .unwrap();
2072 }
2073 }
2074
2075 if self.pending_effects.is_empty() {
2076 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2077 if window.invalidator.is_dirty()
2078 || window.needs_present.get()
2079 || !window.next_frame_callbacks.borrow().is_empty()
2080 {
2081 window.platform_window.schedule_frame();
2082 }
2083 }
2084
2085 self.event_arena.clear();
2086 break;
2087 }
2088 }
2089 }
2090 }
2091
2092 fn release_dropped_entities(&mut self) {
2096 loop {
2097 let dropped = self.entities.take_dropped();
2098 if dropped.is_empty() {
2099 break;
2100 }
2101
2102 for (entity_id, mut entity) in dropped {
2103 self.observers.remove(&entity_id);
2104 self.event_listeners.remove(&entity_id);
2105 self.window_invalidators_by_entity.remove(&entity_id);
2106 self.current_window_by_entity.remove(&entity_id);
2107 for release_callback in self.release_listeners.remove(&entity_id) {
2108 release_callback(entity.as_mut(), self);
2109 }
2110 }
2111 }
2112 }
2113
2114 fn release_dropped_focus_handles(&mut self) {
2116 self.focus_handles
2117 .clone()
2118 .write()
2119 .retain(|handle_id, focus| {
2120 if focus.ref_count.load(SeqCst) == 0 {
2121 for window_handle in self.windows() {
2122 window_handle
2123 .update(self, |_, window, cx| {
2124 if window.focus == Some(handle_id) {
2125 window.blur(cx);
2126 }
2127 })
2128 .unwrap();
2129 }
2130 false
2131 } else {
2132 true
2133 }
2134 });
2135 }
2136
2137 fn apply_notify_effect(&mut self, emitter: EntityId) {
2138 self.pending_notifications.remove(&emitter);
2139
2140 self.observers
2141 .clone()
2142 .retain(&emitter, |handler| handler(self));
2143 }
2144
2145 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2146 self.event_listeners
2147 .clone()
2148 .retain(&emitter, |(stored_type, handler)| {
2149 if *stored_type == event_type {
2150 handler(event, self)
2151 } else {
2152 true
2153 }
2154 });
2155 }
2156
2157 fn apply_refresh_effect(&mut self) {
2158 for window in self.windows.values_mut() {
2159 if let Some(window) = window.as_deref_mut() {
2160 window.refreshing = true;
2161 window.invalidator.set_dirty(true);
2162 }
2163 }
2164 }
2165
2166 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2167 self.pending_global_notifications.remove(&type_id);
2168 self.global_observers
2169 .clone()
2170 .retain(&type_id, |observer| observer(self));
2171 }
2172
2173 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2174 callback(self);
2175 }
2176
2177 fn apply_entity_created_effect(
2178 &mut self,
2179 entity: AnyEntity,
2180 tid: TypeId,
2181 window: Option<WindowId>,
2182 ) {
2183 if let Some(id) = window {
2187 self.current_window_by_entity.insert(entity.entity_id(), id);
2188 }
2189
2190 self.new_entity_observers.clone().retain(&tid, |observer| {
2191 if let Some(id) = window {
2192 self.update_window_id(id, {
2193 let entity = entity.clone();
2194 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2195 })
2196 .expect("All windows should be off the stack when flushing effects");
2197 } else {
2198 (observer)(entity.clone(), &mut None, self)
2199 }
2200 true
2201 });
2202 }
2203
2204 #[inline(always)]
2210 pub fn with_window<R>(
2211 &mut self,
2212 entity_id: EntityId,
2213 f: impl FnOnce(&mut Window, &mut App) -> R,
2214 ) -> Option<R> {
2215 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2216 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2217 .ok()
2218 }
2219
2220 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2221 self.current_window_by_entity
2222 .entry(entity_id)
2223 .or_insert(window);
2224 }
2225
2226 #[inline(always)]
2227 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2228 where
2229 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2230 {
2231 let mut update = Some(update);
2232 let mut result = None;
2233 self.update_window_erased(id, &mut |arguments| {
2234 if let Some((root_view, window, cx)) = arguments {
2235 result = Some(update.take().unwrap()(root_view, window, cx));
2236 } else {
2237 drop(update.take());
2238 drop(result.take());
2239 }
2240 });
2241 result.context("window not found")
2242 }
2243
2244 pub fn to_async(&self) -> AsyncApp {
2247 AsyncApp {
2248 app: self.this.clone(),
2249 background_executor: self.background_executor.clone(),
2250 foreground_executor: self.foreground_executor.clone(),
2251 }
2252 }
2253
2254 pub fn background_executor(&self) -> &BackgroundExecutor {
2256 &self.background_executor
2257 }
2258
2259 pub fn is_test(&self) -> bool {
2262 self.background_executor.is_test()
2263 }
2264
2265 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2267 if self.quitting {
2268 panic!("Can't spawn on main thread after on_app_quit")
2269 };
2270 &self.foreground_executor
2271 }
2272
2273 #[cfg(feature = "profiler")]
2276 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2277 self.foreground_journal.clone()
2278 }
2279
2280 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2297 pub fn start_hang_monitor(
2298 &mut self,
2299 config: crate::profiler::hang::HangMonitorConfig,
2300 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2301 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2302 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2303
2304 if self.hang_monitor.is_some() {
2305 debug_assert!(false, "the hang monitor was started twice");
2306 return Err(HangMonitorError::AlreadyStarted);
2307 }
2308 let detector = HangDetector::new(
2309 self.foreground_journal(),
2310 config.threshold,
2311 config.frame_budget,
2312 );
2313 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2314 .map_err(HangMonitorError::Spawn)?;
2315 self.hang_monitor = Some(monitor);
2316 Ok(())
2317 }
2318
2319 #[track_caller]
2322 #[inline(always)]
2323 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2324 where
2325 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2326 R: 'static,
2327 {
2328 let mut cx = self.prepare_spawn();
2329
2330 self.foreground_executor
2331 .spawn(async move { f(&mut cx).await }.boxed_local())
2332 }
2333
2334 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2338 where
2339 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2340 R: 'static,
2341 {
2342 if self.quitting {
2343 debug_panic!("Can't spawn on main thread after on_app_quit")
2344 };
2345
2346 let mut cx = self.to_async();
2347
2348 self.foreground_executor
2349 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2350 }
2351
2352 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2355 self.push_effect(Effect::Defer {
2356 callback: Box::new(f),
2357 });
2358 }
2359
2360 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2362 &self.asset_source
2363 }
2364
2365 pub fn text_system(&self) -> &Arc<TextSystem> {
2367 &self.text_system
2368 }
2369
2370 pub fn on_missing_glyphs(
2381 &self,
2382 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2383 ) -> Subscription {
2384 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2385
2386 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2387 let callback = self.missing_glyph_callback.clone();
2388 self.spawn(async move |cx| {
2389 while let Ok(missing_glyphs) = receiver.recv().await {
2390 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2391 }
2392 })
2393 .detach();
2394 }
2395 self.text_system.enable_missing_glyph_reporting();
2396
2397 let callback = self.missing_glyph_callback.clone();
2398 let text_system = self.text_system.clone();
2399 Subscription::new(move || {
2400 if callback.remove(®istration) {
2401 text_system.disable_missing_glyph_reporting();
2402 }
2403 })
2404 }
2405
2406 pub fn has_global<G: Global>(&self) -> bool {
2408 self.globals_by_type.contains_key(&TypeId::of::<G>())
2409 }
2410
2411 #[track_caller]
2413 pub fn global<G: Global>(&self) -> &G {
2414 self.globals_by_type
2415 .get(&TypeId::of::<G>())
2416 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2417 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2418 }
2419
2420 pub fn try_global<G: Global>(&self) -> Option<&G> {
2422 self.globals_by_type
2423 .get(&TypeId::of::<G>())
2424 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2425 }
2426
2427 #[track_caller]
2429 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2430 let global_type = TypeId::of::<G>();
2431 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2432 self.globals_by_type
2433 .get_mut(&global_type)
2434 .and_then(|any_state| any_state.downcast_mut::<G>())
2435 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2436 }
2437
2438 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2441 let global_type = TypeId::of::<G>();
2442 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2443 self.globals_by_type
2444 .entry(global_type)
2445 .or_insert_with(|| Box::<G>::default())
2446 .downcast_mut::<G>()
2447 .unwrap()
2448 }
2449
2450 pub fn set_global<G: Global>(&mut self, global: G) {
2452 let global_type = TypeId::of::<G>();
2453 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2454 self.globals_by_type.insert(global_type, Box::new(global));
2455 }
2456
2457 #[cfg(any(test, feature = "test-support"))]
2459 pub fn clear_globals(&mut self) {
2460 self.globals_by_type.drain();
2461 }
2462
2463 pub fn remove_global<G: Global>(&mut self) -> G {
2465 let global_type = TypeId::of::<G>();
2466 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2467 *self
2468 .globals_by_type
2469 .remove(&global_type)
2470 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2471 .downcast()
2472 .unwrap()
2473 }
2474
2475 pub fn observe_global<G: Global>(
2477 &mut self,
2478 mut f: impl FnMut(&mut Self) + 'static,
2479 ) -> Subscription {
2480 let (subscription, activate) = self.global_observers.insert(
2481 TypeId::of::<G>(),
2482 Box::new(move |cx| {
2483 f(cx);
2484 true
2485 }),
2486 );
2487 self.defer(move |_| activate());
2488 subscription
2489 }
2490
2491 #[track_caller]
2493 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2494 GlobalLease::new(
2495 self.globals_by_type
2496 .remove(&TypeId::of::<G>())
2497 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2498 .unwrap(),
2499 )
2500 }
2501
2502 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2504 let global_type = TypeId::of::<G>();
2505
2506 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2507 self.globals_by_type.insert(global_type, lease.global);
2508 }
2509
2510 pub(crate) fn new_entity_observer(
2511 &self,
2512 key: TypeId,
2513 value: NewEntityListener,
2514 ) -> Subscription {
2515 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2516 activate();
2517 subscription
2518 }
2519
2520 pub fn observe_new<T: 'static>(
2523 &self,
2524 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2525 ) -> Subscription {
2526 self.new_entity_observer(
2527 TypeId::of::<T>(),
2528 Box::new(
2529 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2530 any_entity
2531 .downcast::<T>()
2532 .unwrap()
2533 .update(cx, |entity_state, cx| {
2534 on_new(entity_state, window.as_deref_mut(), cx)
2535 })
2536 },
2537 ),
2538 )
2539 }
2540
2541 pub fn observe_release<T>(
2544 &self,
2545 handle: &Entity<T>,
2546 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2547 ) -> Subscription
2548 where
2549 T: 'static,
2550 {
2551 let (subscription, activate) = self.release_listeners.insert(
2552 handle.entity_id(),
2553 Box::new(move |entity, cx| {
2554 let entity = entity.downcast_mut().expect("invalid entity type");
2555 on_release(entity, cx)
2556 }),
2557 );
2558 activate();
2559 subscription
2560 }
2561
2562 pub fn observe_release_in<T>(
2565 &self,
2566 handle: &Entity<T>,
2567 window: &Window,
2568 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2569 ) -> Subscription
2570 where
2571 T: 'static,
2572 {
2573 let window_handle = window.handle;
2574 self.observe_release(handle, move |entity, cx| {
2575 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2576 })
2577 }
2578
2579 pub fn observe_keystrokes(
2584 &mut self,
2585 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2586 ) -> Subscription {
2587 fn inner(
2588 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2589 handler: KeystrokeObserver,
2590 ) -> Subscription {
2591 let (subscription, activate) = keystroke_observers.insert((), handler);
2592 activate();
2593 subscription
2594 }
2595
2596 inner(
2597 &self.keystroke_observers,
2598 Box::new(move |event, window, cx| {
2599 f(event, window, cx);
2600 true
2601 }),
2602 )
2603 }
2604
2605 pub fn intercept_keystrokes(
2610 &mut self,
2611 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2612 ) -> Subscription {
2613 fn inner(
2614 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2615 handler: KeystrokeObserver,
2616 ) -> Subscription {
2617 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2618 activate();
2619 subscription
2620 }
2621
2622 inner(
2623 &self.keystroke_interceptors,
2624 Box::new(move |event, window, cx| {
2625 f(event, window, cx);
2626 true
2627 }),
2628 )
2629 }
2630
2631 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2633 self.keymap.borrow_mut().add_bindings(bindings);
2634 self.pending_effects.push_back(Effect::RefreshWindows);
2635 }
2636
2637 pub fn clear_key_bindings(&mut self) {
2639 self.keymap.borrow_mut().clear();
2640 self.pending_effects.push_back(Effect::RefreshWindows);
2641 }
2642
2643 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2645 self.keymap.clone()
2646 }
2647
2648 pub fn on_action<A: Action>(
2652 &mut self,
2653 listener: impl Fn(&A, &mut Self) + 'static,
2654 ) -> &mut Self {
2655 self.global_action_listeners
2656 .entry(TypeId::of::<A>())
2657 .or_default()
2658 .push(Rc::new(move |action, phase, cx| {
2659 if phase == DispatchPhase::Bubble {
2660 let action = action.downcast_ref().unwrap();
2661 listener(action, cx)
2662 }
2663 }));
2664 self
2665 }
2666
2667 pub fn stop_propagation(&mut self) {
2672 self.propagate_event = false;
2673 }
2674
2675 pub fn propagate(&mut self) {
2680 self.propagate_event = true;
2681 }
2682
2683 pub fn build_action(
2685 &self,
2686 name: &str,
2687 data: Option<serde_json::Value>,
2688 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2689 self.actions.build_action(name, data)
2690 }
2691
2692 pub fn all_action_names(&self) -> &[&'static str] {
2695 self.actions.all_action_names()
2696 }
2697
2698 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2702 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2703 }
2704
2705 pub fn action_schemas(
2707 &self,
2708 generator: &mut schemars::SchemaGenerator,
2709 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2710 self.actions.action_schemas(generator)
2711 }
2712
2713 pub fn action_schema_by_name(
2718 &self,
2719 name: &str,
2720 generator: &mut schemars::SchemaGenerator,
2721 ) -> Option<Option<schemars::Schema>> {
2722 self.actions.action_schema_by_name(name, generator)
2723 }
2724
2725 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2727 self.actions.deprecated_aliases()
2728 }
2729
2730 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2732 self.actions.deprecation_messages()
2733 }
2734
2735 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2737 self.actions.documentation()
2738 }
2739
2740 pub fn on_app_quit<Fut>(
2743 &self,
2744 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2745 ) -> Subscription
2746 where
2747 Fut: 'static + Future<Output = ()>,
2748 {
2749 let (subscription, activate) = self.quit_observers.insert(
2750 (),
2751 Box::new(move |cx| {
2752 let future = on_quit(cx);
2753 future.boxed_local()
2754 }),
2755 );
2756 activate();
2757 subscription
2758 }
2759
2760 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2764 let (subscription, activate) = self.restart_observers.insert(
2765 (),
2766 Box::new(move |cx| {
2767 on_restart(cx);
2768 true
2769 }),
2770 );
2771 activate();
2772 subscription
2773 }
2774
2775 pub fn on_window_closed(
2778 &self,
2779 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2780 ) -> Subscription {
2781 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2782 activate();
2783 subscription
2784 }
2785
2786 pub(crate) fn clear_pending_keystrokes(&mut self) {
2787 for window in self.windows() {
2788 window
2789 .update(self, |_, window, cx| {
2790 window.clear_pending_keystrokes(cx);
2791 })
2792 .ok();
2793 }
2794 }
2795
2796 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2799 let mut action_available = false;
2800 if let Some(window) = self.active_window()
2801 && let Ok(window_action_available) =
2802 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2803 {
2804 action_available = window_action_available;
2805 }
2806
2807 action_available
2808 || self
2809 .global_action_listeners
2810 .contains_key(&action.as_any().type_id())
2811 }
2812
2813 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2815 let menus: Vec<Menu> = menus.into_iter().collect();
2816 self.platform.set_menus(menus, &self.keymap.borrow());
2817 }
2818
2819 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2821 self.platform.get_menus()
2822 }
2823
2824 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2826 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2827 }
2828
2829 pub fn perform_dock_menu_action(&self, action: usize) {
2831 self.platform.perform_dock_menu_action(action);
2832 }
2833
2834 pub fn add_recent_document(&self, path: &Path) {
2839 self.platform.add_recent_document(path);
2840 }
2841
2842 pub fn update_jump_list(
2845 &self,
2846 menus: Vec<MenuItem>,
2847 entries: Vec<SmallVec<[PathBuf; 2]>>,
2848 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2849 self.platform.update_jump_list(menus, entries)
2850 }
2851
2852 pub fn dispatch_action(&mut self, action: &dyn Action) {
2855 if let Some(active_window) = self.active_window() {
2856 active_window
2857 .update(self, |_, window, cx| {
2858 window.dispatch_action(action.boxed_clone(), cx)
2859 })
2860 .log_err();
2861 } else {
2862 self.dispatch_global_action(action);
2863 }
2864 }
2865
2866 fn dispatch_global_action(&mut self, action: &dyn Action) {
2867 self.propagate_event = true;
2868
2869 if let Some(mut global_listeners) = self
2870 .global_action_listeners
2871 .remove(&action.as_any().type_id())
2872 {
2873 for listener in &global_listeners {
2874 listener(action.as_any(), DispatchPhase::Capture, self);
2875 if !self.propagate_event {
2876 break;
2877 }
2878 }
2879
2880 global_listeners.extend(
2881 self.global_action_listeners
2882 .remove(&action.as_any().type_id())
2883 .unwrap_or_default(),
2884 );
2885
2886 self.global_action_listeners
2887 .insert(action.as_any().type_id(), global_listeners);
2888 }
2889
2890 if self.propagate_event
2891 && let Some(mut global_listeners) = self
2892 .global_action_listeners
2893 .remove(&action.as_any().type_id())
2894 {
2895 for listener in global_listeners.iter().rev() {
2896 listener(action.as_any(), DispatchPhase::Bubble, self);
2897 if !self.propagate_event {
2898 break;
2899 }
2900 }
2901
2902 global_listeners.extend(
2903 self.global_action_listeners
2904 .remove(&action.as_any().type_id())
2905 .unwrap_or_default(),
2906 );
2907
2908 self.global_action_listeners
2909 .insert(action.as_any().type_id(), global_listeners);
2910 }
2911 }
2912
2913 pub fn has_active_drag(&self) -> bool {
2915 self.active_drag.is_some()
2916 }
2917
2918 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2920 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2921 }
2922
2923 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2925 if self.active_drag.is_some() {
2926 self.active_drag = None;
2927 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2928 drag.source_window == window.window_handle().window_id()
2929 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2930 }) {
2931 self.platform_owned_drag = None;
2932 }
2933 window.refresh();
2934 true
2935 } else {
2936 false
2937 }
2938 }
2939
2940 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2941 let Some(drag) = self.active_drag.take() else {
2942 return false;
2943 };
2944 self.platform_owned_drag = Some(PlatformOwnedDrag {
2945 source_window,
2946 state: PlatformOwnedDragState::Suspended(drag),
2947 });
2948 true
2949 }
2950
2951 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2952 let Some(platform_drag) = self
2953 .platform_owned_drag
2954 .as_mut()
2955 .filter(|drag| drag.source_window == source_window)
2956 else {
2957 return false;
2958 };
2959 let state = std::mem::replace(
2960 &mut platform_drag.state,
2961 PlatformOwnedDragState::RestoredInSourceWindow,
2962 );
2963 let PlatformOwnedDragState::Suspended(drag) = state else {
2964 return false;
2965 };
2966 self.active_drag = Some(drag);
2967 true
2968 }
2969
2970 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2971 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2972 drag.source_window == source_window
2973 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2974 }) else {
2975 return false;
2976 };
2977 let Some(drag) = self.active_drag.take() else {
2978 return false;
2979 };
2980 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2981 true
2982 }
2983
2984 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2985 if !self
2986 .platform_owned_drag
2987 .as_ref()
2988 .is_some_and(|drag| drag.source_window == source_window)
2989 {
2990 return false;
2991 }
2992 self.platform_owned_drag = None;
2993 self.active_drag = None;
2994 true
2995 }
2996
2997 pub fn set_active_drag_cursor_style(
2999 &mut self,
3000 cursor_style: CursorStyle,
3001 window: &mut Window,
3002 ) -> bool {
3003 if let Some(ref mut drag) = self.active_drag {
3004 drag.cursor_style = Some(cursor_style);
3005 window.refresh();
3006 true
3007 } else {
3008 false
3009 }
3010 }
3011
3012 pub fn set_prompt_builder(
3015 &mut self,
3016 renderer: impl Fn(
3017 PromptLevel,
3018 &str,
3019 Option<&str>,
3020 &[PromptButton],
3021 PromptHandle,
3022 &mut Window,
3023 &mut App,
3024 ) -> RenderablePromptHandle
3025 + 'static,
3026 ) {
3027 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3028 }
3029
3030 pub fn reset_prompt_builder(&mut self) {
3032 self.prompt_builder = Some(PromptBuilder::Default);
3033 }
3034
3035 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3037 let asset_id = (TypeId::of::<A>(), hash(source));
3038 self.loading_assets.remove(&asset_id);
3039 }
3040
3041 #[cfg(any(test, feature = "test-support"))]
3044 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3045 let asset_id = (TypeId::of::<A>(), hash(source));
3046 self.loading_assets.contains_key(&asset_id)
3047 }
3048
3049 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3054 self.asset_entry::<A>(source).get()
3055 }
3056
3057 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3058 let asset_id = (TypeId::of::<A>(), hash(source));
3059 if !self.loading_assets.contains_key(&asset_id) {
3060 let future = A::load(source.clone(), self);
3061 let entry = CachedLoad::new(future, self);
3062 self.loading_assets.insert(asset_id, Box::new(entry));
3063 }
3064 self.loading_assets
3065 .get(&asset_id)
3066 .and_then(|entry| entry.downcast_ref())
3067 .expect("asset cache entries are keyed by their asset type")
3068 }
3069
3070 #[track_caller]
3073 pub fn focus_handle(&self) -> FocusHandle {
3074 FocusHandle::new(&self.focus_handles)
3075 }
3076
3077 pub fn notify(&mut self, entity_id: EntityId) {
3079 let window_invalidators = mem::take(
3080 self.window_invalidators_by_entity
3081 .entry(entity_id)
3082 .or_default(),
3083 );
3084
3085 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3090 .iter()
3091 .filter(|(window_id, _)| {
3092 self.tracked_entities
3093 .get(window_id)
3094 .is_some_and(|set| set.contains(&entity_id))
3095 })
3096 .map(|(_, invalidator)| invalidator.clone())
3097 .collect();
3098
3099 if live_invalidators.is_empty() {
3100 if self.pending_notifications.insert(entity_id) {
3101 self.pending_effects
3102 .push_back(Effect::Notify { emitter: entity_id });
3103 }
3104 } else {
3105 for invalidator in &live_invalidators {
3106 invalidator.invalidate_view(entity_id, self);
3107 }
3108 }
3109
3110 self.window_invalidators_by_entity
3111 .insert(entity_id, window_invalidators);
3112 }
3113
3114 #[cfg(any(test, feature = "test-support", debug_assertions))]
3116 pub fn get_name(&self) -> Option<&'static str> {
3117 self.name
3118 }
3119
3120 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3122 self.platform.can_select_mixed_files_and_dirs()
3123 }
3124
3125 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3130 for window in self.windows.values_mut().flatten() {
3132 _ = window.drop_image(image.clone());
3133 }
3134
3135 if let Some(window) = current_window {
3137 _ = window.drop_image(image);
3138 }
3139 }
3140
3141 #[cfg(debug_assertions)]
3143 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3144 self.inspector_renderer = Some(f);
3145 }
3146
3147 #[cfg(debug_assertions)]
3149 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3150 &mut self,
3151 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3152 ) where
3153 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3154 {
3155 self.inspector_element_registry.register(factory);
3156 }
3157
3158 pub fn init_colors(&mut self) {
3162 self.set_global(GlobalColors(Arc::new(Colors::default())));
3163 }
3164
3165 #[inline(never)]
3166 fn update_window_erased(
3167 &mut self,
3168 window_id: WindowId,
3169 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3170 ) {
3171 self.update(|cx| {
3172 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3173 update(None);
3174 return;
3175 };
3176
3177 let root_view = window.root.clone().unwrap();
3178
3179 cx.window_update_stack.push(window.handle.id);
3180 update(Some((root_view, &mut window, cx)));
3181 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3182 cx.window_update_stack.pop();
3183
3184 if window.removed {
3185 cx.end_platform_drag(window_id);
3186 cx.window_handles.remove(&window_id);
3187 cx.windows.remove(window_id);
3188 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3189 for entity_id in tracked {
3190 if let Some(windows) =
3191 cx.window_invalidators_by_entity.get_mut(&entity_id)
3192 {
3193 windows.remove(&window_id);
3194 }
3195 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3196 cx.current_window_by_entity.remove(&entity_id);
3197 }
3198 }
3199 }
3200
3201 cx.window_closed_observers.clone().retain(&(), |callback| {
3202 callback(cx, window_id);
3203 true
3204 });
3205
3206 let quit_on_empty = match cx.quit_mode {
3207 QuitMode::Explicit => false,
3208 QuitMode::LastWindowClosed => true,
3209 QuitMode::Default => cfg!(not(target_os = "macos")),
3210 };
3211
3212 if quit_on_empty && cx.windows.is_empty() {
3213 cx.quit();
3214 }
3215 } else {
3216 cx.windows.get_mut(window_id)?.replace(window);
3217 }
3218 Some(())
3219 }
3220 if trail(window_id, window, cx).is_none() {
3221 update(None);
3222 }
3223 });
3224 }
3225
3226 #[inline(never)]
3227 fn update_entity_erased(
3228 &mut self,
3229 handle: &AnyEntity,
3230 entity_type: &str,
3231 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3232 ) {
3233 self.update(|cx| {
3234 let mut lease = cx.entities.lease_erased(handle, entity_type);
3235 update(lease.entity.as_deref_mut().unwrap(), cx);
3236 cx.entities.end_lease_erased(handle.entity_id, lease);
3237 });
3238 }
3239
3240 #[inline(never)]
3241 #[track_caller]
3242 fn prepare_spawn(&self) -> AsyncApp {
3243 if self.quitting {
3244 debug_panic!("Can't spawn on main thread after on_app_quit")
3245 };
3246 self.to_async()
3247 }
3248}
3249
3250impl AppContext for App {
3251 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3256 self.update(|cx| {
3257 let slot = cx.entities.reserve();
3258 let handle = slot.clone();
3259 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3260
3261 cx.push_effect(Effect::EntityCreated {
3262 entity: handle.into_any(),
3263 tid: TypeId::of::<T>(),
3264 window: cx.window_update_stack.last().cloned(),
3265 });
3266
3267 cx.entities.insert(slot, entity)
3268 })
3269 }
3270
3271 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3272 Reservation(self.entities.reserve())
3273 }
3274
3275 fn insert_entity<T: 'static>(
3276 &mut self,
3277 reservation: Reservation<T>,
3278 build_entity: impl FnOnce(&mut Context<T>) -> T,
3279 ) -> Entity<T> {
3280 self.update(|cx| {
3281 let slot = reservation.0;
3282 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3283 cx.entities.insert(slot, entity)
3284 })
3285 }
3286
3287 #[inline(always)]
3290 fn update_entity<T: 'static, R>(
3291 &mut self,
3292 handle: &Entity<T>,
3293 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3294 ) -> R {
3295 let mut update = Some(update);
3296 let mut result = None;
3297 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3298 let value = update.take().unwrap()(
3299 entity.downcast_mut::<T>().unwrap(),
3300 &mut Context::new_context(cx, handle.downgrade()),
3301 );
3302 result = Some(value);
3303 });
3304 result.unwrap()
3305 }
3306
3307 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3308 where
3309 T: 'static,
3310 {
3311 GpuiBorrow::new(handle.clone(), self)
3312 }
3313
3314 #[inline(always)]
3315 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3316 where
3317 T: 'static,
3318 {
3319 let entity = self.entities.read(handle);
3320 read(entity, self)
3321 }
3322
3323 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3324 where
3325 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3326 {
3327 self.update_window_id(handle.id, update)
3328 }
3329
3330 fn with_window<R>(
3331 &mut self,
3332 entity_id: EntityId,
3333 f: impl FnOnce(&mut Window, &mut App) -> R,
3334 ) -> Option<R> {
3335 App::with_window(self, entity_id, f)
3336 }
3337
3338 fn read_window<T, R>(
3339 &self,
3340 window: &WindowHandle<T>,
3341 read: impl FnOnce(Entity<T>, &App) -> R,
3342 ) -> Result<R>
3343 where
3344 T: 'static,
3345 {
3346 let window = self
3347 .windows
3348 .get(window.id)
3349 .context("window not found")?
3350 .as_deref()
3351 .expect("attempted to read a window that is already on the stack");
3352
3353 let root_view = window.root.clone().unwrap();
3354 let view = root_view
3355 .downcast::<T>()
3356 .map_err(|_| anyhow!("root view's type has changed"))?;
3357
3358 Ok(read(view, self))
3359 }
3360
3361 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3362 where
3363 R: Send + 'static,
3364 {
3365 self.background_executor.spawn(future)
3366 }
3367
3368 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3369 where
3370 G: Global,
3371 {
3372 let mut g = self.global::<G>();
3373 callback(g, self)
3374 }
3375}
3376
3377pub(crate) enum Effect {
3379 Notify {
3380 emitter: EntityId,
3381 },
3382 Emit {
3383 emitter: EntityId,
3384 event_type: TypeId,
3385 event: ArenaBox<dyn Any>,
3386 },
3387 RefreshWindows,
3388 NotifyGlobalObservers {
3389 global_type: TypeId,
3390 },
3391 Defer {
3392 callback: Box<dyn FnOnce(&mut App) + 'static>,
3393 },
3394 EntityCreated {
3395 entity: AnyEntity,
3396 tid: TypeId,
3397 window: Option<WindowId>,
3398 },
3399}
3400
3401impl std::fmt::Debug for Effect {
3402 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3403 match self {
3404 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3405 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3406 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3407 Effect::NotifyGlobalObservers { global_type } => {
3408 write!(f, "NotifyGlobalObservers({:?})", global_type)
3409 }
3410 Effect::Defer { .. } => write!(f, "Defer(..)"),
3411 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3412 }
3413 }
3414}
3415
3416pub(crate) struct GlobalLease<G: Global> {
3418 global: Box<dyn Any>,
3419 global_type: PhantomData<G>,
3420}
3421
3422impl<G: Global> GlobalLease<G> {
3423 fn new(global: Box<dyn Any>) -> Self {
3424 GlobalLease {
3425 global,
3426 global_type: PhantomData,
3427 }
3428 }
3429}
3430
3431impl<G: Global> Deref for GlobalLease<G> {
3432 type Target = G;
3433
3434 fn deref(&self) -> &Self::Target {
3435 self.global.downcast_ref().unwrap()
3436 }
3437}
3438
3439impl<G: Global> DerefMut for GlobalLease<G> {
3440 fn deref_mut(&mut self) -> &mut Self::Target {
3441 self.global.downcast_mut().unwrap()
3442 }
3443}
3444
3445pub struct AnyDrag {
3448 pub view: AnyView,
3450
3451 pub value: Arc<dyn Any>,
3453
3454 pub cursor_offset: Point<Pixels>,
3457
3458 pub cursor_style: Option<CursorStyle>,
3460
3461 pub external_payload_source: Option<ExternalDragPayloadSource>,
3464}
3465
3466pub type ExternalDragPayloadSource =
3469 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3470
3471#[derive(Clone)]
3474pub struct AnyTooltip {
3475 pub view: AnyView,
3477
3478 pub mouse_position: Point<Pixels>,
3480
3481 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3485}
3486
3487#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3489pub enum InputPreference {
3490 CharacterInput,
3492 KeyBindings,
3494}
3495
3496#[derive(Debug)]
3498pub struct KeystrokeEvent {
3499 pub keystroke: Keystroke,
3501
3502 pub input_preference: InputPreference,
3510
3511 pub action: Option<Box<dyn Action>>,
3513
3514 pub context_stack: Vec<KeyContext>,
3516}
3517
3518struct NullHttpClient;
3519
3520impl HttpClient for NullHttpClient {
3521 fn send(
3522 &self,
3523 _req: http_client::Request<http_client::AsyncBody>,
3524 ) -> futures::future::BoxFuture<
3525 'static,
3526 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3527 > {
3528 async move {
3529 anyhow::bail!("No HttpClient available");
3530 }
3531 .boxed()
3532 }
3533
3534 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3535 None
3536 }
3537
3538 fn proxy(&self) -> Option<&Url> {
3539 None
3540 }
3541}
3542
3543pub struct GpuiBorrow<'a, T> {
3545 inner: Option<Lease<T>>,
3546 app: &'a mut App,
3547}
3548
3549impl<'a, T: 'static> GpuiBorrow<'a, T> {
3550 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3551 app.start_update();
3552 let lease = app.entities.lease(&inner);
3553 Self {
3554 inner: Some(lease),
3555 app,
3556 }
3557 }
3558}
3559
3560impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3561 fn borrow(&self) -> &T {
3562 self.inner.as_ref().unwrap().borrow()
3563 }
3564}
3565
3566impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3567 fn borrow_mut(&mut self) -> &mut T {
3568 self.inner.as_mut().unwrap().borrow_mut()
3569 }
3570}
3571
3572impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3573 type Target = T;
3574
3575 fn deref(&self) -> &Self::Target {
3576 self.inner.as_ref().unwrap()
3577 }
3578}
3579
3580impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3581 fn deref_mut(&mut self) -> &mut T {
3582 self.inner.as_mut().unwrap()
3583 }
3584}
3585
3586impl<'a, T> Drop for GpuiBorrow<'a, T> {
3587 fn drop(&mut self) {
3588 let lease = self.inner.take().unwrap();
3589 self.app.notify(lease.id);
3590 self.app.entities.end_lease(lease);
3591 self.app.finish_update();
3592 }
3593}
3594
3595#[cfg(test)]
3596mod test {
3597 use std::{
3598 cell::{Cell, RefCell},
3599 ffi::OsString,
3600 path::PathBuf,
3601 rc::Rc,
3602 };
3603
3604 #[cfg(unix)]
3605 use std::os::unix::ffi::OsStringExt;
3606
3607 use crate::{
3608 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3609 TestAppContext, Window,
3610 };
3611
3612 fn construction_platform() -> Rc<crate::TestPlatform> {
3613 let dispatcher = std::sync::Arc::new(crate::TestDispatcher::new(0));
3614 crate::TestPlatform::new(
3615 crate::BackgroundExecutor::new(dispatcher.clone()),
3616 crate::ForegroundExecutor::new(dispatcher),
3617 )
3618 }
3619
3620 #[test]
3621 fn application_construction_uses_text_override_without_querying_platform() {
3622 use std::sync::Arc;
3623
3624 let platform = construction_platform();
3625 let backend: Arc<dyn crate::PlatformTextSystem> = Arc::new(crate::NoopTextSystem);
3626 let native_references = Arc::strong_count(&platform.text_system);
3627 let app =
3628 super::Application::with_platform_and_text_system(platform.clone(), backend.clone());
3629
3630 assert_eq!(platform.text_system_calls.get(), 0);
3631 assert_eq!(Arc::strong_count(&platform.text_system), native_references);
3632 assert_eq!(Arc::strong_count(&backend), 2);
3633 drop(app);
3634 assert_eq!(Arc::strong_count(&backend), 1);
3635 }
3636
3637 #[test]
3638 fn application_construction_uses_platform_text_by_default() {
3639 use std::sync::Arc;
3640
3641 let platform = construction_platform();
3642 let native_references = Arc::strong_count(&platform.text_system);
3643 let app = super::Application::with_platform(platform.clone());
3644
3645 assert_eq!(platform.text_system_calls.get(), 1);
3646 assert_eq!(
3647 Arc::strong_count(&platform.text_system),
3648 native_references + 1
3649 );
3650 drop(app);
3651 assert_eq!(Arc::strong_count(&platform.text_system), native_references);
3652 }
3653
3654 struct RenderCounter(Rc<Cell<usize>>);
3655
3656 impl Render for RenderCounter {
3657 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3658 self.0.set(self.0.get() + 1);
3659 Empty
3660 }
3661 }
3662
3663 #[gpui::test]
3664 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3665 let render_count = Rc::new(Cell::new(0));
3666
3667 let _window = cx.add_window({
3668 let render_count = render_count.clone();
3669 move |_, _| RenderCounter(render_count)
3670 });
3671
3672 cx.run_until_parked();
3673 let render_count_before_refresh = render_count.get();
3674
3675 cx.to_async().refresh();
3676
3677 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3678 }
3679
3680 #[gpui::test]
3681 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3682 let observed = Rc::new(RefCell::new(Vec::new()));
3683 let subscription = cx.update(|cx| {
3684 let observed = observed.clone();
3685 cx.on_missing_glyphs(move |missing_glyphs, _| {
3686 observed.borrow_mut().extend_from_slice(missing_glyphs);
3687 })
3688 });
3689 cx.update(|cx| {
3690 cx.text_system()
3691 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3692 });
3693 cx.run_until_parked();
3694 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3695
3696 let second_observed = Rc::new(RefCell::new(Vec::new()));
3697 let second_subscription = cx.update(|cx| {
3698 let second_observed = second_observed.clone();
3699 cx.on_missing_glyphs(move |missing_glyphs, _| {
3700 second_observed
3701 .borrow_mut()
3702 .extend_from_slice(missing_glyphs);
3703 })
3704 });
3705 cx.update(|cx| {
3706 cx.text_system()
3707 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3708 });
3709 cx.run_until_parked();
3710 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3711 assert_eq!(
3712 second_observed.borrow().as_slice(),
3713 &[missing_glyph("replacement")]
3714 );
3715
3716 drop(subscription);
3717 cx.update(|cx| {
3718 cx.text_system()
3719 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3720 });
3721 cx.run_until_parked();
3722 assert_eq!(
3723 second_observed.borrow().as_slice(),
3724 &[
3725 missing_glyph("replacement"),
3726 missing_glyph("after old drop")
3727 ]
3728 );
3729
3730 drop(second_subscription);
3731 cx.update(|cx| {
3732 cx.text_system()
3733 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3734 });
3735 cx.run_until_parked();
3736 assert_eq!(second_observed.borrow().len(), 2);
3737 }
3738
3739 #[test]
3740 fn test_gpui_borrow() {
3741 let cx = TestAppContext::single();
3742 let observation_count = Rc::new(RefCell::new(0));
3743
3744 let state = cx.update(|cx| {
3745 let state = cx.new(|_| false);
3746 cx.observe(&state, {
3747 let observation_count = observation_count.clone();
3748 move |_, _| {
3749 let mut count = observation_count.borrow_mut();
3750 *count += 1;
3751 }
3752 })
3753 .detach();
3754
3755 state
3756 });
3757
3758 cx.update(|cx| {
3759 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3761 });
3762
3763 cx.update(|cx| {
3764 state.write(cx, false);
3765 });
3766
3767 assert_eq!(*observation_count.borrow(), 2);
3768 }
3769
3770 #[gpui::test]
3771 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3772 #[cfg(unix)]
3773 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3774 #[cfg(not(unix))]
3775 let user_data_dir = OsString::from("C:\\zed data");
3776 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3777 let restart_path = PathBuf::from("updated-zed");
3778 let _application =
3779 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3780 let restart = cx.expect_restart();
3781
3782 cx.update(|cx| {
3783 cx.set_restart_path(restart_path.clone());
3784 cx.restart();
3785 });
3786
3787 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3788 assert_eq!(path, Some(restart_path));
3789 assert_eq!(restart_arguments, arguments);
3790 }
3791
3792 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3793 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3794 }
3795}