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,
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::subscription::SingleSubscriberSet;
47use crate::{
48 Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
49 AnyWindowHandle, AppContext, AppLifecyclePhase, Arena, ArenaBox, Asset, AssetSource,
50 BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase,
51 DisplayChanges, DisplayEvent, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle,
52 FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId,
53 Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
54 PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, Point, PowerMode, Priority,
55 PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
56 RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
57 Subscription, SvgRenderer, SystemNotification, SystemNotificationResponse, Task,
58 TextRenderingMode, TextSystem, ThermalState, Window, WindowAppearance, WindowButtonLayout,
59 WindowHandle, WindowId, WindowInvalidator, WindowingRequest,
60 colors::{Colors, GlobalColors},
61 hash, init_app_menus,
62};
63
64mod async_context;
65#[cfg(feature = "bench-support")]
66mod bench_context;
67mod context;
68mod entity_map;
69#[cfg(any(test, feature = "test-support"))]
70mod headless_app_context;
71#[cfg(any(test, feature = "test-support"))]
72mod test_app;
73#[cfg(any(test, feature = "test-support"))]
74mod test_context;
75#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
76mod visual_test_context;
77
78pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
81
82#[doc(hidden)]
85pub struct AppCell {
86 app: RefCell<App>,
87 borrow_origin: Cell<Option<(&'static std::panic::Location<'static>, &'static str)>>,
88}
89
90impl AppCell {
91 #[cold]
92 #[track_caller]
93 fn borrow_failed(&self, kind: &str) -> ! {
94 let attempted = std::panic::Location::caller();
95 if let Some((origin, existing_kind)) = self.borrow_origin.get() {
96 panic!(
97 "RefCell already borrowed: attempted {kind} App borrow at {attempted}; \
98 existing {existing_kind} borrow group began at {origin}"
99 );
100 }
101 panic!(
102 "RefCell already borrowed: attempted {kind} App borrow at {attempted}; origin unavailable"
103 );
104 }
105
106 #[doc(hidden)]
107 #[track_caller]
108 pub fn borrow(&self) -> AppRef<'_> {
109 if option_env!("TRACK_THREAD_BORROWS").is_some() {
110 let thread_id = std::thread::current().id();
111 eprintln!("borrowed {thread_id:?}");
112 }
113 let starts_borrow_group = self.app.try_borrow_mut().is_ok();
116 let borrow = match self.app.try_borrow() {
117 Ok(borrow) => borrow,
118 Err(_) => self.borrow_failed("shared"),
119 };
120 if starts_borrow_group {
121 self.borrow_origin
122 .set(Some((std::panic::Location::caller(), "shared")));
123 }
124 AppRef(borrow)
125 }
126
127 #[doc(hidden)]
128 #[track_caller]
129 pub fn borrow_mut(&self) -> AppRefMut<'_> {
130 match self.try_borrow_mut() {
131 Ok(borrow) => borrow,
132 Err(_) => self.borrow_failed("mutable"),
133 }
134 }
135
136 #[doc(hidden)]
137 #[track_caller]
138 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
139 if option_env!("TRACK_THREAD_BORROWS").is_some() {
140 let thread_id = std::thread::current().id();
141 eprintln!("borrowed {thread_id:?}");
142 }
143 let borrow = self.app.try_borrow_mut()?;
144 self.borrow_origin
145 .set(Some((std::panic::Location::caller(), "mutable")));
146 Ok(AppRefMut(borrow))
147 }
148}
149
150#[doc(hidden)]
151#[derive(Deref, DerefMut)]
152pub struct AppRef<'a>(Ref<'a, App>);
153
154impl Drop for AppRef<'_> {
155 fn drop(&mut self) {
156 if option_env!("TRACK_THREAD_BORROWS").is_some() {
157 let thread_id = std::thread::current().id();
158 eprintln!("dropped borrow from {thread_id:?}");
159 }
160 }
161}
162
163#[doc(hidden)]
164#[derive(Deref, DerefMut)]
165pub struct AppRefMut<'a>(RefMut<'a, App>);
166
167impl Drop for AppRefMut<'_> {
168 fn drop(&mut self) {
169 if option_env!("TRACK_THREAD_BORROWS").is_some() {
170 let thread_id = std::thread::current().id();
171 eprintln!("dropped {thread_id:?}");
172 }
173 }
174}
175
176pub struct Application(Rc<AppCell>);
179
180pub struct ApplicationHandle {
186 app: Rc<AppCell>,
187}
188
189impl ApplicationHandle {
190 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
194 let cx = &mut *self.app.borrow_mut();
195 f(cx)
196 }
197
198 pub fn to_async(&self) -> AsyncApp {
201 self.update(|cx| cx.to_async())
202 }
203}
204
205impl Application {
208 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
210 Self(App::new_app(
211 platform,
212 Arc::new(()),
213 Arc::new(NullHttpClient),
214 ))
215 }
216
217 pub fn with_platform_and_text_system(
222 platform: Rc<dyn Platform>,
223 text_system: Arc<dyn PlatformTextSystem>,
224 ) -> Self {
225 Self(App::new_app_with_text_system(
226 platform,
227 Arc::new(()),
228 Arc::new(NullHttpClient),
229 Some(text_system),
230 ))
231 }
232
233 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
243 let this = Self::with_platform(platform);
244 this.0.borrow_mut().accessibility_force_disabled = true;
245 this
246 }
247
248 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
250 let mut context_lock = self.0.borrow_mut();
251 let asset_source = Arc::new(asset_source);
252 context_lock.asset_source = asset_source.clone();
253 context_lock.svg_renderer = SvgRenderer::new(asset_source);
254 drop(context_lock);
255 self
256 }
257
258 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
260 self.0.borrow_mut().restart_arguments = arguments;
261 self
262 }
263
264 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
266 let mut context_lock = self.0.borrow_mut();
267 context_lock.http_client = http_client;
268 drop(context_lock);
269 self
270 }
271
272 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
275 self.0.borrow_mut().quit_mode = mode;
276 self
277 }
278
279 pub fn with_windowing(self, request: WindowingRequest) -> Self {
286 self.0.borrow().platform.set_initial_windowing(request);
287 self
288 }
289
290 pub fn run<F>(self, on_finish_launching: F)
296 where
297 F: 'static + FnOnce(&mut App),
298 {
299 let this = self.0.clone();
300 let platform = self.0.borrow().platform.clone();
301 platform.run(Box::new(move || {
302 let cx = &mut *this.borrow_mut();
303 cx.displays_changed();
305 #[cfg(gpui_hot_reload)]
306 crate::hot_reload::init(cx);
307 on_finish_launching(cx);
308 }));
309
310 #[cfg(target_family = "wasm")]
311 std::mem::forget(self);
312 }
313
314 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
324 where
325 F: 'static + FnOnce(&mut App),
326 {
327 let this = self.0.clone();
328 let platform = self.0.borrow().platform.clone();
329 platform.run(Box::new(move || {
330 let cx = &mut *this.borrow_mut();
331 cx.displays_changed();
333 #[cfg(gpui_hot_reload)]
334 crate::hot_reload::init(cx);
335 on_finish_launching(cx);
336 }));
337 ApplicationHandle { app: self.0 }
338 }
339
340 pub fn on_open_urls<F>(&self, callback: F) -> &Self
343 where
344 F: 'static + FnMut(Vec<String>),
345 {
346 self.0.borrow().platform.on_open_urls(Box::new(callback));
347 self
348 }
349
350 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
353 where
354 F: 'static + FnMut(&mut App),
355 {
356 let this = Rc::downgrade(&self.0);
357 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
358 if let Some(app) = this.upgrade() {
359 callback(&mut app.borrow_mut());
360 }
361 }));
362 self
363 }
364
365 pub fn background_executor(&self) -> BackgroundExecutor {
367 self.0.borrow().background_executor.clone()
368 }
369
370 pub fn foreground_executor(&self) -> ForegroundExecutor {
372 self.0.borrow().foreground_executor.clone()
373 }
374
375 pub fn text_system(&self) -> Arc<TextSystem> {
377 self.0.borrow().text_system.clone()
378 }
379
380 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
382 self.0.borrow().path_for_auxiliary_executable(name)
383 }
384}
385
386type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
387type AppLifecycleHandler = Box<dyn FnMut(AppLifecyclePhase, &mut App) -> bool + 'static>;
388type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
389
390#[derive(Clone, Copy, PartialEq)]
392struct DisplayState {
393 bounds: Bounds<Pixels>,
394 refresh_interval: Option<Duration>,
395}
396
397impl DisplayState {
398 fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
399 let mut changes = DisplayChanges::empty();
400 changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
401 changes.set(
402 DisplayChanges::REFRESH_INTERVAL,
403 self.refresh_interval != previous.refresh_interval,
404 );
405 changes
406 }
407}
408
409fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
410 platform
411 .displays()
412 .into_iter()
413 .map(|display| {
414 let state = DisplayState {
415 bounds: display.bounds(),
416 refresh_interval: display.refresh_interval(),
417 };
418 (display.id(), state)
419 })
420 .collect()
421}
422
423fn display_events(
425 previous: &HashMap<DisplayId, DisplayState>,
426 current: &HashMap<DisplayId, DisplayState>,
427) -> Vec<DisplayEvent> {
428 let removed = previous
429 .keys()
430 .filter(|id| !current.contains_key(id))
431 .map(|id| DisplayEvent::Removed(*id));
432 let added_or_changed = current.iter().filter_map(|(id, state)| {
433 let Some(previous_state) = previous.get(id) else {
434 return Some(DisplayEvent::Added(*id));
435 };
436 let changes = state.changes_from(previous_state);
437 (!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
438 });
439 removed.chain(added_or_changed).collect()
440}
441type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
442type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
443pub(crate) type KeystrokeObserver =
444 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
445type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
446type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
447type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
448type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
449
450struct MissingGlyphCallbackEntry {
451 registration: Rc<()>,
452 callback: Option<MissingGlyphCallback>,
453}
454
455#[derive(Default)]
456struct MissingGlyphCallbackSlot {
457 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
458}
459
460impl MissingGlyphCallbackSlot {
461 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
462 let registration = Rc::new(());
463 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
464 registration: registration.clone(),
465 callback: Some(callback),
466 });
467 registration
468 }
469
470 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
471 let Some((registration, mut callback)) =
472 self.entry.borrow_mut().as_mut().and_then(|entry| {
473 entry
474 .callback
475 .take()
476 .map(|callback| (entry.registration.clone(), callback))
477 })
478 else {
479 return;
480 };
481 callback(missing_glyphs, cx);
482
483 let mut entry = self.entry.borrow_mut();
484 let is_current = entry
485 .as_ref()
486 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
487 if is_current {
488 let Some(entry) = entry.as_mut() else {
489 return;
490 };
491 entry.callback = Some(callback);
492 }
493 }
494
495 fn remove(&self, registration: &Rc<()>) -> bool {
496 let mut entry = self.entry.borrow_mut();
497 let is_current = entry
498 .as_ref()
499 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
500 if is_current {
501 entry.take();
502 }
503 is_current
504 }
505}
506
507#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
509pub enum QuitMode {
510 #[default]
512 Default,
513 LastWindowClosed,
515 Explicit,
517}
518
519#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
524pub enum CursorHideMode {
525 Never,
527 OnTyping,
529 #[default]
532 OnTypingAndAction,
533}
534
535#[doc(hidden)]
536#[derive(Clone, PartialEq, Eq)]
537pub struct SystemWindowTab {
538 pub id: WindowId,
539 pub title: SharedString,
540 pub handle: AnyWindowHandle,
541 pub last_active_at: Instant,
542}
543
544impl SystemWindowTab {
545 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
547 Self {
548 id: handle.id,
549 title,
550 handle,
551 last_active_at: Instant::now(),
552 }
553 }
554}
555
556#[derive(Default)]
558pub struct SystemWindowTabController {
559 visible: Option<bool>,
560 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
561}
562
563impl Global for SystemWindowTabController {}
564
565impl SystemWindowTabController {
566 pub fn new() -> Self {
568 Self {
569 visible: None,
570 tab_groups: FxHashMap::default(),
571 }
572 }
573
574 pub fn init(cx: &mut App) {
576 cx.set_global(SystemWindowTabController::new());
577 }
578
579 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
581 &self.tab_groups
582 }
583
584 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
586 let controller = cx.global::<SystemWindowTabController>();
587 let current_group = controller
588 .tab_groups
589 .iter()
590 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
591
592 let current_group = current_group?;
593 let group_ids: Vec<_> = controller.tab_groups.keys().collect();
595 let idx = group_ids.iter().position(|g| *g == current_group)?;
596 let next_idx = (idx + 1) % group_ids.len();
597
598 controller
599 .tab_groups
600 .get(group_ids[next_idx])
601 .and_then(|tabs| {
602 tabs.iter()
603 .max_by_key(|tab| tab.last_active_at)
604 .or_else(|| tabs.first())
605 .map(|tab| &tab.handle)
606 })
607 }
608
609 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
611 let controller = cx.global::<SystemWindowTabController>();
612 let current_group = controller
613 .tab_groups
614 .iter()
615 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
616
617 let current_group = current_group?;
618 let group_ids: Vec<_> = controller.tab_groups.keys().collect();
620 let idx = group_ids.iter().position(|g| *g == current_group)?;
621 let prev_idx = if idx == 0 {
622 group_ids.len() - 1
623 } else {
624 idx - 1
625 };
626
627 controller
628 .tab_groups
629 .get(group_ids[prev_idx])
630 .and_then(|tabs| {
631 tabs.iter()
632 .max_by_key(|tab| tab.last_active_at)
633 .or_else(|| tabs.first())
634 .map(|tab| &tab.handle)
635 })
636 }
637
638 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
640 self.tab_groups
641 .values()
642 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
643 }
644
645 pub fn init_visible(cx: &mut App, visible: bool) {
647 let controller = cx.global_mut::<SystemWindowTabController>();
648 if controller.visible.is_none() {
649 controller.visible = Some(visible);
650 }
651 }
652
653 pub fn is_visible(&self) -> bool {
655 self.visible.unwrap_or(false)
656 }
657
658 pub fn set_visible(cx: &mut App, visible: bool) {
660 let controller = cx.global_mut::<SystemWindowTabController>();
661 controller.visible = Some(visible);
662 }
663
664 pub fn update_last_active(cx: &mut App, id: WindowId) {
666 let controller = cx.global_mut::<SystemWindowTabController>();
667 for windows in controller.tab_groups.values_mut() {
668 for tab in windows.iter_mut() {
669 if tab.id == id {
670 tab.last_active_at = Instant::now();
671 }
672 }
673 }
674 }
675
676 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
678 let controller = cx.global_mut::<SystemWindowTabController>();
679 for (_, windows) in controller.tab_groups.iter_mut() {
680 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
681 if ix < windows.len() && current_pos != ix {
682 let window_tab = windows.remove(current_pos);
683 windows.insert(ix, window_tab);
684 }
685 break;
686 }
687 }
688 }
689
690 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
692 let controller = cx.global::<SystemWindowTabController>();
693 let tab = controller
694 .tab_groups
695 .values()
696 .flat_map(|windows| windows.iter())
697 .find(|tab| tab.id == id);
698
699 if tab.map_or(true, |t| t.title == title) {
700 return;
701 }
702
703 let controller = cx.global_mut::<SystemWindowTabController>();
704 for windows in controller.tab_groups.values_mut() {
705 for tab in windows.iter_mut() {
706 if tab.id == id {
707 tab.title = title;
708 return;
709 }
710 }
711 }
712 }
713
714 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
716 let controller = cx.global_mut::<SystemWindowTabController>();
717 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
718 return;
719 };
720
721 let expected_tab_ids: Vec<_> = tabs
722 .iter()
723 .filter(|tab| tab.id != id)
724 .map(|tab| tab.id)
725 .sorted()
726 .collect();
727
728 let mut tab_group_id = None;
729 for (group_id, group_tabs) in &controller.tab_groups {
730 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
731 if tab_ids == expected_tab_ids {
732 tab_group_id = Some(*group_id);
733 break;
734 }
735 }
736
737 if let Some(tab_group_id) = tab_group_id {
738 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
739 tabs.push(tab);
740 }
741 } else {
742 let new_group_id = controller.tab_groups.len();
743 controller.tab_groups.insert(new_group_id, tabs);
744 }
745 }
746
747 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
749 let controller = cx.global_mut::<SystemWindowTabController>();
750 let mut removed_tab = None;
751
752 controller.tab_groups.retain(|_, tabs| {
753 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
754 removed_tab = Some(tabs.remove(pos));
755 }
756 !tabs.is_empty()
757 });
758
759 removed_tab
760 }
761
762 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
764 let removed_tab = Self::remove_tab(cx, id);
765 let controller = cx.global_mut::<SystemWindowTabController>();
766
767 if let Some(tab) = removed_tab {
768 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
769 controller.tab_groups.insert(new_group_id, vec![tab]);
770 }
771 }
772
773 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
775 let controller = cx.global_mut::<SystemWindowTabController>();
776 let Some(initial_tabs) = controller.tabs(id) else {
777 return;
778 };
779
780 let initial_tabs_len = initial_tabs.len();
781 let mut all_tabs = initial_tabs.clone();
782
783 for (_, mut tabs) in controller.tab_groups.drain() {
784 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
785 all_tabs.extend(tabs);
786 }
787
788 controller.tab_groups.insert(0, all_tabs);
789 }
790
791 pub fn select_next_tab(cx: &mut App, id: WindowId) {
793 let controller = cx.global_mut::<SystemWindowTabController>();
794 let Some(tabs) = controller.tabs(id) else {
795 return;
796 };
797
798 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
799 let next_index = (current_index + 1) % tabs.len();
800
801 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
802 window.activate_window();
803 });
804 }
805
806 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
808 let controller = cx.global_mut::<SystemWindowTabController>();
809 let Some(tabs) = controller.tabs(id) else {
810 return;
811 };
812
813 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
814 let previous_index = if current_index == 0 {
815 tabs.len() - 1
816 } else {
817 current_index - 1
818 };
819
820 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
821 window.activate_window();
822 });
823 }
824}
825
826pub(crate) enum GpuiMode {
827 #[cfg(any(test, feature = "test-support"))]
828 Test {
829 skip_drawing: bool,
830 },
831 Production,
832}
833
834impl GpuiMode {
835 #[cfg(any(test, feature = "test-support"))]
836 pub fn test() -> Self {
837 GpuiMode::Test {
838 skip_drawing: false,
839 }
840 }
841
842 #[inline]
843 pub(crate) fn skip_drawing(&self) -> bool {
844 match self {
845 #[cfg(any(test, feature = "test-support"))]
846 GpuiMode::Test { skip_drawing } => *skip_drawing,
847 GpuiMode::Production => false,
848 }
849 }
850}
851
852struct PlatformOwnedDrag {
853 source_window: WindowId,
854 state: PlatformOwnedDragState,
855}
856
857enum PlatformOwnedDragState {
858 Suspended(AnyDrag),
859 RestoredInSourceWindow,
862}
863
864pub struct App {
868 pub(crate) this: Weak<AppCell>,
869 pub(crate) platform: Rc<dyn Platform>,
870 text_system: Arc<TextSystem>,
871
872 pub(crate) actions: Rc<ActionRegistry>,
873 pub(crate) active_drag: Option<AnyDrag>,
874 platform_owned_drag: Option<PlatformOwnedDrag>,
875 pub(crate) background_executor: BackgroundExecutor,
876 pub(crate) foreground_executor: ForegroundExecutor,
877 #[cfg(feature = "profiler")]
878 foreground_journal: crate::profiler::journal::ForegroundJournal,
879 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
880 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
881 pub(crate) entities: EntityMap,
882 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
883 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
884 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
885 pub(crate) focus_handles: Arc<RwLock<FocusMap>>,
886 pub(crate) keymap: Rc<RefCell<Keymap>>,
887 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
888 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
889 pub(crate) global_action_listeners:
890 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
891 pending_effects: VecDeque<Effect>,
892
893 pub(crate) observers: SubscriberSet<EntityId, Handler>,
894 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
895 pub(crate) keystroke_observers: SingleSubscriberSet<KeystrokeObserver>,
896 pub(crate) keystroke_interceptors: SingleSubscriberSet<KeystrokeObserver>,
897 pub(crate) keyboard_layout_observers: SingleSubscriberSet<Handler>,
898 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
899 pub(crate) thermal_state_observers: SingleSubscriberSet<Handler>,
900 desktop_preferences_observers: SingleSubscriberSet<Handler>,
901 pub(crate) display_observers: SingleSubscriberSet<DisplayHandler>,
902 displays: HashMap<DisplayId, DisplayState>,
905 pub(crate) system_sleep_observers: SingleSubscriberSet<Handler>,
906 pub(crate) system_wake_observers: SingleSubscriberSet<Handler>,
907 app_lifecycle_observers: SingleSubscriberSet<AppLifecycleHandler>,
908 memory_warning_observers: SingleSubscriberSet<Handler>,
909 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
910 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
911 pub(crate) quit_observers: SingleSubscriberSet<QuitHandler>,
912 pub(crate) restart_observers: SingleSubscriberSet<Handler>,
913 pub(crate) window_closed_observers: SingleSubscriberSet<WindowClosedHandler>,
914
915 pub(crate) element_arena: RefCell<Arena>,
918 pub(crate) event_arena: Arena,
920
921 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
926
927 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
929 asset_source: Arc<dyn AssetSource>,
930 pub(crate) svg_renderer: SvgRenderer,
931 http_client: Arc<dyn HttpClient>,
932
933 pub(crate) pending_notifications: FxHashSet<EntityId>,
935 pub(crate) pending_global_notifications: TypeIdHashSet,
936 pub(crate) restart_path: Option<PathBuf>,
937 pub(crate) restart_arguments: Vec<OsString>,
938 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
940 pub(crate) prompt_builder: Option<PromptBuilder>,
941 pub(crate) window_invalidators_by_entity:
942 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
943 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
944 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
945 #[cfg(debug_assertions)]
946 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
947 #[cfg(debug_assertions)]
948 pub(crate) inspector_element_registry: InspectorElementRegistry,
949 #[cfg(any(test, feature = "test-support", debug_assertions))]
950 pub(crate) name: Option<&'static str>,
951 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
952
953 pub(crate) window_update_stack: Vec<WindowId>,
954 pub(crate) mode: GpuiMode,
955 pub(crate) cursor_hide_mode: CursorHideMode,
956 pub(crate) reduce_motion: bool,
957 pub(crate) synced_animation_epoch: Instant,
959 power_mode: PowerMode,
960 pub(crate) accessibility_force_disabled: bool,
963 pending_updates: usize,
964 quit_mode: QuitMode,
965 quitting: bool,
966
967 #[cfg(any(test, gpui_leak_detection))]
970 _ref_counts: Arc<RwLock<EntityRefCounts>>,
971}
972
973impl App {
974 #[allow(clippy::new_ret_no_self)]
975 pub(crate) fn new_app(
976 platform: Rc<dyn Platform>,
977 asset_source: Arc<dyn AssetSource>,
978 http_client: Arc<dyn HttpClient>,
979 ) -> Rc<AppCell> {
980 Self::new_app_with_text_system(platform, asset_source, http_client, None)
981 }
982
983 fn new_app_with_text_system(
984 platform: Rc<dyn Platform>,
985 asset_source: Arc<dyn AssetSource>,
986 http_client: Arc<dyn HttpClient>,
987 text_override: Option<Arc<dyn PlatformTextSystem>>,
988 ) -> Rc<AppCell> {
989 let background_executor = platform.background_executor();
990 let foreground_executor = platform.foreground_executor();
991 assert!(
992 background_executor.is_main_thread(),
993 "must construct App on main thread"
994 );
995 #[cfg(feature = "profiler")]
996 let foreground_journal = crate::profiler::journal::install_foreground_journal();
997 let synced_animation_epoch = background_executor.now();
998
999 let backend = text_override.unwrap_or_else(|| platform.text_system());
1000 let text_system = Arc::new(TextSystem::new(backend));
1001 let entities = EntityMap::new();
1002 let keyboard_layout = platform.keyboard_layout();
1003 let keyboard_mapper = platform.keyboard_mapper();
1004 let power_mode = platform.power_mode();
1005
1006 #[cfg(any(test, gpui_leak_detection))]
1007 let _ref_counts = entities.ref_counts_drop_handle();
1008
1009 let app = Rc::new_cyclic(|this| AppCell {
1010 borrow_origin: Cell::new(None),
1011 app: RefCell::new(App {
1012 this: this.clone(),
1013 platform: platform.clone(),
1014 text_system,
1015 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
1016 mode: GpuiMode::Production,
1017 actions: Rc::new(ActionRegistry::default()),
1018 pending_updates: 0,
1019 active_drag: None,
1020 platform_owned_drag: None,
1021 background_executor,
1022 foreground_executor,
1023 #[cfg(feature = "profiler")]
1024 foreground_journal,
1025 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1026 hang_monitor: None,
1027 svg_renderer: SvgRenderer::new(asset_source.clone()),
1028 loading_assets: Default::default(),
1029 asset_source,
1030 http_client,
1031 globals_by_type: Default::default(),
1032 entities,
1033 new_entity_observers: SubscriberSet::new(),
1034 windows: SlotMap::with_key(),
1035 window_update_stack: Vec::new(),
1036 window_handles: FxHashMap::default(),
1037 focus_handles: Arc::new(RwLock::new(FocusMap::default())),
1038 keymap: Rc::new(RefCell::new(Keymap::default())),
1039 keyboard_layout,
1040 keyboard_mapper,
1041 global_action_listeners: Default::default(),
1042 pending_effects: VecDeque::new(),
1043 pending_notifications: FxHashSet::default(),
1044 pending_global_notifications: Default::default(),
1045 observers: SubscriberSet::new(),
1046 tracked_entities: FxHashMap::default(),
1047 window_invalidators_by_entity: FxHashMap::default(),
1048 current_window_by_entity: FxHashMap::default(),
1049 event_listeners: SubscriberSet::new(),
1050 release_listeners: SubscriberSet::new(),
1051 keystroke_observers: SingleSubscriberSet::new(),
1052 keystroke_interceptors: SingleSubscriberSet::new(),
1053 keyboard_layout_observers: SingleSubscriberSet::new(),
1054 missing_glyph_callback: Rc::default(),
1055 thermal_state_observers: SingleSubscriberSet::new(),
1056 desktop_preferences_observers: SingleSubscriberSet::new(),
1057 display_observers: SingleSubscriberSet::new(),
1058 displays: read_displays(platform.as_ref()),
1059 system_sleep_observers: SingleSubscriberSet::new(),
1060 system_wake_observers: SingleSubscriberSet::new(),
1061 app_lifecycle_observers: SingleSubscriberSet::new(),
1062 memory_warning_observers: SingleSubscriberSet::new(),
1063 global_observers: SubscriberSet::new(),
1064 quit_observers: SingleSubscriberSet::new(),
1065 restart_observers: SingleSubscriberSet::new(),
1066 restart_path: None,
1067 restart_arguments: Vec::new(),
1068 window_closed_observers: SingleSubscriberSet::new(),
1069 layout_id_buffer: Default::default(),
1070 propagate_event: true,
1071 prompt_builder: Some(PromptBuilder::Default),
1072 #[cfg(debug_assertions)]
1073 inspector_renderer: None,
1074 #[cfg(debug_assertions)]
1075 inspector_element_registry: InspectorElementRegistry::default(),
1076 quit_mode: QuitMode::default(),
1077 quitting: false,
1078 cursor_hide_mode: CursorHideMode::default(),
1079 reduce_motion: false,
1080 synced_animation_epoch,
1081 power_mode,
1082 accessibility_force_disabled: false,
1083
1084 #[cfg(any(test, feature = "test-support", debug_assertions))]
1085 name: None,
1086 element_arena: RefCell::new(Arena::new(1024 * 1024)),
1087 event_arena: Arena::new(1024 * 1024),
1088
1089 #[cfg(any(test, gpui_leak_detection))]
1090 _ref_counts,
1091 }),
1092 });
1093
1094 init_app_menus(platform.as_ref(), &app.borrow());
1095 SystemWindowTabController::init(&mut app.borrow_mut());
1096 #[cfg(feature = "profiler")]
1097 crate::profiler::journal::observe_power(&app.borrow());
1098
1099 platform.on_keyboard_layout_change(Box::new({
1100 let app = Rc::downgrade(&app);
1101 move || {
1102 if let Some(app) = app.upgrade() {
1103 let cx = &mut app.borrow_mut();
1104 cx.keyboard_layout = cx.platform.keyboard_layout();
1105 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1106 cx.keyboard_layout_observers
1107 .clone()
1108 .retain(move |callback| (callback)(cx));
1109 }
1110 }
1111 }));
1112
1113 platform.on_thermal_state_change(Box::new({
1114 let app = Rc::downgrade(&app);
1115 move || {
1116 if let Some(app) = app.upgrade() {
1117 let cx = &mut app.borrow_mut();
1118 cx.thermal_state_observers
1119 .clone()
1120 .retain(move |callback| (callback)(cx));
1121 }
1122 }
1123 }));
1124
1125 platform.on_desktop_preferences_changed(Box::new({
1126 let app = Rc::downgrade(&app);
1127 move || {
1128 if let Some(app) = app.upgrade() {
1129 app.borrow_mut().update(|cx| {
1130 cx.desktop_preferences_observers
1131 .clone()
1132 .retain(|callback| callback(cx));
1133 });
1134 }
1135 }
1136 }));
1137
1138 platform.on_displays_changed(Box::new({
1139 let app = Rc::downgrade(&app);
1140 move || {
1141 if let Some(app) = app.upgrade() {
1142 app.borrow_mut().displays_changed();
1143 }
1144 }
1145 }));
1146
1147 platform.on_system_sleep(Box::new({
1148 let app = Rc::downgrade(&app);
1149 move || {
1150 if let Some(app) = app.upgrade() {
1151 let cx = &mut app.borrow_mut();
1152 cx.system_sleep_observers
1153 .clone()
1154 .retain(move |callback| (callback)(cx));
1155 }
1156 }
1157 }));
1158
1159 platform.on_system_wake(Box::new({
1160 let app = Rc::downgrade(&app);
1161 move || {
1162 if let Some(app) = app.upgrade() {
1163 let cx = &mut app.borrow_mut();
1164 cx.system_wake_observers
1165 .clone()
1166 .retain(move |callback| (callback)(cx));
1167 }
1168 }
1169 }));
1170
1171 platform.on_app_lifecycle(Box::new({
1172 let app = Rc::downgrade(&app);
1173 move |phase| {
1174 if let Some(app) = app.upgrade() {
1175 app.borrow_mut().update(|cx| {
1176 cx.app_lifecycle_observers
1177 .clone()
1178 .retain(|callback| callback(phase, cx));
1179 });
1180 }
1181 }
1182 }));
1183
1184 platform.on_memory_warning(Box::new({
1185 let app = Rc::downgrade(&app);
1186 move || {
1187 if let Some(app) = app.upgrade() {
1188 app.borrow_mut().update(|cx| {
1189 cx.memory_warning_observers
1190 .clone()
1191 .retain(|callback| callback(cx));
1192 });
1193 }
1194 }
1195 }));
1196
1197 platform.on_power_mode_change(Box::new({
1198 let app = Rc::downgrade(&app);
1199 move || {
1200 if let Some(app) = app.upgrade() {
1201 let power_mode = app.borrow().platform.power_mode();
1202 app.borrow_mut().power_mode = power_mode;
1203 }
1204 }
1205 }));
1206
1207 platform.on_quit(Box::new({
1208 let cx = Rc::downgrade(&app);
1209 move || {
1210 let Some(cx) = cx.upgrade() else {
1211 return true;
1212 };
1213 match cx.try_borrow_mut() {
1214 Ok(mut cx) => {
1215 cx.shutdown();
1216 true
1217 }
1218 Err(_) => {
1219 false
1222 }
1223 }
1224 }
1225 }));
1226
1227 app
1228 }
1229
1230 #[doc(hidden)]
1231 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1232 self.entities.ref_counts_drop_handle()
1233 }
1234
1235 #[cfg(any(test, gpui_leak_detection))]
1241 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1242 self.entities.leak_detector_snapshot()
1243 }
1244
1245 #[cfg(any(test, gpui_leak_detection))]
1257 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1258 self.entities.assert_no_new_leaks(snapshot)
1259 }
1260
1261 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1263 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1264 LeakDetectorSnapshot::default()
1265 }
1266
1267 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1270 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1271
1272 pub fn shutdown(&mut self) {
1278 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1281 let hang_monitor_flush = self
1282 .hang_monitor
1283 .as_ref()
1284 .and_then(|hang_monitor| hang_monitor.request_flush());
1285
1286 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1287
1288 for observer in self.quit_observers.remove() {
1289 futures.push(observer(self));
1290 }
1291
1292 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1293 if let Some(flushed) = hang_monitor_flush {
1294 futures.push(
1295 async move {
1296 if flushed.await.is_err() {
1297 log::warn!("hang monitor exited before flushing");
1298 }
1299 }
1300 .boxed_local(),
1301 );
1302 }
1303
1304 self.windows.clear();
1305 self.window_handles.clear();
1306 self.flush_effects();
1307 self.quitting = true;
1308
1309 let futures = futures::future::join_all(futures);
1310 #[cfg(not(target_family = "wasm"))]
1311 if self
1312 .foreground_executor
1313 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1314 .is_err()
1315 {
1316 log::error!("timed out waiting on app_will_quit");
1317 }
1318 #[cfg(target_family = "wasm")]
1319 self.foreground_executor.spawn(futures).detach();
1320
1321 self.quitting = false;
1322 }
1323
1324 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1326 self.keyboard_layout.as_ref()
1327 }
1328
1329 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1331 &self.keyboard_mapper
1332 }
1333
1334 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1336 where
1337 F: 'static + FnMut(&mut App),
1338 {
1339 self.keyboard_layout_observers.insert(Box::new(move |cx| {
1340 callback(cx);
1341 true
1342 }))
1343 }
1344
1345 pub fn quit(&self) {
1347 self.platform.quit();
1348 }
1349
1350 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1364 if !self.windows.is_empty() {
1365 return Task::ready(Err(anyhow::anyhow!(
1366 "cannot switch windowing modes while windows are open"
1367 )));
1368 }
1369 self.platform.request_windowing(request)
1370 }
1371
1372 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1382 self.platform.graphical_environment()
1383 }
1384
1385 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1388 self.cursor_hide_mode
1389 }
1390
1391 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1394 self.cursor_hide_mode = mode;
1395 }
1396
1397 pub fn is_cursor_visible(&self) -> bool {
1403 self.platform.is_cursor_visible()
1404 }
1405
1406 pub fn reduce_motion(&self) -> bool {
1409 self.reduce_motion
1410 }
1411
1412 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1415 if self.reduce_motion != reduce_motion {
1416 self.reduce_motion = reduce_motion;
1417 self.refresh_windows();
1418 }
1419 }
1420
1421 pub fn refresh_windows(&mut self) {
1424 self.pending_effects.push_back(Effect::RefreshWindows);
1425 }
1426
1427 #[inline(always)]
1428 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1429 self.start_update();
1430 let result = update(self);
1431 self.finish_update();
1432 result
1433 }
1434
1435 pub(crate) fn start_update(&mut self) {
1436 self.pending_updates += 1;
1437 }
1438
1439 #[inline(never)]
1440 pub(crate) fn finish_update(&mut self) {
1441 if self.pending_updates == 1 {
1442 self.flush_effects();
1443 }
1444 self.pending_updates -= 1;
1445 }
1446
1447 pub fn observe<W>(
1449 &mut self,
1450 entity: &Entity<W>,
1451 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1452 ) -> Subscription
1453 where
1454 W: 'static,
1455 {
1456 self.observe_internal(entity, move |e, cx| {
1457 on_notify(e, cx);
1458 true
1459 })
1460 }
1461
1462 pub(crate) fn detect_accessed_entities<R>(
1463 &mut self,
1464 callback: impl FnOnce(&mut App) -> R,
1465 ) -> (R, FxHashSet<EntityId>) {
1466 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1467 let result = callback(self);
1468 let entities_accessed_in_callback = self
1469 .entities
1470 .accessed_entities
1471 .get_mut()
1472 .difference(&accessed_entities_start)
1473 .copied()
1474 .collect::<FxHashSet<EntityId>>();
1475 (result, entities_accessed_in_callback)
1476 }
1477
1478 pub(crate) fn record_entities_accessed(
1479 &mut self,
1480 window_handle: AnyWindowHandle,
1481 invalidator: WindowInvalidator,
1482 entities: &FxHashSet<EntityId>,
1483 ) {
1484 let mut tracked_entities =
1485 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1486 for entity in tracked_entities.iter() {
1487 self.window_invalidators_by_entity
1488 .entry(*entity)
1489 .and_modify(|windows| {
1490 windows.remove(&window_handle.id);
1491 });
1492 }
1493 for entity in entities.iter() {
1494 self.window_invalidators_by_entity
1495 .entry(*entity)
1496 .or_default()
1497 .insert(window_handle.id, invalidator.clone());
1498 self.current_window_by_entity
1499 .insert(*entity, window_handle.id);
1500 }
1501 tracked_entities.clear();
1502 tracked_entities.extend(entities.iter().copied());
1503 self.tracked_entities
1504 .insert(window_handle.id, tracked_entities);
1505 }
1506
1507 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1508 let (subscription, activate) = self.observers.insert_pending(key, value);
1509 self.defer(move |_| activate());
1510 subscription
1511 }
1512
1513 pub(crate) fn observe_internal<W>(
1514 &mut self,
1515 entity: &Entity<W>,
1516 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1517 ) -> Subscription
1518 where
1519 W: 'static,
1520 {
1521 let entity_id = entity.entity_id();
1522 let handle = entity.downgrade();
1523 self.new_observer(
1524 entity_id,
1525 Box::new(move |cx| {
1526 if let Some(entity) = handle.upgrade() {
1527 on_notify(entity, cx)
1528 } else {
1529 false
1530 }
1531 }),
1532 )
1533 }
1534
1535 pub fn subscribe<T, Event>(
1538 &mut self,
1539 entity: &Entity<T>,
1540 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1541 ) -> Subscription
1542 where
1543 T: 'static + EventEmitter<Event>,
1544 Event: 'static,
1545 {
1546 self.subscribe_internal(entity, move |entity, event, cx| {
1547 on_event(entity, event, cx);
1548 true
1549 })
1550 }
1551
1552 pub(crate) fn new_subscription(
1553 &mut self,
1554 key: EntityId,
1555 value: (TypeId, Listener),
1556 ) -> Subscription {
1557 let (subscription, activate) = self.event_listeners.insert_pending(key, value);
1558 self.defer(move |_| activate());
1559 subscription
1560 }
1561 pub(crate) fn subscribe_internal<T, Evt>(
1562 &mut self,
1563 entity: &Entity<T>,
1564 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1565 ) -> Subscription
1566 where
1567 T: 'static + EventEmitter<Evt>,
1568 Evt: 'static,
1569 {
1570 let entity_id = entity.entity_id();
1571 let handle = entity.downgrade();
1572 self.new_subscription(
1573 entity_id,
1574 (
1575 TypeId::of::<Evt>(),
1576 Box::new(move |event, cx| {
1577 let event: &Evt = event.downcast_ref().expect("invalid event type");
1578 if let Some(entity) = handle.upgrade() {
1579 on_event(entity, event, cx)
1580 } else {
1581 false
1582 }
1583 }),
1584 ),
1585 )
1586 }
1587
1588 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1592 self.windows
1593 .keys()
1594 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1595 .collect()
1596 }
1597
1598 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1604 self.platform.window_stack()
1605 }
1606
1607 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1609 self.platform.active_window()
1610 }
1611
1612 pub fn open_window<V: 'static + Render>(
1616 &mut self,
1617 options: crate::WindowOptions,
1618 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1619 ) -> anyhow::Result<WindowHandle<V>> {
1620 self.update(|cx| {
1621 let id = cx.windows.insert(None);
1622 let handle = WindowHandle::new(id);
1623 match Window::new(handle.into(), options, cx) {
1624 Ok(mut window) => {
1625 cx.window_update_stack.push(id);
1626 let root_view = build_root_view(&mut window, cx);
1627 cx.window_update_stack.pop();
1628 window.root.replace(root_view.into());
1629 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1630
1631 let clear = window.draw(cx);
1636 clear.clear(cx);
1637
1638 cx.window_handles.insert(id, window.handle);
1639 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1640 Ok(handle)
1641 }
1642 Err(e) => {
1643 cx.windows.remove(id);
1644 Err(e)
1645 }
1646 }
1647 })
1648 }
1649
1650 pub fn activate(&self, ignoring_other_apps: bool) {
1652 self.platform.activate(ignoring_other_apps);
1653 }
1654
1655 pub fn hide(&self) {
1657 self.platform.hide();
1658 }
1659
1660 pub fn hide_other_apps(&self) {
1662 self.platform.hide_other_apps();
1663 }
1664
1665 pub fn unhide_other_apps(&self) {
1667 self.platform.unhide_other_apps();
1668 }
1669
1670 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1672 self.platform.displays()
1673 }
1674
1675 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1677 self.platform.primary_display()
1678 }
1679
1680 pub fn is_screen_capture_supported(&self) -> bool {
1682 self.platform.is_screen_capture_supported()
1683 }
1684
1685 pub fn screen_capture_sources(
1687 &self,
1688 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1689 self.platform.screen_capture_sources()
1690 }
1691
1692 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1694 self.displays()
1695 .iter()
1696 .find(|display| display.id() == id)
1697 .cloned()
1698 }
1699
1700 pub fn thermal_state(&self) -> ThermalState {
1702 self.platform.thermal_state()
1703 }
1704
1705 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1707 self.platform.prevent_idle_sleep(reason)
1708 }
1709
1710 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1712 where
1713 F: 'static + FnMut(&mut App),
1714 {
1715 self.thermal_state_observers.insert(Box::new(move |cx| {
1716 callback(cx);
1717 true
1718 }))
1719 }
1720
1721 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1726 where
1727 F: 'static + FnMut(&mut App),
1728 {
1729 self.system_sleep_observers.insert(Box::new(move |cx| {
1730 callback(cx);
1731 true
1732 }))
1733 }
1734
1735 pub(crate) fn displays_changed(&mut self) {
1736 let current = read_displays(self.platform.as_ref());
1737 let events = display_events(&self.displays, ¤t);
1738 self.displays = current;
1739 for event in &events {
1740 let DisplayEvent::Changed { id, .. } = *event else {
1741 continue;
1742 };
1743 for handle in self.windows() {
1744 self.update_window(handle, |_, window, cx| {
1745 if window.display_id == Some(id) {
1746 window.notify_display_observers(cx);
1747 }
1748 })
1749 .log_err();
1750 }
1751 }
1752 for event in events {
1753 self.display_observers
1754 .clone()
1755 .retain(|callback| (callback)(event, self));
1756 }
1757 }
1758
1759 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1760 self.displays.contains_key(&id)
1761 }
1762
1763 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1766 self.displays.get(&id)?.refresh_interval
1767 }
1768
1769 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1772 where
1773 F: 'static + FnMut(DisplayEvent, &mut App),
1774 {
1775 self.display_observers.insert(Box::new(move |event, cx| {
1776 callback(event, cx);
1777 true
1778 }))
1779 }
1780
1781 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1783 where
1784 F: 'static + FnMut(&mut App),
1785 {
1786 self.system_wake_observers.insert(Box::new(move |cx| {
1787 callback(cx);
1788 true
1789 }))
1790 }
1791
1792 pub fn on_app_lifecycle(
1800 &self,
1801 mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
1802 ) -> Subscription {
1803 self.app_lifecycle_observers
1804 .insert(Box::new(move |phase, cx| {
1805 callback(phase, cx);
1806 true
1807 }))
1808 }
1809
1810 pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
1813 self.memory_warning_observers.insert(Box::new(move |cx| {
1814 callback(cx);
1815 true
1816 }))
1817 }
1818
1819 pub fn window_appearance(&self) -> WindowAppearance {
1821 self.platform.window_appearance()
1822 }
1823
1824 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1835 self.platform.set_window_appearance(appearance);
1836 }
1837
1838 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1840 self.platform.button_layout()
1841 }
1842
1843 pub fn desktop_preferences(&self) -> crate::DesktopPreferences {
1845 self.platform.desktop_preferences()
1846 }
1847
1848 pub fn observe_desktop_preferences(
1851 &self,
1852 mut callback: impl FnMut(&mut App) + 'static,
1853 ) -> Subscription {
1854 self.desktop_preferences_observers
1855 .insert(Box::new(move |cx| {
1856 callback(cx);
1857 true
1858 }))
1859 }
1860
1861 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1863 self.platform.read_from_clipboard()
1864 }
1865
1866 pub fn read_from_clipboard_async(
1874 &self,
1875 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1876 self.platform.read_from_clipboard_async()
1877 }
1878
1879 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1881 self.text_rendering_mode.set(mode);
1882 }
1883
1884 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1886 self.text_rendering_mode.get()
1887 }
1888
1889 pub fn power_mode(&self) -> PowerMode {
1892 self.power_mode
1893 }
1894
1895 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1897 self.platform.write_to_clipboard(item)
1898 }
1899
1900 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1903 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1904 self.platform.read_from_primary()
1905 }
1906
1907 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1910 pub fn write_to_primary(&self, item: ClipboardItem) {
1911 self.platform.write_to_primary(item)
1912 }
1913
1914 #[cfg(target_os = "macos")]
1920 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1921 self.platform.read_from_find_pasteboard()
1922 }
1923
1924 #[cfg(target_os = "macos")]
1930 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1931 self.platform.write_to_find_pasteboard(item)
1932 }
1933
1934 pub fn write_credentials(
1936 &self,
1937 url: &str,
1938 username: &str,
1939 password: &[u8],
1940 ) -> Task<Result<()>> {
1941 self.platform.write_credentials(url, username, password)
1942 }
1943
1944 #[cfg(target_os = "macos")]
1952 pub fn write_credentials_if_not_exists(
1953 &self,
1954 url: &str,
1955 username: &str,
1956 password: &[u8],
1957 ) -> Task<Result<bool>> {
1958 self.platform
1959 .write_credentials_if_not_exists(url, username, password)
1960 }
1961
1962 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1964 self.platform.read_credentials(url)
1965 }
1966
1967 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1969 self.platform.delete_credentials(url)
1970 }
1971
1972 pub fn open_url(&self, url: &str) {
1974 self.platform.open_url(url);
1975 }
1976
1977 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1984 self.platform.register_url_scheme(scheme)
1985 }
1986
1987 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1994 self.platform.set_app_identity(identifier, name);
1995 }
1996
1997 pub fn show_system_notification(&self, notification: SystemNotification) {
2004 self.platform.show_system_notification(notification);
2005 }
2006
2007 pub fn dismiss_system_notification(&self, tag: &str) {
2012 self.platform.dismiss_system_notification(tag);
2013 }
2014
2015 pub fn on_system_notification_response<F>(&self, mut callback: F)
2019 where
2020 F: 'static + FnMut(SystemNotificationResponse, &mut App),
2021 {
2022 let this = self.this.clone();
2023 self.platform
2024 .on_system_notification_response(Box::new(move |response| {
2025 if let Some(app) = this.upgrade() {
2026 callback(response, &mut app.borrow_mut());
2027 }
2028 }));
2029 }
2030
2031 pub fn app_path(&self) -> Result<PathBuf> {
2035 self.platform.app_path()
2036 }
2037
2038 pub fn compositor_name(&self) -> &'static str {
2042 self.platform.compositor_name()
2043 }
2044
2045 pub fn platform_info(&self) -> crate::PlatformInfo {
2047 self.platform.platform_info()
2048 }
2049
2050 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
2052 self.platform.path_for_auxiliary_executable(name)
2053 }
2054
2055 pub fn prompt_for_paths(
2061 &self,
2062 options: PathPromptOptions,
2063 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
2064 self.platform.prompt_for_paths(options)
2065 }
2066
2067 pub fn prompt_for_new_path(
2074 &self,
2075 directory: &Path,
2076 suggested_name: Option<&str>,
2077 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
2078 self.platform.prompt_for_new_path(directory, suggested_name)
2079 }
2080
2081 pub fn reveal_path(&self, path: &Path) {
2083 self.platform.reveal_path(path)
2084 }
2085
2086 pub fn open_with_system(&self, path: &Path) {
2088 self.platform.open_with_system(path)
2089 }
2090
2091 pub fn should_auto_hide_scrollbars(&self) -> bool {
2093 self.platform.should_auto_hide_scrollbars()
2094 }
2095
2096 pub fn restart(&mut self) {
2098 self.restart_observers
2099 .clone()
2100 .retain(|observer| observer(self));
2101 self.platform.restart(
2102 self.restart_path.take(),
2103 std::mem::take(&mut self.restart_arguments),
2104 )
2105 }
2106
2107 pub fn set_restart_path(&mut self, path: PathBuf) {
2109 self.restart_path = Some(path);
2110 }
2111
2112 pub fn http_client(&self) -> Arc<dyn HttpClient> {
2114 self.http_client.clone()
2115 }
2116
2117 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
2119 self.http_client = new_client;
2120 }
2121
2122 pub fn set_quit_mode(&mut self, mode: QuitMode) {
2125 self.quit_mode = mode;
2126 }
2127
2128 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
2137 self.platform.set_activation_policy(policy);
2138 }
2139
2140 pub fn svg_renderer(&self) -> SvgRenderer {
2142 self.svg_renderer.clone()
2143 }
2144
2145 pub(crate) fn push_effect(&mut self, effect: Effect) {
2146 match &effect {
2147 Effect::Notify { emitter } => {
2148 if !self.pending_notifications.insert(*emitter) {
2149 return;
2150 }
2151 }
2152 Effect::NotifyGlobalObservers { global_type } => {
2153 if !self.pending_global_notifications.insert(*global_type) {
2154 return;
2155 }
2156 }
2157 _ => {}
2158 };
2159
2160 self.pending_effects.push_back(effect);
2161 }
2162
2163 fn flush_effects(&mut self) {
2167 loop {
2168 self.release_dropped_entities();
2169 self.release_dropped_focus_handles();
2170 if let Some(effect) = self.pending_effects.pop_front() {
2171 match effect {
2172 Effect::Notify { emitter } => {
2173 self.apply_notify_effect(emitter);
2174 }
2175
2176 Effect::Emit {
2177 emitter,
2178 event_type,
2179 event,
2180 } => self.apply_emit_effect(emitter, event_type, &*event),
2181
2182 Effect::RefreshWindows => {
2183 self.apply_refresh_effect();
2184 }
2185
2186 Effect::NotifyGlobalObservers { global_type } => {
2187 self.apply_notify_global_observers_effect(global_type);
2188 }
2189
2190 Effect::Defer { callback } => {
2191 self.apply_defer_effect(callback);
2192 }
2193 Effect::EntityCreated {
2194 entity,
2195 tid,
2196 window,
2197 } => {
2198 self.apply_entity_created_effect(entity, tid, window);
2199 }
2200 }
2201 } else {
2202 #[cfg(any(test, feature = "test-support"))]
2203 if matches!(self.mode, GpuiMode::Test { .. }) {
2204 for window in self
2205 .windows
2206 .values()
2207 .filter_map(|window| {
2208 let window = window.as_deref()?;
2209 window.invalidator.is_dirty().then_some(window.handle)
2210 })
2211 .collect::<Vec<_>>()
2212 {
2213 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2214 .unwrap();
2215 }
2216 }
2217
2218 if self.pending_effects.is_empty() {
2219 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2220 if window.invalidator.is_dirty()
2221 || window.needs_present.get()
2222 || !window.next_frame_callbacks.borrow().is_empty()
2223 {
2224 window.platform_window.schedule_frame();
2225 }
2226 }
2227
2228 self.event_arena.clear();
2229 break;
2230 }
2231 }
2232 }
2233 }
2234
2235 fn release_dropped_entities(&mut self) {
2239 loop {
2240 let dropped = self.entities.take_dropped();
2241 if dropped.is_empty() {
2242 break;
2243 }
2244
2245 for (entity_id, mut entity) in dropped {
2246 self.observers.remove(&entity_id);
2247 self.event_listeners.remove(&entity_id);
2248 self.window_invalidators_by_entity.remove(&entity_id);
2249 self.current_window_by_entity.remove(&entity_id);
2250 for release_callback in self.release_listeners.remove(&entity_id) {
2251 release_callback(entity.as_mut(), self);
2252 }
2253 }
2254 }
2255 }
2256
2257 fn release_dropped_focus_handles(&mut self) {
2259 let focus_handles = self.focus_handles.clone();
2260 let mut focus_handles = focus_handles.write();
2261 let FocusMap {
2262 handles,
2263 dropped_handles,
2264 } = &mut *focus_handles;
2265 if dropped_handles.is_empty() {
2266 return;
2267 }
2268
2269 let windows = self
2270 .windows
2271 .values()
2272 .filter_map(|window| {
2273 let window = window.as_ref()?;
2274 dropped_handles
2275 .contains(&window.focus?)
2276 .then_some(window.handle)
2277 })
2278 .collect::<SmallVec<[_; 1]>>();
2279 for handle_id in dropped_handles.drain(..) {
2280 handles.remove(handle_id);
2281 }
2282 drop(focus_handles);
2283
2284 for window_handle in windows {
2285 window_handle
2286 .update(self, |_, window, cx| window.blur(cx))
2287 .ok();
2288 }
2289 }
2290
2291 fn apply_notify_effect(&mut self, emitter: EntityId) {
2292 self.pending_notifications.remove(&emitter);
2293
2294 self.observers
2295 .clone()
2296 .retain(&emitter, |handler| handler(self));
2297 }
2298
2299 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2300 self.event_listeners
2301 .clone()
2302 .retain(&emitter, |(stored_type, handler)| {
2303 if *stored_type == event_type {
2304 handler(event, self)
2305 } else {
2306 true
2307 }
2308 });
2309 }
2310
2311 fn apply_refresh_effect(&mut self) {
2312 for window in self.windows.values_mut() {
2313 if let Some(window) = window.as_deref_mut() {
2314 window.refreshing = true;
2315 window.invalidator.set_dirty(true);
2316 }
2317 }
2318 }
2319
2320 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2321 self.pending_global_notifications.remove(&type_id);
2322 self.global_observers
2323 .clone()
2324 .retain(&type_id, |observer| observer(self));
2325 }
2326
2327 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2328 callback(self);
2329 }
2330
2331 fn apply_entity_created_effect(
2332 &mut self,
2333 entity: AnyEntity,
2334 tid: TypeId,
2335 window: Option<WindowId>,
2336 ) {
2337 if let Some(id) = window {
2341 self.current_window_by_entity.insert(entity.entity_id(), id);
2342 }
2343
2344 self.new_entity_observers.clone().retain(&tid, |observer| {
2345 if let Some(id) = window {
2346 self.update_window_id(id, {
2347 let entity = entity.clone();
2348 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2349 })
2350 .expect("All windows should be off the stack when flushing effects");
2351 } else {
2352 (observer)(entity.clone(), &mut None, self)
2353 }
2354 true
2355 });
2356 }
2357
2358 #[inline(always)]
2364 pub fn with_window<R>(
2365 &mut self,
2366 entity_id: EntityId,
2367 f: impl FnOnce(&mut Window, &mut App) -> R,
2368 ) -> Option<R> {
2369 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2370 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2371 .ok()
2372 }
2373
2374 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2375 self.current_window_by_entity
2376 .entry(entity_id)
2377 .or_insert(window);
2378 }
2379
2380 #[inline(always)]
2381 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2382 where
2383 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2384 {
2385 let mut update = Some(update);
2386 let mut result = None;
2387 self.update_window_erased(id, &mut |arguments| {
2388 if let Some((root_view, window, cx)) = arguments {
2389 result = Some(update.take().unwrap()(root_view, window, cx));
2390 } else {
2391 drop(update.take());
2392 drop(result.take());
2393 }
2394 });
2395 result.context("window not found")
2396 }
2397
2398 pub fn to_async(&self) -> AsyncApp {
2401 AsyncApp {
2402 app: self.this.clone(),
2403 background_executor: self.background_executor.clone(),
2404 foreground_executor: self.foreground_executor.clone(),
2405 }
2406 }
2407
2408 pub fn background_executor(&self) -> &BackgroundExecutor {
2410 &self.background_executor
2411 }
2412
2413 pub fn is_test(&self) -> bool {
2416 self.background_executor.is_test()
2417 }
2418
2419 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2421 if self.quitting {
2422 panic!("Can't spawn on main thread after on_app_quit")
2423 };
2424 &self.foreground_executor
2425 }
2426
2427 #[cfg(feature = "profiler")]
2430 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2431 self.foreground_journal.clone()
2432 }
2433
2434 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2451 pub fn start_hang_monitor(
2452 &mut self,
2453 config: crate::profiler::hang::HangMonitorConfig,
2454 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2455 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2456 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2457
2458 if self.hang_monitor.is_some() {
2459 debug_assert!(false, "the hang monitor was started twice");
2460 return Err(HangMonitorError::AlreadyStarted);
2461 }
2462 let detector = HangDetector::new(
2463 self.foreground_journal(),
2464 config.threshold,
2465 config.frame_budget,
2466 );
2467 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2468 .map_err(HangMonitorError::Spawn)?;
2469 self.hang_monitor = Some(monitor);
2470 Ok(())
2471 }
2472
2473 #[track_caller]
2476 #[inline(always)]
2477 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2478 where
2479 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2480 R: 'static,
2481 {
2482 let mut cx = self.prepare_spawn();
2483
2484 self.foreground_executor
2485 .spawn(async move { f(&mut cx).await }.boxed_local())
2486 }
2487
2488 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2492 where
2493 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2494 R: 'static,
2495 {
2496 if self.quitting {
2497 debug_panic!("Can't spawn on main thread after on_app_quit")
2498 };
2499
2500 let mut cx = self.to_async();
2501
2502 self.foreground_executor
2503 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2504 }
2505
2506 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2509 self.push_effect(Effect::Defer {
2510 callback: Box::new(f),
2511 });
2512 }
2513
2514 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2516 &self.asset_source
2517 }
2518
2519 pub fn text_system(&self) -> &Arc<TextSystem> {
2521 &self.text_system
2522 }
2523
2524 pub fn on_missing_glyphs(
2535 &self,
2536 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2537 ) -> Subscription {
2538 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2539
2540 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2541 let callback = self.missing_glyph_callback.clone();
2542 self.spawn(async move |cx| {
2543 while let Ok(missing_glyphs) = receiver.recv().await {
2544 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2545 }
2546 })
2547 .detach();
2548 }
2549 self.text_system.enable_missing_glyph_reporting();
2550
2551 let callback = self.missing_glyph_callback.clone();
2552 let text_system = self.text_system.clone();
2553 Subscription::new(move || {
2554 if callback.remove(®istration) {
2555 text_system.disable_missing_glyph_reporting();
2556 }
2557 })
2558 }
2559
2560 pub fn has_global<G: Global>(&self) -> bool {
2562 self.globals_by_type.contains_key(&TypeId::of::<G>())
2563 }
2564
2565 #[track_caller]
2567 pub fn global<G: Global>(&self) -> &G {
2568 self.globals_by_type
2569 .get(&TypeId::of::<G>())
2570 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2571 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2572 }
2573
2574 pub fn try_global<G: Global>(&self) -> Option<&G> {
2576 self.globals_by_type
2577 .get(&TypeId::of::<G>())
2578 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2579 }
2580
2581 #[track_caller]
2583 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2584 let global_type = TypeId::of::<G>();
2585 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2586 self.globals_by_type
2587 .get_mut(&global_type)
2588 .and_then(|any_state| any_state.downcast_mut::<G>())
2589 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2590 }
2591
2592 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2595 let global_type = TypeId::of::<G>();
2596 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2597 self.globals_by_type
2598 .entry(global_type)
2599 .or_insert_with(|| Box::<G>::default())
2600 .downcast_mut::<G>()
2601 .unwrap()
2602 }
2603
2604 pub fn set_global<G: Global>(&mut self, global: G) {
2606 let global_type = TypeId::of::<G>();
2607 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2608 self.globals_by_type.insert(global_type, Box::new(global));
2609 }
2610
2611 #[cfg(any(test, feature = "test-support"))]
2613 pub fn clear_globals(&mut self) {
2614 self.globals_by_type.drain();
2615 }
2616
2617 pub fn remove_global<G: Global>(&mut self) -> G {
2619 let global_type = TypeId::of::<G>();
2620 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2621 *self
2622 .globals_by_type
2623 .remove(&global_type)
2624 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2625 .downcast()
2626 .unwrap()
2627 }
2628
2629 pub fn observe_global<G: Global>(
2631 &mut self,
2632 mut f: impl FnMut(&mut Self) + 'static,
2633 ) -> Subscription {
2634 let (subscription, activate) = self.global_observers.insert_pending(
2635 TypeId::of::<G>(),
2636 Box::new(move |cx| {
2637 f(cx);
2638 true
2639 }),
2640 );
2641 self.defer(move |_| activate());
2642 subscription
2643 }
2644
2645 #[track_caller]
2647 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2648 GlobalLease::new(
2649 self.globals_by_type
2650 .remove(&TypeId::of::<G>())
2651 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2652 .unwrap(),
2653 )
2654 }
2655
2656 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2658 let global_type = TypeId::of::<G>();
2659
2660 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2661 self.globals_by_type.insert(global_type, lease.global);
2662 }
2663
2664 pub(crate) fn new_entity_observer(
2665 &self,
2666 key: TypeId,
2667 value: NewEntityListener,
2668 ) -> Subscription {
2669 self.new_entity_observers.insert(key, value)
2670 }
2671
2672 pub fn observe_new<T: 'static>(
2675 &self,
2676 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2677 ) -> Subscription {
2678 self.new_entity_observer(
2679 TypeId::of::<T>(),
2680 Box::new(
2681 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2682 any_entity
2683 .downcast::<T>()
2684 .unwrap()
2685 .update(cx, |entity_state, cx| {
2686 on_new(entity_state, window.as_deref_mut(), cx)
2687 })
2688 },
2689 ),
2690 )
2691 }
2692
2693 pub fn observe_release<T>(
2696 &self,
2697 handle: &Entity<T>,
2698 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2699 ) -> Subscription
2700 where
2701 T: 'static,
2702 {
2703 self.release_listeners.insert(
2704 handle.entity_id(),
2705 Box::new(move |entity, cx| {
2706 let entity = entity.downcast_mut().expect("invalid entity type");
2707 on_release(entity, cx)
2708 }),
2709 )
2710 }
2711
2712 pub fn observe_release_in<T>(
2715 &self,
2716 handle: &Entity<T>,
2717 window: &Window,
2718 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2719 ) -> Subscription
2720 where
2721 T: 'static,
2722 {
2723 let window_handle = window.handle;
2724 self.observe_release(handle, move |entity, cx| {
2725 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2726 })
2727 }
2728
2729 pub fn observe_keystrokes(
2734 &mut self,
2735 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2736 ) -> Subscription {
2737 self.keystroke_observers
2738 .insert(Box::new(move |event, window, cx| {
2739 f(event, window, cx);
2740 true
2741 }))
2742 }
2743
2744 pub fn intercept_keystrokes(
2749 &mut self,
2750 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2751 ) -> Subscription {
2752 self.keystroke_interceptors
2753 .insert(Box::new(move |event, window, cx| {
2754 f(event, window, cx);
2755 true
2756 }))
2757 }
2758
2759 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2761 self.keymap.borrow_mut().add_bindings(bindings);
2762 self.pending_effects.push_back(Effect::RefreshWindows);
2763 }
2764
2765 pub fn clear_key_bindings(&mut self) {
2767 self.keymap.borrow_mut().clear();
2768 self.pending_effects.push_back(Effect::RefreshWindows);
2769 }
2770
2771 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2773 self.keymap.clone()
2774 }
2775
2776 pub fn on_action<A: Action>(
2780 &mut self,
2781 listener: impl Fn(&A, &mut Self) + 'static,
2782 ) -> &mut Self {
2783 self.global_action_listeners
2784 .entry(TypeId::of::<A>())
2785 .or_default()
2786 .push(Rc::new(move |action, phase, cx| {
2787 if phase == DispatchPhase::Bubble {
2788 let action = action.downcast_ref().unwrap();
2789 listener(action, cx)
2790 }
2791 }));
2792 self
2793 }
2794
2795 pub fn stop_propagation(&mut self) {
2800 self.propagate_event = false;
2801 }
2802
2803 pub fn propagate(&mut self) {
2808 self.propagate_event = true;
2809 }
2810
2811 pub fn build_action(
2813 &self,
2814 name: &str,
2815 data: Option<serde_json::Value>,
2816 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2817 self.actions.build_action(name, data)
2818 }
2819
2820 pub fn all_action_names(&self) -> &[&'static str] {
2823 self.actions.all_action_names()
2824 }
2825
2826 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2830 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2831 }
2832
2833 pub fn action_schemas(
2835 &self,
2836 generator: &mut schemars::SchemaGenerator,
2837 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2838 self.actions.action_schemas(generator)
2839 }
2840
2841 pub fn action_schema_by_name(
2846 &self,
2847 name: &str,
2848 generator: &mut schemars::SchemaGenerator,
2849 ) -> Option<Option<schemars::Schema>> {
2850 self.actions.action_schema_by_name(name, generator)
2851 }
2852
2853 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2855 self.actions.deprecated_aliases()
2856 }
2857
2858 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2860 self.actions.deprecation_messages()
2861 }
2862
2863 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2865 self.actions.documentation()
2866 }
2867
2868 pub fn on_app_quit<Fut>(
2871 &self,
2872 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2873 ) -> Subscription
2874 where
2875 Fut: 'static + Future<Output = ()>,
2876 {
2877 self.quit_observers.insert(Box::new(move |cx| {
2878 let future = on_quit(cx);
2879 future.boxed_local()
2880 }))
2881 }
2882
2883 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2887 self.restart_observers.insert(Box::new(move |cx| {
2888 on_restart(cx);
2889 true
2890 }))
2891 }
2892
2893 pub fn on_window_closed(
2896 &self,
2897 on_closed: impl FnMut(&mut App, WindowId) + 'static,
2898 ) -> Subscription {
2899 self.window_closed_observers.insert(Box::new(on_closed))
2900 }
2901
2902 pub(crate) fn clear_pending_keystrokes(&mut self) {
2903 for window in self.windows() {
2904 window
2905 .update(self, |_, window, cx| {
2906 window.clear_pending_keystrokes(cx);
2907 })
2908 .ok();
2909 }
2910 }
2911
2912 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2915 let mut action_available = false;
2916 if let Some(window) = self.active_window()
2917 && let Ok(window_action_available) =
2918 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2919 {
2920 action_available = window_action_available;
2921 }
2922
2923 action_available
2924 || self
2925 .global_action_listeners
2926 .contains_key(&action.as_any().type_id())
2927 }
2928
2929 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2931 let menus: Vec<Menu> = menus.into_iter().collect();
2932 self.platform.set_menus(menus, &self.keymap.borrow());
2933 }
2934
2935 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2937 self.platform.get_menus()
2938 }
2939
2940 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2942 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2943 }
2944
2945 pub fn perform_dock_menu_action(&self, action: usize) {
2947 self.platform.perform_dock_menu_action(action);
2948 }
2949
2950 pub fn add_recent_document(&self, path: &Path) {
2955 self.platform.add_recent_document(path);
2956 }
2957
2958 pub fn update_jump_list(
2961 &self,
2962 menus: Vec<MenuItem>,
2963 entries: Vec<SmallVec<[PathBuf; 2]>>,
2964 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2965 self.platform.update_jump_list(menus, entries)
2966 }
2967
2968 pub fn dispatch_action(&mut self, action: &dyn Action) {
2971 if let Some(active_window) = self.active_window() {
2972 active_window
2973 .update(self, |_, window, cx| {
2974 window.dispatch_action(action.boxed_clone(), cx)
2975 })
2976 .log_err();
2977 } else {
2978 self.dispatch_global_action(action);
2979 }
2980 }
2981
2982 fn dispatch_global_action(&mut self, action: &dyn Action) {
2983 self.propagate_event = true;
2984
2985 if let Some(mut global_listeners) = self
2986 .global_action_listeners
2987 .remove(&action.as_any().type_id())
2988 {
2989 for listener in &global_listeners {
2990 listener(action.as_any(), DispatchPhase::Capture, self);
2991 if !self.propagate_event {
2992 break;
2993 }
2994 }
2995
2996 global_listeners.extend(
2997 self.global_action_listeners
2998 .remove(&action.as_any().type_id())
2999 .unwrap_or_default(),
3000 );
3001
3002 self.global_action_listeners
3003 .insert(action.as_any().type_id(), global_listeners);
3004 }
3005
3006 if self.propagate_event
3007 && let Some(mut global_listeners) = self
3008 .global_action_listeners
3009 .remove(&action.as_any().type_id())
3010 {
3011 for listener in global_listeners.iter().rev() {
3012 listener(action.as_any(), DispatchPhase::Bubble, self);
3013 if !self.propagate_event {
3014 break;
3015 }
3016 }
3017
3018 global_listeners.extend(
3019 self.global_action_listeners
3020 .remove(&action.as_any().type_id())
3021 .unwrap_or_default(),
3022 );
3023
3024 self.global_action_listeners
3025 .insert(action.as_any().type_id(), global_listeners);
3026 }
3027 }
3028
3029 pub fn has_active_drag(&self) -> bool {
3031 self.active_drag.is_some()
3032 }
3033
3034 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3036 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3037 }
3038
3039 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3041 if self.active_drag.is_some() {
3042 self.active_drag = None;
3043 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
3044 drag.source_window == window.window_handle().window_id()
3045 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3046 }) {
3047 self.platform_owned_drag = None;
3048 }
3049 window.refresh();
3050 true
3051 } else {
3052 false
3053 }
3054 }
3055
3056 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3057 let Some(drag) = self.active_drag.take() else {
3058 return false;
3059 };
3060 self.platform_owned_drag = Some(PlatformOwnedDrag {
3061 source_window,
3062 state: PlatformOwnedDragState::Suspended(drag),
3063 });
3064 true
3065 }
3066
3067 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
3068 let Some(platform_drag) = self
3069 .platform_owned_drag
3070 .as_mut()
3071 .filter(|drag| drag.source_window == source_window)
3072 else {
3073 return false;
3074 };
3075 let state = std::mem::replace(
3076 &mut platform_drag.state,
3077 PlatformOwnedDragState::RestoredInSourceWindow,
3078 );
3079 let PlatformOwnedDragState::Suspended(drag) = state else {
3080 return false;
3081 };
3082 self.active_drag = Some(drag);
3083 true
3084 }
3085
3086 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3087 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
3088 drag.source_window == source_window
3089 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3090 }) else {
3091 return false;
3092 };
3093 let Some(drag) = self.active_drag.take() else {
3094 return false;
3095 };
3096 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
3097 true
3098 }
3099
3100 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
3101 if !self
3102 .platform_owned_drag
3103 .as_ref()
3104 .is_some_and(|drag| drag.source_window == source_window)
3105 {
3106 return false;
3107 }
3108 self.platform_owned_drag = None;
3109 self.active_drag = None;
3110 true
3111 }
3112
3113 pub fn set_active_drag_cursor_style(
3115 &mut self,
3116 cursor_style: CursorStyle,
3117 window: &mut Window,
3118 ) -> bool {
3119 if let Some(ref mut drag) = self.active_drag {
3120 drag.cursor_style = Some(cursor_style);
3121 window.refresh();
3122 true
3123 } else {
3124 false
3125 }
3126 }
3127
3128 pub fn set_prompt_builder(
3131 &mut self,
3132 renderer: impl Fn(
3133 PromptLevel,
3134 &str,
3135 Option<&str>,
3136 &[PromptButton],
3137 PromptHandle,
3138 &mut Window,
3139 &mut App,
3140 ) -> RenderablePromptHandle
3141 + 'static,
3142 ) {
3143 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3144 }
3145
3146 pub fn reset_prompt_builder(&mut self) {
3148 self.prompt_builder = Some(PromptBuilder::Default);
3149 }
3150
3151 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3153 let asset_id = (TypeId::of::<A>(), hash(source));
3154 self.loading_assets.remove(&asset_id);
3155 }
3156
3157 #[cfg(any(test, feature = "test-support"))]
3160 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3161 let asset_id = (TypeId::of::<A>(), hash(source));
3162 self.loading_assets.contains_key(&asset_id)
3163 }
3164
3165 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3170 self.asset_entry::<A>(source).get()
3171 }
3172
3173 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3174 let asset_id = (TypeId::of::<A>(), hash(source));
3175 if !self.loading_assets.contains_key(&asset_id) {
3176 let future = A::load(source.clone(), self);
3177 let entry = CachedLoad::new(future, self);
3178 self.loading_assets.insert(asset_id, Box::new(entry));
3179 }
3180 self.loading_assets
3181 .get(&asset_id)
3182 .and_then(|entry| entry.downcast_ref())
3183 .expect("asset cache entries are keyed by their asset type")
3184 }
3185
3186 #[track_caller]
3189 pub fn focus_handle(&self) -> FocusHandle {
3190 FocusHandle::new(&self.focus_handles)
3191 }
3192
3193 pub fn notify(&mut self, entity_id: EntityId) {
3195 let window_invalidators = mem::take(
3196 self.window_invalidators_by_entity
3197 .entry(entity_id)
3198 .or_default(),
3199 );
3200
3201 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3206 .iter()
3207 .filter(|(window_id, _)| {
3208 self.tracked_entities
3209 .get(window_id)
3210 .is_some_and(|set| set.contains(&entity_id))
3211 })
3212 .map(|(_, invalidator)| invalidator.clone())
3213 .collect();
3214
3215 if live_invalidators.is_empty() {
3216 if self.pending_notifications.insert(entity_id) {
3217 self.pending_effects
3218 .push_back(Effect::Notify { emitter: entity_id });
3219 }
3220 } else {
3221 for invalidator in &live_invalidators {
3222 invalidator.invalidate_view(entity_id, self);
3223 }
3224 }
3225
3226 self.window_invalidators_by_entity
3227 .insert(entity_id, window_invalidators);
3228 }
3229
3230 #[cfg(any(test, feature = "test-support", debug_assertions))]
3232 pub fn get_name(&self) -> Option<&'static str> {
3233 self.name
3234 }
3235
3236 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3238 self.platform.can_select_mixed_files_and_dirs()
3239 }
3240
3241 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3246 for window in self.windows.values_mut().flatten() {
3248 _ = window.drop_image(image.clone());
3249 }
3250
3251 if let Some(window) = current_window {
3253 _ = window.drop_image(image);
3254 }
3255 }
3256
3257 #[cfg(debug_assertions)]
3259 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3260 self.inspector_renderer = Some(f);
3261 }
3262
3263 #[cfg(debug_assertions)]
3265 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3266 &mut self,
3267 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3268 ) where
3269 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3270 {
3271 self.inspector_element_registry.register(factory);
3272 }
3273
3274 pub fn init_colors(&mut self) {
3278 self.set_global(GlobalColors(Arc::new(Colors::default())));
3279 }
3280
3281 #[inline(never)]
3282 fn update_window_erased(
3283 &mut self,
3284 window_id: WindowId,
3285 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3286 ) {
3287 self.update(|cx| {
3288 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3289 update(None);
3290 return;
3291 };
3292
3293 let root_view = window.root.clone().unwrap();
3294
3295 cx.window_update_stack.push(window.handle.id);
3296 update(Some((root_view, &mut window, cx)));
3297 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3298 cx.window_update_stack.pop();
3299
3300 if window.removed {
3301 cx.end_platform_drag(window_id);
3302 cx.window_handles.remove(&window_id);
3303 cx.windows.remove(window_id);
3304 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3305 for entity_id in tracked {
3306 if let Some(windows) =
3307 cx.window_invalidators_by_entity.get_mut(&entity_id)
3308 {
3309 windows.remove(&window_id);
3310 }
3311 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3312 cx.current_window_by_entity.remove(&entity_id);
3313 }
3314 }
3315 }
3316
3317 cx.window_closed_observers.clone().retain(|callback| {
3318 callback(cx, window_id);
3319 true
3320 });
3321
3322 let quit_on_empty = match cx.quit_mode {
3323 QuitMode::Explicit => false,
3324 QuitMode::LastWindowClosed => true,
3325 QuitMode::Default => cfg!(not(target_os = "macos")),
3326 };
3327
3328 if quit_on_empty && cx.windows.is_empty() {
3329 cx.quit();
3330 }
3331 } else {
3332 cx.windows.get_mut(window_id)?.replace(window);
3333 }
3334 Some(())
3335 }
3336 if trail(window_id, window, cx).is_none() {
3337 update(None);
3338 }
3339 });
3340 }
3341
3342 #[inline(never)]
3343 fn update_entity_erased(
3344 &mut self,
3345 handle: &AnyEntity,
3346 entity_type: &str,
3347 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3348 ) {
3349 self.update(|cx| {
3350 let mut lease = cx.entities.lease_erased(handle, entity_type);
3351 update(lease.entity.as_deref_mut().unwrap(), cx);
3352 cx.entities.end_lease_erased(handle.entity_id, lease);
3353 });
3354 }
3355
3356 #[inline(never)]
3357 #[track_caller]
3358 fn prepare_spawn(&self) -> AsyncApp {
3359 if self.quitting {
3360 debug_panic!("Can't spawn on main thread after on_app_quit")
3361 };
3362 self.to_async()
3363 }
3364}
3365
3366impl AppContext for App {
3367 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3372 self.update(|cx| {
3373 let slot = cx.entities.reserve();
3374 let handle = slot.clone();
3375 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3376
3377 cx.push_effect(Effect::EntityCreated {
3378 entity: handle.into_any(),
3379 tid: TypeId::of::<T>(),
3380 window: cx.window_update_stack.last().cloned(),
3381 });
3382
3383 cx.entities.insert(slot, entity)
3384 })
3385 }
3386
3387 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3388 Reservation(self.entities.reserve())
3389 }
3390
3391 fn insert_entity<T: 'static>(
3392 &mut self,
3393 reservation: Reservation<T>,
3394 build_entity: impl FnOnce(&mut Context<T>) -> T,
3395 ) -> Entity<T> {
3396 self.update(|cx| {
3397 let slot = reservation.0;
3398 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3399 cx.entities.insert(slot, entity)
3400 })
3401 }
3402
3403 #[inline(always)]
3406 fn update_entity<T: 'static, R>(
3407 &mut self,
3408 handle: &Entity<T>,
3409 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3410 ) -> R {
3411 let mut update = Some(update);
3412 let mut result = None;
3413 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3414 let value = update.take().unwrap()(
3415 entity.downcast_mut::<T>().unwrap(),
3416 &mut Context::new_context(cx, handle.downgrade()),
3417 );
3418 result = Some(value);
3419 });
3420 result.unwrap()
3421 }
3422
3423 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3424 where
3425 T: 'static,
3426 {
3427 GpuiBorrow::new(handle.clone(), self)
3428 }
3429
3430 #[inline(always)]
3431 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3432 where
3433 T: 'static,
3434 {
3435 let entity = self.entities.read(handle);
3436 read(entity, self)
3437 }
3438
3439 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3440 where
3441 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3442 {
3443 self.update_window_id(handle.id, update)
3444 }
3445
3446 fn with_window<R>(
3447 &mut self,
3448 entity_id: EntityId,
3449 f: impl FnOnce(&mut Window, &mut App) -> R,
3450 ) -> Option<R> {
3451 App::with_window(self, entity_id, f)
3452 }
3453
3454 fn read_window<T, R>(
3455 &self,
3456 window: &WindowHandle<T>,
3457 read: impl FnOnce(Entity<T>, &App) -> R,
3458 ) -> Result<R>
3459 where
3460 T: 'static,
3461 {
3462 let window = self
3463 .windows
3464 .get(window.id)
3465 .context("window not found")?
3466 .as_deref()
3467 .expect("attempted to read a window that is already on the stack");
3468
3469 let root_view = window.root.clone().unwrap();
3470 let view = root_view
3471 .downcast::<T>()
3472 .map_err(|_| anyhow!("root view's type has changed"))?;
3473
3474 Ok(read(view, self))
3475 }
3476
3477 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3478 where
3479 R: Send + 'static,
3480 {
3481 self.background_executor.spawn(future)
3482 }
3483
3484 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3485 where
3486 G: Global,
3487 {
3488 let g = self.global::<G>();
3489 callback(g, self)
3490 }
3491}
3492
3493pub(crate) enum Effect {
3495 Notify {
3496 emitter: EntityId,
3497 },
3498 Emit {
3499 emitter: EntityId,
3500 event_type: TypeId,
3501 event: ArenaBox<dyn Any>,
3502 },
3503 RefreshWindows,
3504 NotifyGlobalObservers {
3505 global_type: TypeId,
3506 },
3507 Defer {
3508 callback: Box<dyn FnOnce(&mut App) + 'static>,
3509 },
3510 EntityCreated {
3511 entity: AnyEntity,
3512 tid: TypeId,
3513 window: Option<WindowId>,
3514 },
3515}
3516
3517impl std::fmt::Debug for Effect {
3518 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3519 match self {
3520 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3521 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3522 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3523 Effect::NotifyGlobalObservers { global_type } => {
3524 write!(f, "NotifyGlobalObservers({:?})", global_type)
3525 }
3526 Effect::Defer { .. } => write!(f, "Defer(..)"),
3527 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3528 }
3529 }
3530}
3531
3532pub(crate) struct GlobalLease<G: Global> {
3534 global: Box<dyn Any>,
3535 global_type: PhantomData<G>,
3536}
3537
3538impl<G: Global> GlobalLease<G> {
3539 fn new(global: Box<dyn Any>) -> Self {
3540 GlobalLease {
3541 global,
3542 global_type: PhantomData,
3543 }
3544 }
3545}
3546
3547impl<G: Global> Deref for GlobalLease<G> {
3548 type Target = G;
3549
3550 fn deref(&self) -> &Self::Target {
3551 self.global.downcast_ref().unwrap()
3552 }
3553}
3554
3555impl<G: Global> DerefMut for GlobalLease<G> {
3556 fn deref_mut(&mut self) -> &mut Self::Target {
3557 self.global.downcast_mut().unwrap()
3558 }
3559}
3560
3561pub struct AnyDrag {
3564 pub view: AnyView,
3566
3567 pub value: Arc<dyn Any>,
3569
3570 pub cursor_offset: Point<Pixels>,
3573
3574 pub cursor_style: Option<CursorStyle>,
3576
3577 pub external_payload_source: Option<ExternalDragPayloadSource>,
3580}
3581
3582pub type ExternalDragPayloadSource =
3585 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3586
3587#[derive(Clone)]
3590pub struct AnyTooltip {
3591 pub view: AnyView,
3593
3594 pub mouse_position: Point<Pixels>,
3596
3597 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3601}
3602
3603#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3605pub enum InputPreference {
3606 CharacterInput,
3608 KeyBindings,
3610}
3611
3612#[derive(Debug)]
3614pub struct KeystrokeEvent {
3615 pub keystroke: Keystroke,
3617
3618 pub input_preference: InputPreference,
3626
3627 pub action: Option<Box<dyn Action>>,
3629
3630 pub context_stack: Vec<KeyContext>,
3632}
3633
3634struct NullHttpClient;
3635
3636impl HttpClient for NullHttpClient {
3637 fn send(
3638 &self,
3639 _req: http_client::Request<http_client::AsyncBody>,
3640 ) -> futures::future::BoxFuture<
3641 'static,
3642 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3643 > {
3644 async move {
3645 anyhow::bail!("No HttpClient available");
3646 }
3647 .boxed()
3648 }
3649
3650 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3651 None
3652 }
3653
3654 fn proxy(&self) -> Option<&Url> {
3655 None
3656 }
3657}
3658
3659pub struct GpuiBorrow<'a, T> {
3661 inner: Option<Lease<T>>,
3662 app: &'a mut App,
3663}
3664
3665impl<'a, T: 'static> GpuiBorrow<'a, T> {
3666 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3667 app.start_update();
3668 let lease = app.entities.lease(&inner);
3669 Self {
3670 inner: Some(lease),
3671 app,
3672 }
3673 }
3674}
3675
3676impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3677 fn borrow(&self) -> &T {
3678 self.inner.as_ref().unwrap().borrow()
3679 }
3680}
3681
3682impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3683 fn borrow_mut(&mut self) -> &mut T {
3684 self.inner.as_mut().unwrap().borrow_mut()
3685 }
3686}
3687
3688impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3689 type Target = T;
3690
3691 fn deref(&self) -> &Self::Target {
3692 self.inner.as_ref().unwrap()
3693 }
3694}
3695
3696impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3697 fn deref_mut(&mut self) -> &mut T {
3698 self.inner.as_mut().unwrap()
3699 }
3700}
3701
3702impl<'a, T> Drop for GpuiBorrow<'a, T> {
3703 fn drop(&mut self) {
3704 let lease = self.inner.take().unwrap();
3705 self.app.notify(lease.id);
3706 self.app.entities.end_lease(lease);
3707 self.app.finish_update();
3708 }
3709}
3710
3711#[cfg(test)]
3712mod test {
3713 use std::{
3714 cell::{Cell, RefCell},
3715 ffi::OsString,
3716 path::PathBuf,
3717 rc::Rc,
3718 };
3719
3720 #[cfg(unix)]
3721 use std::os::unix::ffi::OsStringExt;
3722
3723 use crate::{
3724 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3725 TestAppContext, Window,
3726 };
3727
3728 fn construction_platform() -> Rc<crate::TestPlatform> {
3729 let dispatcher = std::sync::Arc::new(crate::TestDispatcher::new(0));
3730 crate::TestPlatform::new(
3731 crate::BackgroundExecutor::new(dispatcher.clone()),
3732 crate::ForegroundExecutor::new(dispatcher),
3733 )
3734 }
3735
3736 #[test]
3737 fn application_construction_uses_text_override_without_querying_platform() {
3738 use std::sync::Arc;
3739
3740 let platform = construction_platform();
3741 let backend: Arc<dyn crate::PlatformTextSystem> = Arc::new(crate::NoopTextSystem);
3742 let native_references = Arc::strong_count(&platform.text_system);
3743 let app =
3744 super::Application::with_platform_and_text_system(platform.clone(), backend.clone());
3745
3746 assert_eq!(platform.text_system_calls.get(), 0);
3747 assert_eq!(Arc::strong_count(&platform.text_system), native_references);
3748 assert_eq!(Arc::strong_count(&backend), 2);
3749 drop(app);
3750 assert_eq!(Arc::strong_count(&backend), 1);
3751 }
3752
3753 #[test]
3754 fn application_construction_uses_platform_text_by_default() {
3755 use std::sync::Arc;
3756
3757 let platform = construction_platform();
3758 let native_references = Arc::strong_count(&platform.text_system);
3759 let app = super::Application::with_platform(platform.clone());
3760
3761 assert_eq!(platform.text_system_calls.get(), 1);
3762 assert_eq!(
3763 Arc::strong_count(&platform.text_system),
3764 native_references + 1
3765 );
3766 drop(app);
3767 assert_eq!(Arc::strong_count(&platform.text_system), native_references);
3768 }
3769
3770 #[gpui::test]
3771 fn app_borrow_diagnostics(cx: &mut TestAppContext) {
3772 use std::panic::{AssertUnwindSafe, catch_unwind};
3773
3774 let app = cx.app.clone();
3775 let first_line = line!() + 1;
3776 let first = app.borrow();
3777 let second = app.borrow();
3778 drop(first);
3779 assert!(app.try_borrow_mut().is_err());
3780 let attempted_line = line!() + 1;
3781 let panic = catch_unwind(AssertUnwindSafe(|| drop(app.borrow_mut())));
3782 let message = *panic
3783 .expect_err("conflicting borrow")
3784 .downcast::<String>()
3785 .unwrap();
3786 assert!(message.contains(&format!(
3787 "mutable App borrow at {}:{attempted_line}:",
3788 file!()
3789 )));
3790 assert!(message.contains(&format!(
3791 "shared borrow group began at {}:{first_line}:",
3792 file!()
3793 )));
3794 drop(second);
3795
3796 let origin_line = line!() + 2;
3797 let panic = catch_unwind(AssertUnwindSafe(|| {
3798 let _borrow = app.try_borrow_mut().expect("initial borrow");
3799 drop(app.borrow());
3800 }));
3801 let message = *panic
3802 .expect_err("conflicting borrow")
3803 .downcast::<String>()
3804 .unwrap();
3805 assert!(message.contains("attempted shared App borrow"));
3806 assert!(message.contains(&format!(
3807 "mutable borrow group began at {}:{origin_line}:",
3808 file!()
3809 )));
3810
3811 let next_line = line!() + 1;
3812 let _borrow = app.borrow();
3813 assert_eq!(
3814 app.borrow_origin.get().expect("new origin").0.line(),
3815 next_line
3816 );
3817 }
3818
3819 struct RenderCounter(Rc<Cell<usize>>);
3820
3821 impl Render for RenderCounter {
3822 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3823 self.0.set(self.0.get() + 1);
3824 Empty
3825 }
3826 }
3827
3828 #[gpui::test]
3829 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3830 let render_count = Rc::new(Cell::new(0));
3831
3832 let _window = cx.add_window({
3833 let render_count = render_count.clone();
3834 move |_, _| RenderCounter(render_count)
3835 });
3836
3837 cx.run_until_parked();
3838 let render_count_before_refresh = render_count.get();
3839
3840 cx.to_async().refresh();
3841
3842 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3843 }
3844
3845 #[gpui::test]
3846 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3847 let observed = Rc::new(RefCell::new(Vec::new()));
3848 let subscription = cx.update(|cx| {
3849 let observed = observed.clone();
3850 cx.on_missing_glyphs(move |missing_glyphs, _| {
3851 observed.borrow_mut().extend_from_slice(missing_glyphs);
3852 })
3853 });
3854 cx.update(|cx| {
3855 cx.text_system()
3856 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3857 });
3858 cx.run_until_parked();
3859 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3860
3861 let second_observed = Rc::new(RefCell::new(Vec::new()));
3862 let second_subscription = cx.update(|cx| {
3863 let second_observed = second_observed.clone();
3864 cx.on_missing_glyphs(move |missing_glyphs, _| {
3865 second_observed
3866 .borrow_mut()
3867 .extend_from_slice(missing_glyphs);
3868 })
3869 });
3870 cx.update(|cx| {
3871 cx.text_system()
3872 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3873 });
3874 cx.run_until_parked();
3875 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3876 assert_eq!(
3877 second_observed.borrow().as_slice(),
3878 &[missing_glyph("replacement")]
3879 );
3880
3881 drop(subscription);
3882 cx.update(|cx| {
3883 cx.text_system()
3884 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3885 });
3886 cx.run_until_parked();
3887 assert_eq!(
3888 second_observed.borrow().as_slice(),
3889 &[
3890 missing_glyph("replacement"),
3891 missing_glyph("after old drop")
3892 ]
3893 );
3894
3895 drop(second_subscription);
3896 cx.update(|cx| {
3897 cx.text_system()
3898 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3899 });
3900 cx.run_until_parked();
3901 assert_eq!(second_observed.borrow().len(), 2);
3902 }
3903
3904 #[test]
3905 fn test_gpui_borrow() {
3906 let cx = TestAppContext::single();
3907 let observation_count = Rc::new(RefCell::new(0));
3908
3909 let state = cx.update(|cx| {
3910 let state = cx.new(|_| false);
3911 cx.observe(&state, {
3912 let observation_count = observation_count.clone();
3913 move |_, _| {
3914 let mut count = observation_count.borrow_mut();
3915 *count += 1;
3916 }
3917 })
3918 .detach();
3919
3920 state
3921 });
3922
3923 cx.update(|cx| {
3924 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3926 });
3927
3928 cx.update(|cx| {
3929 state.write(cx, false);
3930 });
3931
3932 assert_eq!(*observation_count.borrow(), 2);
3933 }
3934
3935 #[gpui::test]
3936 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3937 #[cfg(unix)]
3938 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3939 #[cfg(not(unix))]
3940 let user_data_dir = OsString::from("C:\\zed data");
3941 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3942 let restart_path = PathBuf::from("updated-zed");
3943 let _application =
3944 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3945 let restart = cx.expect_restart();
3946
3947 cx.update(|cx| {
3948 cx.set_restart_path(restart_path.clone());
3949 cx.restart();
3950 });
3951
3952 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3953 assert_eq!(path, Some(restart_path));
3954 assert_eq!(restart_arguments, arguments);
3955 }
3956
3957 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3958 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3959 }
3960}