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 pub(crate) display_observers: SingleSubscriberSet<DisplayHandler>,
901 displays: HashMap<DisplayId, DisplayState>,
904 pub(crate) system_sleep_observers: SingleSubscriberSet<Handler>,
905 pub(crate) system_wake_observers: SingleSubscriberSet<Handler>,
906 app_lifecycle_observers: SingleSubscriberSet<AppLifecycleHandler>,
907 memory_warning_observers: SingleSubscriberSet<Handler>,
908 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
909 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
910 pub(crate) quit_observers: SingleSubscriberSet<QuitHandler>,
911 pub(crate) restart_observers: SingleSubscriberSet<Handler>,
912 pub(crate) window_closed_observers: SingleSubscriberSet<WindowClosedHandler>,
913
914 pub(crate) element_arena: RefCell<Arena>,
917 pub(crate) event_arena: Arena,
919
920 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
925
926 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
928 asset_source: Arc<dyn AssetSource>,
929 pub(crate) svg_renderer: SvgRenderer,
930 http_client: Arc<dyn HttpClient>,
931
932 pub(crate) pending_notifications: FxHashSet<EntityId>,
934 pub(crate) pending_global_notifications: TypeIdHashSet,
935 pub(crate) restart_path: Option<PathBuf>,
936 pub(crate) restart_arguments: Vec<OsString>,
937 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
939 pub(crate) prompt_builder: Option<PromptBuilder>,
940 pub(crate) window_invalidators_by_entity:
941 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
942 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
943 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
944 #[cfg(debug_assertions)]
945 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
946 #[cfg(debug_assertions)]
947 pub(crate) inspector_element_registry: InspectorElementRegistry,
948 #[cfg(any(test, feature = "test-support", debug_assertions))]
949 pub(crate) name: Option<&'static str>,
950 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
951
952 pub(crate) window_update_stack: Vec<WindowId>,
953 pub(crate) mode: GpuiMode,
954 pub(crate) cursor_hide_mode: CursorHideMode,
955 pub(crate) reduce_motion: bool,
956 pub(crate) synced_animation_epoch: Instant,
958 power_mode: PowerMode,
959 pub(crate) accessibility_force_disabled: bool,
962 pending_updates: usize,
963 quit_mode: QuitMode,
964 quitting: bool,
965
966 #[cfg(any(test, gpui_leak_detection))]
969 _ref_counts: Arc<RwLock<EntityRefCounts>>,
970}
971
972impl App {
973 #[allow(clippy::new_ret_no_self)]
974 pub(crate) fn new_app(
975 platform: Rc<dyn Platform>,
976 asset_source: Arc<dyn AssetSource>,
977 http_client: Arc<dyn HttpClient>,
978 ) -> Rc<AppCell> {
979 Self::new_app_with_text_system(platform, asset_source, http_client, None)
980 }
981
982 fn new_app_with_text_system(
983 platform: Rc<dyn Platform>,
984 asset_source: Arc<dyn AssetSource>,
985 http_client: Arc<dyn HttpClient>,
986 text_override: Option<Arc<dyn PlatformTextSystem>>,
987 ) -> Rc<AppCell> {
988 let background_executor = platform.background_executor();
989 let foreground_executor = platform.foreground_executor();
990 assert!(
991 background_executor.is_main_thread(),
992 "must construct App on main thread"
993 );
994 #[cfg(feature = "profiler")]
995 let foreground_journal = crate::profiler::journal::install_foreground_journal();
996 let synced_animation_epoch = background_executor.now();
997
998 let backend = text_override.unwrap_or_else(|| platform.text_system());
999 let text_system = Arc::new(TextSystem::new(backend));
1000 let entities = EntityMap::new();
1001 let keyboard_layout = platform.keyboard_layout();
1002 let keyboard_mapper = platform.keyboard_mapper();
1003 let power_mode = platform.power_mode();
1004
1005 #[cfg(any(test, gpui_leak_detection))]
1006 let _ref_counts = entities.ref_counts_drop_handle();
1007
1008 let app = Rc::new_cyclic(|this| AppCell {
1009 borrow_origin: Cell::new(None),
1010 app: RefCell::new(App {
1011 this: this.clone(),
1012 platform: platform.clone(),
1013 text_system,
1014 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
1015 mode: GpuiMode::Production,
1016 actions: Rc::new(ActionRegistry::default()),
1017 pending_updates: 0,
1018 active_drag: None,
1019 platform_owned_drag: None,
1020 background_executor,
1021 foreground_executor,
1022 #[cfg(feature = "profiler")]
1023 foreground_journal,
1024 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1025 hang_monitor: None,
1026 svg_renderer: SvgRenderer::new(asset_source.clone()),
1027 loading_assets: Default::default(),
1028 asset_source,
1029 http_client,
1030 globals_by_type: Default::default(),
1031 entities,
1032 new_entity_observers: SubscriberSet::new(),
1033 windows: SlotMap::with_key(),
1034 window_update_stack: Vec::new(),
1035 window_handles: FxHashMap::default(),
1036 focus_handles: Arc::new(RwLock::new(FocusMap::default())),
1037 keymap: Rc::new(RefCell::new(Keymap::default())),
1038 keyboard_layout,
1039 keyboard_mapper,
1040 global_action_listeners: Default::default(),
1041 pending_effects: VecDeque::new(),
1042 pending_notifications: FxHashSet::default(),
1043 pending_global_notifications: Default::default(),
1044 observers: SubscriberSet::new(),
1045 tracked_entities: FxHashMap::default(),
1046 window_invalidators_by_entity: FxHashMap::default(),
1047 current_window_by_entity: FxHashMap::default(),
1048 event_listeners: SubscriberSet::new(),
1049 release_listeners: SubscriberSet::new(),
1050 keystroke_observers: SingleSubscriberSet::new(),
1051 keystroke_interceptors: SingleSubscriberSet::new(),
1052 keyboard_layout_observers: SingleSubscriberSet::new(),
1053 missing_glyph_callback: Rc::default(),
1054 thermal_state_observers: SingleSubscriberSet::new(),
1055 display_observers: SingleSubscriberSet::new(),
1056 displays: read_displays(platform.as_ref()),
1057 system_sleep_observers: SingleSubscriberSet::new(),
1058 system_wake_observers: SingleSubscriberSet::new(),
1059 app_lifecycle_observers: SingleSubscriberSet::new(),
1060 memory_warning_observers: SingleSubscriberSet::new(),
1061 global_observers: SubscriberSet::new(),
1062 quit_observers: SingleSubscriberSet::new(),
1063 restart_observers: SingleSubscriberSet::new(),
1064 restart_path: None,
1065 restart_arguments: Vec::new(),
1066 window_closed_observers: SingleSubscriberSet::new(),
1067 layout_id_buffer: Default::default(),
1068 propagate_event: true,
1069 prompt_builder: Some(PromptBuilder::Default),
1070 #[cfg(debug_assertions)]
1071 inspector_renderer: None,
1072 #[cfg(debug_assertions)]
1073 inspector_element_registry: InspectorElementRegistry::default(),
1074 quit_mode: QuitMode::default(),
1075 quitting: false,
1076 cursor_hide_mode: CursorHideMode::default(),
1077 reduce_motion: false,
1078 synced_animation_epoch,
1079 power_mode,
1080 accessibility_force_disabled: false,
1081
1082 #[cfg(any(test, feature = "test-support", debug_assertions))]
1083 name: None,
1084 element_arena: RefCell::new(Arena::new(1024 * 1024)),
1085 event_arena: Arena::new(1024 * 1024),
1086
1087 #[cfg(any(test, gpui_leak_detection))]
1088 _ref_counts,
1089 }),
1090 });
1091
1092 init_app_menus(platform.as_ref(), &app.borrow());
1093 SystemWindowTabController::init(&mut app.borrow_mut());
1094 #[cfg(feature = "profiler")]
1095 crate::profiler::journal::observe_power(&app.borrow());
1096
1097 platform.on_keyboard_layout_change(Box::new({
1098 let app = Rc::downgrade(&app);
1099 move || {
1100 if let Some(app) = app.upgrade() {
1101 let cx = &mut app.borrow_mut();
1102 cx.keyboard_layout = cx.platform.keyboard_layout();
1103 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1104 cx.keyboard_layout_observers
1105 .clone()
1106 .retain(move |callback| (callback)(cx));
1107 }
1108 }
1109 }));
1110
1111 platform.on_thermal_state_change(Box::new({
1112 let app = Rc::downgrade(&app);
1113 move || {
1114 if let Some(app) = app.upgrade() {
1115 let cx = &mut app.borrow_mut();
1116 cx.thermal_state_observers
1117 .clone()
1118 .retain(move |callback| (callback)(cx));
1119 }
1120 }
1121 }));
1122
1123 platform.on_displays_changed(Box::new({
1124 let app = Rc::downgrade(&app);
1125 move || {
1126 if let Some(app) = app.upgrade() {
1127 app.borrow_mut().displays_changed();
1128 }
1129 }
1130 }));
1131
1132 platform.on_system_sleep(Box::new({
1133 let app = Rc::downgrade(&app);
1134 move || {
1135 if let Some(app) = app.upgrade() {
1136 let cx = &mut app.borrow_mut();
1137 cx.system_sleep_observers
1138 .clone()
1139 .retain(move |callback| (callback)(cx));
1140 }
1141 }
1142 }));
1143
1144 platform.on_system_wake(Box::new({
1145 let app = Rc::downgrade(&app);
1146 move || {
1147 if let Some(app) = app.upgrade() {
1148 let cx = &mut app.borrow_mut();
1149 cx.system_wake_observers
1150 .clone()
1151 .retain(move |callback| (callback)(cx));
1152 }
1153 }
1154 }));
1155
1156 platform.on_app_lifecycle(Box::new({
1157 let app = Rc::downgrade(&app);
1158 move |phase| {
1159 if let Some(app) = app.upgrade() {
1160 app.borrow_mut().update(|cx| {
1161 cx.app_lifecycle_observers
1162 .clone()
1163 .retain(|callback| callback(phase, cx));
1164 });
1165 }
1166 }
1167 }));
1168
1169 platform.on_memory_warning(Box::new({
1170 let app = Rc::downgrade(&app);
1171 move || {
1172 if let Some(app) = app.upgrade() {
1173 app.borrow_mut().update(|cx| {
1174 cx.memory_warning_observers
1175 .clone()
1176 .retain(|callback| callback(cx));
1177 });
1178 }
1179 }
1180 }));
1181
1182 platform.on_power_mode_change(Box::new({
1183 let app = Rc::downgrade(&app);
1184 move || {
1185 if let Some(app) = app.upgrade() {
1186 let power_mode = app.borrow().platform.power_mode();
1187 app.borrow_mut().power_mode = power_mode;
1188 }
1189 }
1190 }));
1191
1192 platform.on_quit(Box::new({
1193 let cx = Rc::downgrade(&app);
1194 move || {
1195 let Some(cx) = cx.upgrade() else {
1196 return true;
1197 };
1198 match cx.try_borrow_mut() {
1199 Ok(mut cx) => {
1200 cx.shutdown();
1201 true
1202 }
1203 Err(_) => {
1204 false
1207 }
1208 }
1209 }
1210 }));
1211
1212 app
1213 }
1214
1215 #[doc(hidden)]
1216 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1217 self.entities.ref_counts_drop_handle()
1218 }
1219
1220 #[cfg(any(test, gpui_leak_detection))]
1226 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1227 self.entities.leak_detector_snapshot()
1228 }
1229
1230 #[cfg(any(test, gpui_leak_detection))]
1242 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1243 self.entities.assert_no_new_leaks(snapshot)
1244 }
1245
1246 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1248 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1249 LeakDetectorSnapshot::default()
1250 }
1251
1252 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1255 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1256
1257 pub fn shutdown(&mut self) {
1263 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1266 let hang_monitor_flush = self
1267 .hang_monitor
1268 .as_ref()
1269 .and_then(|hang_monitor| hang_monitor.request_flush());
1270
1271 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1272
1273 for observer in self.quit_observers.remove() {
1274 futures.push(observer(self));
1275 }
1276
1277 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1278 if let Some(flushed) = hang_monitor_flush {
1279 futures.push(
1280 async move {
1281 if flushed.await.is_err() {
1282 log::warn!("hang monitor exited before flushing");
1283 }
1284 }
1285 .boxed_local(),
1286 );
1287 }
1288
1289 self.windows.clear();
1290 self.window_handles.clear();
1291 self.flush_effects();
1292 self.quitting = true;
1293
1294 let futures = futures::future::join_all(futures);
1295 #[cfg(not(target_family = "wasm"))]
1296 if self
1297 .foreground_executor
1298 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1299 .is_err()
1300 {
1301 log::error!("timed out waiting on app_will_quit");
1302 }
1303 #[cfg(target_family = "wasm")]
1304 self.foreground_executor.spawn(futures).detach();
1305
1306 self.quitting = false;
1307 }
1308
1309 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1311 self.keyboard_layout.as_ref()
1312 }
1313
1314 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1316 &self.keyboard_mapper
1317 }
1318
1319 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1321 where
1322 F: 'static + FnMut(&mut App),
1323 {
1324 self.keyboard_layout_observers.insert(Box::new(move |cx| {
1325 callback(cx);
1326 true
1327 }))
1328 }
1329
1330 pub fn quit(&self) {
1332 self.platform.quit();
1333 }
1334
1335 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1349 if !self.windows.is_empty() {
1350 return Task::ready(Err(anyhow::anyhow!(
1351 "cannot switch windowing modes while windows are open"
1352 )));
1353 }
1354 self.platform.request_windowing(request)
1355 }
1356
1357 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1367 self.platform.graphical_environment()
1368 }
1369
1370 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1373 self.cursor_hide_mode
1374 }
1375
1376 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1379 self.cursor_hide_mode = mode;
1380 }
1381
1382 pub fn is_cursor_visible(&self) -> bool {
1388 self.platform.is_cursor_visible()
1389 }
1390
1391 pub fn reduce_motion(&self) -> bool {
1394 self.reduce_motion
1395 }
1396
1397 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1400 if self.reduce_motion != reduce_motion {
1401 self.reduce_motion = reduce_motion;
1402 self.refresh_windows();
1403 }
1404 }
1405
1406 pub fn refresh_windows(&mut self) {
1409 self.pending_effects.push_back(Effect::RefreshWindows);
1410 }
1411
1412 #[inline(always)]
1413 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1414 self.start_update();
1415 let result = update(self);
1416 self.finish_update();
1417 result
1418 }
1419
1420 pub(crate) fn start_update(&mut self) {
1421 self.pending_updates += 1;
1422 }
1423
1424 #[inline(never)]
1425 pub(crate) fn finish_update(&mut self) {
1426 if self.pending_updates == 1 {
1427 self.flush_effects();
1428 }
1429 self.pending_updates -= 1;
1430 }
1431
1432 pub fn observe<W>(
1434 &mut self,
1435 entity: &Entity<W>,
1436 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1437 ) -> Subscription
1438 where
1439 W: 'static,
1440 {
1441 self.observe_internal(entity, move |e, cx| {
1442 on_notify(e, cx);
1443 true
1444 })
1445 }
1446
1447 pub(crate) fn detect_accessed_entities<R>(
1448 &mut self,
1449 callback: impl FnOnce(&mut App) -> R,
1450 ) -> (R, FxHashSet<EntityId>) {
1451 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1452 let result = callback(self);
1453 let entities_accessed_in_callback = self
1454 .entities
1455 .accessed_entities
1456 .get_mut()
1457 .difference(&accessed_entities_start)
1458 .copied()
1459 .collect::<FxHashSet<EntityId>>();
1460 (result, entities_accessed_in_callback)
1461 }
1462
1463 pub(crate) fn record_entities_accessed(
1464 &mut self,
1465 window_handle: AnyWindowHandle,
1466 invalidator: WindowInvalidator,
1467 entities: &FxHashSet<EntityId>,
1468 ) {
1469 let mut tracked_entities =
1470 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1471 for entity in tracked_entities.iter() {
1472 self.window_invalidators_by_entity
1473 .entry(*entity)
1474 .and_modify(|windows| {
1475 windows.remove(&window_handle.id);
1476 });
1477 }
1478 for entity in entities.iter() {
1479 self.window_invalidators_by_entity
1480 .entry(*entity)
1481 .or_default()
1482 .insert(window_handle.id, invalidator.clone());
1483 self.current_window_by_entity
1484 .insert(*entity, window_handle.id);
1485 }
1486 tracked_entities.clear();
1487 tracked_entities.extend(entities.iter().copied());
1488 self.tracked_entities
1489 .insert(window_handle.id, tracked_entities);
1490 }
1491
1492 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1493 let (subscription, activate) = self.observers.insert_pending(key, value);
1494 self.defer(move |_| activate());
1495 subscription
1496 }
1497
1498 pub(crate) fn observe_internal<W>(
1499 &mut self,
1500 entity: &Entity<W>,
1501 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1502 ) -> Subscription
1503 where
1504 W: 'static,
1505 {
1506 let entity_id = entity.entity_id();
1507 let handle = entity.downgrade();
1508 self.new_observer(
1509 entity_id,
1510 Box::new(move |cx| {
1511 if let Some(entity) = handle.upgrade() {
1512 on_notify(entity, cx)
1513 } else {
1514 false
1515 }
1516 }),
1517 )
1518 }
1519
1520 pub fn subscribe<T, Event>(
1523 &mut self,
1524 entity: &Entity<T>,
1525 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1526 ) -> Subscription
1527 where
1528 T: 'static + EventEmitter<Event>,
1529 Event: 'static,
1530 {
1531 self.subscribe_internal(entity, move |entity, event, cx| {
1532 on_event(entity, event, cx);
1533 true
1534 })
1535 }
1536
1537 pub(crate) fn new_subscription(
1538 &mut self,
1539 key: EntityId,
1540 value: (TypeId, Listener),
1541 ) -> Subscription {
1542 let (subscription, activate) = self.event_listeners.insert_pending(key, value);
1543 self.defer(move |_| activate());
1544 subscription
1545 }
1546 pub(crate) fn subscribe_internal<T, Evt>(
1547 &mut self,
1548 entity: &Entity<T>,
1549 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1550 ) -> Subscription
1551 where
1552 T: 'static + EventEmitter<Evt>,
1553 Evt: 'static,
1554 {
1555 let entity_id = entity.entity_id();
1556 let handle = entity.downgrade();
1557 self.new_subscription(
1558 entity_id,
1559 (
1560 TypeId::of::<Evt>(),
1561 Box::new(move |event, cx| {
1562 let event: &Evt = event.downcast_ref().expect("invalid event type");
1563 if let Some(entity) = handle.upgrade() {
1564 on_event(entity, event, cx)
1565 } else {
1566 false
1567 }
1568 }),
1569 ),
1570 )
1571 }
1572
1573 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1577 self.windows
1578 .keys()
1579 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1580 .collect()
1581 }
1582
1583 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1589 self.platform.window_stack()
1590 }
1591
1592 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1594 self.platform.active_window()
1595 }
1596
1597 pub fn open_window<V: 'static + Render>(
1601 &mut self,
1602 options: crate::WindowOptions,
1603 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1604 ) -> anyhow::Result<WindowHandle<V>> {
1605 self.update(|cx| {
1606 let id = cx.windows.insert(None);
1607 let handle = WindowHandle::new(id);
1608 match Window::new(handle.into(), options, cx) {
1609 Ok(mut window) => {
1610 cx.window_update_stack.push(id);
1611 let root_view = build_root_view(&mut window, cx);
1612 cx.window_update_stack.pop();
1613 window.root.replace(root_view.into());
1614 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1615
1616 let clear = window.draw(cx);
1621 clear.clear(cx);
1622
1623 cx.window_handles.insert(id, window.handle);
1624 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1625 Ok(handle)
1626 }
1627 Err(e) => {
1628 cx.windows.remove(id);
1629 Err(e)
1630 }
1631 }
1632 })
1633 }
1634
1635 pub fn activate(&self, ignoring_other_apps: bool) {
1637 self.platform.activate(ignoring_other_apps);
1638 }
1639
1640 pub fn hide(&self) {
1642 self.platform.hide();
1643 }
1644
1645 pub fn hide_other_apps(&self) {
1647 self.platform.hide_other_apps();
1648 }
1649
1650 pub fn unhide_other_apps(&self) {
1652 self.platform.unhide_other_apps();
1653 }
1654
1655 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1657 self.platform.displays()
1658 }
1659
1660 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1662 self.platform.primary_display()
1663 }
1664
1665 pub fn is_screen_capture_supported(&self) -> bool {
1667 self.platform.is_screen_capture_supported()
1668 }
1669
1670 pub fn screen_capture_sources(
1672 &self,
1673 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1674 self.platform.screen_capture_sources()
1675 }
1676
1677 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1679 self.displays()
1680 .iter()
1681 .find(|display| display.id() == id)
1682 .cloned()
1683 }
1684
1685 pub fn thermal_state(&self) -> ThermalState {
1687 self.platform.thermal_state()
1688 }
1689
1690 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1692 self.platform.prevent_idle_sleep(reason)
1693 }
1694
1695 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1697 where
1698 F: 'static + FnMut(&mut App),
1699 {
1700 self.thermal_state_observers.insert(Box::new(move |cx| {
1701 callback(cx);
1702 true
1703 }))
1704 }
1705
1706 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1711 where
1712 F: 'static + FnMut(&mut App),
1713 {
1714 self.system_sleep_observers.insert(Box::new(move |cx| {
1715 callback(cx);
1716 true
1717 }))
1718 }
1719
1720 pub(crate) fn displays_changed(&mut self) {
1721 let current = read_displays(self.platform.as_ref());
1722 let events = display_events(&self.displays, ¤t);
1723 self.displays = current;
1724 for event in &events {
1725 let DisplayEvent::Changed { id, .. } = *event else {
1726 continue;
1727 };
1728 for handle in self.windows() {
1729 self.update_window(handle, |_, window, cx| {
1730 if window.display_id == Some(id) {
1731 window.notify_display_observers(cx);
1732 }
1733 })
1734 .log_err();
1735 }
1736 }
1737 for event in events {
1738 self.display_observers
1739 .clone()
1740 .retain(|callback| (callback)(event, self));
1741 }
1742 }
1743
1744 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1745 self.displays.contains_key(&id)
1746 }
1747
1748 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1751 self.displays.get(&id)?.refresh_interval
1752 }
1753
1754 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1757 where
1758 F: 'static + FnMut(DisplayEvent, &mut App),
1759 {
1760 self.display_observers.insert(Box::new(move |event, cx| {
1761 callback(event, cx);
1762 true
1763 }))
1764 }
1765
1766 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1768 where
1769 F: 'static + FnMut(&mut App),
1770 {
1771 self.system_wake_observers.insert(Box::new(move |cx| {
1772 callback(cx);
1773 true
1774 }))
1775 }
1776
1777 pub fn on_app_lifecycle(
1785 &self,
1786 mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
1787 ) -> Subscription {
1788 self.app_lifecycle_observers
1789 .insert(Box::new(move |phase, cx| {
1790 callback(phase, cx);
1791 true
1792 }))
1793 }
1794
1795 pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
1798 self.memory_warning_observers.insert(Box::new(move |cx| {
1799 callback(cx);
1800 true
1801 }))
1802 }
1803
1804 pub fn window_appearance(&self) -> WindowAppearance {
1806 self.platform.window_appearance()
1807 }
1808
1809 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1820 self.platform.set_window_appearance(appearance);
1821 }
1822
1823 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1825 self.platform.button_layout()
1826 }
1827
1828 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1830 self.platform.read_from_clipboard()
1831 }
1832
1833 pub fn read_from_clipboard_async(
1841 &self,
1842 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1843 self.platform.read_from_clipboard_async()
1844 }
1845
1846 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1848 self.text_rendering_mode.set(mode);
1849 }
1850
1851 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1853 self.text_rendering_mode.get()
1854 }
1855
1856 pub fn power_mode(&self) -> PowerMode {
1859 self.power_mode
1860 }
1861
1862 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1864 self.platform.write_to_clipboard(item)
1865 }
1866
1867 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1870 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1871 self.platform.read_from_primary()
1872 }
1873
1874 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1877 pub fn write_to_primary(&self, item: ClipboardItem) {
1878 self.platform.write_to_primary(item)
1879 }
1880
1881 #[cfg(target_os = "macos")]
1887 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1888 self.platform.read_from_find_pasteboard()
1889 }
1890
1891 #[cfg(target_os = "macos")]
1897 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1898 self.platform.write_to_find_pasteboard(item)
1899 }
1900
1901 pub fn write_credentials(
1903 &self,
1904 url: &str,
1905 username: &str,
1906 password: &[u8],
1907 ) -> Task<Result<()>> {
1908 self.platform.write_credentials(url, username, password)
1909 }
1910
1911 #[cfg(target_os = "macos")]
1919 pub fn write_credentials_if_not_exists(
1920 &self,
1921 url: &str,
1922 username: &str,
1923 password: &[u8],
1924 ) -> Task<Result<bool>> {
1925 self.platform
1926 .write_credentials_if_not_exists(url, username, password)
1927 }
1928
1929 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1931 self.platform.read_credentials(url)
1932 }
1933
1934 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1936 self.platform.delete_credentials(url)
1937 }
1938
1939 pub fn open_url(&self, url: &str) {
1941 self.platform.open_url(url);
1942 }
1943
1944 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1951 self.platform.register_url_scheme(scheme)
1952 }
1953
1954 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1961 self.platform.set_app_identity(identifier, name);
1962 }
1963
1964 pub fn show_system_notification(&self, notification: SystemNotification) {
1971 self.platform.show_system_notification(notification);
1972 }
1973
1974 pub fn dismiss_system_notification(&self, tag: &str) {
1979 self.platform.dismiss_system_notification(tag);
1980 }
1981
1982 pub fn on_system_notification_response<F>(&self, mut callback: F)
1986 where
1987 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1988 {
1989 let this = self.this.clone();
1990 self.platform
1991 .on_system_notification_response(Box::new(move |response| {
1992 if let Some(app) = this.upgrade() {
1993 callback(response, &mut app.borrow_mut());
1994 }
1995 }));
1996 }
1997
1998 pub fn app_path(&self) -> Result<PathBuf> {
2002 self.platform.app_path()
2003 }
2004
2005 pub fn compositor_name(&self) -> &'static str {
2009 self.platform.compositor_name()
2010 }
2011
2012 pub fn platform_info(&self) -> crate::PlatformInfo {
2014 self.platform.platform_info()
2015 }
2016
2017 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
2019 self.platform.path_for_auxiliary_executable(name)
2020 }
2021
2022 pub fn prompt_for_paths(
2028 &self,
2029 options: PathPromptOptions,
2030 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
2031 self.platform.prompt_for_paths(options)
2032 }
2033
2034 pub fn prompt_for_new_path(
2041 &self,
2042 directory: &Path,
2043 suggested_name: Option<&str>,
2044 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
2045 self.platform.prompt_for_new_path(directory, suggested_name)
2046 }
2047
2048 pub fn reveal_path(&self, path: &Path) {
2050 self.platform.reveal_path(path)
2051 }
2052
2053 pub fn open_with_system(&self, path: &Path) {
2055 self.platform.open_with_system(path)
2056 }
2057
2058 pub fn should_auto_hide_scrollbars(&self) -> bool {
2060 self.platform.should_auto_hide_scrollbars()
2061 }
2062
2063 pub fn restart(&mut self) {
2065 self.restart_observers
2066 .clone()
2067 .retain(|observer| observer(self));
2068 self.platform.restart(
2069 self.restart_path.take(),
2070 std::mem::take(&mut self.restart_arguments),
2071 )
2072 }
2073
2074 pub fn set_restart_path(&mut self, path: PathBuf) {
2076 self.restart_path = Some(path);
2077 }
2078
2079 pub fn http_client(&self) -> Arc<dyn HttpClient> {
2081 self.http_client.clone()
2082 }
2083
2084 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
2086 self.http_client = new_client;
2087 }
2088
2089 pub fn set_quit_mode(&mut self, mode: QuitMode) {
2092 self.quit_mode = mode;
2093 }
2094
2095 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
2104 self.platform.set_activation_policy(policy);
2105 }
2106
2107 pub fn svg_renderer(&self) -> SvgRenderer {
2109 self.svg_renderer.clone()
2110 }
2111
2112 pub(crate) fn push_effect(&mut self, effect: Effect) {
2113 match &effect {
2114 Effect::Notify { emitter } => {
2115 if !self.pending_notifications.insert(*emitter) {
2116 return;
2117 }
2118 }
2119 Effect::NotifyGlobalObservers { global_type } => {
2120 if !self.pending_global_notifications.insert(*global_type) {
2121 return;
2122 }
2123 }
2124 _ => {}
2125 };
2126
2127 self.pending_effects.push_back(effect);
2128 }
2129
2130 fn flush_effects(&mut self) {
2134 loop {
2135 self.release_dropped_entities();
2136 self.release_dropped_focus_handles();
2137 if let Some(effect) = self.pending_effects.pop_front() {
2138 match effect {
2139 Effect::Notify { emitter } => {
2140 self.apply_notify_effect(emitter);
2141 }
2142
2143 Effect::Emit {
2144 emitter,
2145 event_type,
2146 event,
2147 } => self.apply_emit_effect(emitter, event_type, &*event),
2148
2149 Effect::RefreshWindows => {
2150 self.apply_refresh_effect();
2151 }
2152
2153 Effect::NotifyGlobalObservers { global_type } => {
2154 self.apply_notify_global_observers_effect(global_type);
2155 }
2156
2157 Effect::Defer { callback } => {
2158 self.apply_defer_effect(callback);
2159 }
2160 Effect::EntityCreated {
2161 entity,
2162 tid,
2163 window,
2164 } => {
2165 self.apply_entity_created_effect(entity, tid, window);
2166 }
2167 }
2168 } else {
2169 #[cfg(any(test, feature = "test-support"))]
2170 if matches!(self.mode, GpuiMode::Test { .. }) {
2171 for window in self
2172 .windows
2173 .values()
2174 .filter_map(|window| {
2175 let window = window.as_deref()?;
2176 window.invalidator.is_dirty().then_some(window.handle)
2177 })
2178 .collect::<Vec<_>>()
2179 {
2180 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2181 .unwrap();
2182 }
2183 }
2184
2185 if self.pending_effects.is_empty() {
2186 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2187 if window.invalidator.is_dirty()
2188 || window.needs_present.get()
2189 || !window.next_frame_callbacks.borrow().is_empty()
2190 {
2191 window.platform_window.schedule_frame();
2192 }
2193 }
2194
2195 self.event_arena.clear();
2196 break;
2197 }
2198 }
2199 }
2200 }
2201
2202 fn release_dropped_entities(&mut self) {
2206 loop {
2207 let dropped = self.entities.take_dropped();
2208 if dropped.is_empty() {
2209 break;
2210 }
2211
2212 for (entity_id, mut entity) in dropped {
2213 self.observers.remove(&entity_id);
2214 self.event_listeners.remove(&entity_id);
2215 self.window_invalidators_by_entity.remove(&entity_id);
2216 self.current_window_by_entity.remove(&entity_id);
2217 for release_callback in self.release_listeners.remove(&entity_id) {
2218 release_callback(entity.as_mut(), self);
2219 }
2220 }
2221 }
2222 }
2223
2224 fn release_dropped_focus_handles(&mut self) {
2226 let focus_handles = self.focus_handles.clone();
2227 let mut focus_handles = focus_handles.write();
2228 let FocusMap {
2229 handles,
2230 dropped_handles,
2231 } = &mut *focus_handles;
2232 if dropped_handles.is_empty() {
2233 return;
2234 }
2235
2236 let windows = self
2237 .windows
2238 .values()
2239 .filter_map(|window| {
2240 let window = window.as_ref()?;
2241 dropped_handles
2242 .contains(&window.focus?)
2243 .then_some(window.handle)
2244 })
2245 .collect::<SmallVec<[_; 1]>>();
2246 for handle_id in dropped_handles.drain(..) {
2247 handles.remove(handle_id);
2248 }
2249 drop(focus_handles);
2250
2251 for window_handle in windows {
2252 window_handle
2253 .update(self, |_, window, cx| window.blur(cx))
2254 .ok();
2255 }
2256 }
2257
2258 fn apply_notify_effect(&mut self, emitter: EntityId) {
2259 self.pending_notifications.remove(&emitter);
2260
2261 self.observers
2262 .clone()
2263 .retain(&emitter, |handler| handler(self));
2264 }
2265
2266 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2267 self.event_listeners
2268 .clone()
2269 .retain(&emitter, |(stored_type, handler)| {
2270 if *stored_type == event_type {
2271 handler(event, self)
2272 } else {
2273 true
2274 }
2275 });
2276 }
2277
2278 fn apply_refresh_effect(&mut self) {
2279 for window in self.windows.values_mut() {
2280 if let Some(window) = window.as_deref_mut() {
2281 window.refreshing = true;
2282 window.invalidator.set_dirty(true);
2283 }
2284 }
2285 }
2286
2287 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2288 self.pending_global_notifications.remove(&type_id);
2289 self.global_observers
2290 .clone()
2291 .retain(&type_id, |observer| observer(self));
2292 }
2293
2294 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2295 callback(self);
2296 }
2297
2298 fn apply_entity_created_effect(
2299 &mut self,
2300 entity: AnyEntity,
2301 tid: TypeId,
2302 window: Option<WindowId>,
2303 ) {
2304 if let Some(id) = window {
2308 self.current_window_by_entity.insert(entity.entity_id(), id);
2309 }
2310
2311 self.new_entity_observers.clone().retain(&tid, |observer| {
2312 if let Some(id) = window {
2313 self.update_window_id(id, {
2314 let entity = entity.clone();
2315 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2316 })
2317 .expect("All windows should be off the stack when flushing effects");
2318 } else {
2319 (observer)(entity.clone(), &mut None, self)
2320 }
2321 true
2322 });
2323 }
2324
2325 #[inline(always)]
2331 pub fn with_window<R>(
2332 &mut self,
2333 entity_id: EntityId,
2334 f: impl FnOnce(&mut Window, &mut App) -> R,
2335 ) -> Option<R> {
2336 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2337 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2338 .ok()
2339 }
2340
2341 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2342 self.current_window_by_entity
2343 .entry(entity_id)
2344 .or_insert(window);
2345 }
2346
2347 #[inline(always)]
2348 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2349 where
2350 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2351 {
2352 let mut update = Some(update);
2353 let mut result = None;
2354 self.update_window_erased(id, &mut |arguments| {
2355 if let Some((root_view, window, cx)) = arguments {
2356 result = Some(update.take().unwrap()(root_view, window, cx));
2357 } else {
2358 drop(update.take());
2359 drop(result.take());
2360 }
2361 });
2362 result.context("window not found")
2363 }
2364
2365 pub fn to_async(&self) -> AsyncApp {
2368 AsyncApp {
2369 app: self.this.clone(),
2370 background_executor: self.background_executor.clone(),
2371 foreground_executor: self.foreground_executor.clone(),
2372 }
2373 }
2374
2375 pub fn background_executor(&self) -> &BackgroundExecutor {
2377 &self.background_executor
2378 }
2379
2380 pub fn is_test(&self) -> bool {
2383 self.background_executor.is_test()
2384 }
2385
2386 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2388 if self.quitting {
2389 panic!("Can't spawn on main thread after on_app_quit")
2390 };
2391 &self.foreground_executor
2392 }
2393
2394 #[cfg(feature = "profiler")]
2397 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2398 self.foreground_journal.clone()
2399 }
2400
2401 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2418 pub fn start_hang_monitor(
2419 &mut self,
2420 config: crate::profiler::hang::HangMonitorConfig,
2421 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2422 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2423 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2424
2425 if self.hang_monitor.is_some() {
2426 debug_assert!(false, "the hang monitor was started twice");
2427 return Err(HangMonitorError::AlreadyStarted);
2428 }
2429 let detector = HangDetector::new(
2430 self.foreground_journal(),
2431 config.threshold,
2432 config.frame_budget,
2433 );
2434 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2435 .map_err(HangMonitorError::Spawn)?;
2436 self.hang_monitor = Some(monitor);
2437 Ok(())
2438 }
2439
2440 #[track_caller]
2443 #[inline(always)]
2444 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2445 where
2446 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2447 R: 'static,
2448 {
2449 let mut cx = self.prepare_spawn();
2450
2451 self.foreground_executor
2452 .spawn(async move { f(&mut cx).await }.boxed_local())
2453 }
2454
2455 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2459 where
2460 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2461 R: 'static,
2462 {
2463 if self.quitting {
2464 debug_panic!("Can't spawn on main thread after on_app_quit")
2465 };
2466
2467 let mut cx = self.to_async();
2468
2469 self.foreground_executor
2470 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2471 }
2472
2473 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2476 self.push_effect(Effect::Defer {
2477 callback: Box::new(f),
2478 });
2479 }
2480
2481 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2483 &self.asset_source
2484 }
2485
2486 pub fn text_system(&self) -> &Arc<TextSystem> {
2488 &self.text_system
2489 }
2490
2491 pub fn on_missing_glyphs(
2502 &self,
2503 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2504 ) -> Subscription {
2505 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2506
2507 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2508 let callback = self.missing_glyph_callback.clone();
2509 self.spawn(async move |cx| {
2510 while let Ok(missing_glyphs) = receiver.recv().await {
2511 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2512 }
2513 })
2514 .detach();
2515 }
2516 self.text_system.enable_missing_glyph_reporting();
2517
2518 let callback = self.missing_glyph_callback.clone();
2519 let text_system = self.text_system.clone();
2520 Subscription::new(move || {
2521 if callback.remove(®istration) {
2522 text_system.disable_missing_glyph_reporting();
2523 }
2524 })
2525 }
2526
2527 pub fn has_global<G: Global>(&self) -> bool {
2529 self.globals_by_type.contains_key(&TypeId::of::<G>())
2530 }
2531
2532 #[track_caller]
2534 pub fn global<G: Global>(&self) -> &G {
2535 self.globals_by_type
2536 .get(&TypeId::of::<G>())
2537 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2538 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2539 }
2540
2541 pub fn try_global<G: Global>(&self) -> Option<&G> {
2543 self.globals_by_type
2544 .get(&TypeId::of::<G>())
2545 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2546 }
2547
2548 #[track_caller]
2550 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2551 let global_type = TypeId::of::<G>();
2552 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2553 self.globals_by_type
2554 .get_mut(&global_type)
2555 .and_then(|any_state| any_state.downcast_mut::<G>())
2556 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2557 }
2558
2559 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2562 let global_type = TypeId::of::<G>();
2563 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2564 self.globals_by_type
2565 .entry(global_type)
2566 .or_insert_with(|| Box::<G>::default())
2567 .downcast_mut::<G>()
2568 .unwrap()
2569 }
2570
2571 pub fn set_global<G: Global>(&mut self, global: G) {
2573 let global_type = TypeId::of::<G>();
2574 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2575 self.globals_by_type.insert(global_type, Box::new(global));
2576 }
2577
2578 #[cfg(any(test, feature = "test-support"))]
2580 pub fn clear_globals(&mut self) {
2581 self.globals_by_type.drain();
2582 }
2583
2584 pub fn remove_global<G: Global>(&mut self) -> G {
2586 let global_type = TypeId::of::<G>();
2587 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2588 *self
2589 .globals_by_type
2590 .remove(&global_type)
2591 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2592 .downcast()
2593 .unwrap()
2594 }
2595
2596 pub fn observe_global<G: Global>(
2598 &mut self,
2599 mut f: impl FnMut(&mut Self) + 'static,
2600 ) -> Subscription {
2601 let (subscription, activate) = self.global_observers.insert_pending(
2602 TypeId::of::<G>(),
2603 Box::new(move |cx| {
2604 f(cx);
2605 true
2606 }),
2607 );
2608 self.defer(move |_| activate());
2609 subscription
2610 }
2611
2612 #[track_caller]
2614 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2615 GlobalLease::new(
2616 self.globals_by_type
2617 .remove(&TypeId::of::<G>())
2618 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2619 .unwrap(),
2620 )
2621 }
2622
2623 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2625 let global_type = TypeId::of::<G>();
2626
2627 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2628 self.globals_by_type.insert(global_type, lease.global);
2629 }
2630
2631 pub(crate) fn new_entity_observer(
2632 &self,
2633 key: TypeId,
2634 value: NewEntityListener,
2635 ) -> Subscription {
2636 self.new_entity_observers.insert(key, value)
2637 }
2638
2639 pub fn observe_new<T: 'static>(
2642 &self,
2643 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2644 ) -> Subscription {
2645 self.new_entity_observer(
2646 TypeId::of::<T>(),
2647 Box::new(
2648 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2649 any_entity
2650 .downcast::<T>()
2651 .unwrap()
2652 .update(cx, |entity_state, cx| {
2653 on_new(entity_state, window.as_deref_mut(), cx)
2654 })
2655 },
2656 ),
2657 )
2658 }
2659
2660 pub fn observe_release<T>(
2663 &self,
2664 handle: &Entity<T>,
2665 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2666 ) -> Subscription
2667 where
2668 T: 'static,
2669 {
2670 self.release_listeners.insert(
2671 handle.entity_id(),
2672 Box::new(move |entity, cx| {
2673 let entity = entity.downcast_mut().expect("invalid entity type");
2674 on_release(entity, cx)
2675 }),
2676 )
2677 }
2678
2679 pub fn observe_release_in<T>(
2682 &self,
2683 handle: &Entity<T>,
2684 window: &Window,
2685 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2686 ) -> Subscription
2687 where
2688 T: 'static,
2689 {
2690 let window_handle = window.handle;
2691 self.observe_release(handle, move |entity, cx| {
2692 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2693 })
2694 }
2695
2696 pub fn observe_keystrokes(
2701 &mut self,
2702 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2703 ) -> Subscription {
2704 self.keystroke_observers
2705 .insert(Box::new(move |event, window, cx| {
2706 f(event, window, cx);
2707 true
2708 }))
2709 }
2710
2711 pub fn intercept_keystrokes(
2716 &mut self,
2717 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2718 ) -> Subscription {
2719 self.keystroke_interceptors
2720 .insert(Box::new(move |event, window, cx| {
2721 f(event, window, cx);
2722 true
2723 }))
2724 }
2725
2726 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2728 self.keymap.borrow_mut().add_bindings(bindings);
2729 self.pending_effects.push_back(Effect::RefreshWindows);
2730 }
2731
2732 pub fn clear_key_bindings(&mut self) {
2734 self.keymap.borrow_mut().clear();
2735 self.pending_effects.push_back(Effect::RefreshWindows);
2736 }
2737
2738 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2740 self.keymap.clone()
2741 }
2742
2743 pub fn on_action<A: Action>(
2747 &mut self,
2748 listener: impl Fn(&A, &mut Self) + 'static,
2749 ) -> &mut Self {
2750 self.global_action_listeners
2751 .entry(TypeId::of::<A>())
2752 .or_default()
2753 .push(Rc::new(move |action, phase, cx| {
2754 if phase == DispatchPhase::Bubble {
2755 let action = action.downcast_ref().unwrap();
2756 listener(action, cx)
2757 }
2758 }));
2759 self
2760 }
2761
2762 pub fn stop_propagation(&mut self) {
2767 self.propagate_event = false;
2768 }
2769
2770 pub fn propagate(&mut self) {
2775 self.propagate_event = true;
2776 }
2777
2778 pub fn build_action(
2780 &self,
2781 name: &str,
2782 data: Option<serde_json::Value>,
2783 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2784 self.actions.build_action(name, data)
2785 }
2786
2787 pub fn all_action_names(&self) -> &[&'static str] {
2790 self.actions.all_action_names()
2791 }
2792
2793 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2797 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2798 }
2799
2800 pub fn action_schemas(
2802 &self,
2803 generator: &mut schemars::SchemaGenerator,
2804 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2805 self.actions.action_schemas(generator)
2806 }
2807
2808 pub fn action_schema_by_name(
2813 &self,
2814 name: &str,
2815 generator: &mut schemars::SchemaGenerator,
2816 ) -> Option<Option<schemars::Schema>> {
2817 self.actions.action_schema_by_name(name, generator)
2818 }
2819
2820 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2822 self.actions.deprecated_aliases()
2823 }
2824
2825 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2827 self.actions.deprecation_messages()
2828 }
2829
2830 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2832 self.actions.documentation()
2833 }
2834
2835 pub fn on_app_quit<Fut>(
2838 &self,
2839 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2840 ) -> Subscription
2841 where
2842 Fut: 'static + Future<Output = ()>,
2843 {
2844 self.quit_observers.insert(Box::new(move |cx| {
2845 let future = on_quit(cx);
2846 future.boxed_local()
2847 }))
2848 }
2849
2850 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2854 self.restart_observers.insert(Box::new(move |cx| {
2855 on_restart(cx);
2856 true
2857 }))
2858 }
2859
2860 pub fn on_window_closed(
2863 &self,
2864 on_closed: impl FnMut(&mut App, WindowId) + 'static,
2865 ) -> Subscription {
2866 self.window_closed_observers.insert(Box::new(on_closed))
2867 }
2868
2869 pub(crate) fn clear_pending_keystrokes(&mut self) {
2870 for window in self.windows() {
2871 window
2872 .update(self, |_, window, cx| {
2873 window.clear_pending_keystrokes(cx);
2874 })
2875 .ok();
2876 }
2877 }
2878
2879 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2882 let mut action_available = false;
2883 if let Some(window) = self.active_window()
2884 && let Ok(window_action_available) =
2885 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2886 {
2887 action_available = window_action_available;
2888 }
2889
2890 action_available
2891 || self
2892 .global_action_listeners
2893 .contains_key(&action.as_any().type_id())
2894 }
2895
2896 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2898 let menus: Vec<Menu> = menus.into_iter().collect();
2899 self.platform.set_menus(menus, &self.keymap.borrow());
2900 }
2901
2902 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2904 self.platform.get_menus()
2905 }
2906
2907 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2909 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2910 }
2911
2912 pub fn perform_dock_menu_action(&self, action: usize) {
2914 self.platform.perform_dock_menu_action(action);
2915 }
2916
2917 pub fn add_recent_document(&self, path: &Path) {
2922 self.platform.add_recent_document(path);
2923 }
2924
2925 pub fn update_jump_list(
2928 &self,
2929 menus: Vec<MenuItem>,
2930 entries: Vec<SmallVec<[PathBuf; 2]>>,
2931 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2932 self.platform.update_jump_list(menus, entries)
2933 }
2934
2935 pub fn dispatch_action(&mut self, action: &dyn Action) {
2938 if let Some(active_window) = self.active_window() {
2939 active_window
2940 .update(self, |_, window, cx| {
2941 window.dispatch_action(action.boxed_clone(), cx)
2942 })
2943 .log_err();
2944 } else {
2945 self.dispatch_global_action(action);
2946 }
2947 }
2948
2949 fn dispatch_global_action(&mut self, action: &dyn Action) {
2950 self.propagate_event = true;
2951
2952 if let Some(mut global_listeners) = self
2953 .global_action_listeners
2954 .remove(&action.as_any().type_id())
2955 {
2956 for listener in &global_listeners {
2957 listener(action.as_any(), DispatchPhase::Capture, self);
2958 if !self.propagate_event {
2959 break;
2960 }
2961 }
2962
2963 global_listeners.extend(
2964 self.global_action_listeners
2965 .remove(&action.as_any().type_id())
2966 .unwrap_or_default(),
2967 );
2968
2969 self.global_action_listeners
2970 .insert(action.as_any().type_id(), global_listeners);
2971 }
2972
2973 if self.propagate_event
2974 && let Some(mut global_listeners) = self
2975 .global_action_listeners
2976 .remove(&action.as_any().type_id())
2977 {
2978 for listener in global_listeners.iter().rev() {
2979 listener(action.as_any(), DispatchPhase::Bubble, self);
2980 if !self.propagate_event {
2981 break;
2982 }
2983 }
2984
2985 global_listeners.extend(
2986 self.global_action_listeners
2987 .remove(&action.as_any().type_id())
2988 .unwrap_or_default(),
2989 );
2990
2991 self.global_action_listeners
2992 .insert(action.as_any().type_id(), global_listeners);
2993 }
2994 }
2995
2996 pub fn has_active_drag(&self) -> bool {
2998 self.active_drag.is_some()
2999 }
3000
3001 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3003 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3004 }
3005
3006 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3008 if self.active_drag.is_some() {
3009 self.active_drag = None;
3010 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
3011 drag.source_window == window.window_handle().window_id()
3012 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3013 }) {
3014 self.platform_owned_drag = None;
3015 }
3016 window.refresh();
3017 true
3018 } else {
3019 false
3020 }
3021 }
3022
3023 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3024 let Some(drag) = self.active_drag.take() else {
3025 return false;
3026 };
3027 self.platform_owned_drag = Some(PlatformOwnedDrag {
3028 source_window,
3029 state: PlatformOwnedDragState::Suspended(drag),
3030 });
3031 true
3032 }
3033
3034 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
3035 let Some(platform_drag) = self
3036 .platform_owned_drag
3037 .as_mut()
3038 .filter(|drag| drag.source_window == source_window)
3039 else {
3040 return false;
3041 };
3042 let state = std::mem::replace(
3043 &mut platform_drag.state,
3044 PlatformOwnedDragState::RestoredInSourceWindow,
3045 );
3046 let PlatformOwnedDragState::Suspended(drag) = state else {
3047 return false;
3048 };
3049 self.active_drag = Some(drag);
3050 true
3051 }
3052
3053 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3054 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
3055 drag.source_window == source_window
3056 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3057 }) else {
3058 return false;
3059 };
3060 let Some(drag) = self.active_drag.take() else {
3061 return false;
3062 };
3063 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
3064 true
3065 }
3066
3067 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
3068 if !self
3069 .platform_owned_drag
3070 .as_ref()
3071 .is_some_and(|drag| drag.source_window == source_window)
3072 {
3073 return false;
3074 }
3075 self.platform_owned_drag = None;
3076 self.active_drag = None;
3077 true
3078 }
3079
3080 pub fn set_active_drag_cursor_style(
3082 &mut self,
3083 cursor_style: CursorStyle,
3084 window: &mut Window,
3085 ) -> bool {
3086 if let Some(ref mut drag) = self.active_drag {
3087 drag.cursor_style = Some(cursor_style);
3088 window.refresh();
3089 true
3090 } else {
3091 false
3092 }
3093 }
3094
3095 pub fn set_prompt_builder(
3098 &mut self,
3099 renderer: impl Fn(
3100 PromptLevel,
3101 &str,
3102 Option<&str>,
3103 &[PromptButton],
3104 PromptHandle,
3105 &mut Window,
3106 &mut App,
3107 ) -> RenderablePromptHandle
3108 + 'static,
3109 ) {
3110 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3111 }
3112
3113 pub fn reset_prompt_builder(&mut self) {
3115 self.prompt_builder = Some(PromptBuilder::Default);
3116 }
3117
3118 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3120 let asset_id = (TypeId::of::<A>(), hash(source));
3121 self.loading_assets.remove(&asset_id);
3122 }
3123
3124 #[cfg(any(test, feature = "test-support"))]
3127 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3128 let asset_id = (TypeId::of::<A>(), hash(source));
3129 self.loading_assets.contains_key(&asset_id)
3130 }
3131
3132 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3137 self.asset_entry::<A>(source).get()
3138 }
3139
3140 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3141 let asset_id = (TypeId::of::<A>(), hash(source));
3142 if !self.loading_assets.contains_key(&asset_id) {
3143 let future = A::load(source.clone(), self);
3144 let entry = CachedLoad::new(future, self);
3145 self.loading_assets.insert(asset_id, Box::new(entry));
3146 }
3147 self.loading_assets
3148 .get(&asset_id)
3149 .and_then(|entry| entry.downcast_ref())
3150 .expect("asset cache entries are keyed by their asset type")
3151 }
3152
3153 #[track_caller]
3156 pub fn focus_handle(&self) -> FocusHandle {
3157 FocusHandle::new(&self.focus_handles)
3158 }
3159
3160 pub fn notify(&mut self, entity_id: EntityId) {
3162 let window_invalidators = mem::take(
3163 self.window_invalidators_by_entity
3164 .entry(entity_id)
3165 .or_default(),
3166 );
3167
3168 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3173 .iter()
3174 .filter(|(window_id, _)| {
3175 self.tracked_entities
3176 .get(window_id)
3177 .is_some_and(|set| set.contains(&entity_id))
3178 })
3179 .map(|(_, invalidator)| invalidator.clone())
3180 .collect();
3181
3182 if live_invalidators.is_empty() {
3183 if self.pending_notifications.insert(entity_id) {
3184 self.pending_effects
3185 .push_back(Effect::Notify { emitter: entity_id });
3186 }
3187 } else {
3188 for invalidator in &live_invalidators {
3189 invalidator.invalidate_view(entity_id, self);
3190 }
3191 }
3192
3193 self.window_invalidators_by_entity
3194 .insert(entity_id, window_invalidators);
3195 }
3196
3197 #[cfg(any(test, feature = "test-support", debug_assertions))]
3199 pub fn get_name(&self) -> Option<&'static str> {
3200 self.name
3201 }
3202
3203 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3205 self.platform.can_select_mixed_files_and_dirs()
3206 }
3207
3208 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3213 for window in self.windows.values_mut().flatten() {
3215 _ = window.drop_image(image.clone());
3216 }
3217
3218 if let Some(window) = current_window {
3220 _ = window.drop_image(image);
3221 }
3222 }
3223
3224 #[cfg(debug_assertions)]
3226 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3227 self.inspector_renderer = Some(f);
3228 }
3229
3230 #[cfg(debug_assertions)]
3232 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3233 &mut self,
3234 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3235 ) where
3236 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3237 {
3238 self.inspector_element_registry.register(factory);
3239 }
3240
3241 pub fn init_colors(&mut self) {
3245 self.set_global(GlobalColors(Arc::new(Colors::default())));
3246 }
3247
3248 #[inline(never)]
3249 fn update_window_erased(
3250 &mut self,
3251 window_id: WindowId,
3252 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3253 ) {
3254 self.update(|cx| {
3255 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3256 update(None);
3257 return;
3258 };
3259
3260 let root_view = window.root.clone().unwrap();
3261
3262 cx.window_update_stack.push(window.handle.id);
3263 update(Some((root_view, &mut window, cx)));
3264 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3265 cx.window_update_stack.pop();
3266
3267 if window.removed {
3268 cx.end_platform_drag(window_id);
3269 cx.window_handles.remove(&window_id);
3270 cx.windows.remove(window_id);
3271 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3272 for entity_id in tracked {
3273 if let Some(windows) =
3274 cx.window_invalidators_by_entity.get_mut(&entity_id)
3275 {
3276 windows.remove(&window_id);
3277 }
3278 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3279 cx.current_window_by_entity.remove(&entity_id);
3280 }
3281 }
3282 }
3283
3284 cx.window_closed_observers.clone().retain(|callback| {
3285 callback(cx, window_id);
3286 true
3287 });
3288
3289 let quit_on_empty = match cx.quit_mode {
3290 QuitMode::Explicit => false,
3291 QuitMode::LastWindowClosed => true,
3292 QuitMode::Default => cfg!(not(target_os = "macos")),
3293 };
3294
3295 if quit_on_empty && cx.windows.is_empty() {
3296 cx.quit();
3297 }
3298 } else {
3299 cx.windows.get_mut(window_id)?.replace(window);
3300 }
3301 Some(())
3302 }
3303 if trail(window_id, window, cx).is_none() {
3304 update(None);
3305 }
3306 });
3307 }
3308
3309 #[inline(never)]
3310 fn update_entity_erased(
3311 &mut self,
3312 handle: &AnyEntity,
3313 entity_type: &str,
3314 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3315 ) {
3316 self.update(|cx| {
3317 let mut lease = cx.entities.lease_erased(handle, entity_type);
3318 update(lease.entity.as_deref_mut().unwrap(), cx);
3319 cx.entities.end_lease_erased(handle.entity_id, lease);
3320 });
3321 }
3322
3323 #[inline(never)]
3324 #[track_caller]
3325 fn prepare_spawn(&self) -> AsyncApp {
3326 if self.quitting {
3327 debug_panic!("Can't spawn on main thread after on_app_quit")
3328 };
3329 self.to_async()
3330 }
3331}
3332
3333impl AppContext for App {
3334 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3339 self.update(|cx| {
3340 let slot = cx.entities.reserve();
3341 let handle = slot.clone();
3342 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3343
3344 cx.push_effect(Effect::EntityCreated {
3345 entity: handle.into_any(),
3346 tid: TypeId::of::<T>(),
3347 window: cx.window_update_stack.last().cloned(),
3348 });
3349
3350 cx.entities.insert(slot, entity)
3351 })
3352 }
3353
3354 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3355 Reservation(self.entities.reserve())
3356 }
3357
3358 fn insert_entity<T: 'static>(
3359 &mut self,
3360 reservation: Reservation<T>,
3361 build_entity: impl FnOnce(&mut Context<T>) -> T,
3362 ) -> Entity<T> {
3363 self.update(|cx| {
3364 let slot = reservation.0;
3365 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3366 cx.entities.insert(slot, entity)
3367 })
3368 }
3369
3370 #[inline(always)]
3373 fn update_entity<T: 'static, R>(
3374 &mut self,
3375 handle: &Entity<T>,
3376 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3377 ) -> R {
3378 let mut update = Some(update);
3379 let mut result = None;
3380 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3381 let value = update.take().unwrap()(
3382 entity.downcast_mut::<T>().unwrap(),
3383 &mut Context::new_context(cx, handle.downgrade()),
3384 );
3385 result = Some(value);
3386 });
3387 result.unwrap()
3388 }
3389
3390 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3391 where
3392 T: 'static,
3393 {
3394 GpuiBorrow::new(handle.clone(), self)
3395 }
3396
3397 #[inline(always)]
3398 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3399 where
3400 T: 'static,
3401 {
3402 let entity = self.entities.read(handle);
3403 read(entity, self)
3404 }
3405
3406 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3407 where
3408 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3409 {
3410 self.update_window_id(handle.id, update)
3411 }
3412
3413 fn with_window<R>(
3414 &mut self,
3415 entity_id: EntityId,
3416 f: impl FnOnce(&mut Window, &mut App) -> R,
3417 ) -> Option<R> {
3418 App::with_window(self, entity_id, f)
3419 }
3420
3421 fn read_window<T, R>(
3422 &self,
3423 window: &WindowHandle<T>,
3424 read: impl FnOnce(Entity<T>, &App) -> R,
3425 ) -> Result<R>
3426 where
3427 T: 'static,
3428 {
3429 let window = self
3430 .windows
3431 .get(window.id)
3432 .context("window not found")?
3433 .as_deref()
3434 .expect("attempted to read a window that is already on the stack");
3435
3436 let root_view = window.root.clone().unwrap();
3437 let view = root_view
3438 .downcast::<T>()
3439 .map_err(|_| anyhow!("root view's type has changed"))?;
3440
3441 Ok(read(view, self))
3442 }
3443
3444 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3445 where
3446 R: Send + 'static,
3447 {
3448 self.background_executor.spawn(future)
3449 }
3450
3451 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3452 where
3453 G: Global,
3454 {
3455 let g = self.global::<G>();
3456 callback(g, self)
3457 }
3458}
3459
3460pub(crate) enum Effect {
3462 Notify {
3463 emitter: EntityId,
3464 },
3465 Emit {
3466 emitter: EntityId,
3467 event_type: TypeId,
3468 event: ArenaBox<dyn Any>,
3469 },
3470 RefreshWindows,
3471 NotifyGlobalObservers {
3472 global_type: TypeId,
3473 },
3474 Defer {
3475 callback: Box<dyn FnOnce(&mut App) + 'static>,
3476 },
3477 EntityCreated {
3478 entity: AnyEntity,
3479 tid: TypeId,
3480 window: Option<WindowId>,
3481 },
3482}
3483
3484impl std::fmt::Debug for Effect {
3485 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3486 match self {
3487 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3488 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3489 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3490 Effect::NotifyGlobalObservers { global_type } => {
3491 write!(f, "NotifyGlobalObservers({:?})", global_type)
3492 }
3493 Effect::Defer { .. } => write!(f, "Defer(..)"),
3494 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3495 }
3496 }
3497}
3498
3499pub(crate) struct GlobalLease<G: Global> {
3501 global: Box<dyn Any>,
3502 global_type: PhantomData<G>,
3503}
3504
3505impl<G: Global> GlobalLease<G> {
3506 fn new(global: Box<dyn Any>) -> Self {
3507 GlobalLease {
3508 global,
3509 global_type: PhantomData,
3510 }
3511 }
3512}
3513
3514impl<G: Global> Deref for GlobalLease<G> {
3515 type Target = G;
3516
3517 fn deref(&self) -> &Self::Target {
3518 self.global.downcast_ref().unwrap()
3519 }
3520}
3521
3522impl<G: Global> DerefMut for GlobalLease<G> {
3523 fn deref_mut(&mut self) -> &mut Self::Target {
3524 self.global.downcast_mut().unwrap()
3525 }
3526}
3527
3528pub struct AnyDrag {
3531 pub view: AnyView,
3533
3534 pub value: Arc<dyn Any>,
3536
3537 pub cursor_offset: Point<Pixels>,
3540
3541 pub cursor_style: Option<CursorStyle>,
3543
3544 pub external_payload_source: Option<ExternalDragPayloadSource>,
3547}
3548
3549pub type ExternalDragPayloadSource =
3552 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3553
3554#[derive(Clone)]
3557pub struct AnyTooltip {
3558 pub view: AnyView,
3560
3561 pub mouse_position: Point<Pixels>,
3563
3564 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3568}
3569
3570#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3572pub enum InputPreference {
3573 CharacterInput,
3575 KeyBindings,
3577}
3578
3579#[derive(Debug)]
3581pub struct KeystrokeEvent {
3582 pub keystroke: Keystroke,
3584
3585 pub input_preference: InputPreference,
3593
3594 pub action: Option<Box<dyn Action>>,
3596
3597 pub context_stack: Vec<KeyContext>,
3599}
3600
3601struct NullHttpClient;
3602
3603impl HttpClient for NullHttpClient {
3604 fn send(
3605 &self,
3606 _req: http_client::Request<http_client::AsyncBody>,
3607 ) -> futures::future::BoxFuture<
3608 'static,
3609 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3610 > {
3611 async move {
3612 anyhow::bail!("No HttpClient available");
3613 }
3614 .boxed()
3615 }
3616
3617 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3618 None
3619 }
3620
3621 fn proxy(&self) -> Option<&Url> {
3622 None
3623 }
3624}
3625
3626pub struct GpuiBorrow<'a, T> {
3628 inner: Option<Lease<T>>,
3629 app: &'a mut App,
3630}
3631
3632impl<'a, T: 'static> GpuiBorrow<'a, T> {
3633 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3634 app.start_update();
3635 let lease = app.entities.lease(&inner);
3636 Self {
3637 inner: Some(lease),
3638 app,
3639 }
3640 }
3641}
3642
3643impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3644 fn borrow(&self) -> &T {
3645 self.inner.as_ref().unwrap().borrow()
3646 }
3647}
3648
3649impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3650 fn borrow_mut(&mut self) -> &mut T {
3651 self.inner.as_mut().unwrap().borrow_mut()
3652 }
3653}
3654
3655impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3656 type Target = T;
3657
3658 fn deref(&self) -> &Self::Target {
3659 self.inner.as_ref().unwrap()
3660 }
3661}
3662
3663impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3664 fn deref_mut(&mut self) -> &mut T {
3665 self.inner.as_mut().unwrap()
3666 }
3667}
3668
3669impl<'a, T> Drop for GpuiBorrow<'a, T> {
3670 fn drop(&mut self) {
3671 let lease = self.inner.take().unwrap();
3672 self.app.notify(lease.id);
3673 self.app.entities.end_lease(lease);
3674 self.app.finish_update();
3675 }
3676}
3677
3678#[cfg(test)]
3679mod test {
3680 use std::{
3681 cell::{Cell, RefCell},
3682 ffi::OsString,
3683 path::PathBuf,
3684 rc::Rc,
3685 };
3686
3687 #[cfg(unix)]
3688 use std::os::unix::ffi::OsStringExt;
3689
3690 use crate::{
3691 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3692 TestAppContext, Window,
3693 };
3694
3695 fn construction_platform() -> Rc<crate::TestPlatform> {
3696 let dispatcher = std::sync::Arc::new(crate::TestDispatcher::new(0));
3697 crate::TestPlatform::new(
3698 crate::BackgroundExecutor::new(dispatcher.clone()),
3699 crate::ForegroundExecutor::new(dispatcher),
3700 )
3701 }
3702
3703 #[test]
3704 fn application_construction_uses_text_override_without_querying_platform() {
3705 use std::sync::Arc;
3706
3707 let platform = construction_platform();
3708 let backend: Arc<dyn crate::PlatformTextSystem> = Arc::new(crate::NoopTextSystem);
3709 let native_references = Arc::strong_count(&platform.text_system);
3710 let app =
3711 super::Application::with_platform_and_text_system(platform.clone(), backend.clone());
3712
3713 assert_eq!(platform.text_system_calls.get(), 0);
3714 assert_eq!(Arc::strong_count(&platform.text_system), native_references);
3715 assert_eq!(Arc::strong_count(&backend), 2);
3716 drop(app);
3717 assert_eq!(Arc::strong_count(&backend), 1);
3718 }
3719
3720 #[test]
3721 fn application_construction_uses_platform_text_by_default() {
3722 use std::sync::Arc;
3723
3724 let platform = construction_platform();
3725 let native_references = Arc::strong_count(&platform.text_system);
3726 let app = super::Application::with_platform(platform.clone());
3727
3728 assert_eq!(platform.text_system_calls.get(), 1);
3729 assert_eq!(
3730 Arc::strong_count(&platform.text_system),
3731 native_references + 1
3732 );
3733 drop(app);
3734 assert_eq!(Arc::strong_count(&platform.text_system), native_references);
3735 }
3736
3737 #[gpui::test]
3738 fn app_borrow_diagnostics(cx: &mut TestAppContext) {
3739 use std::panic::{AssertUnwindSafe, catch_unwind};
3740
3741 let app = cx.app.clone();
3742 let first_line = line!() + 1;
3743 let first = app.borrow();
3744 let second = app.borrow();
3745 drop(first);
3746 assert!(app.try_borrow_mut().is_err());
3747 let attempted_line = line!() + 1;
3748 let panic = catch_unwind(AssertUnwindSafe(|| drop(app.borrow_mut())));
3749 let message = *panic
3750 .expect_err("conflicting borrow")
3751 .downcast::<String>()
3752 .unwrap();
3753 assert!(message.contains(&format!(
3754 "mutable App borrow at {}:{attempted_line}:",
3755 file!()
3756 )));
3757 assert!(message.contains(&format!(
3758 "shared borrow group began at {}:{first_line}:",
3759 file!()
3760 )));
3761 drop(second);
3762
3763 let origin_line = line!() + 2;
3764 let panic = catch_unwind(AssertUnwindSafe(|| {
3765 let _borrow = app.try_borrow_mut().expect("initial borrow");
3766 drop(app.borrow());
3767 }));
3768 let message = *panic
3769 .expect_err("conflicting borrow")
3770 .downcast::<String>()
3771 .unwrap();
3772 assert!(message.contains("attempted shared App borrow"));
3773 assert!(message.contains(&format!(
3774 "mutable borrow group began at {}:{origin_line}:",
3775 file!()
3776 )));
3777
3778 let next_line = line!() + 1;
3779 let _borrow = app.borrow();
3780 assert_eq!(
3781 app.borrow_origin.get().expect("new origin").0.line(),
3782 next_line
3783 );
3784 }
3785
3786 struct RenderCounter(Rc<Cell<usize>>);
3787
3788 impl Render for RenderCounter {
3789 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3790 self.0.set(self.0.get() + 1);
3791 Empty
3792 }
3793 }
3794
3795 #[gpui::test]
3796 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3797 let render_count = Rc::new(Cell::new(0));
3798
3799 let _window = cx.add_window({
3800 let render_count = render_count.clone();
3801 move |_, _| RenderCounter(render_count)
3802 });
3803
3804 cx.run_until_parked();
3805 let render_count_before_refresh = render_count.get();
3806
3807 cx.to_async().refresh();
3808
3809 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3810 }
3811
3812 #[gpui::test]
3813 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3814 let observed = Rc::new(RefCell::new(Vec::new()));
3815 let subscription = cx.update(|cx| {
3816 let observed = observed.clone();
3817 cx.on_missing_glyphs(move |missing_glyphs, _| {
3818 observed.borrow_mut().extend_from_slice(missing_glyphs);
3819 })
3820 });
3821 cx.update(|cx| {
3822 cx.text_system()
3823 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3824 });
3825 cx.run_until_parked();
3826 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3827
3828 let second_observed = Rc::new(RefCell::new(Vec::new()));
3829 let second_subscription = cx.update(|cx| {
3830 let second_observed = second_observed.clone();
3831 cx.on_missing_glyphs(move |missing_glyphs, _| {
3832 second_observed
3833 .borrow_mut()
3834 .extend_from_slice(missing_glyphs);
3835 })
3836 });
3837 cx.update(|cx| {
3838 cx.text_system()
3839 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3840 });
3841 cx.run_until_parked();
3842 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3843 assert_eq!(
3844 second_observed.borrow().as_slice(),
3845 &[missing_glyph("replacement")]
3846 );
3847
3848 drop(subscription);
3849 cx.update(|cx| {
3850 cx.text_system()
3851 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3852 });
3853 cx.run_until_parked();
3854 assert_eq!(
3855 second_observed.borrow().as_slice(),
3856 &[
3857 missing_glyph("replacement"),
3858 missing_glyph("after old drop")
3859 ]
3860 );
3861
3862 drop(second_subscription);
3863 cx.update(|cx| {
3864 cx.text_system()
3865 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3866 });
3867 cx.run_until_parked();
3868 assert_eq!(second_observed.borrow().len(), 2);
3869 }
3870
3871 #[test]
3872 fn test_gpui_borrow() {
3873 let cx = TestAppContext::single();
3874 let observation_count = Rc::new(RefCell::new(0));
3875
3876 let state = cx.update(|cx| {
3877 let state = cx.new(|_| false);
3878 cx.observe(&state, {
3879 let observation_count = observation_count.clone();
3880 move |_, _| {
3881 let mut count = observation_count.borrow_mut();
3882 *count += 1;
3883 }
3884 })
3885 .detach();
3886
3887 state
3888 });
3889
3890 cx.update(|cx| {
3891 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3893 });
3894
3895 cx.update(|cx| {
3896 state.write(cx, false);
3897 });
3898
3899 assert_eq!(*observation_count.borrow(), 2);
3900 }
3901
3902 #[gpui::test]
3903 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3904 #[cfg(unix)]
3905 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3906 #[cfg(not(unix))]
3907 let user_data_dir = OsString::from("C:\\zed data");
3908 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3909 let restart_path = PathBuf::from("updated-zed");
3910 let _application =
3911 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3912 let restart = cx.expect_restart();
3913
3914 cx.update(|cx| {
3915 cx.set_restart_path(restart_path.clone());
3916 cx.restart();
3917 });
3918
3919 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3920 assert_eq!(path, Some(restart_path));
3921 assert_eq!(restart_arguments, arguments);
3922 }
3923
3924 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3925 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3926 }
3927}