1use scheduler::Instant;
2use std::{
3 any::{TypeId, type_name},
4 cell::{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(any(feature = "inspector", 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, Point, PowerMode, Priority, PromptBuilder,
55 PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle,
56 Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
57 SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
58 ThermalState, Window, WindowAppearance, WindowBounds, WindowButtonLayout, WindowHandle,
59 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
90struct AppBorrowError {
91 attempted: &'static std::panic::Location<'static>,
92 kind: &'static str,
93 origin: Option<(&'static std::panic::Location<'static>, &'static str)>,
94}
95
96impl std::fmt::Display for AppBorrowError {
97 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 let Self {
99 attempted,
100 kind,
101 origin,
102 } = self;
103 write!(
104 formatter,
105 "RefCell already borrowed: attempted {kind} App borrow at {attempted}; "
106 )?;
107 match origin {
108 Some((origin, existing_kind)) => write!(
109 formatter,
110 "existing {existing_kind} borrow group began at {origin}"
111 ),
112 None => write!(formatter, "origin unavailable"),
113 }
114 }
115}
116
117impl std::fmt::Debug for AppBorrowError {
118 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 std::fmt::Display::fmt(self, formatter)
120 }
121}
122
123impl std::error::Error for AppBorrowError {}
124
125impl AppCell {
126 #[doc(hidden)]
127 #[track_caller]
128 pub fn borrow(&self) -> AppRef<'_> {
129 if option_env!("TRACK_THREAD_BORROWS").is_some() {
130 let thread_id = std::thread::current().id();
131 eprintln!("borrowed {thread_id:?}");
132 }
133 let starts_borrow_group = self.app.try_borrow_mut().is_ok();
136 let attempted = std::panic::Location::caller();
137 let borrow = self
138 .app
139 .try_borrow()
140 .map_err(|_error| AppBorrowError {
141 attempted,
142 kind: "shared",
143 origin: self.borrow_origin.get(),
144 })
145 .unwrap();
146 if starts_borrow_group {
147 self.borrow_origin
148 .set(Some((std::panic::Location::caller(), "shared")));
149 }
150 AppRef(borrow)
151 }
152
153 #[doc(hidden)]
154 #[track_caller]
155 pub fn borrow_mut(&self) -> AppRefMut<'_> {
156 self.try_borrow_mut().unwrap()
157 }
158
159 #[doc(hidden)]
160 #[track_caller]
161 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>> {
162 if option_env!("TRACK_THREAD_BORROWS").is_some() {
163 let thread_id = std::thread::current().id();
164 eprintln!("borrowed {thread_id:?}");
165 }
166 let borrow = match self.app.try_borrow_mut() {
167 Ok(borrow) => borrow,
168 Err(_error) => {
169 return Err(AppBorrowError {
170 attempted: std::panic::Location::caller(),
171 kind: "mutable",
172 origin: self.borrow_origin.get(),
173 }
174 .into());
175 }
176 };
177 self.borrow_origin
178 .set(Some((std::panic::Location::caller(), "mutable")));
179 Ok(AppRefMut(borrow))
180 }
181}
182
183#[doc(hidden)]
184#[derive(Deref, DerefMut)]
185pub struct AppRef<'a>(Ref<'a, App>);
186
187impl Drop for AppRef<'_> {
188 fn drop(&mut self) {
189 if option_env!("TRACK_THREAD_BORROWS").is_some() {
190 let thread_id = std::thread::current().id();
191 eprintln!("dropped borrow from {thread_id:?}");
192 }
193 }
194}
195
196#[doc(hidden)]
197#[derive(Deref, DerefMut)]
198pub struct AppRefMut<'a>(RefMut<'a, App>);
199
200impl Drop for AppRefMut<'_> {
201 fn drop(&mut self) {
202 if option_env!("TRACK_THREAD_BORROWS").is_some() {
203 let thread_id = std::thread::current().id();
204 eprintln!("dropped {thread_id:?}");
205 }
206 }
207}
208
209pub struct Application(Rc<AppCell>);
212
213pub struct ApplicationHandle {
219 app: Rc<AppCell>,
220}
221
222impl ApplicationHandle {
223 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
227 let cx = &mut *self.app.borrow_mut();
228 f(cx)
229 }
230
231 pub fn to_async(&self) -> AsyncApp {
234 self.update(|cx| cx.to_async())
235 }
236}
237
238impl Application {
241 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
243 Self(App::new_app(
244 platform,
245 Arc::new(()),
246 Arc::new(NullHttpClient),
247 ))
248 }
249
250 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
260 let this = Self::with_platform(platform);
261 this.0.borrow_mut().accessibility_force_disabled = true;
262 this
263 }
264
265 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
267 let mut context_lock = self.0.borrow_mut();
268 let asset_source = Arc::new(asset_source);
269 context_lock.asset_source = asset_source.clone();
270 context_lock.svg_renderer = SvgRenderer::new(asset_source);
271 drop(context_lock);
272 self
273 }
274
275 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
277 self.0.borrow_mut().restart_arguments = arguments;
278 self
279 }
280
281 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
283 let mut context_lock = self.0.borrow_mut();
284 context_lock.http_client = http_client;
285 drop(context_lock);
286 self
287 }
288
289 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
292 self.0.borrow_mut().quit_mode = mode;
293 self
294 }
295
296 pub fn with_windowing(self, request: WindowingRequest) -> Self {
303 self.0.borrow().platform.set_initial_windowing(request);
304 self
305 }
306
307 pub fn run<F>(self, on_finish_launching: F)
313 where
314 F: 'static + FnOnce(&mut App),
315 {
316 let this = self.0.clone();
317 let platform = self.0.borrow().platform.clone();
318 platform.run(Box::new(move || {
319 let cx = &mut *this.borrow_mut();
320 cx.displays_changed();
322 #[cfg(gpui_hot_reload)]
323 crate::hot_reload::init(cx);
324 on_finish_launching(cx);
325 }));
326
327 #[cfg(target_family = "wasm")]
328 std::mem::forget(self);
329 }
330
331 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
341 where
342 F: 'static + FnOnce(&mut App),
343 {
344 let this = self.0.clone();
345 let platform = self.0.borrow().platform.clone();
346 platform.run(Box::new(move || {
347 let cx = &mut *this.borrow_mut();
348 cx.displays_changed();
350 #[cfg(gpui_hot_reload)]
351 crate::hot_reload::init(cx);
352 on_finish_launching(cx);
353 }));
354 ApplicationHandle { app: self.0 }
355 }
356
357 pub fn on_open_urls<F>(&self, callback: F) -> &Self
360 where
361 F: 'static + FnMut(Vec<String>),
362 {
363 self.0.borrow().platform.on_open_urls(Box::new(callback));
364 self
365 }
366
367 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
370 where
371 F: 'static + FnMut(&mut App),
372 {
373 let this = Rc::downgrade(&self.0);
374 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
375 if let Some(app) = this.upgrade() {
376 callback(&mut app.borrow_mut());
377 }
378 }));
379 self
380 }
381
382 pub fn background_executor(&self) -> BackgroundExecutor {
384 self.0.borrow().background_executor.clone()
385 }
386
387 pub fn foreground_executor(&self) -> ForegroundExecutor {
389 self.0.borrow().foreground_executor.clone()
390 }
391
392 pub fn text_system(&self) -> Arc<TextSystem> {
394 self.0.borrow().text_system.clone()
395 }
396
397 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
399 self.0.borrow().path_for_auxiliary_executable(name)
400 }
401}
402
403type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
404type AppLifecycleHandler = Box<dyn FnMut(AppLifecyclePhase, &mut App) -> bool + 'static>;
405type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
406
407#[derive(Clone, Copy, PartialEq)]
409struct DisplayState {
410 bounds: Bounds<Pixels>,
411 refresh_interval: Option<Duration>,
412}
413
414impl DisplayState {
415 fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
416 let mut changes = DisplayChanges::empty();
417 changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
418 changes.set(
419 DisplayChanges::REFRESH_INTERVAL,
420 self.refresh_interval != previous.refresh_interval,
421 );
422 changes
423 }
424}
425
426fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
427 platform
428 .displays()
429 .into_iter()
430 .map(|display| {
431 let state = DisplayState {
432 bounds: display.bounds(),
433 refresh_interval: display.refresh_interval(),
434 };
435 (display.id(), state)
436 })
437 .collect()
438}
439
440fn display_events(
442 previous: &HashMap<DisplayId, DisplayState>,
443 current: &HashMap<DisplayId, DisplayState>,
444) -> Vec<DisplayEvent> {
445 let removed = previous
446 .keys()
447 .filter(|id| !current.contains_key(id))
448 .map(|id| DisplayEvent::Removed(*id));
449 let added_or_changed = current.iter().filter_map(|(id, state)| {
450 let Some(previous_state) = previous.get(id) else {
451 return Some(DisplayEvent::Added(*id));
452 };
453 let changes = state.changes_from(previous_state);
454 (!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
455 });
456 removed.chain(added_or_changed).collect()
457}
458type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
459type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
460pub(crate) type KeystrokeObserver =
461 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
462type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
463type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
464type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
465type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
466
467struct MissingGlyphCallbackEntry {
468 registration: Rc<()>,
469 callback: Option<MissingGlyphCallback>,
470}
471
472#[derive(Default)]
473struct MissingGlyphCallbackSlot {
474 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
475}
476
477impl MissingGlyphCallbackSlot {
478 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
479 let registration = Rc::new(());
480 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
481 registration: registration.clone(),
482 callback: Some(callback),
483 });
484 registration
485 }
486
487 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
488 let Some((registration, mut callback)) =
489 self.entry.borrow_mut().as_mut().and_then(|entry| {
490 entry
491 .callback
492 .take()
493 .map(|callback| (entry.registration.clone(), callback))
494 })
495 else {
496 return;
497 };
498 callback(missing_glyphs, cx);
499
500 let mut entry = self.entry.borrow_mut();
501 let is_current = entry
502 .as_ref()
503 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
504 if is_current {
505 let Some(entry) = entry.as_mut() else {
506 return;
507 };
508 entry.callback = Some(callback);
509 }
510 }
511
512 fn remove(&self, registration: &Rc<()>) -> bool {
513 let mut entry = self.entry.borrow_mut();
514 let is_current = entry
515 .as_ref()
516 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
517 if is_current {
518 entry.take();
519 }
520 is_current
521 }
522}
523
524#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
526pub enum QuitMode {
527 #[default]
529 Default,
530 LastWindowClosed,
532 Explicit,
534}
535
536#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
541pub enum CursorHideMode {
542 Never,
544 OnTyping,
546 #[default]
549 OnTypingAndAction,
550}
551
552#[doc(hidden)]
553#[derive(Clone, PartialEq, Eq)]
554pub struct SystemWindowTab {
555 pub id: WindowId,
556 pub title: SharedString,
557 pub handle: AnyWindowHandle,
558 pub last_active_at: Instant,
559}
560
561impl SystemWindowTab {
562 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
564 Self {
565 id: handle.id,
566 title,
567 handle,
568 last_active_at: Instant::now(),
569 }
570 }
571}
572
573#[derive(Default)]
575pub struct SystemWindowTabController {
576 visible: Option<bool>,
577 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
578}
579
580impl Global for SystemWindowTabController {}
581
582impl SystemWindowTabController {
583 pub fn new() -> Self {
585 Self {
586 visible: None,
587 tab_groups: FxHashMap::default(),
588 }
589 }
590
591 pub fn init(cx: &mut App) {
593 cx.set_global(SystemWindowTabController::new());
594 }
595
596 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
598 &self.tab_groups
599 }
600
601 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
603 let controller = cx.global::<SystemWindowTabController>();
604 let current_group = controller
605 .tab_groups
606 .iter()
607 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
608
609 let current_group = current_group?;
610 let group_ids: Vec<_> = controller.tab_groups.keys().collect();
612 let idx = group_ids.iter().position(|g| *g == current_group)?;
613 let next_idx = (idx + 1) % group_ids.len();
614
615 controller
616 .tab_groups
617 .get(group_ids[next_idx])
618 .and_then(|tabs| {
619 tabs.iter()
620 .max_by_key(|tab| tab.last_active_at)
621 .or_else(|| tabs.first())
622 .map(|tab| &tab.handle)
623 })
624 }
625
626 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
628 let controller = cx.global::<SystemWindowTabController>();
629 let current_group = controller
630 .tab_groups
631 .iter()
632 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
633
634 let current_group = current_group?;
635 let group_ids: Vec<_> = controller.tab_groups.keys().collect();
637 let idx = group_ids.iter().position(|g| *g == current_group)?;
638 let prev_idx = if idx == 0 {
639 group_ids.len() - 1
640 } else {
641 idx - 1
642 };
643
644 controller
645 .tab_groups
646 .get(group_ids[prev_idx])
647 .and_then(|tabs| {
648 tabs.iter()
649 .max_by_key(|tab| tab.last_active_at)
650 .or_else(|| tabs.first())
651 .map(|tab| &tab.handle)
652 })
653 }
654
655 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
657 self.tab_groups
658 .values()
659 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
660 }
661
662 pub fn init_visible(cx: &mut App, visible: bool) {
664 let controller = cx.global_mut::<SystemWindowTabController>();
665 if controller.visible.is_none() {
666 controller.visible = Some(visible);
667 }
668 }
669
670 pub fn is_visible(&self) -> bool {
672 self.visible.unwrap_or(false)
673 }
674
675 pub fn set_visible(cx: &mut App, visible: bool) {
677 let controller = cx.global_mut::<SystemWindowTabController>();
678 controller.visible = Some(visible);
679 }
680
681 pub fn update_last_active(cx: &mut App, id: WindowId) {
683 let controller = cx.global_mut::<SystemWindowTabController>();
684 for windows in controller.tab_groups.values_mut() {
685 for tab in windows.iter_mut() {
686 if tab.id == id {
687 tab.last_active_at = Instant::now();
688 }
689 }
690 }
691 }
692
693 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
695 let controller = cx.global_mut::<SystemWindowTabController>();
696 for (_, windows) in controller.tab_groups.iter_mut() {
697 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
698 if ix < windows.len() && current_pos != ix {
699 let window_tab = windows.remove(current_pos);
700 windows.insert(ix, window_tab);
701 }
702 break;
703 }
704 }
705 }
706
707 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
709 let controller = cx.global::<SystemWindowTabController>();
710 let tab = controller
711 .tab_groups
712 .values()
713 .flat_map(|windows| windows.iter())
714 .find(|tab| tab.id == id);
715
716 if tab.map_or(true, |t| t.title == title) {
717 return;
718 }
719
720 let controller = cx.global_mut::<SystemWindowTabController>();
721 for windows in controller.tab_groups.values_mut() {
722 for tab in windows.iter_mut() {
723 if tab.id == id {
724 tab.title = title;
725 return;
726 }
727 }
728 }
729 }
730
731 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
733 let controller = cx.global_mut::<SystemWindowTabController>();
734 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
735 return;
736 };
737
738 let expected_tab_ids: Vec<_> = tabs
739 .iter()
740 .filter(|tab| tab.id != id)
741 .map(|tab| tab.id)
742 .sorted()
743 .collect();
744
745 let mut tab_group_id = None;
746 for (group_id, group_tabs) in &controller.tab_groups {
747 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
748 if tab_ids == expected_tab_ids {
749 tab_group_id = Some(*group_id);
750 break;
751 }
752 }
753
754 if let Some(tab_group_id) = tab_group_id {
755 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
756 tabs.push(tab);
757 }
758 } else {
759 let new_group_id = controller.tab_groups.len();
760 controller.tab_groups.insert(new_group_id, tabs);
761 }
762 }
763
764 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
766 let controller = cx.global_mut::<SystemWindowTabController>();
767 let mut removed_tab = None;
768
769 controller.tab_groups.retain(|_, tabs| {
770 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
771 removed_tab = Some(tabs.remove(pos));
772 }
773 !tabs.is_empty()
774 });
775
776 removed_tab
777 }
778
779 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
781 let removed_tab = Self::remove_tab(cx, id);
782 let controller = cx.global_mut::<SystemWindowTabController>();
783
784 if let Some(tab) = removed_tab {
785 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
786 controller.tab_groups.insert(new_group_id, vec![tab]);
787 }
788 }
789
790 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
792 let controller = cx.global_mut::<SystemWindowTabController>();
793 let Some(initial_tabs) = controller.tabs(id) else {
794 return;
795 };
796
797 let initial_tabs_len = initial_tabs.len();
798 let mut all_tabs = initial_tabs.clone();
799
800 for (_, mut tabs) in controller.tab_groups.drain() {
801 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
802 all_tabs.extend(tabs);
803 }
804
805 controller.tab_groups.insert(0, all_tabs);
806 }
807
808 pub fn select_next_tab(cx: &mut App, id: WindowId) {
810 let controller = cx.global_mut::<SystemWindowTabController>();
811 let Some(tabs) = controller.tabs(id) else {
812 return;
813 };
814
815 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
816 let next_index = (current_index + 1) % tabs.len();
817
818 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
819 window.activate_window();
820 });
821 }
822
823 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
825 let controller = cx.global_mut::<SystemWindowTabController>();
826 let Some(tabs) = controller.tabs(id) else {
827 return;
828 };
829
830 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
831 let previous_index = if current_index == 0 {
832 tabs.len() - 1
833 } else {
834 current_index - 1
835 };
836
837 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
838 window.activate_window();
839 });
840 }
841}
842
843pub(crate) enum GpuiMode {
844 #[cfg(any(test, feature = "test-support"))]
845 Test {
846 skip_drawing: bool,
847 },
848 Production,
849}
850
851impl GpuiMode {
852 #[cfg(any(test, feature = "test-support"))]
853 pub fn test() -> Self {
854 GpuiMode::Test {
855 skip_drawing: false,
856 }
857 }
858
859 #[inline]
860 pub(crate) fn skip_drawing(&self) -> bool {
861 match self {
862 #[cfg(any(test, feature = "test-support"))]
863 GpuiMode::Test { skip_drawing } => *skip_drawing,
864 GpuiMode::Production => false,
865 }
866 }
867}
868
869struct PlatformOwnedDrag {
870 source_window: WindowId,
871 state: PlatformOwnedDragState,
872}
873
874enum PlatformOwnedDragState {
875 Suspended(AnyDrag),
876 RestoredInSourceWindow,
879}
880
881pub struct App {
885 pub(crate) this: Weak<AppCell>,
886 pub(crate) platform: Rc<dyn Platform>,
887 text_system: Arc<TextSystem>,
888
889 pub(crate) actions: Rc<ActionRegistry>,
890 pub(crate) active_drag: Option<AnyDrag>,
891 platform_owned_drag: Option<PlatformOwnedDrag>,
892 pub(crate) background_executor: BackgroundExecutor,
893 pub(crate) foreground_executor: ForegroundExecutor,
894 #[cfg(feature = "profiler")]
895 foreground_journal: crate::profiler::journal::ForegroundJournal,
896 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
897 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
898 pub(crate) entities: EntityMap,
899 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
900 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
901 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
902 pub(crate) focus_handles: Arc<RwLock<FocusMap>>,
903 pub(crate) keymap: Rc<RefCell<Keymap>>,
904 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
905 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
906 pub(crate) global_action_listeners:
907 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
908 pending_effects: VecDeque<Effect>,
909
910 pub(crate) observers: SubscriberSet<EntityId, Handler>,
911 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
912 pub(crate) keystroke_observers: SingleSubscriberSet<KeystrokeObserver>,
913 pub(crate) keystroke_interceptors: SingleSubscriberSet<KeystrokeObserver>,
914 pub(crate) keyboard_layout_observers: SingleSubscriberSet<Handler>,
915 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
916 pub(crate) thermal_state_observers: SingleSubscriberSet<Handler>,
917 pub(crate) display_observers: SingleSubscriberSet<DisplayHandler>,
918 displays: HashMap<DisplayId, DisplayState>,
921 pub(crate) system_sleep_observers: SingleSubscriberSet<Handler>,
922 pub(crate) system_wake_observers: SingleSubscriberSet<Handler>,
923 app_lifecycle_observers: SingleSubscriberSet<AppLifecycleHandler>,
924 memory_warning_observers: SingleSubscriberSet<Handler>,
925 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
926 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
927 pub(crate) quit_observers: SingleSubscriberSet<QuitHandler>,
928 pub(crate) restart_observers: SingleSubscriberSet<Handler>,
929 pub(crate) window_closed_observers: SingleSubscriberSet<WindowClosedHandler>,
930
931 pub(crate) element_arena: Rc<RefCell<Arena>>,
939 pub(crate) event_arena: Arena,
941
942 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
947
948 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
950 asset_source: Arc<dyn AssetSource>,
951 pub(crate) svg_renderer: SvgRenderer,
952 http_client: Arc<dyn HttpClient>,
953
954 pub(crate) pending_notifications: FxHashSet<EntityId>,
956 pub(crate) pending_global_notifications: TypeIdHashSet,
957 pub(crate) restart_path: Option<PathBuf>,
958 pub(crate) restart_arguments: Vec<OsString>,
959 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
961 pub(crate) prompt_builder: Option<PromptBuilder>,
962 pub(crate) window_invalidators_by_entity:
963 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
964 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
965 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
966 #[cfg(any(feature = "inspector", debug_assertions))]
967 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
968 #[cfg(any(feature = "inspector", debug_assertions))]
969 pub(crate) inspector_element_registry: InspectorElementRegistry,
970 #[cfg(any(test, feature = "test-support", debug_assertions))]
971 pub(crate) name: Option<&'static str>,
972 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
973
974 pub(crate) window_update_stack: Vec<WindowUpdateEntry>,
975 pub(crate) mode: GpuiMode,
976 pub(crate) cursor_hide_mode: CursorHideMode,
977 pub(crate) reduce_motion: bool,
978 pub(crate) synced_animation_epoch: Instant,
980 power_mode: PowerMode,
981 pub(crate) accessibility_force_disabled: bool,
984 pending_updates: usize,
985 quit_mode: QuitMode,
986 quitting: bool,
987
988 #[cfg(any(test, gpui_leak_detection))]
991 _ref_counts: Arc<RwLock<EntityRefCounts>>,
992}
993
994#[derive(Clone, Copy)]
995pub(crate) struct WindowUpdateEntry {
996 window_id: WindowId,
997 bounds: WindowBounds,
998 display_id: Option<DisplayId>,
999}
1000
1001impl App {
1002 #[allow(clippy::new_ret_no_self)]
1003 pub(crate) fn new_app(
1004 platform: Rc<dyn Platform>,
1005 asset_source: Arc<dyn AssetSource>,
1006 http_client: Arc<dyn HttpClient>,
1007 ) -> Rc<AppCell> {
1008 let background_executor = platform.background_executor();
1009 let foreground_executor = platform.foreground_executor();
1010 assert!(
1011 background_executor.is_main_thread(),
1012 "must construct App on main thread"
1013 );
1014 #[cfg(feature = "profiler")]
1015 let foreground_journal = crate::profiler::journal::install_foreground_journal();
1016 let synced_animation_epoch = background_executor.now();
1017
1018 let text_system = Arc::new(TextSystem::new(platform.text_system()));
1019 let entities = EntityMap::new();
1020 let keyboard_layout = platform.keyboard_layout();
1021 let keyboard_mapper = platform.keyboard_mapper();
1022 let power_mode = platform.power_mode();
1023
1024 #[cfg(any(test, gpui_leak_detection))]
1025 let _ref_counts = entities.ref_counts_drop_handle();
1026
1027 let app = Rc::new_cyclic(|this| AppCell {
1028 borrow_origin: Cell::new(None),
1029 app: RefCell::new(App {
1030 this: this.clone(),
1031 platform: platform.clone(),
1032 text_system,
1033 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
1034 mode: GpuiMode::Production,
1035 actions: Rc::new(ActionRegistry::default()),
1036 pending_updates: 0,
1037 active_drag: None,
1038 platform_owned_drag: None,
1039 background_executor,
1040 foreground_executor,
1041 #[cfg(feature = "profiler")]
1042 foreground_journal,
1043 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1044 hang_monitor: None,
1045 svg_renderer: SvgRenderer::new(asset_source.clone()),
1046 loading_assets: Default::default(),
1047 asset_source,
1048 http_client,
1049 globals_by_type: Default::default(),
1050 entities,
1051 new_entity_observers: SubscriberSet::new(),
1052 windows: SlotMap::with_key(),
1053 window_update_stack: Vec::new(),
1054 window_handles: FxHashMap::default(),
1055 focus_handles: Arc::new(RwLock::new(FocusMap::default())),
1056 keymap: Rc::new(RefCell::new(Keymap::default())),
1057 keyboard_layout,
1058 keyboard_mapper,
1059 global_action_listeners: Default::default(),
1060 pending_effects: VecDeque::new(),
1061 pending_notifications: FxHashSet::default(),
1062 pending_global_notifications: Default::default(),
1063 observers: SubscriberSet::new(),
1064 tracked_entities: FxHashMap::default(),
1065 window_invalidators_by_entity: FxHashMap::default(),
1066 current_window_by_entity: FxHashMap::default(),
1067 event_listeners: SubscriberSet::new(),
1068 release_listeners: SubscriberSet::new(),
1069 keystroke_observers: SingleSubscriberSet::new(),
1070 keystroke_interceptors: SingleSubscriberSet::new(),
1071 keyboard_layout_observers: SingleSubscriberSet::new(),
1072 missing_glyph_callback: Rc::default(),
1073 thermal_state_observers: SingleSubscriberSet::new(),
1074 display_observers: SingleSubscriberSet::new(),
1075 displays: read_displays(platform.as_ref()),
1076 system_sleep_observers: SingleSubscriberSet::new(),
1077 system_wake_observers: SingleSubscriberSet::new(),
1078 app_lifecycle_observers: SingleSubscriberSet::new(),
1079 memory_warning_observers: SingleSubscriberSet::new(),
1080 global_observers: SubscriberSet::new(),
1081 quit_observers: SingleSubscriberSet::new(),
1082 restart_observers: SingleSubscriberSet::new(),
1083 restart_path: None,
1084 restart_arguments: Vec::new(),
1085 window_closed_observers: SingleSubscriberSet::new(),
1086 layout_id_buffer: Default::default(),
1087 propagate_event: true,
1088 prompt_builder: Some(PromptBuilder::Default),
1089 #[cfg(any(feature = "inspector", debug_assertions))]
1090 inspector_renderer: None,
1091 #[cfg(any(feature = "inspector", debug_assertions))]
1092 inspector_element_registry: InspectorElementRegistry::default(),
1093 quit_mode: QuitMode::default(),
1094 quitting: false,
1095 cursor_hide_mode: CursorHideMode::default(),
1096 reduce_motion: false,
1097 synced_animation_epoch,
1098 power_mode,
1099 accessibility_force_disabled: false,
1100
1101 #[cfg(any(test, feature = "test-support", debug_assertions))]
1102 name: None,
1103 element_arena: Rc::new(RefCell::new(Arena::new(1024 * 1024))),
1104 event_arena: Arena::new(1024 * 1024),
1105
1106 #[cfg(any(test, gpui_leak_detection))]
1107 _ref_counts,
1108 }),
1109 });
1110
1111 init_app_menus(platform.as_ref(), &app.borrow());
1112 SystemWindowTabController::init(&mut app.borrow_mut());
1113 #[cfg(feature = "profiler")]
1114 crate::profiler::journal::observe_power(&app.borrow());
1115
1116 platform.on_keyboard_layout_change(Box::new({
1117 let app = Rc::downgrade(&app);
1118 move || {
1119 if let Some(app) = app.upgrade() {
1120 let cx = &mut app.borrow_mut();
1121 cx.keyboard_layout = cx.platform.keyboard_layout();
1122 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1123 cx.keyboard_layout_observers
1124 .clone()
1125 .retain(move |callback| (callback)(cx));
1126 }
1127 }
1128 }));
1129
1130 platform.on_thermal_state_change(Box::new({
1131 let app = Rc::downgrade(&app);
1132 move || {
1133 if let Some(app) = app.upgrade() {
1134 let cx = &mut app.borrow_mut();
1135 cx.thermal_state_observers
1136 .clone()
1137 .retain(move |callback| (callback)(cx));
1138 }
1139 }
1140 }));
1141
1142 platform.on_displays_changed(Box::new({
1143 let app = Rc::downgrade(&app);
1144 move || {
1145 if let Some(app) = app.upgrade() {
1146 app.borrow_mut().displays_changed();
1147 }
1148 }
1149 }));
1150
1151 platform.on_system_sleep(Box::new({
1152 let app = Rc::downgrade(&app);
1153 move || {
1154 if let Some(app) = app.upgrade() {
1155 let cx = &mut app.borrow_mut();
1156 cx.system_sleep_observers
1157 .clone()
1158 .retain(move |callback| (callback)(cx));
1159 }
1160 }
1161 }));
1162
1163 platform.on_system_wake(Box::new({
1164 let app = Rc::downgrade(&app);
1165 move || {
1166 if let Some(app) = app.upgrade() {
1167 let cx = &mut app.borrow_mut();
1168 cx.system_wake_observers
1169 .clone()
1170 .retain(move |callback| (callback)(cx));
1171 }
1172 }
1173 }));
1174
1175 platform.on_app_lifecycle(Box::new({
1176 let app = Rc::downgrade(&app);
1177 move |phase| {
1178 if let Some(app) = app.upgrade() {
1179 app.borrow_mut().update(|cx| {
1180 cx.app_lifecycle_observers
1181 .clone()
1182 .retain(|callback| callback(phase, cx));
1183 });
1184 }
1185 }
1186 }));
1187
1188 platform.on_memory_warning(Box::new({
1189 let app = Rc::downgrade(&app);
1190 move || {
1191 if let Some(app) = app.upgrade() {
1192 app.borrow_mut().update(|cx| {
1193 cx.memory_warning_observers
1194 .clone()
1195 .retain(|callback| callback(cx));
1196 });
1197 }
1198 }
1199 }));
1200
1201 platform.on_power_mode_change(Box::new({
1202 let app = Rc::downgrade(&app);
1203 move || {
1204 if let Some(app) = app.upgrade() {
1205 let power_mode = app.borrow().platform.power_mode();
1206 app.borrow_mut().power_mode = power_mode;
1207 }
1208 }
1209 }));
1210
1211 platform.on_quit(Box::new({
1212 let cx = Rc::downgrade(&app);
1213 move || {
1214 let Some(cx) = cx.upgrade() else {
1215 return true;
1216 };
1217 match cx.try_borrow_mut() {
1218 Ok(mut cx) => {
1219 cx.shutdown();
1220 true
1221 }
1222 Err(_) => {
1223 false
1226 }
1227 }
1228 }
1229 }));
1230
1231 app
1232 }
1233
1234 #[doc(hidden)]
1235 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1236 self.entities.ref_counts_drop_handle()
1237 }
1238
1239 #[cfg(any(test, gpui_leak_detection))]
1245 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1246 self.entities.leak_detector_snapshot()
1247 }
1248
1249 #[cfg(any(test, gpui_leak_detection))]
1261 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1262 self.entities.assert_no_new_leaks(snapshot)
1263 }
1264
1265 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1267 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1268 LeakDetectorSnapshot::default()
1269 }
1270
1271 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1274 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1275
1276 pub fn shutdown(&mut self) {
1282 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1285 let hang_monitor_flush = self
1286 .hang_monitor
1287 .as_ref()
1288 .and_then(|hang_monitor| hang_monitor.request_flush());
1289
1290 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1291
1292 for observer in self.quit_observers.remove() {
1293 futures.push(observer(self));
1294 }
1295
1296 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1297 if let Some(flushed) = hang_monitor_flush {
1298 futures.push(
1299 async move {
1300 if flushed.await.is_err() {
1301 log::warn!("hang monitor exited before flushing");
1302 }
1303 }
1304 .boxed_local(),
1305 );
1306 }
1307
1308 self.windows.clear();
1309 self.window_handles.clear();
1310 self.flush_effects();
1311 self.quitting = true;
1312
1313 let futures = futures::future::join_all(futures);
1314 #[cfg(not(target_family = "wasm"))]
1315 if self
1316 .foreground_executor
1317 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1318 .is_err()
1319 {
1320 log::error!("timed out waiting on app_will_quit");
1321 }
1322 #[cfg(target_family = "wasm")]
1323 self.foreground_executor.spawn(futures).detach();
1324
1325 self.quitting = false;
1326 }
1327
1328 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1330 self.keyboard_layout.as_ref()
1331 }
1332
1333 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1335 &self.keyboard_mapper
1336 }
1337
1338 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1340 where
1341 F: 'static + FnMut(&mut App),
1342 {
1343 self.keyboard_layout_observers.insert(Box::new(move |cx| {
1344 callback(cx);
1345 true
1346 }))
1347 }
1348
1349 pub fn quit(&self) {
1351 self.platform.quit();
1352 }
1353
1354 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1368 if !self.windows.is_empty() {
1369 return Task::ready(Err(anyhow::anyhow!(
1370 "cannot switch windowing modes while windows are open"
1371 )));
1372 }
1373 self.platform.request_windowing(request)
1374 }
1375
1376 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1386 self.platform.graphical_environment()
1387 }
1388
1389 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1392 self.cursor_hide_mode
1393 }
1394
1395 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1398 self.cursor_hide_mode = mode;
1399 }
1400
1401 pub fn is_cursor_visible(&self) -> bool {
1407 self.platform.is_cursor_visible()
1408 }
1409
1410 pub fn reduce_motion(&self) -> bool {
1413 self.reduce_motion
1414 }
1415
1416 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1419 if self.reduce_motion != reduce_motion {
1420 self.reduce_motion = reduce_motion;
1421 self.refresh_windows();
1422 }
1423 }
1424
1425 pub fn refresh_windows(&mut self) {
1428 self.pending_effects.push_back(Effect::RefreshWindows);
1429 }
1430
1431 #[inline(always)]
1432 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1433 self.start_update();
1434 let result = update(self);
1435 self.finish_update();
1436 result
1437 }
1438
1439 pub(crate) fn start_update(&mut self) {
1440 self.pending_updates += 1;
1441 }
1442
1443 #[inline(never)]
1444 pub(crate) fn finish_update(&mut self) {
1445 if self.pending_updates == 1 {
1446 self.flush_effects();
1447 }
1448 self.pending_updates -= 1;
1449 }
1450
1451 pub fn observe<W>(
1453 &mut self,
1454 entity: &Entity<W>,
1455 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1456 ) -> Subscription
1457 where
1458 W: 'static,
1459 {
1460 self.observe_internal(entity, move |e, cx| {
1461 on_notify(e, cx);
1462 true
1463 })
1464 }
1465
1466 pub(crate) fn detect_accessed_entities<R>(
1467 &mut self,
1468 callback: impl FnOnce(&mut App) -> R,
1469 ) -> (R, FxHashSet<EntityId>) {
1470 self.entities.push_access_scope();
1471 let result = callback(self);
1472 (result, self.entities.pop_access_scope())
1473 }
1474
1475 pub(crate) fn record_entities_accessed(
1476 &mut self,
1477 window_handle: AnyWindowHandle,
1478 invalidator: WindowInvalidator,
1479 entities: &FxHashSet<EntityId>,
1480 ) {
1481 let mut tracked_entities =
1482 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1483 for entity in tracked_entities.iter() {
1484 self.window_invalidators_by_entity
1485 .entry(*entity)
1486 .and_modify(|windows| {
1487 windows.remove(&window_handle.id);
1488 });
1489 }
1490 for entity in entities.iter() {
1491 self.window_invalidators_by_entity
1492 .entry(*entity)
1493 .or_default()
1494 .insert(window_handle.id, invalidator.clone());
1495 self.current_window_by_entity
1496 .insert(*entity, window_handle.id);
1497 }
1498 tracked_entities.clear();
1499 tracked_entities.extend(entities.iter().copied());
1500 self.tracked_entities
1501 .insert(window_handle.id, tracked_entities);
1502 }
1503
1504 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1505 let (subscription, activate) = self.observers.insert_pending(key, value);
1506 self.defer(move |_| activate());
1507 subscription
1508 }
1509
1510 pub(crate) fn observe_internal<W>(
1511 &mut self,
1512 entity: &Entity<W>,
1513 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1514 ) -> Subscription
1515 where
1516 W: 'static,
1517 {
1518 let entity_id = entity.entity_id();
1519 let handle = entity.downgrade();
1520 self.new_observer(
1521 entity_id,
1522 Box::new(move |cx| {
1523 if let Some(entity) = handle.upgrade() {
1524 on_notify(entity, cx)
1525 } else {
1526 false
1527 }
1528 }),
1529 )
1530 }
1531
1532 pub fn subscribe<T, Event>(
1535 &mut self,
1536 entity: &Entity<T>,
1537 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1538 ) -> Subscription
1539 where
1540 T: 'static + EventEmitter<Event>,
1541 Event: 'static,
1542 {
1543 self.subscribe_internal(entity, move |entity, event, cx| {
1544 on_event(entity, event, cx);
1545 true
1546 })
1547 }
1548
1549 pub(crate) fn new_subscription(
1550 &mut self,
1551 key: EntityId,
1552 value: (TypeId, Listener),
1553 ) -> Subscription {
1554 let (subscription, activate) = self.event_listeners.insert_pending(key, value);
1555 self.defer(move |_| activate());
1556 subscription
1557 }
1558 pub(crate) fn subscribe_internal<T, Evt>(
1559 &mut self,
1560 entity: &Entity<T>,
1561 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1562 ) -> Subscription
1563 where
1564 T: 'static + EventEmitter<Evt>,
1565 Evt: 'static,
1566 {
1567 let entity_id = entity.entity_id();
1568 let handle = entity.downgrade();
1569 self.new_subscription(
1570 entity_id,
1571 (
1572 TypeId::of::<Evt>(),
1573 Box::new(move |event, cx| {
1574 let event: &Evt = event.downcast_ref().expect("invalid event type");
1575 if let Some(entity) = handle.upgrade() {
1576 on_event(entity, event, cx)
1577 } else {
1578 false
1579 }
1580 }),
1581 ),
1582 )
1583 }
1584
1585 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1589 self.windows
1590 .keys()
1591 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1592 .collect()
1593 }
1594
1595 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1601 self.platform.window_stack()
1602 }
1603
1604 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1606 self.platform.active_window()
1607 }
1608
1609 pub fn active_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1611 let (display_id, _) = self.active_window_placement()?;
1612 self.find_display(display_id?)
1613 }
1614
1615 pub(crate) fn active_window_placement(&self) -> Option<(Option<DisplayId>, WindowBounds)> {
1616 let window_id = self.active_window()?.window_id();
1617
1618 if let Some(state) = self
1619 .window_update_stack
1620 .iter()
1621 .rev()
1622 .find(|state| state.window_id == window_id)
1623 {
1624 return Some((state.display_id, state.bounds));
1625 }
1626
1627 let window = self.windows.get(window_id)?.as_ref()?;
1628 Some((window.display_id(), window.last_window_bounds()))
1629 }
1630
1631 pub(crate) fn sync_window_update_entry(&mut self, window: &Window) {
1632 if let Some(state) = self
1633 .window_update_stack
1634 .iter_mut()
1635 .rev()
1636 .find(|state| state.window_id == window.handle.id)
1637 {
1638 state.bounds = window.last_window_bounds();
1639 state.display_id = window.display_id();
1640 }
1641 }
1642
1643 pub fn open_window<V: 'static + Render>(
1647 &mut self,
1648 options: crate::WindowOptions,
1649 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1650 ) -> anyhow::Result<WindowHandle<V>> {
1651 self.update(|cx| {
1652 let id = cx.windows.insert(None);
1653 let handle = WindowHandle::new(id);
1654 match Window::new(handle.into(), options, cx) {
1655 Ok(mut window) => {
1656 cx.window_update_stack.push(WindowUpdateEntry {
1657 window_id: id,
1658 bounds: window.last_window_bounds(),
1659 display_id: window.display_id(),
1660 });
1661 let root_view = build_root_view(&mut window, cx);
1662 cx.window_update_stack.pop();
1663 window.root.replace(root_view.into());
1664 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1665
1666 let clear = window.draw(cx);
1671 clear.clear(cx);
1672
1673 cx.window_handles.insert(id, window.handle);
1674 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1675 Ok(handle)
1676 }
1677 Err(e) => {
1678 cx.windows.remove(id);
1679 Err(e)
1680 }
1681 }
1682 })
1683 }
1684
1685 pub fn activate(&self, ignoring_other_apps: bool) {
1687 self.platform.activate(ignoring_other_apps);
1688 }
1689
1690 pub fn hide(&self) {
1692 self.platform.hide();
1693 }
1694
1695 pub fn hide_other_apps(&self) {
1697 self.platform.hide_other_apps();
1698 }
1699
1700 pub fn unhide_other_apps(&self) {
1702 self.platform.unhide_other_apps();
1703 }
1704
1705 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1707 self.platform.displays()
1708 }
1709
1710 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1712 self.platform.primary_display()
1713 }
1714
1715 pub fn is_screen_capture_supported(&self) -> bool {
1717 self.platform.is_screen_capture_supported()
1718 }
1719
1720 pub fn screen_capture_sources(
1722 &self,
1723 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1724 self.platform.screen_capture_sources()
1725 }
1726
1727 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1729 self.displays()
1730 .iter()
1731 .find(|display| display.id() == id)
1732 .cloned()
1733 }
1734
1735 pub fn debug_state(&self) -> serde_json::Value {
1742 let displays = self
1743 .platform
1744 .displays()
1745 .into_iter()
1746 .map(|display| {
1747 serde_json::json!({
1748 "id": u64::from(display.id()),
1749 "uuid": display.uuid().ok().map(|uuid| uuid.to_string()),
1750 "bounds": display.bounds(),
1751 "visible_bounds": display.visible_bounds(),
1752 "refresh_interval_seconds": display
1753 .refresh_interval()
1754 .map(|interval| interval.as_secs_f64()),
1755 })
1756 })
1757 .collect::<Vec<_>>();
1758 let windows = self
1759 .windows
1760 .iter()
1761 .map(|(window_id, window)| match window {
1762 Some(window) => window.debug_state(),
1763 None => serde_json::json!({ "id": window_id.as_u64(), "updating": true }),
1764 })
1765 .collect::<Vec<_>>();
1766 serde_json::json!({
1767 "compositor": self.platform.compositor_name(),
1768 "thermal_state": format!("{:?}", self.platform.thermal_state()),
1769 "power_mode": {
1770 "cached": format!("{:?}", self.power_mode),
1771 "platform": format!("{:?}", self.platform.power_mode()),
1772 },
1773 "window_appearance": format!("{:?}", self.platform.window_appearance()),
1774 "cursor_visible": self.platform.is_cursor_visible(),
1775 "active_window_id": self
1776 .platform
1777 .active_window()
1778 .map(|handle| handle.window_id().as_u64()),
1779 "window_stack": self.platform.window_stack().map(|stack| {
1780 stack
1781 .into_iter()
1782 .map(|handle| handle.window_id().as_u64())
1783 .collect::<Vec<_>>()
1784 }),
1785 "primary_display_id": self
1786 .platform
1787 .primary_display()
1788 .map(|display| u64::from(display.id())),
1789 "displays": displays,
1790 "windows": windows,
1791 "platform": self.platform.debug_state(),
1792 })
1793 }
1794
1795 pub fn thermal_state(&self) -> ThermalState {
1797 self.platform.thermal_state()
1798 }
1799
1800 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1802 self.platform.prevent_idle_sleep(reason)
1803 }
1804
1805 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1807 where
1808 F: 'static + FnMut(&mut App),
1809 {
1810 self.thermal_state_observers.insert(Box::new(move |cx| {
1811 callback(cx);
1812 true
1813 }))
1814 }
1815
1816 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1821 where
1822 F: 'static + FnMut(&mut App),
1823 {
1824 self.system_sleep_observers.insert(Box::new(move |cx| {
1825 callback(cx);
1826 true
1827 }))
1828 }
1829
1830 pub(crate) fn displays_changed(&mut self) {
1831 let current = read_displays(self.platform.as_ref());
1832 let events = display_events(&self.displays, ¤t);
1833 self.displays = current;
1834 for event in &events {
1835 let DisplayEvent::Changed { id, .. } = *event else {
1836 continue;
1837 };
1838 for handle in self.windows() {
1839 self.update_window(handle, |_, window, cx| {
1840 if window.display_id == Some(id) {
1841 window.notify_display_observers(cx);
1842 }
1843 })
1844 .log_err();
1845 }
1846 }
1847 for event in events {
1848 self.display_observers
1849 .clone()
1850 .retain(|callback| (callback)(event, self));
1851 }
1852 }
1853
1854 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1855 self.displays.contains_key(&id)
1856 }
1857
1858 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1861 self.displays.get(&id)?.refresh_interval
1862 }
1863
1864 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1867 where
1868 F: 'static + FnMut(DisplayEvent, &mut App),
1869 {
1870 self.display_observers.insert(Box::new(move |event, cx| {
1871 callback(event, cx);
1872 true
1873 }))
1874 }
1875
1876 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1878 where
1879 F: 'static + FnMut(&mut App),
1880 {
1881 self.system_wake_observers.insert(Box::new(move |cx| {
1882 callback(cx);
1883 true
1884 }))
1885 }
1886
1887 pub fn on_app_lifecycle(
1895 &self,
1896 mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
1897 ) -> Subscription {
1898 self.app_lifecycle_observers
1899 .insert(Box::new(move |phase, cx| {
1900 callback(phase, cx);
1901 true
1902 }))
1903 }
1904
1905 pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
1908 self.memory_warning_observers.insert(Box::new(move |cx| {
1909 callback(cx);
1910 true
1911 }))
1912 }
1913
1914 pub fn window_appearance(&self) -> WindowAppearance {
1916 self.platform.window_appearance()
1917 }
1918
1919 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1930 self.platform.set_window_appearance(appearance);
1931 }
1932
1933 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1935 self.platform.button_layout()
1936 }
1937
1938 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1940 self.platform.read_from_clipboard()
1941 }
1942
1943 pub fn read_from_clipboard_async(
1951 &self,
1952 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1953 self.platform.read_from_clipboard_async()
1954 }
1955
1956 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1958 self.text_rendering_mode.set(mode);
1959 }
1960
1961 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1963 self.text_rendering_mode.get()
1964 }
1965
1966 pub fn power_mode(&self) -> PowerMode {
1969 self.power_mode
1970 }
1971
1972 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1974 self.platform.write_to_clipboard(item)
1975 }
1976
1977 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1980 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1981 self.platform.read_from_primary()
1982 }
1983
1984 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1987 pub fn write_to_primary(&self, item: ClipboardItem) {
1988 self.platform.write_to_primary(item)
1989 }
1990
1991 #[cfg(target_os = "macos")]
1997 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1998 self.platform.read_from_find_pasteboard()
1999 }
2000
2001 #[cfg(target_os = "macos")]
2007 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
2008 self.platform.write_to_find_pasteboard(item)
2009 }
2010
2011 pub fn write_credentials(
2013 &self,
2014 url: &str,
2015 username: &str,
2016 password: &[u8],
2017 ) -> Task<Result<()>> {
2018 self.platform.write_credentials(url, username, password)
2019 }
2020
2021 #[cfg(target_os = "macos")]
2029 pub fn write_credentials_if_not_exists(
2030 &self,
2031 url: &str,
2032 username: &str,
2033 password: &[u8],
2034 ) -> Task<Result<bool>> {
2035 self.platform
2036 .write_credentials_if_not_exists(url, username, password)
2037 }
2038
2039 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
2041 self.platform.read_credentials(url)
2042 }
2043
2044 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
2046 self.platform.delete_credentials(url)
2047 }
2048
2049 pub fn open_url(&self, url: &str) {
2051 self.platform.open_url(url);
2052 }
2053
2054 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
2061 self.platform.register_url_scheme(scheme)
2062 }
2063
2064 pub fn set_app_identity(&self, identifier: &str, name: &str) {
2071 self.platform.set_app_identity(identifier, name);
2072 }
2073
2074 pub fn show_system_notification(&self, notification: SystemNotification) {
2081 self.platform.show_system_notification(notification);
2082 }
2083
2084 pub fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
2092 self.platform.dismiss_system_notification(tag)
2093 }
2094
2095 pub fn on_system_notification_response<F>(&self, mut callback: F)
2099 where
2100 F: 'static + FnMut(SystemNotificationResponse, &mut App),
2101 {
2102 let this = self.this.clone();
2103 self.platform
2104 .on_system_notification_response(Box::new(move |response| {
2105 if let Some(app) = this.upgrade() {
2106 callback(response, &mut app.borrow_mut());
2107 }
2108 }));
2109 }
2110
2111 pub fn app_path(&self) -> Result<PathBuf> {
2115 self.platform.app_path()
2116 }
2117
2118 pub fn compositor_name(&self) -> &'static str {
2122 self.platform.compositor_name()
2123 }
2124
2125 pub fn platform_info(&self) -> crate::PlatformInfo {
2127 self.platform.platform_info()
2128 }
2129
2130 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
2132 self.platform.path_for_auxiliary_executable(name)
2133 }
2134
2135 pub fn prompt_for_paths(
2141 &self,
2142 options: PathPromptOptions,
2143 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
2144 self.platform.prompt_for_paths(options)
2145 }
2146
2147 pub fn prompt_for_new_path(
2154 &self,
2155 directory: &Path,
2156 suggested_name: Option<&str>,
2157 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
2158 self.platform.prompt_for_new_path(directory, suggested_name)
2159 }
2160
2161 pub fn reveal_path(&self, path: &Path) {
2163 self.platform.reveal_path(path)
2164 }
2165
2166 pub fn open_with_system(&self, path: &Path) {
2168 self.platform.open_with_system(path)
2169 }
2170
2171 pub fn should_auto_hide_scrollbars(&self) -> bool {
2173 self.platform.should_auto_hide_scrollbars()
2174 }
2175
2176 pub fn restart(&mut self) {
2178 self.restart_observers
2179 .clone()
2180 .retain(|observer| observer(self));
2181 self.platform.restart(
2182 self.restart_path.take(),
2183 std::mem::take(&mut self.restart_arguments),
2184 )
2185 }
2186
2187 pub fn set_restart_path(&mut self, path: PathBuf) {
2189 self.restart_path = Some(path);
2190 }
2191
2192 pub fn http_client(&self) -> Arc<dyn HttpClient> {
2194 self.http_client.clone()
2195 }
2196
2197 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
2199 self.http_client = new_client;
2200 }
2201
2202 pub fn set_quit_mode(&mut self, mode: QuitMode) {
2205 self.quit_mode = mode;
2206 }
2207
2208 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
2217 self.platform.set_activation_policy(policy);
2218 }
2219
2220 pub fn svg_renderer(&self) -> SvgRenderer {
2222 self.svg_renderer.clone()
2223 }
2224
2225 pub(crate) fn push_effect(&mut self, effect: Effect) {
2226 match &effect {
2227 Effect::Notify { emitter } => {
2228 if !self.pending_notifications.insert(*emitter) {
2229 return;
2230 }
2231 }
2232 Effect::NotifyGlobalObservers { global_type } => {
2233 if !self.pending_global_notifications.insert(*global_type) {
2234 return;
2235 }
2236 }
2237 _ => {}
2238 };
2239
2240 self.pending_effects.push_back(effect);
2241 }
2242
2243 fn flush_effects(&mut self) {
2247 loop {
2248 self.release_dropped_entities();
2249 self.release_dropped_focus_handles();
2250 if let Some(effect) = self.pending_effects.pop_front() {
2251 match effect {
2252 Effect::Notify { emitter } => {
2253 self.apply_notify_effect(emitter);
2254 }
2255
2256 Effect::Emit {
2257 emitter,
2258 event_type,
2259 event,
2260 } => self.apply_emit_effect(emitter, event_type, &*event),
2261
2262 Effect::RefreshWindows => {
2263 self.apply_refresh_effect();
2264 }
2265
2266 Effect::NotifyGlobalObservers { global_type } => {
2267 self.apply_notify_global_observers_effect(global_type);
2268 }
2269
2270 Effect::Defer { callback } => {
2271 self.apply_defer_effect(callback);
2272 }
2273 Effect::EntityCreated {
2274 entity,
2275 tid,
2276 window,
2277 } => {
2278 self.apply_entity_created_effect(entity, tid, window);
2279 }
2280 }
2281 } else {
2282 #[cfg(any(test, feature = "test-support"))]
2283 if matches!(self.mode, GpuiMode::Test { .. }) {
2284 for window in self
2285 .windows
2286 .values()
2287 .filter_map(|window| {
2288 let window = window.as_deref()?;
2289 window.invalidator.is_dirty().then_some(window.handle)
2290 })
2291 .collect::<Vec<_>>()
2292 {
2293 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2294 .unwrap();
2295 }
2296 }
2297
2298 if self.pending_effects.is_empty() {
2299 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2300 if window.invalidator.is_dirty()
2301 || window.needs_present.get()
2302 || !window.next_frame_callbacks.borrow().is_empty()
2303 {
2304 window.platform_window.schedule_frame();
2305 }
2306 }
2307
2308 self.event_arena.clear();
2309 break;
2310 }
2311 }
2312 }
2313 }
2314
2315 fn release_dropped_entities(&mut self) {
2319 loop {
2320 let dropped = self.entities.take_dropped();
2321 if dropped.is_empty() {
2322 break;
2323 }
2324
2325 for (entity_id, mut entity) in dropped {
2326 self.observers.remove(&entity_id);
2327 self.event_listeners.remove(&entity_id);
2328 self.window_invalidators_by_entity.remove(&entity_id);
2329 self.current_window_by_entity.remove(&entity_id);
2330 for release_callback in self.release_listeners.remove(&entity_id) {
2331 release_callback(entity.as_mut(), self);
2332 }
2333 }
2334 }
2335 }
2336
2337 fn release_dropped_focus_handles(&mut self) {
2339 let focus_handles = self.focus_handles.clone();
2340 let mut focus_handles = focus_handles.write();
2341 let FocusMap {
2342 handles,
2343 dropped_handles,
2344 } = &mut *focus_handles;
2345 if dropped_handles.is_empty() {
2346 return;
2347 }
2348
2349 let windows = self
2350 .windows
2351 .values()
2352 .filter_map(|window| {
2353 let window = window.as_ref()?;
2354 dropped_handles
2355 .contains(&window.focus?)
2356 .then_some(window.handle)
2357 })
2358 .collect::<SmallVec<[_; 1]>>();
2359 for handle_id in dropped_handles.drain(..) {
2360 handles.remove(handle_id);
2361 }
2362 drop(focus_handles);
2363
2364 for window_handle in windows {
2365 window_handle
2366 .update(self, |_, window, cx| window.blur(cx))
2367 .ok();
2368 }
2369 }
2370
2371 fn apply_notify_effect(&mut self, emitter: EntityId) {
2372 self.pending_notifications.remove(&emitter);
2373
2374 self.observers
2375 .clone()
2376 .retain(&emitter, |handler| handler(self));
2377 }
2378
2379 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2380 self.event_listeners
2381 .clone()
2382 .retain(&emitter, |(stored_type, handler)| {
2383 if *stored_type == event_type {
2384 handler(event, self)
2385 } else {
2386 true
2387 }
2388 });
2389 }
2390
2391 fn apply_refresh_effect(&mut self) {
2392 for window in self.windows.values_mut() {
2393 if let Some(window) = window.as_deref_mut() {
2394 window.refreshing = true;
2395 window.invalidator.set_dirty(true);
2396 }
2397 }
2398 }
2399
2400 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2401 self.pending_global_notifications.remove(&type_id);
2402 self.global_observers
2403 .clone()
2404 .retain(&type_id, |observer| observer(self));
2405 }
2406
2407 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2408 callback(self);
2409 }
2410
2411 fn apply_entity_created_effect(
2412 &mut self,
2413 entity: AnyEntity,
2414 tid: TypeId,
2415 window: Option<WindowId>,
2416 ) {
2417 if let Some(id) = window {
2421 self.current_window_by_entity.insert(entity.entity_id(), id);
2422 }
2423
2424 self.new_entity_observers.clone().retain(&tid, |observer| {
2425 if let Some(id) = window {
2426 self.update_window_id(id, {
2427 let entity = entity.clone();
2428 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2429 })
2430 .expect("All windows should be off the stack when flushing effects");
2431 } else {
2432 (observer)(entity.clone(), &mut None, self)
2433 }
2434 true
2435 });
2436 }
2437
2438 #[inline(always)]
2444 pub fn with_window<R>(
2445 &mut self,
2446 entity_id: EntityId,
2447 f: impl FnOnce(&mut Window, &mut App) -> R,
2448 ) -> Option<R> {
2449 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2450 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2451 .ok()
2452 }
2453
2454 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2455 self.current_window_by_entity
2456 .entry(entity_id)
2457 .or_insert(window);
2458 }
2459
2460 #[inline(always)]
2461 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2462 where
2463 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2464 {
2465 let mut update = Some(update);
2466 let mut result = None;
2467 self.update_window_erased(id, &mut |arguments| {
2468 if let Some((root_view, window, cx)) = arguments {
2469 result = Some(update.take().unwrap()(root_view, window, cx));
2470 } else {
2471 drop(update.take());
2472 drop(result.take());
2473 }
2474 });
2475 result.context("window not found")
2476 }
2477
2478 pub fn to_async(&self) -> AsyncApp {
2481 AsyncApp {
2482 app: self.this.clone(),
2483 background_executor: self.background_executor.clone(),
2484 foreground_executor: self.foreground_executor.clone(),
2485 }
2486 }
2487
2488 pub fn background_executor(&self) -> &BackgroundExecutor {
2490 &self.background_executor
2491 }
2492
2493 pub fn is_test(&self) -> bool {
2496 self.background_executor.is_test()
2497 }
2498
2499 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2501 if self.quitting {
2502 panic!("Can't spawn on main thread after on_app_quit")
2503 };
2504 &self.foreground_executor
2505 }
2506
2507 #[cfg(feature = "profiler")]
2510 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2511 self.foreground_journal.clone()
2512 }
2513
2514 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2531 pub fn start_hang_monitor(
2532 &mut self,
2533 config: crate::profiler::hang::HangMonitorConfig,
2534 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2535 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2536 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2537
2538 if self.hang_monitor.is_some() {
2539 debug_assert!(false, "the hang monitor was started twice");
2540 return Err(HangMonitorError::AlreadyStarted);
2541 }
2542 let detector = HangDetector::new(
2543 self.foreground_journal(),
2544 config.threshold,
2545 config.frame_budget,
2546 );
2547 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2548 .map_err(HangMonitorError::Spawn)?;
2549 self.hang_monitor = Some(monitor);
2550 Ok(())
2551 }
2552
2553 #[track_caller]
2556 #[inline(always)]
2557 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2558 where
2559 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2560 R: 'static,
2561 {
2562 let mut cx = self.prepare_spawn();
2563
2564 self.foreground_executor
2565 .spawn(async move { f(&mut cx).await }.boxed_local())
2566 }
2567
2568 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2572 where
2573 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2574 R: 'static,
2575 {
2576 if self.quitting {
2577 debug_panic!("Can't spawn on main thread after on_app_quit")
2578 };
2579
2580 let mut cx = self.to_async();
2581
2582 self.foreground_executor
2583 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2584 }
2585
2586 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2589 self.push_effect(Effect::Defer {
2590 callback: Box::new(f),
2591 });
2592 }
2593
2594 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2596 &self.asset_source
2597 }
2598
2599 pub fn text_system(&self) -> &Arc<TextSystem> {
2601 &self.text_system
2602 }
2603
2604 pub fn on_missing_glyphs(
2615 &self,
2616 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2617 ) -> Subscription {
2618 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2619
2620 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2621 let callback = self.missing_glyph_callback.clone();
2622 self.spawn(async move |cx| {
2623 while let Ok(missing_glyphs) = receiver.recv().await {
2624 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2625 }
2626 })
2627 .detach();
2628 }
2629 self.text_system.enable_missing_glyph_reporting();
2630
2631 let callback = self.missing_glyph_callback.clone();
2632 let text_system = self.text_system.clone();
2633 Subscription::new(move || {
2634 if callback.remove(®istration) {
2635 text_system.disable_missing_glyph_reporting();
2636 }
2637 })
2638 }
2639
2640 pub fn has_global<G: Global>(&self) -> bool {
2642 self.globals_by_type.contains_key(&TypeId::of::<G>())
2643 }
2644
2645 #[track_caller]
2647 pub fn global<G: Global>(&self) -> &G {
2648 self.globals_by_type
2649 .get(&TypeId::of::<G>())
2650 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2651 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2652 }
2653
2654 pub fn try_global<G: Global>(&self) -> Option<&G> {
2656 self.globals_by_type
2657 .get(&TypeId::of::<G>())
2658 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2659 }
2660
2661 #[track_caller]
2663 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2664 let global_type = TypeId::of::<G>();
2665 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2666 self.globals_by_type
2667 .get_mut(&global_type)
2668 .and_then(|any_state| any_state.downcast_mut::<G>())
2669 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2670 }
2671
2672 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2675 let global_type = TypeId::of::<G>();
2676 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2677 self.globals_by_type
2678 .entry(global_type)
2679 .or_insert_with(|| Box::<G>::default())
2680 .downcast_mut::<G>()
2681 .unwrap()
2682 }
2683
2684 pub fn set_global<G: Global>(&mut self, global: G) {
2686 let global_type = TypeId::of::<G>();
2687 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2688 self.globals_by_type.insert(global_type, Box::new(global));
2689 }
2690
2691 #[cfg(any(test, feature = "test-support"))]
2693 pub fn clear_globals(&mut self) {
2694 self.globals_by_type.drain();
2695 }
2696
2697 pub fn remove_global<G: Global>(&mut self) -> G {
2699 let global_type = TypeId::of::<G>();
2700 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2701 *self
2702 .globals_by_type
2703 .remove(&global_type)
2704 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2705 .downcast()
2706 .unwrap()
2707 }
2708
2709 pub fn observe_global<G: Global>(
2711 &mut self,
2712 mut f: impl FnMut(&mut Self) + 'static,
2713 ) -> Subscription {
2714 let (subscription, activate) = self.global_observers.insert_pending(
2715 TypeId::of::<G>(),
2716 Box::new(move |cx| {
2717 f(cx);
2718 true
2719 }),
2720 );
2721 self.defer(move |_| activate());
2722 subscription
2723 }
2724
2725 #[track_caller]
2727 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2728 GlobalLease::new(
2729 self.globals_by_type
2730 .remove(&TypeId::of::<G>())
2731 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2732 .unwrap(),
2733 )
2734 }
2735
2736 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2738 let global_type = TypeId::of::<G>();
2739
2740 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2741 self.globals_by_type.insert(global_type, lease.global);
2742 }
2743
2744 pub(crate) fn new_entity_observer(
2745 &self,
2746 key: TypeId,
2747 value: NewEntityListener,
2748 ) -> Subscription {
2749 self.new_entity_observers.insert(key, value)
2750 }
2751
2752 pub fn observe_new<T: 'static>(
2755 &self,
2756 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2757 ) -> Subscription {
2758 self.new_entity_observer(
2759 TypeId::of::<T>(),
2760 Box::new(
2761 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2762 any_entity
2763 .downcast::<T>()
2764 .unwrap()
2765 .update(cx, |entity_state, cx| {
2766 on_new(entity_state, window.as_deref_mut(), cx)
2767 })
2768 },
2769 ),
2770 )
2771 }
2772
2773 pub fn observe_release<T>(
2776 &self,
2777 handle: &Entity<T>,
2778 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2779 ) -> Subscription
2780 where
2781 T: 'static,
2782 {
2783 self.release_listeners.insert(
2784 handle.entity_id(),
2785 Box::new(move |entity, cx| {
2786 let entity = entity.downcast_mut().expect("invalid entity type");
2787 on_release(entity, cx)
2788 }),
2789 )
2790 }
2791
2792 pub fn observe_release_in<T>(
2795 &self,
2796 handle: &Entity<T>,
2797 window: &Window,
2798 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2799 ) -> Subscription
2800 where
2801 T: 'static,
2802 {
2803 let window_handle = window.handle;
2804 self.observe_release(handle, move |entity, cx| {
2805 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2806 })
2807 }
2808
2809 pub fn observe_keystrokes(
2814 &mut self,
2815 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2816 ) -> Subscription {
2817 self.keystroke_observers
2818 .insert(Box::new(move |event, window, cx| {
2819 f(event, window, cx);
2820 true
2821 }))
2822 }
2823
2824 pub fn intercept_keystrokes(
2829 &mut self,
2830 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2831 ) -> Subscription {
2832 self.keystroke_interceptors
2833 .insert(Box::new(move |event, window, cx| {
2834 f(event, window, cx);
2835 true
2836 }))
2837 }
2838
2839 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2841 self.keymap.borrow_mut().add_bindings(bindings);
2842 self.pending_effects.push_back(Effect::RefreshWindows);
2843 }
2844
2845 pub fn clear_key_bindings(&mut self) {
2847 self.keymap.borrow_mut().clear();
2848 self.pending_effects.push_back(Effect::RefreshWindows);
2849 }
2850
2851 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2853 self.keymap.clone()
2854 }
2855
2856 pub fn on_action<A: Action>(
2860 &mut self,
2861 listener: impl Fn(&A, &mut Self) + 'static,
2862 ) -> &mut Self {
2863 self.global_action_listeners
2864 .entry(TypeId::of::<A>())
2865 .or_default()
2866 .push(Rc::new(move |action, phase, cx| {
2867 if phase == DispatchPhase::Bubble {
2868 let action = action.downcast_ref().unwrap();
2869 listener(action, cx)
2870 }
2871 }));
2872 self
2873 }
2874
2875 pub fn stop_propagation(&mut self) {
2880 self.propagate_event = false;
2881 }
2882
2883 pub fn propagate(&mut self) {
2888 self.propagate_event = true;
2889 }
2890
2891 pub fn build_action(
2893 &self,
2894 name: &str,
2895 data: Option<serde_json::Value>,
2896 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2897 self.actions.build_action(name, data)
2898 }
2899
2900 pub fn all_action_names(&self) -> &[&'static str] {
2903 self.actions.all_action_names()
2904 }
2905
2906 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2910 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2911 }
2912
2913 pub fn action_schemas(
2915 &self,
2916 generator: &mut schemars::SchemaGenerator,
2917 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2918 self.actions.action_schemas(generator)
2919 }
2920
2921 pub fn action_schema_by_name(
2926 &self,
2927 name: &str,
2928 generator: &mut schemars::SchemaGenerator,
2929 ) -> Option<Option<schemars::Schema>> {
2930 self.actions.action_schema_by_name(name, generator)
2931 }
2932
2933 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2935 self.actions.deprecated_aliases()
2936 }
2937
2938 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2940 self.actions.deprecation_messages()
2941 }
2942
2943 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2945 self.actions.documentation()
2946 }
2947
2948 pub fn on_app_quit<Fut>(
2951 &self,
2952 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2953 ) -> Subscription
2954 where
2955 Fut: 'static + Future<Output = ()>,
2956 {
2957 self.quit_observers.insert(Box::new(move |cx| {
2958 let future = on_quit(cx);
2959 future.boxed_local()
2960 }))
2961 }
2962
2963 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2967 self.restart_observers.insert(Box::new(move |cx| {
2968 on_restart(cx);
2969 true
2970 }))
2971 }
2972
2973 pub fn on_window_closed(
2976 &self,
2977 on_closed: impl FnMut(&mut App, WindowId) + 'static,
2978 ) -> Subscription {
2979 self.window_closed_observers.insert(Box::new(on_closed))
2980 }
2981
2982 pub(crate) fn clear_pending_keystrokes(&mut self) {
2983 for window in self.windows() {
2984 window
2985 .update(self, |_, window, cx| {
2986 window.clear_pending_keystrokes(cx);
2987 })
2988 .ok();
2989 }
2990 }
2991
2992 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2995 let mut action_available = false;
2996 if let Some(window) = self.active_window()
2997 && let Ok(window_action_available) =
2998 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2999 {
3000 action_available = window_action_available;
3001 }
3002
3003 action_available
3004 || self
3005 .global_action_listeners
3006 .contains_key(&action.as_any().type_id())
3007 }
3008
3009 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
3011 let menus: Vec<Menu> = menus.into_iter().collect();
3012 self.platform.set_menus(menus, &self.keymap.borrow());
3013 }
3014
3015 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
3017 self.platform.get_menus()
3018 }
3019
3020 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
3022 self.platform.set_dock_menu(menus, &self.keymap.borrow())
3023 }
3024
3025 pub fn perform_dock_menu_action(&self, action: usize) {
3027 self.platform.perform_dock_menu_action(action);
3028 }
3029
3030 pub fn add_recent_document(&self, path: &Path) {
3035 self.platform.add_recent_document(path);
3036 }
3037
3038 pub fn update_jump_list(
3041 &self,
3042 menus: Vec<MenuItem>,
3043 entries: Vec<SmallVec<[PathBuf; 2]>>,
3044 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
3045 self.platform.update_jump_list(menus, entries)
3046 }
3047
3048 pub fn dispatch_action(&mut self, action: &dyn Action) {
3051 if let Some(active_window) = self.active_window() {
3052 active_window
3053 .update(self, |_, window, cx| {
3054 window.dispatch_action(action.boxed_clone(), cx)
3055 })
3056 .log_err();
3057 } else {
3058 self.dispatch_global_action(action);
3059 }
3060 }
3061
3062 fn dispatch_global_action(&mut self, action: &dyn Action) {
3063 self.propagate_event = true;
3064
3065 if let Some(mut global_listeners) = self
3066 .global_action_listeners
3067 .remove(&action.as_any().type_id())
3068 {
3069 for listener in &global_listeners {
3070 listener(action.as_any(), DispatchPhase::Capture, self);
3071 if !self.propagate_event {
3072 break;
3073 }
3074 }
3075
3076 global_listeners.extend(
3077 self.global_action_listeners
3078 .remove(&action.as_any().type_id())
3079 .unwrap_or_default(),
3080 );
3081
3082 self.global_action_listeners
3083 .insert(action.as_any().type_id(), global_listeners);
3084 }
3085
3086 if self.propagate_event
3087 && let Some(mut global_listeners) = self
3088 .global_action_listeners
3089 .remove(&action.as_any().type_id())
3090 {
3091 for listener in global_listeners.iter().rev() {
3092 listener(action.as_any(), DispatchPhase::Bubble, self);
3093 if !self.propagate_event {
3094 break;
3095 }
3096 }
3097
3098 global_listeners.extend(
3099 self.global_action_listeners
3100 .remove(&action.as_any().type_id())
3101 .unwrap_or_default(),
3102 );
3103
3104 self.global_action_listeners
3105 .insert(action.as_any().type_id(), global_listeners);
3106 }
3107 }
3108
3109 pub fn has_active_drag(&self) -> bool {
3111 self.active_drag.is_some()
3112 }
3113
3114 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3116 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3117 }
3118
3119 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3121 if self.active_drag.is_some() {
3122 self.active_drag = None;
3123 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
3124 drag.source_window == window.window_handle().window_id()
3125 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3126 }) {
3127 self.platform_owned_drag = None;
3128 }
3129 window.refresh();
3130 true
3131 } else {
3132 false
3133 }
3134 }
3135
3136 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3137 let Some(drag) = self.active_drag.take() else {
3138 return false;
3139 };
3140 self.platform_owned_drag = Some(PlatformOwnedDrag {
3141 source_window,
3142 state: PlatformOwnedDragState::Suspended(drag),
3143 });
3144 true
3145 }
3146
3147 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
3148 let Some(platform_drag) = self
3149 .platform_owned_drag
3150 .as_mut()
3151 .filter(|drag| drag.source_window == source_window)
3152 else {
3153 return false;
3154 };
3155 let state = std::mem::replace(
3156 &mut platform_drag.state,
3157 PlatformOwnedDragState::RestoredInSourceWindow,
3158 );
3159 let PlatformOwnedDragState::Suspended(drag) = state else {
3160 return false;
3161 };
3162 self.active_drag = Some(drag);
3163 true
3164 }
3165
3166 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3167 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
3168 drag.source_window == source_window
3169 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3170 }) else {
3171 return false;
3172 };
3173 let Some(drag) = self.active_drag.take() else {
3174 return false;
3175 };
3176 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
3177 true
3178 }
3179
3180 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
3181 if !self
3182 .platform_owned_drag
3183 .as_ref()
3184 .is_some_and(|drag| drag.source_window == source_window)
3185 {
3186 return false;
3187 }
3188 self.platform_owned_drag = None;
3189 self.active_drag = None;
3190 true
3191 }
3192
3193 pub fn set_active_drag_cursor_style(
3195 &mut self,
3196 cursor_style: CursorStyle,
3197 window: &mut Window,
3198 ) -> bool {
3199 if let Some(ref mut drag) = self.active_drag {
3200 drag.cursor_style = Some(cursor_style);
3201 window.refresh();
3202 true
3203 } else {
3204 false
3205 }
3206 }
3207
3208 pub fn set_prompt_builder(
3211 &mut self,
3212 renderer: impl Fn(
3213 PromptLevel,
3214 &str,
3215 Option<&str>,
3216 &[PromptButton],
3217 PromptHandle,
3218 &mut Window,
3219 &mut App,
3220 ) -> RenderablePromptHandle
3221 + 'static,
3222 ) {
3223 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3224 }
3225
3226 pub fn reset_prompt_builder(&mut self) {
3228 self.prompt_builder = Some(PromptBuilder::Default);
3229 }
3230
3231 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3233 let asset_id = (TypeId::of::<A>(), hash(source));
3234 self.loading_assets.remove(&asset_id);
3235 }
3236
3237 #[cfg(any(test, feature = "test-support"))]
3240 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3241 let asset_id = (TypeId::of::<A>(), hash(source));
3242 self.loading_assets.contains_key(&asset_id)
3243 }
3244
3245 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3250 self.asset_entry::<A>(source).get()
3251 }
3252
3253 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3254 let asset_id = (TypeId::of::<A>(), hash(source));
3255 if !self.loading_assets.contains_key(&asset_id) {
3256 let future = A::load(source.clone(), self);
3257 let entry = CachedLoad::new(future, self);
3258 self.loading_assets.insert(asset_id, Box::new(entry));
3259 }
3260 self.loading_assets
3261 .get(&asset_id)
3262 .and_then(|entry| entry.downcast_ref())
3263 .expect("asset cache entries are keyed by their asset type")
3264 }
3265
3266 #[track_caller]
3269 pub fn focus_handle(&self) -> FocusHandle {
3270 FocusHandle::new(&self.focus_handles)
3271 }
3272
3273 pub fn notify(&mut self, entity_id: EntityId) {
3275 let window_invalidators = mem::take(
3276 self.window_invalidators_by_entity
3277 .entry(entity_id)
3278 .or_default(),
3279 );
3280
3281 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3286 .iter()
3287 .filter(|(window_id, _)| {
3288 self.tracked_entities
3289 .get(window_id)
3290 .is_some_and(|set| set.contains(&entity_id))
3291 })
3292 .map(|(_, invalidator)| invalidator.clone())
3293 .collect();
3294
3295 if live_invalidators.is_empty() {
3296 if self.pending_notifications.insert(entity_id) {
3297 self.pending_effects
3298 .push_back(Effect::Notify { emitter: entity_id });
3299 }
3300 } else {
3301 for invalidator in &live_invalidators {
3302 invalidator.invalidate_view(entity_id, self);
3303 }
3304 }
3305
3306 self.window_invalidators_by_entity
3307 .insert(entity_id, window_invalidators);
3308 }
3309
3310 #[cfg(any(test, feature = "test-support", debug_assertions))]
3312 pub fn get_name(&self) -> Option<&'static str> {
3313 self.name
3314 }
3315
3316 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3318 self.platform.can_select_mixed_files_and_dirs()
3319 }
3320
3321 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3326 for window in self.windows.values_mut().flatten() {
3328 _ = window.drop_image(image.clone());
3329 }
3330
3331 if let Some(window) = current_window {
3333 _ = window.drop_image(image);
3334 }
3335 }
3336
3337 #[cfg(any(feature = "inspector", debug_assertions))]
3339 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3340 self.inspector_renderer = Some(f);
3341 }
3342
3343 #[cfg(any(feature = "inspector", debug_assertions))]
3345 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3346 &mut self,
3347 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3348 ) where
3349 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3350 {
3351 self.inspector_element_registry.register(factory);
3352 }
3353
3354 pub fn init_colors(&mut self) {
3358 self.set_global(GlobalColors(Arc::new(Colors::default())));
3359 }
3360
3361 #[inline(never)]
3362 fn update_window_erased(
3363 &mut self,
3364 window_id: WindowId,
3365 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3366 ) {
3367 self.update(|cx| {
3368 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3369 update(None);
3370 return;
3371 };
3372
3373 let root_view = window.root.clone().unwrap();
3374
3375 cx.window_update_stack.push(WindowUpdateEntry {
3376 window_id: window.handle.id,
3377 bounds: window.last_window_bounds(),
3378 display_id: window.display_id(),
3379 });
3380 update(Some((root_view, &mut window, cx)));
3381 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3382 cx.window_update_stack.pop();
3383
3384 if window.removed {
3385 cx.end_platform_drag(window_id);
3386 cx.window_handles.remove(&window_id);
3387 cx.windows.remove(window_id);
3388 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3389 for entity_id in tracked {
3390 if let Some(windows) =
3391 cx.window_invalidators_by_entity.get_mut(&entity_id)
3392 {
3393 windows.remove(&window_id);
3394 }
3395 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3396 cx.current_window_by_entity.remove(&entity_id);
3397 }
3398 }
3399 }
3400
3401 cx.window_closed_observers.clone().retain(|callback| {
3402 callback(cx, window_id);
3403 true
3404 });
3405
3406 let quit_on_empty = match cx.quit_mode {
3407 QuitMode::Explicit => false,
3408 QuitMode::LastWindowClosed => true,
3409 QuitMode::Default => cfg!(not(target_os = "macos")),
3410 };
3411
3412 if quit_on_empty && cx.windows.is_empty() {
3413 cx.quit();
3414 }
3415 } else {
3416 cx.windows.get_mut(window_id)?.replace(window);
3417 }
3418 Some(())
3419 }
3420 if trail(window_id, window, cx).is_none() {
3421 update(None);
3422 }
3423 });
3424 }
3425
3426 #[inline(never)]
3427 fn update_entity_erased(
3428 &mut self,
3429 handle: &AnyEntity,
3430 entity_type: &str,
3431 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3432 ) {
3433 self.update(|cx| {
3434 let mut lease = cx.entities.lease_erased(handle, entity_type);
3435 update(lease.entity.as_deref_mut().unwrap(), cx);
3436 cx.entities.end_lease_erased(handle.entity_id, lease);
3437 });
3438 }
3439
3440 #[inline(never)]
3441 #[track_caller]
3442 fn prepare_spawn(&self) -> AsyncApp {
3443 if self.quitting {
3444 debug_panic!("Can't spawn on main thread after on_app_quit")
3445 };
3446 self.to_async()
3447 }
3448}
3449
3450impl AppContext for App {
3451 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3456 self.update(|cx| {
3457 let slot = cx.entities.reserve();
3458 let handle = slot.clone();
3459 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3460
3461 cx.push_effect(Effect::EntityCreated {
3462 entity: handle.into_any(),
3463 tid: TypeId::of::<T>(),
3464 window: cx.window_update_stack.last().map(|state| state.window_id),
3465 });
3466
3467 cx.entities.insert(slot, entity)
3468 })
3469 }
3470
3471 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3472 Reservation(self.entities.reserve())
3473 }
3474
3475 fn insert_entity<T: 'static>(
3476 &mut self,
3477 reservation: Reservation<T>,
3478 build_entity: impl FnOnce(&mut Context<T>) -> T,
3479 ) -> Entity<T> {
3480 self.update(|cx| {
3481 let slot = reservation.0;
3482 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3483 cx.entities.insert(slot, entity)
3484 })
3485 }
3486
3487 #[inline(always)]
3490 fn update_entity<T: 'static, R>(
3491 &mut self,
3492 handle: &Entity<T>,
3493 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3494 ) -> R {
3495 let mut update = Some(update);
3496 let mut result = None;
3497 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3498 let value = update.take().unwrap()(
3499 entity.downcast_mut::<T>().unwrap(),
3500 &mut Context::new_context(cx, handle.downgrade()),
3501 );
3502 result = Some(value);
3503 });
3504 result.unwrap()
3505 }
3506
3507 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3508 where
3509 T: 'static,
3510 {
3511 GpuiBorrow::new(handle.clone(), self)
3512 }
3513
3514 #[inline(always)]
3515 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3516 where
3517 T: 'static,
3518 {
3519 let entity = self.entities.read(handle);
3520 read(entity, self)
3521 }
3522
3523 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3524 where
3525 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3526 {
3527 self.update_window_id(handle.id, update)
3528 }
3529
3530 fn with_window<R>(
3531 &mut self,
3532 entity_id: EntityId,
3533 f: impl FnOnce(&mut Window, &mut App) -> R,
3534 ) -> Option<R> {
3535 App::with_window(self, entity_id, f)
3536 }
3537
3538 fn read_window<T, R>(
3539 &self,
3540 window: &WindowHandle<T>,
3541 read: impl FnOnce(Entity<T>, &App) -> R,
3542 ) -> Result<R>
3543 where
3544 T: 'static,
3545 {
3546 let window = self
3547 .windows
3548 .get(window.id)
3549 .context("window not found")?
3550 .as_deref()
3551 .expect("attempted to read a window that is already on the stack");
3552
3553 let root_view = window.root.clone().unwrap();
3554 let view = root_view
3555 .downcast::<T>()
3556 .map_err(|_| anyhow!("root view's type has changed"))?;
3557
3558 Ok(read(view, self))
3559 }
3560
3561 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3562 where
3563 R: Send + 'static,
3564 {
3565 self.background_executor.spawn(future)
3566 }
3567
3568 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3569 where
3570 G: Global,
3571 {
3572 let g = self.global::<G>();
3573 callback(g, self)
3574 }
3575}
3576
3577pub(crate) enum Effect {
3579 Notify {
3580 emitter: EntityId,
3581 },
3582 Emit {
3583 emitter: EntityId,
3584 event_type: TypeId,
3585 event: ArenaBox<dyn Any>,
3586 },
3587 RefreshWindows,
3588 NotifyGlobalObservers {
3589 global_type: TypeId,
3590 },
3591 Defer {
3592 callback: Box<dyn FnOnce(&mut App) + 'static>,
3593 },
3594 EntityCreated {
3595 entity: AnyEntity,
3596 tid: TypeId,
3597 window: Option<WindowId>,
3598 },
3599}
3600
3601impl std::fmt::Debug for Effect {
3602 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3603 match self {
3604 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3605 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3606 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3607 Effect::NotifyGlobalObservers { global_type } => {
3608 write!(f, "NotifyGlobalObservers({:?})", global_type)
3609 }
3610 Effect::Defer { .. } => write!(f, "Defer(..)"),
3611 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3612 }
3613 }
3614}
3615
3616pub(crate) struct GlobalLease<G: Global> {
3618 global: Box<dyn Any>,
3619 global_type: PhantomData<G>,
3620}
3621
3622impl<G: Global> GlobalLease<G> {
3623 fn new(global: Box<dyn Any>) -> Self {
3624 GlobalLease {
3625 global,
3626 global_type: PhantomData,
3627 }
3628 }
3629}
3630
3631impl<G: Global> Deref for GlobalLease<G> {
3632 type Target = G;
3633
3634 fn deref(&self) -> &Self::Target {
3635 self.global.downcast_ref().unwrap()
3636 }
3637}
3638
3639impl<G: Global> DerefMut for GlobalLease<G> {
3640 fn deref_mut(&mut self) -> &mut Self::Target {
3641 self.global.downcast_mut().unwrap()
3642 }
3643}
3644
3645pub struct AnyDrag {
3648 pub view: AnyView,
3650
3651 pub value: Arc<dyn Any>,
3653
3654 pub cursor_offset: Point<Pixels>,
3657
3658 pub cursor_style: Option<CursorStyle>,
3660
3661 pub external_payload_source: Option<ExternalDragPayloadSource>,
3664}
3665
3666pub type ExternalDragPayloadSource =
3669 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3670
3671#[derive(Clone)]
3674pub struct AnyTooltip {
3675 pub view: AnyView,
3677
3678 pub mouse_position: Point<Pixels>,
3680
3681 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3685}
3686
3687#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3689pub enum InputPreference {
3690 CharacterInput,
3692 KeyBindings,
3694}
3695
3696#[derive(Debug)]
3698pub struct KeystrokeEvent {
3699 pub keystroke: Keystroke,
3701
3702 pub input_preference: InputPreference,
3710
3711 pub action: Option<Box<dyn Action>>,
3713
3714 pub context_stack: Vec<KeyContext>,
3716}
3717
3718struct NullHttpClient;
3719
3720impl HttpClient for NullHttpClient {
3721 fn send(
3722 &self,
3723 _req: http_client::Request<http_client::AsyncBody>,
3724 ) -> futures::future::BoxFuture<
3725 'static,
3726 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3727 > {
3728 async move {
3729 anyhow::bail!("No HttpClient available");
3730 }
3731 .boxed()
3732 }
3733
3734 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3735 None
3736 }
3737
3738 fn proxy(&self) -> Option<&Url> {
3739 None
3740 }
3741}
3742
3743pub struct GpuiBorrow<'a, T> {
3745 inner: Option<Lease<T>>,
3746 app: &'a mut App,
3747}
3748
3749impl<'a, T: 'static> GpuiBorrow<'a, T> {
3750 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3751 app.start_update();
3752 let lease = app.entities.lease(&inner);
3753 Self {
3754 inner: Some(lease),
3755 app,
3756 }
3757 }
3758}
3759
3760impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3761 fn borrow(&self) -> &T {
3762 self.inner.as_ref().unwrap().borrow()
3763 }
3764}
3765
3766impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3767 fn borrow_mut(&mut self) -> &mut T {
3768 self.inner.as_mut().unwrap().borrow_mut()
3769 }
3770}
3771
3772impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3773 type Target = T;
3774
3775 fn deref(&self) -> &Self::Target {
3776 self.inner.as_ref().unwrap()
3777 }
3778}
3779
3780impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3781 fn deref_mut(&mut self) -> &mut T {
3782 self.inner.as_mut().unwrap()
3783 }
3784}
3785
3786impl<'a, T> Drop for GpuiBorrow<'a, T> {
3787 fn drop(&mut self) {
3788 let lease = self.inner.take().unwrap();
3789 self.app.notify(lease.id);
3790 self.app.entities.end_lease(lease);
3791 self.app.finish_update();
3792 }
3793}
3794
3795#[cfg(test)]
3796mod test {
3797 use std::{
3798 cell::{Cell, RefCell},
3799 ffi::OsString,
3800 path::PathBuf,
3801 rc::Rc,
3802 };
3803
3804 #[cfg(unix)]
3805 use std::os::unix::ffi::OsStringExt;
3806
3807 use crate::{
3808 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3809 TestAppContext, Window,
3810 };
3811
3812 #[gpui::test]
3813 fn app_borrow_diagnostics(cx: &mut TestAppContext) {
3814 use std::panic::{AssertUnwindSafe, catch_unwind};
3815
3816 let app = cx.app.clone();
3817 let first_line = line!() + 1;
3818 let first = app.borrow();
3819 let second = app.borrow();
3820 drop(first);
3821 assert!(app.try_borrow_mut().is_err());
3822 let attempted_line = line!() + 1;
3823 let panic = catch_unwind(AssertUnwindSafe(|| drop(app.borrow_mut())));
3824 let message = *panic
3825 .expect_err("conflicting borrow")
3826 .downcast::<String>()
3827 .unwrap();
3828 assert!(message.contains(&format!(
3829 "mutable App borrow at {}:{attempted_line}:",
3830 file!()
3831 )));
3832 assert!(message.contains(&format!(
3833 "shared borrow group began at {}:{first_line}:",
3834 file!()
3835 )));
3836 drop(second);
3837
3838 let origin_line = line!() + 2;
3839 let panic = catch_unwind(AssertUnwindSafe(|| {
3840 let _borrow = app.try_borrow_mut().expect("initial borrow");
3841 drop(app.borrow());
3842 }));
3843 let message = *panic
3844 .expect_err("conflicting borrow")
3845 .downcast::<String>()
3846 .unwrap();
3847 assert!(message.contains("attempted shared App borrow"));
3848 assert!(message.contains(&format!(
3849 "mutable borrow group began at {}:{origin_line}:",
3850 file!()
3851 )));
3852
3853 let next_line = line!() + 1;
3854 let _borrow = app.borrow();
3855 assert_eq!(
3856 app.borrow_origin.get().expect("new origin").0.line(),
3857 next_line
3858 );
3859 }
3860
3861 struct RenderCounter(Rc<Cell<usize>>);
3862
3863 impl Render for RenderCounter {
3864 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3865 self.0.set(self.0.get() + 1);
3866 Empty
3867 }
3868 }
3869
3870 #[gpui::test]
3871 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3872 let render_count = Rc::new(Cell::new(0));
3873
3874 let _window = cx.add_window({
3875 let render_count = render_count.clone();
3876 move |_, _| RenderCounter(render_count)
3877 });
3878
3879 cx.run_until_parked();
3880 let render_count_before_refresh = render_count.get();
3881
3882 cx.to_async().refresh();
3883
3884 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3885 }
3886
3887 #[gpui::test]
3888 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3889 let observed = Rc::new(RefCell::new(Vec::new()));
3890 let subscription = cx.update(|cx| {
3891 let observed = observed.clone();
3892 cx.on_missing_glyphs(move |missing_glyphs, _| {
3893 observed.borrow_mut().extend_from_slice(missing_glyphs);
3894 })
3895 });
3896 cx.update(|cx| {
3897 cx.text_system()
3898 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3899 });
3900 cx.run_until_parked();
3901 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3902
3903 let second_observed = Rc::new(RefCell::new(Vec::new()));
3904 let second_subscription = cx.update(|cx| {
3905 let second_observed = second_observed.clone();
3906 cx.on_missing_glyphs(move |missing_glyphs, _| {
3907 second_observed
3908 .borrow_mut()
3909 .extend_from_slice(missing_glyphs);
3910 })
3911 });
3912 cx.update(|cx| {
3913 cx.text_system()
3914 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3915 });
3916 cx.run_until_parked();
3917 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3918 assert_eq!(
3919 second_observed.borrow().as_slice(),
3920 &[missing_glyph("replacement")]
3921 );
3922
3923 drop(subscription);
3924 cx.update(|cx| {
3925 cx.text_system()
3926 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3927 });
3928 cx.run_until_parked();
3929 assert_eq!(
3930 second_observed.borrow().as_slice(),
3931 &[
3932 missing_glyph("replacement"),
3933 missing_glyph("after old drop")
3934 ]
3935 );
3936
3937 drop(second_subscription);
3938 cx.update(|cx| {
3939 cx.text_system()
3940 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3941 });
3942 cx.run_until_parked();
3943 assert_eq!(second_observed.borrow().len(), 2);
3944 }
3945
3946 #[test]
3947 fn test_gpui_borrow() {
3948 let cx = TestAppContext::single();
3949 let observation_count = Rc::new(RefCell::new(0));
3950
3951 let state = cx.update(|cx| {
3952 let state = cx.new(|_| false);
3953 cx.observe(&state, {
3954 let observation_count = observation_count.clone();
3955 move |_, _| {
3956 let mut count = observation_count.borrow_mut();
3957 *count += 1;
3958 }
3959 })
3960 .detach();
3961
3962 state
3963 });
3964
3965 cx.update(|cx| {
3966 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3968 });
3969
3970 cx.update(|cx| {
3971 state.write(cx, false);
3972 });
3973
3974 assert_eq!(*observation_count.borrow(), 2);
3975 }
3976
3977 #[gpui::test]
3978 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3979 #[cfg(unix)]
3980 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3981 #[cfg(not(unix))]
3982 let user_data_dir = OsString::from("C:\\zed data");
3983 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3984 let restart_path = PathBuf::from("updated-zed");
3985 let _application =
3986 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3987 let restart = cx.expect_restart();
3988
3989 cx.update(|cx| {
3990 cx.set_restart_path(restart_path.clone());
3991 cx.restart();
3992 });
3993
3994 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3995 assert_eq!(path, Some(restart_path));
3996 assert_eq!(restart_arguments, arguments);
3997 }
3998
3999 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
4000 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
4001 }
4002}