1use scheduler::Instant;
2use std::{
3 any::{TypeId, type_name},
4 cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
5 ffi::OsString,
6 marker::PhantomData,
7 mem,
8 ops::{Deref, DerefMut},
9 path::{Path, PathBuf},
10 rc::{Rc, Weak},
11 sync::Arc,
12 time::Duration,
13};
14
15use anyhow::{Context as _, Result, anyhow};
16use derive_more::{Deref, DerefMut};
17use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
18use itertools::Itertools;
19use parking_lot::RwLock;
20use slotmap::SlotMap;
21
22pub use async_context::*;
23#[cfg(feature = "bench-support")]
24pub use bench_context::{
25 BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
26 MetricReport, bench_platform,
27};
28use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
29pub use context::*;
30pub use entity_map::*;
31use gpui_util::{ResultExt, debug_panic};
32#[cfg(any(test, feature = "test-support"))]
33pub use headless_app_context::*;
34use http_client::{HttpClient, Url};
35use smallvec::SmallVec;
36#[cfg(any(test, feature = "test-support"))]
37pub use test_app::*;
38#[cfg(any(test, feature = "test-support"))]
39pub use test_context::*;
40#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
41pub use visual_test_context::*;
42
43#[cfg(any(feature = "inspector", debug_assertions))]
44use crate::InspectorElementRegistry;
45use crate::asset_cache::CachedLoad;
46use crate::{
47 Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
48 AnyWindowHandle, AppContext, AppLifecyclePhase, Arena, ArenaBox, Asset, AssetSource,
49 BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase,
50 DisplayChanges, DisplayEvent, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle,
51 FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId,
52 Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
53 PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
54 PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
55 ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
56 SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
57 ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
58 WindowInvalidator, WindowingRequest,
59 colors::{Colors, GlobalColors},
60 hash, init_app_menus,
61};
62
63mod async_context;
64#[cfg(feature = "bench-support")]
65mod bench_context;
66mod context;
67mod entity_map;
68#[cfg(any(test, feature = "test-support"))]
69mod headless_app_context;
70#[cfg(any(test, feature = "test-support"))]
71mod test_app;
72#[cfg(any(test, feature = "test-support"))]
73mod test_context;
74#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
75mod visual_test_context;
76
77pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
80
81#[doc(hidden)]
84pub struct AppCell {
85 app: RefCell<App>,
86 borrow_origin: Cell<Option<(&'static std::panic::Location<'static>, &'static str)>>,
87}
88
89impl AppCell {
90 #[cold]
91 #[track_caller]
92 fn borrow_failed(&self, kind: &str) -> ! {
93 let attempted = std::panic::Location::caller();
94 if let Some((origin, existing_kind)) = self.borrow_origin.get() {
95 panic!(
96 "RefCell already borrowed: attempted {kind} App borrow at {attempted}; \
97 existing {existing_kind} borrow group began at {origin}"
98 );
99 }
100 panic!(
101 "RefCell already borrowed: attempted {kind} App borrow at {attempted}; origin unavailable"
102 );
103 }
104
105 #[doc(hidden)]
106 #[track_caller]
107 pub fn borrow(&self) -> AppRef<'_> {
108 if option_env!("TRACK_THREAD_BORROWS").is_some() {
109 let thread_id = std::thread::current().id();
110 eprintln!("borrowed {thread_id:?}");
111 }
112 let starts_borrow_group = self.app.try_borrow_mut().is_ok();
115 let borrow = match self.app.try_borrow() {
116 Ok(borrow) => borrow,
117 Err(_) => self.borrow_failed("shared"),
118 };
119 if starts_borrow_group {
120 self.borrow_origin
121 .set(Some((std::panic::Location::caller(), "shared")));
122 }
123 AppRef(borrow)
124 }
125
126 #[doc(hidden)]
127 #[track_caller]
128 pub fn borrow_mut(&self) -> AppRefMut<'_> {
129 match self.try_borrow_mut() {
130 Ok(borrow) => borrow,
131 Err(_) => self.borrow_failed("mutable"),
132 }
133 }
134
135 #[doc(hidden)]
136 #[track_caller]
137 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
138 if option_env!("TRACK_THREAD_BORROWS").is_some() {
139 let thread_id = std::thread::current().id();
140 eprintln!("borrowed {thread_id:?}");
141 }
142 let borrow = self.app.try_borrow_mut()?;
143 self.borrow_origin
144 .set(Some((std::panic::Location::caller(), "mutable")));
145 Ok(AppRefMut(borrow))
146 }
147}
148
149#[doc(hidden)]
150#[derive(Deref, DerefMut)]
151pub struct AppRef<'a>(Ref<'a, App>);
152
153impl Drop for AppRef<'_> {
154 fn drop(&mut self) {
155 if option_env!("TRACK_THREAD_BORROWS").is_some() {
156 let thread_id = std::thread::current().id();
157 eprintln!("dropped borrow from {thread_id:?}");
158 }
159 }
160}
161
162#[doc(hidden)]
163#[derive(Deref, DerefMut)]
164pub struct AppRefMut<'a>(RefMut<'a, App>);
165
166impl Drop for AppRefMut<'_> {
167 fn drop(&mut self) {
168 if option_env!("TRACK_THREAD_BORROWS").is_some() {
169 let thread_id = std::thread::current().id();
170 eprintln!("dropped {thread_id:?}");
171 }
172 }
173}
174
175pub struct Application(Rc<AppCell>);
178
179pub struct ApplicationHandle {
185 app: Rc<AppCell>,
186}
187
188impl ApplicationHandle {
189 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
193 let cx = &mut *self.app.borrow_mut();
194 f(cx)
195 }
196
197 pub fn to_async(&self) -> AsyncApp {
200 self.update(|cx| cx.to_async())
201 }
202}
203
204impl Application {
207 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
209 Self(App::new_app(
210 platform,
211 Arc::new(()),
212 Arc::new(NullHttpClient),
213 ))
214 }
215
216 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
226 let this = Self::with_platform(platform);
227 this.0.borrow_mut().accessibility_force_disabled = true;
228 this
229 }
230
231 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
233 let mut context_lock = self.0.borrow_mut();
234 let asset_source = Arc::new(asset_source);
235 context_lock.asset_source = asset_source.clone();
236 context_lock.svg_renderer = SvgRenderer::new(asset_source);
237 drop(context_lock);
238 self
239 }
240
241 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
243 self.0.borrow_mut().restart_arguments = arguments;
244 self
245 }
246
247 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
249 let mut context_lock = self.0.borrow_mut();
250 context_lock.http_client = http_client;
251 drop(context_lock);
252 self
253 }
254
255 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
258 self.0.borrow_mut().quit_mode = mode;
259 self
260 }
261
262 pub fn with_windowing(self, request: WindowingRequest) -> Self {
269 self.0.borrow().platform.set_initial_windowing(request);
270 self
271 }
272
273 pub fn run<F>(self, on_finish_launching: F)
279 where
280 F: 'static + FnOnce(&mut App),
281 {
282 let this = self.0.clone();
283 let platform = self.0.borrow().platform.clone();
284 platform.run(Box::new(move || {
285 let cx = &mut *this.borrow_mut();
286 cx.displays_changed();
288 #[cfg(gpui_hot_reload)]
289 crate::hot_reload::init(cx);
290 on_finish_launching(cx);
291 }));
292
293 #[cfg(target_family = "wasm")]
294 std::mem::forget(self);
295 }
296
297 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
307 where
308 F: 'static + FnOnce(&mut App),
309 {
310 let this = self.0.clone();
311 let platform = self.0.borrow().platform.clone();
312 platform.run(Box::new(move || {
313 let cx = &mut *this.borrow_mut();
314 cx.displays_changed();
316 #[cfg(gpui_hot_reload)]
317 crate::hot_reload::init(cx);
318 on_finish_launching(cx);
319 }));
320 ApplicationHandle { app: self.0 }
321 }
322
323 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
326 where
327 F: 'static + FnMut(Vec<String>),
328 {
329 self.0.borrow().platform.on_open_urls(Box::new(callback));
330 self
331 }
332
333 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
336 where
337 F: 'static + FnMut(&mut App),
338 {
339 let this = Rc::downgrade(&self.0);
340 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
341 if let Some(app) = this.upgrade() {
342 callback(&mut app.borrow_mut());
343 }
344 }));
345 self
346 }
347
348 pub fn background_executor(&self) -> BackgroundExecutor {
350 self.0.borrow().background_executor.clone()
351 }
352
353 pub fn foreground_executor(&self) -> ForegroundExecutor {
355 self.0.borrow().foreground_executor.clone()
356 }
357
358 pub fn text_system(&self) -> Arc<TextSystem> {
360 self.0.borrow().text_system.clone()
361 }
362
363 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
365 self.0.borrow().path_for_auxiliary_executable(name)
366 }
367}
368
369type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
370type AppLifecycleHandler = Box<dyn FnMut(AppLifecyclePhase, &mut App) -> bool + 'static>;
371type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
372
373#[derive(Clone, Copy, PartialEq)]
375struct DisplayState {
376 bounds: Bounds<Pixels>,
377 refresh_interval: Option<Duration>,
378}
379
380impl DisplayState {
381 fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
382 let mut changes = DisplayChanges::empty();
383 changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
384 changes.set(
385 DisplayChanges::REFRESH_INTERVAL,
386 self.refresh_interval != previous.refresh_interval,
387 );
388 changes
389 }
390}
391
392fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
393 platform
394 .displays()
395 .into_iter()
396 .map(|display| {
397 let state = DisplayState {
398 bounds: display.bounds(),
399 refresh_interval: display.refresh_interval(),
400 };
401 (display.id(), state)
402 })
403 .collect()
404}
405
406fn display_events(
408 previous: &HashMap<DisplayId, DisplayState>,
409 current: &HashMap<DisplayId, DisplayState>,
410) -> Vec<DisplayEvent> {
411 let removed = previous
412 .keys()
413 .filter(|id| !current.contains_key(id))
414 .map(|id| DisplayEvent::Removed(*id));
415 let added_or_changed = current.iter().filter_map(|(id, state)| {
416 let Some(previous_state) = previous.get(id) else {
417 return Some(DisplayEvent::Added(*id));
418 };
419 let changes = state.changes_from(previous_state);
420 (!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
421 });
422 removed.chain(added_or_changed).collect()
423}
424type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
425type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
426pub(crate) type KeystrokeObserver =
427 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
428type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
429type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
430type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
431type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
432
433struct MissingGlyphCallbackEntry {
434 registration: Rc<()>,
435 callback: Option<MissingGlyphCallback>,
436}
437
438#[derive(Default)]
439struct MissingGlyphCallbackSlot {
440 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
441}
442
443impl MissingGlyphCallbackSlot {
444 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
445 let registration = Rc::new(());
446 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
447 registration: registration.clone(),
448 callback: Some(callback),
449 });
450 registration
451 }
452
453 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
454 let Some((registration, mut callback)) =
455 self.entry.borrow_mut().as_mut().and_then(|entry| {
456 entry
457 .callback
458 .take()
459 .map(|callback| (entry.registration.clone(), callback))
460 })
461 else {
462 return;
463 };
464 callback(missing_glyphs, cx);
465
466 let mut entry = self.entry.borrow_mut();
467 let is_current = entry
468 .as_ref()
469 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
470 if is_current {
471 let Some(entry) = entry.as_mut() else {
472 return;
473 };
474 entry.callback = Some(callback);
475 }
476 }
477
478 fn remove(&self, registration: &Rc<()>) -> bool {
479 let mut entry = self.entry.borrow_mut();
480 let is_current = entry
481 .as_ref()
482 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
483 if is_current {
484 entry.take();
485 }
486 is_current
487 }
488}
489
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
492pub enum QuitMode {
493 #[default]
495 Default,
496 LastWindowClosed,
498 Explicit,
500}
501
502#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
507pub enum CursorHideMode {
508 Never,
510 OnTyping,
512 #[default]
515 OnTypingAndAction,
516}
517
518#[doc(hidden)]
519#[derive(Clone, PartialEq, Eq)]
520pub struct SystemWindowTab {
521 pub id: WindowId,
522 pub title: SharedString,
523 pub handle: AnyWindowHandle,
524 pub last_active_at: Instant,
525}
526
527impl SystemWindowTab {
528 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
530 Self {
531 id: handle.id,
532 title,
533 handle,
534 last_active_at: Instant::now(),
535 }
536 }
537}
538
539#[derive(Default)]
541pub struct SystemWindowTabController {
542 visible: Option<bool>,
543 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
544}
545
546impl Global for SystemWindowTabController {}
547
548impl SystemWindowTabController {
549 pub fn new() -> Self {
551 Self {
552 visible: None,
553 tab_groups: FxHashMap::default(),
554 }
555 }
556
557 pub fn init(cx: &mut App) {
559 cx.set_global(SystemWindowTabController::new());
560 }
561
562 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
564 &self.tab_groups
565 }
566
567 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
569 let controller = cx.global::<SystemWindowTabController>();
570 let current_group = controller
571 .tab_groups
572 .iter()
573 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
574
575 let current_group = current_group?;
576 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
578 let idx = group_ids.iter().position(|g| *g == current_group)?;
579 let next_idx = (idx + 1) % group_ids.len();
580
581 controller
582 .tab_groups
583 .get(group_ids[next_idx])
584 .and_then(|tabs| {
585 tabs.iter()
586 .max_by_key(|tab| tab.last_active_at)
587 .or_else(|| tabs.first())
588 .map(|tab| &tab.handle)
589 })
590 }
591
592 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
594 let controller = cx.global::<SystemWindowTabController>();
595 let current_group = controller
596 .tab_groups
597 .iter()
598 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
599
600 let current_group = current_group?;
601 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
603 let idx = group_ids.iter().position(|g| *g == current_group)?;
604 let prev_idx = if idx == 0 {
605 group_ids.len() - 1
606 } else {
607 idx - 1
608 };
609
610 controller
611 .tab_groups
612 .get(group_ids[prev_idx])
613 .and_then(|tabs| {
614 tabs.iter()
615 .max_by_key(|tab| tab.last_active_at)
616 .or_else(|| tabs.first())
617 .map(|tab| &tab.handle)
618 })
619 }
620
621 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
623 self.tab_groups
624 .values()
625 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
626 }
627
628 pub fn init_visible(cx: &mut App, visible: bool) {
630 let mut controller = cx.global_mut::<SystemWindowTabController>();
631 if controller.visible.is_none() {
632 controller.visible = Some(visible);
633 }
634 }
635
636 pub fn is_visible(&self) -> bool {
638 self.visible.unwrap_or(false)
639 }
640
641 pub fn set_visible(cx: &mut App, visible: bool) {
643 let mut controller = cx.global_mut::<SystemWindowTabController>();
644 controller.visible = Some(visible);
645 }
646
647 pub fn update_last_active(cx: &mut App, id: WindowId) {
649 let mut controller = cx.global_mut::<SystemWindowTabController>();
650 for windows in controller.tab_groups.values_mut() {
651 for tab in windows.iter_mut() {
652 if tab.id == id {
653 tab.last_active_at = Instant::now();
654 }
655 }
656 }
657 }
658
659 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
661 let mut controller = cx.global_mut::<SystemWindowTabController>();
662 for (_, windows) in controller.tab_groups.iter_mut() {
663 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
664 if ix < windows.len() && current_pos != ix {
665 let window_tab = windows.remove(current_pos);
666 windows.insert(ix, window_tab);
667 }
668 break;
669 }
670 }
671 }
672
673 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
675 let controller = cx.global::<SystemWindowTabController>();
676 let tab = controller
677 .tab_groups
678 .values()
679 .flat_map(|windows| windows.iter())
680 .find(|tab| tab.id == id);
681
682 if tab.map_or(true, |t| t.title == title) {
683 return;
684 }
685
686 let mut controller = cx.global_mut::<SystemWindowTabController>();
687 for windows in controller.tab_groups.values_mut() {
688 for tab in windows.iter_mut() {
689 if tab.id == id {
690 tab.title = title;
691 return;
692 }
693 }
694 }
695 }
696
697 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
699 let mut controller = cx.global_mut::<SystemWindowTabController>();
700 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
701 return;
702 };
703
704 let mut expected_tab_ids: Vec<_> = tabs
705 .iter()
706 .filter(|tab| tab.id != id)
707 .map(|tab| tab.id)
708 .sorted()
709 .collect();
710
711 let mut tab_group_id = None;
712 for (group_id, group_tabs) in &controller.tab_groups {
713 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
714 if tab_ids == expected_tab_ids {
715 tab_group_id = Some(*group_id);
716 break;
717 }
718 }
719
720 if let Some(tab_group_id) = tab_group_id {
721 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
722 tabs.push(tab);
723 }
724 } else {
725 let new_group_id = controller.tab_groups.len();
726 controller.tab_groups.insert(new_group_id, tabs);
727 }
728 }
729
730 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
732 let mut controller = cx.global_mut::<SystemWindowTabController>();
733 let mut removed_tab = None;
734
735 controller.tab_groups.retain(|_, tabs| {
736 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
737 removed_tab = Some(tabs.remove(pos));
738 }
739 !tabs.is_empty()
740 });
741
742 removed_tab
743 }
744
745 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
747 let mut removed_tab = Self::remove_tab(cx, id);
748 let mut controller = cx.global_mut::<SystemWindowTabController>();
749
750 if let Some(tab) = removed_tab {
751 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
752 controller.tab_groups.insert(new_group_id, vec![tab]);
753 }
754 }
755
756 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
758 let mut controller = cx.global_mut::<SystemWindowTabController>();
759 let Some(initial_tabs) = controller.tabs(id) else {
760 return;
761 };
762
763 let initial_tabs_len = initial_tabs.len();
764 let mut all_tabs = initial_tabs.clone();
765
766 for (_, mut tabs) in controller.tab_groups.drain() {
767 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
768 all_tabs.extend(tabs);
769 }
770
771 controller.tab_groups.insert(0, all_tabs);
772 }
773
774 pub fn select_next_tab(cx: &mut App, id: WindowId) {
776 let mut controller = cx.global_mut::<SystemWindowTabController>();
777 let Some(tabs) = controller.tabs(id) else {
778 return;
779 };
780
781 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
782 let next_index = (current_index + 1) % tabs.len();
783
784 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
785 window.activate_window();
786 });
787 }
788
789 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
791 let mut controller = cx.global_mut::<SystemWindowTabController>();
792 let Some(tabs) = controller.tabs(id) else {
793 return;
794 };
795
796 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
797 let previous_index = if current_index == 0 {
798 tabs.len() - 1
799 } else {
800 current_index - 1
801 };
802
803 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
804 window.activate_window();
805 });
806 }
807}
808
809pub(crate) enum GpuiMode {
810 #[cfg(any(test, feature = "test-support"))]
811 Test {
812 skip_drawing: bool,
813 },
814 Production,
815}
816
817impl GpuiMode {
818 #[cfg(any(test, feature = "test-support"))]
819 pub fn test() -> Self {
820 GpuiMode::Test {
821 skip_drawing: false,
822 }
823 }
824
825 #[inline]
826 pub(crate) fn skip_drawing(&self) -> bool {
827 match self {
828 #[cfg(any(test, feature = "test-support"))]
829 GpuiMode::Test { skip_drawing } => *skip_drawing,
830 GpuiMode::Production => false,
831 }
832 }
833}
834
835struct PlatformOwnedDrag {
836 source_window: WindowId,
837 state: PlatformOwnedDragState,
838}
839
840enum PlatformOwnedDragState {
841 Suspended(AnyDrag),
842 RestoredInSourceWindow,
845}
846
847pub struct App {
851 pub(crate) this: Weak<AppCell>,
852 pub(crate) platform: Rc<dyn Platform>,
853 text_system: Arc<TextSystem>,
854
855 pub(crate) actions: Rc<ActionRegistry>,
856 pub(crate) active_drag: Option<AnyDrag>,
857 platform_owned_drag: Option<PlatformOwnedDrag>,
858 pub(crate) background_executor: BackgroundExecutor,
859 pub(crate) foreground_executor: ForegroundExecutor,
860 #[cfg(feature = "profiler")]
861 foreground_journal: crate::profiler::journal::ForegroundJournal,
862 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
863 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
864 pub(crate) entities: EntityMap,
865 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
866 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
867 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
868 pub(crate) focus_handles: Arc<RwLock<FocusMap>>,
869 pub(crate) keymap: Rc<RefCell<Keymap>>,
870 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
871 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
872 pub(crate) global_action_listeners:
873 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
874 pending_effects: VecDeque<Effect>,
875
876 pub(crate) observers: SubscriberSet<EntityId, Handler>,
877 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
878 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
879 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
880 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
881 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
882 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
883 pub(crate) display_observers: SubscriberSet<(), DisplayHandler>,
884 displays: HashMap<DisplayId, DisplayState>,
887 pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
888 pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
889 app_lifecycle_observers: SubscriberSet<(), AppLifecycleHandler>,
890 memory_warning_observers: SubscriberSet<(), Handler>,
891 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
892 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
893 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
894 pub(crate) restart_observers: SubscriberSet<(), Handler>,
895 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
896
897 pub(crate) element_arena: RefCell<Arena>,
900 pub(crate) event_arena: Arena,
902
903 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
908
909 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
911 asset_source: Arc<dyn AssetSource>,
912 pub(crate) svg_renderer: SvgRenderer,
913 http_client: Arc<dyn HttpClient>,
914
915 pub(crate) pending_notifications: FxHashSet<EntityId>,
917 pub(crate) pending_global_notifications: TypeIdHashSet,
918 pub(crate) restart_path: Option<PathBuf>,
919 pub(crate) restart_arguments: Vec<OsString>,
920 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
922 pub(crate) prompt_builder: Option<PromptBuilder>,
923 pub(crate) window_invalidators_by_entity:
924 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
925 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
926 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
927 #[cfg(any(feature = "inspector", debug_assertions))]
928 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
929 #[cfg(any(feature = "inspector", debug_assertions))]
930 pub(crate) inspector_element_registry: InspectorElementRegistry,
931 #[cfg(any(test, feature = "test-support", debug_assertions))]
932 pub(crate) name: Option<&'static str>,
933 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
934
935 pub(crate) window_update_stack: Vec<WindowId>,
936 pub(crate) mode: GpuiMode,
937 pub(crate) cursor_hide_mode: CursorHideMode,
938 pub(crate) reduce_motion: bool,
939 pub(crate) synced_animation_epoch: Instant,
941 pub(crate) accessibility_force_disabled: bool,
944 pending_updates: usize,
945 quit_mode: QuitMode,
946 quitting: bool,
947
948 #[cfg(any(test, gpui_leak_detection))]
951 _ref_counts: Arc<RwLock<EntityRefCounts>>,
952}
953
954impl App {
955 #[allow(clippy::new_ret_no_self)]
956 pub(crate) fn new_app(
957 platform: Rc<dyn Platform>,
958 asset_source: Arc<dyn AssetSource>,
959 http_client: Arc<dyn HttpClient>,
960 ) -> Rc<AppCell> {
961 let background_executor = platform.background_executor();
962 let foreground_executor = platform.foreground_executor();
963 assert!(
964 background_executor.is_main_thread(),
965 "must construct App on main thread"
966 );
967 #[cfg(feature = "profiler")]
968 let foreground_journal = crate::profiler::journal::install_foreground_journal();
969 let synced_animation_epoch = background_executor.now();
970
971 let text_system = Arc::new(TextSystem::new(platform.text_system()));
972 let entities = EntityMap::new();
973 let keyboard_layout = platform.keyboard_layout();
974 let keyboard_mapper = platform.keyboard_mapper();
975
976 #[cfg(any(test, gpui_leak_detection))]
977 let _ref_counts = entities.ref_counts_drop_handle();
978
979 let app = Rc::new_cyclic(|this| AppCell {
980 borrow_origin: Cell::new(None),
981 app: RefCell::new(App {
982 this: this.clone(),
983 platform: platform.clone(),
984 text_system,
985 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
986 mode: GpuiMode::Production,
987 actions: Rc::new(ActionRegistry::default()),
988 pending_updates: 0,
989 active_drag: None,
990 platform_owned_drag: None,
991 background_executor,
992 foreground_executor,
993 #[cfg(feature = "profiler")]
994 foreground_journal,
995 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
996 hang_monitor: None,
997 svg_renderer: SvgRenderer::new(asset_source.clone()),
998 loading_assets: Default::default(),
999 asset_source,
1000 http_client,
1001 globals_by_type: Default::default(),
1002 entities,
1003 new_entity_observers: SubscriberSet::new(),
1004 windows: SlotMap::with_key(),
1005 window_update_stack: Vec::new(),
1006 window_handles: FxHashMap::default(),
1007 focus_handles: Arc::new(RwLock::new(FocusMap::default())),
1008 keymap: Rc::new(RefCell::new(Keymap::default())),
1009 keyboard_layout,
1010 keyboard_mapper,
1011 global_action_listeners: Default::default(),
1012 pending_effects: VecDeque::new(),
1013 pending_notifications: FxHashSet::default(),
1014 pending_global_notifications: Default::default(),
1015 observers: SubscriberSet::new(),
1016 tracked_entities: FxHashMap::default(),
1017 window_invalidators_by_entity: FxHashMap::default(),
1018 current_window_by_entity: FxHashMap::default(),
1019 event_listeners: SubscriberSet::new(),
1020 release_listeners: SubscriberSet::new(),
1021 keystroke_observers: SubscriberSet::new(),
1022 keystroke_interceptors: SubscriberSet::new(),
1023 keyboard_layout_observers: SubscriberSet::new(),
1024 missing_glyph_callback: Rc::default(),
1025 thermal_state_observers: SubscriberSet::new(),
1026 display_observers: SubscriberSet::new(),
1027 displays: read_displays(platform.as_ref()),
1028 system_sleep_observers: SubscriberSet::new(),
1029 system_wake_observers: SubscriberSet::new(),
1030 app_lifecycle_observers: SubscriberSet::new(),
1031 memory_warning_observers: SubscriberSet::new(),
1032 global_observers: SubscriberSet::new(),
1033 quit_observers: SubscriberSet::new(),
1034 restart_observers: SubscriberSet::new(),
1035 restart_path: None,
1036 restart_arguments: Vec::new(),
1037 window_closed_observers: SubscriberSet::new(),
1038 layout_id_buffer: Default::default(),
1039 propagate_event: true,
1040 prompt_builder: Some(PromptBuilder::Default),
1041 #[cfg(any(feature = "inspector", debug_assertions))]
1042 inspector_renderer: None,
1043 #[cfg(any(feature = "inspector", debug_assertions))]
1044 inspector_element_registry: InspectorElementRegistry::default(),
1045 quit_mode: QuitMode::default(),
1046 quitting: false,
1047 cursor_hide_mode: CursorHideMode::default(),
1048 reduce_motion: false,
1049 synced_animation_epoch,
1050 accessibility_force_disabled: false,
1051
1052 #[cfg(any(test, feature = "test-support", debug_assertions))]
1053 name: None,
1054 element_arena: RefCell::new(Arena::new(1024 * 1024)),
1055 event_arena: Arena::new(1024 * 1024),
1056
1057 #[cfg(any(test, gpui_leak_detection))]
1058 _ref_counts,
1059 }),
1060 });
1061
1062 init_app_menus(platform.as_ref(), &app.borrow());
1063 SystemWindowTabController::init(&mut app.borrow_mut());
1064 #[cfg(feature = "profiler")]
1065 crate::profiler::journal::observe_power(&app.borrow());
1066
1067 platform.on_keyboard_layout_change(Box::new({
1068 let app = Rc::downgrade(&app);
1069 move || {
1070 if let Some(app) = app.upgrade() {
1071 let cx = &mut app.borrow_mut();
1072 cx.keyboard_layout = cx.platform.keyboard_layout();
1073 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1074 cx.keyboard_layout_observers
1075 .clone()
1076 .retain(&(), move |callback| (callback)(cx));
1077 }
1078 }
1079 }));
1080
1081 platform.on_thermal_state_change(Box::new({
1082 let app = Rc::downgrade(&app);
1083 move || {
1084 if let Some(app) = app.upgrade() {
1085 let cx = &mut app.borrow_mut();
1086 cx.thermal_state_observers
1087 .clone()
1088 .retain(&(), move |callback| (callback)(cx));
1089 }
1090 }
1091 }));
1092
1093 platform.on_displays_changed(Box::new({
1094 let app = Rc::downgrade(&app);
1095 move || {
1096 if let Some(app) = app.upgrade() {
1097 app.borrow_mut().displays_changed();
1098 }
1099 }
1100 }));
1101
1102 platform.on_system_sleep(Box::new({
1103 let app = Rc::downgrade(&app);
1104 move || {
1105 if let Some(app) = app.upgrade() {
1106 let cx = &mut app.borrow_mut();
1107 cx.system_sleep_observers
1108 .clone()
1109 .retain(&(), move |callback| (callback)(cx));
1110 }
1111 }
1112 }));
1113
1114 platform.on_system_wake(Box::new({
1115 let app = Rc::downgrade(&app);
1116 move || {
1117 if let Some(app) = app.upgrade() {
1118 let cx = &mut app.borrow_mut();
1119 cx.system_wake_observers
1120 .clone()
1121 .retain(&(), move |callback| (callback)(cx));
1122 }
1123 }
1124 }));
1125
1126 platform.on_app_lifecycle(Box::new({
1127 let app = Rc::downgrade(&app);
1128 move |phase| {
1129 if let Some(app) = app.upgrade() {
1130 app.borrow_mut().update(|cx| {
1131 cx.app_lifecycle_observers
1132 .clone()
1133 .retain(&(), |callback| callback(phase, cx));
1134 });
1135 }
1136 }
1137 }));
1138
1139 platform.on_memory_warning(Box::new({
1140 let app = Rc::downgrade(&app);
1141 move || {
1142 if let Some(app) = app.upgrade() {
1143 app.borrow_mut().update(|cx| {
1144 cx.memory_warning_observers
1145 .clone()
1146 .retain(&(), |callback| callback(cx));
1147 });
1148 }
1149 }
1150 }));
1151
1152 platform.on_quit(Box::new({
1153 let cx = Rc::downgrade(&app);
1154 move || {
1155 let Some(cx) = cx.upgrade() else {
1156 return true;
1157 };
1158 match cx.try_borrow_mut() {
1159 Ok(mut cx) => {
1160 cx.shutdown();
1161 true
1162 }
1163 Err(_) => {
1164 false
1167 }
1168 }
1169 }
1170 }));
1171
1172 app
1173 }
1174
1175 #[doc(hidden)]
1176 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1177 self.entities.ref_counts_drop_handle()
1178 }
1179
1180 #[cfg(any(test, gpui_leak_detection))]
1186 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1187 self.entities.leak_detector_snapshot()
1188 }
1189
1190 #[cfg(any(test, gpui_leak_detection))]
1202 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1203 self.entities.assert_no_new_leaks(snapshot)
1204 }
1205
1206 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1208 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1209 LeakDetectorSnapshot::default()
1210 }
1211
1212 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1215 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1216
1217 pub fn shutdown(&mut self) {
1223 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1226 let hang_monitor_flush = self
1227 .hang_monitor
1228 .as_ref()
1229 .and_then(|hang_monitor| hang_monitor.request_flush());
1230
1231 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1232
1233 for observer in self.quit_observers.remove(&()) {
1234 futures.push(observer(self));
1235 }
1236
1237 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1238 if let Some(flushed) = hang_monitor_flush {
1239 futures.push(
1240 async move {
1241 if flushed.await.is_err() {
1242 log::warn!("hang monitor exited before flushing");
1243 }
1244 }
1245 .boxed_local(),
1246 );
1247 }
1248
1249 self.windows.clear();
1250 self.window_handles.clear();
1251 self.flush_effects();
1252 self.quitting = true;
1253
1254 let futures = futures::future::join_all(futures);
1255 #[cfg(not(target_family = "wasm"))]
1256 if self
1257 .foreground_executor
1258 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1259 .is_err()
1260 {
1261 log::error!("timed out waiting on app_will_quit");
1262 }
1263 #[cfg(target_family = "wasm")]
1264 self.foreground_executor.spawn(futures).detach();
1265
1266 self.quitting = false;
1267 }
1268
1269 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1271 self.keyboard_layout.as_ref()
1272 }
1273
1274 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1276 &self.keyboard_mapper
1277 }
1278
1279 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1281 where
1282 F: 'static + FnMut(&mut App),
1283 {
1284 let (subscription, activate) = self.keyboard_layout_observers.insert(
1285 (),
1286 Box::new(move |cx| {
1287 callback(cx);
1288 true
1289 }),
1290 );
1291 activate();
1292 subscription
1293 }
1294
1295 pub fn quit(&self) {
1297 self.platform.quit();
1298 }
1299
1300 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1314 if !self.windows.is_empty() {
1315 return Task::ready(Err(anyhow::anyhow!(
1316 "cannot switch windowing modes while windows are open"
1317 )));
1318 }
1319 self.platform.request_windowing(request)
1320 }
1321
1322 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1332 self.platform.graphical_environment()
1333 }
1334
1335 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1338 self.cursor_hide_mode
1339 }
1340
1341 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1344 self.cursor_hide_mode = mode;
1345 }
1346
1347 pub fn is_cursor_visible(&self) -> bool {
1353 self.platform.is_cursor_visible()
1354 }
1355
1356 pub fn reduce_motion(&self) -> bool {
1359 self.reduce_motion
1360 }
1361
1362 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1365 if self.reduce_motion != reduce_motion {
1366 self.reduce_motion = reduce_motion;
1367 self.refresh_windows();
1368 }
1369 }
1370
1371 pub fn refresh_windows(&mut self) {
1374 self.pending_effects.push_back(Effect::RefreshWindows);
1375 }
1376
1377 #[inline(always)]
1378 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1379 self.start_update();
1380 let result = update(self);
1381 self.finish_update();
1382 result
1383 }
1384
1385 pub(crate) fn start_update(&mut self) {
1386 self.pending_updates += 1;
1387 }
1388
1389 #[inline(never)]
1390 pub(crate) fn finish_update(&mut self) {
1391 if self.pending_updates == 1 {
1392 self.flush_effects();
1393 }
1394 self.pending_updates -= 1;
1395 }
1396
1397 pub fn observe<W>(
1399 &mut self,
1400 entity: &Entity<W>,
1401 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1402 ) -> Subscription
1403 where
1404 W: 'static,
1405 {
1406 self.observe_internal(entity, move |e, cx| {
1407 on_notify(e, cx);
1408 true
1409 })
1410 }
1411
1412 pub(crate) fn detect_accessed_entities<R>(
1413 &mut self,
1414 callback: impl FnOnce(&mut App) -> R,
1415 ) -> (R, FxHashSet<EntityId>) {
1416 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1417 let result = callback(self);
1418 let entities_accessed_in_callback = self
1419 .entities
1420 .accessed_entities
1421 .get_mut()
1422 .difference(&accessed_entities_start)
1423 .copied()
1424 .collect::<FxHashSet<EntityId>>();
1425 (result, entities_accessed_in_callback)
1426 }
1427
1428 pub(crate) fn record_entities_accessed(
1429 &mut self,
1430 window_handle: AnyWindowHandle,
1431 invalidator: WindowInvalidator,
1432 entities: &FxHashSet<EntityId>,
1433 ) {
1434 let mut tracked_entities =
1435 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1436 for entity in tracked_entities.iter() {
1437 self.window_invalidators_by_entity
1438 .entry(*entity)
1439 .and_modify(|windows| {
1440 windows.remove(&window_handle.id);
1441 });
1442 }
1443 for entity in entities.iter() {
1444 self.window_invalidators_by_entity
1445 .entry(*entity)
1446 .or_default()
1447 .insert(window_handle.id, invalidator.clone());
1448 self.current_window_by_entity
1449 .insert(*entity, window_handle.id);
1450 }
1451 tracked_entities.clear();
1452 tracked_entities.extend(entities.iter().copied());
1453 self.tracked_entities
1454 .insert(window_handle.id, tracked_entities);
1455 }
1456
1457 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1458 let (subscription, activate) = self.observers.insert(key, value);
1459 self.defer(move |_| activate());
1460 subscription
1461 }
1462
1463 pub(crate) fn observe_internal<W>(
1464 &mut self,
1465 entity: &Entity<W>,
1466 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1467 ) -> Subscription
1468 where
1469 W: 'static,
1470 {
1471 let entity_id = entity.entity_id();
1472 let handle = entity.downgrade();
1473 self.new_observer(
1474 entity_id,
1475 Box::new(move |cx| {
1476 if let Some(entity) = handle.upgrade() {
1477 on_notify(entity, cx)
1478 } else {
1479 false
1480 }
1481 }),
1482 )
1483 }
1484
1485 pub fn subscribe<T, Event>(
1488 &mut self,
1489 entity: &Entity<T>,
1490 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1491 ) -> Subscription
1492 where
1493 T: 'static + EventEmitter<Event>,
1494 Event: 'static,
1495 {
1496 self.subscribe_internal(entity, move |entity, event, cx| {
1497 on_event(entity, event, cx);
1498 true
1499 })
1500 }
1501
1502 pub(crate) fn new_subscription(
1503 &mut self,
1504 key: EntityId,
1505 value: (TypeId, Listener),
1506 ) -> Subscription {
1507 let (subscription, activate) = self.event_listeners.insert(key, value);
1508 self.defer(move |_| activate());
1509 subscription
1510 }
1511 pub(crate) fn subscribe_internal<T, Evt>(
1512 &mut self,
1513 entity: &Entity<T>,
1514 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1515 ) -> Subscription
1516 where
1517 T: 'static + EventEmitter<Evt>,
1518 Evt: 'static,
1519 {
1520 let entity_id = entity.entity_id();
1521 let handle = entity.downgrade();
1522 self.new_subscription(
1523 entity_id,
1524 (
1525 TypeId::of::<Evt>(),
1526 Box::new(move |event, cx| {
1527 let event: &Evt = event.downcast_ref().expect("invalid event type");
1528 if let Some(entity) = handle.upgrade() {
1529 on_event(entity, event, cx)
1530 } else {
1531 false
1532 }
1533 }),
1534 ),
1535 )
1536 }
1537
1538 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1542 self.windows
1543 .keys()
1544 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1545 .collect()
1546 }
1547
1548 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1554 self.platform.window_stack()
1555 }
1556
1557 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1559 self.platform.active_window()
1560 }
1561
1562 pub fn open_window<V: 'static + Render>(
1566 &mut self,
1567 options: crate::WindowOptions,
1568 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1569 ) -> anyhow::Result<WindowHandle<V>> {
1570 self.update(|cx| {
1571 let id = cx.windows.insert(None);
1572 let handle = WindowHandle::new(id);
1573 match Window::new(handle.into(), options, cx) {
1574 Ok(mut window) => {
1575 cx.window_update_stack.push(id);
1576 let root_view = build_root_view(&mut window, cx);
1577 cx.window_update_stack.pop();
1578 window.root.replace(root_view.into());
1579 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1580
1581 let clear = window.draw(cx);
1586 clear.clear(cx);
1587
1588 cx.window_handles.insert(id, window.handle);
1589 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1590 Ok(handle)
1591 }
1592 Err(e) => {
1593 cx.windows.remove(id);
1594 Err(e)
1595 }
1596 }
1597 })
1598 }
1599
1600 pub fn activate(&self, ignoring_other_apps: bool) {
1602 self.platform.activate(ignoring_other_apps);
1603 }
1604
1605 pub fn hide(&self) {
1607 self.platform.hide();
1608 }
1609
1610 pub fn hide_other_apps(&self) {
1612 self.platform.hide_other_apps();
1613 }
1614
1615 pub fn unhide_other_apps(&self) {
1617 self.platform.unhide_other_apps();
1618 }
1619
1620 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1622 self.platform.displays()
1623 }
1624
1625 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1627 self.platform.primary_display()
1628 }
1629
1630 pub fn is_screen_capture_supported(&self) -> bool {
1632 self.platform.is_screen_capture_supported()
1633 }
1634
1635 pub fn screen_capture_sources(
1637 &self,
1638 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1639 self.platform.screen_capture_sources()
1640 }
1641
1642 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1644 self.displays()
1645 .iter()
1646 .find(|display| display.id() == id)
1647 .cloned()
1648 }
1649
1650 pub fn thermal_state(&self) -> ThermalState {
1652 self.platform.thermal_state()
1653 }
1654
1655 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1657 self.platform.prevent_idle_sleep(reason)
1658 }
1659
1660 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1662 where
1663 F: 'static + FnMut(&mut App),
1664 {
1665 let (subscription, activate) = self.thermal_state_observers.insert(
1666 (),
1667 Box::new(move |cx| {
1668 callback(cx);
1669 true
1670 }),
1671 );
1672 activate();
1673 subscription
1674 }
1675
1676 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1681 where
1682 F: 'static + FnMut(&mut App),
1683 {
1684 let (subscription, activate) = self.system_sleep_observers.insert(
1685 (),
1686 Box::new(move |cx| {
1687 callback(cx);
1688 true
1689 }),
1690 );
1691 activate();
1692 subscription
1693 }
1694
1695 pub(crate) fn displays_changed(&mut self) {
1696 let current = read_displays(self.platform.as_ref());
1697 let events = display_events(&self.displays, ¤t);
1698 self.displays = current;
1699 for event in &events {
1700 let DisplayEvent::Changed { id, .. } = *event else {
1701 continue;
1702 };
1703 for handle in self.windows() {
1704 self.update_window(handle, |_, window, cx| {
1705 if window.display_id == Some(id) {
1706 window.notify_display_observers(cx);
1707 }
1708 })
1709 .log_err();
1710 }
1711 }
1712 for event in events {
1713 self.display_observers
1714 .clone()
1715 .retain(&(), |callback| (callback)(event, self));
1716 }
1717 }
1718
1719 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1720 self.displays.contains_key(&id)
1721 }
1722
1723 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1726 self.displays.get(&id)?.refresh_interval
1727 }
1728
1729 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1732 where
1733 F: 'static + FnMut(DisplayEvent, &mut App),
1734 {
1735 let (subscription, activate) = self.display_observers.insert(
1736 (),
1737 Box::new(move |event, cx| {
1738 callback(event, cx);
1739 true
1740 }),
1741 );
1742 activate();
1743 subscription
1744 }
1745
1746 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1748 where
1749 F: 'static + FnMut(&mut App),
1750 {
1751 let (subscription, activate) = self.system_wake_observers.insert(
1752 (),
1753 Box::new(move |cx| {
1754 callback(cx);
1755 true
1756 }),
1757 );
1758 activate();
1759 subscription
1760 }
1761
1762 pub fn on_app_lifecycle(
1770 &self,
1771 mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
1772 ) -> Subscription {
1773 let (subscription, activate) = self.app_lifecycle_observers.insert(
1774 (),
1775 Box::new(move |phase, cx| {
1776 callback(phase, cx);
1777 true
1778 }),
1779 );
1780 activate();
1781 subscription
1782 }
1783
1784 pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
1787 let (subscription, activate) = self.memory_warning_observers.insert(
1788 (),
1789 Box::new(move |cx| {
1790 callback(cx);
1791 true
1792 }),
1793 );
1794 activate();
1795 subscription
1796 }
1797
1798 pub fn window_appearance(&self) -> WindowAppearance {
1800 self.platform.window_appearance()
1801 }
1802
1803 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1814 self.platform.set_window_appearance(appearance);
1815 }
1816
1817 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1819 self.platform.button_layout()
1820 }
1821
1822 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1824 self.platform.read_from_clipboard()
1825 }
1826
1827 pub fn read_from_clipboard_async(
1835 &self,
1836 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1837 self.platform.read_from_clipboard_async()
1838 }
1839
1840 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1842 self.text_rendering_mode.set(mode);
1843 }
1844
1845 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1847 self.text_rendering_mode.get()
1848 }
1849
1850 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1852 self.platform.write_to_clipboard(item)
1853 }
1854
1855 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1858 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1859 self.platform.read_from_primary()
1860 }
1861
1862 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1865 pub fn write_to_primary(&self, item: ClipboardItem) {
1866 self.platform.write_to_primary(item)
1867 }
1868
1869 #[cfg(target_os = "macos")]
1875 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1876 self.platform.read_from_find_pasteboard()
1877 }
1878
1879 #[cfg(target_os = "macos")]
1885 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1886 self.platform.write_to_find_pasteboard(item)
1887 }
1888
1889 pub fn write_credentials(
1891 &self,
1892 url: &str,
1893 username: &str,
1894 password: &[u8],
1895 ) -> Task<Result<()>> {
1896 self.platform.write_credentials(url, username, password)
1897 }
1898
1899 #[cfg(target_os = "macos")]
1907 pub fn write_credentials_if_not_exists(
1908 &self,
1909 url: &str,
1910 username: &str,
1911 password: &[u8],
1912 ) -> Task<Result<bool>> {
1913 self.platform
1914 .write_credentials_if_not_exists(url, username, password)
1915 }
1916
1917 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1919 self.platform.read_credentials(url)
1920 }
1921
1922 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1924 self.platform.delete_credentials(url)
1925 }
1926
1927 pub fn open_url(&self, url: &str) {
1929 self.platform.open_url(url);
1930 }
1931
1932 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1939 self.platform.register_url_scheme(scheme)
1940 }
1941
1942 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1949 self.platform.set_app_identity(identifier, name);
1950 }
1951
1952 pub fn show_system_notification(&self, notification: SystemNotification) {
1959 self.platform.show_system_notification(notification);
1960 }
1961
1962 pub fn dismiss_system_notification(&self, tag: &str) {
1967 self.platform.dismiss_system_notification(tag);
1968 }
1969
1970 pub fn on_system_notification_response<F>(&self, mut callback: F)
1974 where
1975 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1976 {
1977 let this = self.this.clone();
1978 self.platform
1979 .on_system_notification_response(Box::new(move |response| {
1980 if let Some(app) = this.upgrade() {
1981 callback(response, &mut app.borrow_mut());
1982 }
1983 }));
1984 }
1985
1986 pub fn app_path(&self) -> Result<PathBuf> {
1990 self.platform.app_path()
1991 }
1992
1993 pub fn compositor_name(&self) -> &'static str {
1997 self.platform.compositor_name()
1998 }
1999
2000 pub fn platform_info(&self) -> crate::PlatformInfo {
2002 self.platform.platform_info()
2003 }
2004
2005 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
2007 self.platform.path_for_auxiliary_executable(name)
2008 }
2009
2010 pub fn prompt_for_paths(
2016 &self,
2017 options: PathPromptOptions,
2018 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
2019 self.platform.prompt_for_paths(options)
2020 }
2021
2022 pub fn prompt_for_new_path(
2029 &self,
2030 directory: &Path,
2031 suggested_name: Option<&str>,
2032 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
2033 self.platform.prompt_for_new_path(directory, suggested_name)
2034 }
2035
2036 pub fn reveal_path(&self, path: &Path) {
2038 self.platform.reveal_path(path)
2039 }
2040
2041 pub fn open_with_system(&self, path: &Path) {
2043 self.platform.open_with_system(path)
2044 }
2045
2046 pub fn should_auto_hide_scrollbars(&self) -> bool {
2048 self.platform.should_auto_hide_scrollbars()
2049 }
2050
2051 pub fn restart(&mut self) {
2053 self.restart_observers
2054 .clone()
2055 .retain(&(), |observer| observer(self));
2056 self.platform.restart(
2057 self.restart_path.take(),
2058 std::mem::take(&mut self.restart_arguments),
2059 )
2060 }
2061
2062 pub fn set_restart_path(&mut self, path: PathBuf) {
2064 self.restart_path = Some(path);
2065 }
2066
2067 pub fn http_client(&self) -> Arc<dyn HttpClient> {
2069 self.http_client.clone()
2070 }
2071
2072 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
2074 self.http_client = new_client;
2075 }
2076
2077 pub fn set_quit_mode(&mut self, mode: QuitMode) {
2080 self.quit_mode = mode;
2081 }
2082
2083 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
2092 self.platform.set_activation_policy(policy);
2093 }
2094
2095 pub fn svg_renderer(&self) -> SvgRenderer {
2097 self.svg_renderer.clone()
2098 }
2099
2100 pub(crate) fn push_effect(&mut self, effect: Effect) {
2101 match &effect {
2102 Effect::Notify { emitter } => {
2103 if !self.pending_notifications.insert(*emitter) {
2104 return;
2105 }
2106 }
2107 Effect::NotifyGlobalObservers { global_type } => {
2108 if !self.pending_global_notifications.insert(*global_type) {
2109 return;
2110 }
2111 }
2112 _ => {}
2113 };
2114
2115 self.pending_effects.push_back(effect);
2116 }
2117
2118 fn flush_effects(&mut self) {
2122 loop {
2123 self.release_dropped_entities();
2124 self.release_dropped_focus_handles();
2125 if let Some(effect) = self.pending_effects.pop_front() {
2126 match effect {
2127 Effect::Notify { emitter } => {
2128 self.apply_notify_effect(emitter);
2129 }
2130
2131 Effect::Emit {
2132 emitter,
2133 event_type,
2134 event,
2135 } => self.apply_emit_effect(emitter, event_type, &*event),
2136
2137 Effect::RefreshWindows => {
2138 self.apply_refresh_effect();
2139 }
2140
2141 Effect::NotifyGlobalObservers { global_type } => {
2142 self.apply_notify_global_observers_effect(global_type);
2143 }
2144
2145 Effect::Defer { callback } => {
2146 self.apply_defer_effect(callback);
2147 }
2148 Effect::EntityCreated {
2149 entity,
2150 tid,
2151 window,
2152 } => {
2153 self.apply_entity_created_effect(entity, tid, window);
2154 }
2155 }
2156 } else {
2157 #[cfg(any(test, feature = "test-support"))]
2158 if matches!(self.mode, GpuiMode::Test { .. }) {
2159 for window in self
2160 .windows
2161 .values()
2162 .filter_map(|window| {
2163 let window = window.as_deref()?;
2164 window.invalidator.is_dirty().then_some(window.handle)
2165 })
2166 .collect::<Vec<_>>()
2167 {
2168 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2169 .unwrap();
2170 }
2171 }
2172
2173 if self.pending_effects.is_empty() {
2174 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2175 if window.invalidator.is_dirty()
2176 || window.needs_present.get()
2177 || !window.next_frame_callbacks.borrow().is_empty()
2178 {
2179 window.platform_window.schedule_frame();
2180 }
2181 }
2182
2183 self.event_arena.clear();
2184 break;
2185 }
2186 }
2187 }
2188 }
2189
2190 fn release_dropped_entities(&mut self) {
2194 loop {
2195 let dropped = self.entities.take_dropped();
2196 if dropped.is_empty() {
2197 break;
2198 }
2199
2200 for (entity_id, mut entity) in dropped {
2201 self.observers.remove(&entity_id);
2202 self.event_listeners.remove(&entity_id);
2203 self.window_invalidators_by_entity.remove(&entity_id);
2204 self.current_window_by_entity.remove(&entity_id);
2205 for release_callback in self.release_listeners.remove(&entity_id) {
2206 release_callback(entity.as_mut(), self);
2207 }
2208 }
2209 }
2210 }
2211
2212 fn release_dropped_focus_handles(&mut self) {
2214 let focus_handles = self.focus_handles.clone();
2215 let mut focus_handles = focus_handles.write();
2216 let FocusMap {
2217 handles,
2218 dropped_handles,
2219 } = &mut *focus_handles;
2220 if dropped_handles.is_empty() {
2221 return;
2222 }
2223
2224 let windows = self
2225 .windows
2226 .values()
2227 .filter_map(|window| {
2228 let window = window.as_ref()?;
2229 dropped_handles
2230 .contains(&window.focus?)
2231 .then_some(window.handle)
2232 })
2233 .collect::<SmallVec<[_; 1]>>();
2234 for handle_id in dropped_handles.drain(..) {
2235 handles.remove(handle_id);
2236 }
2237 drop(focus_handles);
2238
2239 for window_handle in windows {
2240 window_handle
2241 .update(self, |_, window, cx| window.blur(cx))
2242 .ok();
2243 }
2244 }
2245
2246 fn apply_notify_effect(&mut self, emitter: EntityId) {
2247 self.pending_notifications.remove(&emitter);
2248
2249 self.observers
2250 .clone()
2251 .retain(&emitter, |handler| handler(self));
2252 }
2253
2254 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2255 self.event_listeners
2256 .clone()
2257 .retain(&emitter, |(stored_type, handler)| {
2258 if *stored_type == event_type {
2259 handler(event, self)
2260 } else {
2261 true
2262 }
2263 });
2264 }
2265
2266 fn apply_refresh_effect(&mut self) {
2267 for window in self.windows.values_mut() {
2268 if let Some(window) = window.as_deref_mut() {
2269 window.refreshing = true;
2270 window.invalidator.set_dirty(true);
2271 }
2272 }
2273 }
2274
2275 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2276 self.pending_global_notifications.remove(&type_id);
2277 self.global_observers
2278 .clone()
2279 .retain(&type_id, |observer| observer(self));
2280 }
2281
2282 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2283 callback(self);
2284 }
2285
2286 fn apply_entity_created_effect(
2287 &mut self,
2288 entity: AnyEntity,
2289 tid: TypeId,
2290 window: Option<WindowId>,
2291 ) {
2292 if let Some(id) = window {
2296 self.current_window_by_entity.insert(entity.entity_id(), id);
2297 }
2298
2299 self.new_entity_observers.clone().retain(&tid, |observer| {
2300 if let Some(id) = window {
2301 self.update_window_id(id, {
2302 let entity = entity.clone();
2303 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2304 })
2305 .expect("All windows should be off the stack when flushing effects");
2306 } else {
2307 (observer)(entity.clone(), &mut None, self)
2308 }
2309 true
2310 });
2311 }
2312
2313 #[inline(always)]
2319 pub fn with_window<R>(
2320 &mut self,
2321 entity_id: EntityId,
2322 f: impl FnOnce(&mut Window, &mut App) -> R,
2323 ) -> Option<R> {
2324 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2325 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2326 .ok()
2327 }
2328
2329 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2330 self.current_window_by_entity
2331 .entry(entity_id)
2332 .or_insert(window);
2333 }
2334
2335 #[inline(always)]
2336 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2337 where
2338 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2339 {
2340 let mut update = Some(update);
2341 let mut result = None;
2342 self.update_window_erased(id, &mut |arguments| {
2343 if let Some((root_view, window, cx)) = arguments {
2344 result = Some(update.take().unwrap()(root_view, window, cx));
2345 } else {
2346 drop(update.take());
2347 drop(result.take());
2348 }
2349 });
2350 result.context("window not found")
2351 }
2352
2353 pub fn to_async(&self) -> AsyncApp {
2356 AsyncApp {
2357 app: self.this.clone(),
2358 background_executor: self.background_executor.clone(),
2359 foreground_executor: self.foreground_executor.clone(),
2360 }
2361 }
2362
2363 pub fn background_executor(&self) -> &BackgroundExecutor {
2365 &self.background_executor
2366 }
2367
2368 pub fn is_test(&self) -> bool {
2371 self.background_executor.is_test()
2372 }
2373
2374 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2376 if self.quitting {
2377 panic!("Can't spawn on main thread after on_app_quit")
2378 };
2379 &self.foreground_executor
2380 }
2381
2382 #[cfg(feature = "profiler")]
2385 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2386 self.foreground_journal.clone()
2387 }
2388
2389 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2406 pub fn start_hang_monitor(
2407 &mut self,
2408 config: crate::profiler::hang::HangMonitorConfig,
2409 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2410 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2411 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2412
2413 if self.hang_monitor.is_some() {
2414 debug_assert!(false, "the hang monitor was started twice");
2415 return Err(HangMonitorError::AlreadyStarted);
2416 }
2417 let detector = HangDetector::new(
2418 self.foreground_journal(),
2419 config.threshold,
2420 config.frame_budget,
2421 );
2422 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2423 .map_err(HangMonitorError::Spawn)?;
2424 self.hang_monitor = Some(monitor);
2425 Ok(())
2426 }
2427
2428 #[track_caller]
2431 #[inline(always)]
2432 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2433 where
2434 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2435 R: 'static,
2436 {
2437 let mut cx = self.prepare_spawn();
2438
2439 self.foreground_executor
2440 .spawn(async move { f(&mut cx).await }.boxed_local())
2441 }
2442
2443 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2447 where
2448 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2449 R: 'static,
2450 {
2451 if self.quitting {
2452 debug_panic!("Can't spawn on main thread after on_app_quit")
2453 };
2454
2455 let mut cx = self.to_async();
2456
2457 self.foreground_executor
2458 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2459 }
2460
2461 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2464 self.push_effect(Effect::Defer {
2465 callback: Box::new(f),
2466 });
2467 }
2468
2469 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2471 &self.asset_source
2472 }
2473
2474 pub fn text_system(&self) -> &Arc<TextSystem> {
2476 &self.text_system
2477 }
2478
2479 pub fn on_missing_glyphs(
2490 &self,
2491 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2492 ) -> Subscription {
2493 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2494
2495 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2496 let callback = self.missing_glyph_callback.clone();
2497 self.spawn(async move |cx| {
2498 while let Ok(missing_glyphs) = receiver.recv().await {
2499 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2500 }
2501 })
2502 .detach();
2503 }
2504 self.text_system.enable_missing_glyph_reporting();
2505
2506 let callback = self.missing_glyph_callback.clone();
2507 let text_system = self.text_system.clone();
2508 Subscription::new(move || {
2509 if callback.remove(®istration) {
2510 text_system.disable_missing_glyph_reporting();
2511 }
2512 })
2513 }
2514
2515 pub fn has_global<G: Global>(&self) -> bool {
2517 self.globals_by_type.contains_key(&TypeId::of::<G>())
2518 }
2519
2520 #[track_caller]
2522 pub fn global<G: Global>(&self) -> &G {
2523 self.globals_by_type
2524 .get(&TypeId::of::<G>())
2525 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2526 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2527 }
2528
2529 pub fn try_global<G: Global>(&self) -> Option<&G> {
2531 self.globals_by_type
2532 .get(&TypeId::of::<G>())
2533 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2534 }
2535
2536 #[track_caller]
2538 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2539 let global_type = TypeId::of::<G>();
2540 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2541 self.globals_by_type
2542 .get_mut(&global_type)
2543 .and_then(|any_state| any_state.downcast_mut::<G>())
2544 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2545 }
2546
2547 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2550 let global_type = TypeId::of::<G>();
2551 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2552 self.globals_by_type
2553 .entry(global_type)
2554 .or_insert_with(|| Box::<G>::default())
2555 .downcast_mut::<G>()
2556 .unwrap()
2557 }
2558
2559 pub fn set_global<G: Global>(&mut self, global: G) {
2561 let global_type = TypeId::of::<G>();
2562 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2563 self.globals_by_type.insert(global_type, Box::new(global));
2564 }
2565
2566 #[cfg(any(test, feature = "test-support"))]
2568 pub fn clear_globals(&mut self) {
2569 self.globals_by_type.drain();
2570 }
2571
2572 pub fn remove_global<G: Global>(&mut self) -> G {
2574 let global_type = TypeId::of::<G>();
2575 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2576 *self
2577 .globals_by_type
2578 .remove(&global_type)
2579 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2580 .downcast()
2581 .unwrap()
2582 }
2583
2584 pub fn observe_global<G: Global>(
2586 &mut self,
2587 mut f: impl FnMut(&mut Self) + 'static,
2588 ) -> Subscription {
2589 let (subscription, activate) = self.global_observers.insert(
2590 TypeId::of::<G>(),
2591 Box::new(move |cx| {
2592 f(cx);
2593 true
2594 }),
2595 );
2596 self.defer(move |_| activate());
2597 subscription
2598 }
2599
2600 #[track_caller]
2602 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2603 GlobalLease::new(
2604 self.globals_by_type
2605 .remove(&TypeId::of::<G>())
2606 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2607 .unwrap(),
2608 )
2609 }
2610
2611 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2613 let global_type = TypeId::of::<G>();
2614
2615 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2616 self.globals_by_type.insert(global_type, lease.global);
2617 }
2618
2619 pub(crate) fn new_entity_observer(
2620 &self,
2621 key: TypeId,
2622 value: NewEntityListener,
2623 ) -> Subscription {
2624 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2625 activate();
2626 subscription
2627 }
2628
2629 pub fn observe_new<T: 'static>(
2632 &self,
2633 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2634 ) -> Subscription {
2635 self.new_entity_observer(
2636 TypeId::of::<T>(),
2637 Box::new(
2638 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2639 any_entity
2640 .downcast::<T>()
2641 .unwrap()
2642 .update(cx, |entity_state, cx| {
2643 on_new(entity_state, window.as_deref_mut(), cx)
2644 })
2645 },
2646 ),
2647 )
2648 }
2649
2650 pub fn observe_release<T>(
2653 &self,
2654 handle: &Entity<T>,
2655 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2656 ) -> Subscription
2657 where
2658 T: 'static,
2659 {
2660 let (subscription, activate) = self.release_listeners.insert(
2661 handle.entity_id(),
2662 Box::new(move |entity, cx| {
2663 let entity = entity.downcast_mut().expect("invalid entity type");
2664 on_release(entity, cx)
2665 }),
2666 );
2667 activate();
2668 subscription
2669 }
2670
2671 pub fn observe_release_in<T>(
2674 &self,
2675 handle: &Entity<T>,
2676 window: &Window,
2677 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2678 ) -> Subscription
2679 where
2680 T: 'static,
2681 {
2682 let window_handle = window.handle;
2683 self.observe_release(handle, move |entity, cx| {
2684 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2685 })
2686 }
2687
2688 pub fn observe_keystrokes(
2693 &mut self,
2694 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2695 ) -> Subscription {
2696 fn inner(
2697 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2698 handler: KeystrokeObserver,
2699 ) -> Subscription {
2700 let (subscription, activate) = keystroke_observers.insert((), handler);
2701 activate();
2702 subscription
2703 }
2704
2705 inner(
2706 &self.keystroke_observers,
2707 Box::new(move |event, window, cx| {
2708 f(event, window, cx);
2709 true
2710 }),
2711 )
2712 }
2713
2714 pub fn intercept_keystrokes(
2719 &mut self,
2720 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2721 ) -> Subscription {
2722 fn inner(
2723 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2724 handler: KeystrokeObserver,
2725 ) -> Subscription {
2726 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2727 activate();
2728 subscription
2729 }
2730
2731 inner(
2732 &self.keystroke_interceptors,
2733 Box::new(move |event, window, cx| {
2734 f(event, window, cx);
2735 true
2736 }),
2737 )
2738 }
2739
2740 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2742 self.keymap.borrow_mut().add_bindings(bindings);
2743 self.pending_effects.push_back(Effect::RefreshWindows);
2744 }
2745
2746 pub fn clear_key_bindings(&mut self) {
2748 self.keymap.borrow_mut().clear();
2749 self.pending_effects.push_back(Effect::RefreshWindows);
2750 }
2751
2752 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2754 self.keymap.clone()
2755 }
2756
2757 pub fn on_action<A: Action>(
2761 &mut self,
2762 listener: impl Fn(&A, &mut Self) + 'static,
2763 ) -> &mut Self {
2764 self.global_action_listeners
2765 .entry(TypeId::of::<A>())
2766 .or_default()
2767 .push(Rc::new(move |action, phase, cx| {
2768 if phase == DispatchPhase::Bubble {
2769 let action = action.downcast_ref().unwrap();
2770 listener(action, cx)
2771 }
2772 }));
2773 self
2774 }
2775
2776 pub fn stop_propagation(&mut self) {
2781 self.propagate_event = false;
2782 }
2783
2784 pub fn propagate(&mut self) {
2789 self.propagate_event = true;
2790 }
2791
2792 pub fn build_action(
2794 &self,
2795 name: &str,
2796 data: Option<serde_json::Value>,
2797 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2798 self.actions.build_action(name, data)
2799 }
2800
2801 pub fn all_action_names(&self) -> &[&'static str] {
2804 self.actions.all_action_names()
2805 }
2806
2807 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2811 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2812 }
2813
2814 pub fn action_schemas(
2816 &self,
2817 generator: &mut schemars::SchemaGenerator,
2818 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2819 self.actions.action_schemas(generator)
2820 }
2821
2822 pub fn action_schema_by_name(
2827 &self,
2828 name: &str,
2829 generator: &mut schemars::SchemaGenerator,
2830 ) -> Option<Option<schemars::Schema>> {
2831 self.actions.action_schema_by_name(name, generator)
2832 }
2833
2834 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2836 self.actions.deprecated_aliases()
2837 }
2838
2839 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2841 self.actions.deprecation_messages()
2842 }
2843
2844 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2846 self.actions.documentation()
2847 }
2848
2849 pub fn on_app_quit<Fut>(
2852 &self,
2853 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2854 ) -> Subscription
2855 where
2856 Fut: 'static + Future<Output = ()>,
2857 {
2858 let (subscription, activate) = self.quit_observers.insert(
2859 (),
2860 Box::new(move |cx| {
2861 let future = on_quit(cx);
2862 future.boxed_local()
2863 }),
2864 );
2865 activate();
2866 subscription
2867 }
2868
2869 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2873 let (subscription, activate) = self.restart_observers.insert(
2874 (),
2875 Box::new(move |cx| {
2876 on_restart(cx);
2877 true
2878 }),
2879 );
2880 activate();
2881 subscription
2882 }
2883
2884 pub fn on_window_closed(
2887 &self,
2888 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2889 ) -> Subscription {
2890 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2891 activate();
2892 subscription
2893 }
2894
2895 pub(crate) fn clear_pending_keystrokes(&mut self) {
2896 for window in self.windows() {
2897 window
2898 .update(self, |_, window, cx| {
2899 window.clear_pending_keystrokes(cx);
2900 })
2901 .ok();
2902 }
2903 }
2904
2905 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2908 let mut action_available = false;
2909 if let Some(window) = self.active_window()
2910 && let Ok(window_action_available) =
2911 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2912 {
2913 action_available = window_action_available;
2914 }
2915
2916 action_available
2917 || self
2918 .global_action_listeners
2919 .contains_key(&action.as_any().type_id())
2920 }
2921
2922 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2924 let menus: Vec<Menu> = menus.into_iter().collect();
2925 self.platform.set_menus(menus, &self.keymap.borrow());
2926 }
2927
2928 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2930 self.platform.get_menus()
2931 }
2932
2933 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2935 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2936 }
2937
2938 pub fn perform_dock_menu_action(&self, action: usize) {
2940 self.platform.perform_dock_menu_action(action);
2941 }
2942
2943 pub fn add_recent_document(&self, path: &Path) {
2948 self.platform.add_recent_document(path);
2949 }
2950
2951 pub fn update_jump_list(
2954 &self,
2955 menus: Vec<MenuItem>,
2956 entries: Vec<SmallVec<[PathBuf; 2]>>,
2957 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2958 self.platform.update_jump_list(menus, entries)
2959 }
2960
2961 pub fn dispatch_action(&mut self, action: &dyn Action) {
2964 if let Some(active_window) = self.active_window() {
2965 active_window
2966 .update(self, |_, window, cx| {
2967 window.dispatch_action(action.boxed_clone(), cx)
2968 })
2969 .log_err();
2970 } else {
2971 self.dispatch_global_action(action);
2972 }
2973 }
2974
2975 fn dispatch_global_action(&mut self, action: &dyn Action) {
2976 self.propagate_event = true;
2977
2978 if let Some(mut global_listeners) = self
2979 .global_action_listeners
2980 .remove(&action.as_any().type_id())
2981 {
2982 for listener in &global_listeners {
2983 listener(action.as_any(), DispatchPhase::Capture, self);
2984 if !self.propagate_event {
2985 break;
2986 }
2987 }
2988
2989 global_listeners.extend(
2990 self.global_action_listeners
2991 .remove(&action.as_any().type_id())
2992 .unwrap_or_default(),
2993 );
2994
2995 self.global_action_listeners
2996 .insert(action.as_any().type_id(), global_listeners);
2997 }
2998
2999 if self.propagate_event
3000 && let Some(mut global_listeners) = self
3001 .global_action_listeners
3002 .remove(&action.as_any().type_id())
3003 {
3004 for listener in global_listeners.iter().rev() {
3005 listener(action.as_any(), DispatchPhase::Bubble, self);
3006 if !self.propagate_event {
3007 break;
3008 }
3009 }
3010
3011 global_listeners.extend(
3012 self.global_action_listeners
3013 .remove(&action.as_any().type_id())
3014 .unwrap_or_default(),
3015 );
3016
3017 self.global_action_listeners
3018 .insert(action.as_any().type_id(), global_listeners);
3019 }
3020 }
3021
3022 pub fn has_active_drag(&self) -> bool {
3024 self.active_drag.is_some()
3025 }
3026
3027 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3029 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3030 }
3031
3032 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3034 if self.active_drag.is_some() {
3035 self.active_drag = None;
3036 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
3037 drag.source_window == window.window_handle().window_id()
3038 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3039 }) {
3040 self.platform_owned_drag = None;
3041 }
3042 window.refresh();
3043 true
3044 } else {
3045 false
3046 }
3047 }
3048
3049 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3050 let Some(drag) = self.active_drag.take() else {
3051 return false;
3052 };
3053 self.platform_owned_drag = Some(PlatformOwnedDrag {
3054 source_window,
3055 state: PlatformOwnedDragState::Suspended(drag),
3056 });
3057 true
3058 }
3059
3060 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
3061 let Some(platform_drag) = self
3062 .platform_owned_drag
3063 .as_mut()
3064 .filter(|drag| drag.source_window == source_window)
3065 else {
3066 return false;
3067 };
3068 let state = std::mem::replace(
3069 &mut platform_drag.state,
3070 PlatformOwnedDragState::RestoredInSourceWindow,
3071 );
3072 let PlatformOwnedDragState::Suspended(drag) = state else {
3073 return false;
3074 };
3075 self.active_drag = Some(drag);
3076 true
3077 }
3078
3079 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3080 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
3081 drag.source_window == source_window
3082 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3083 }) else {
3084 return false;
3085 };
3086 let Some(drag) = self.active_drag.take() else {
3087 return false;
3088 };
3089 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
3090 true
3091 }
3092
3093 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
3094 if !self
3095 .platform_owned_drag
3096 .as_ref()
3097 .is_some_and(|drag| drag.source_window == source_window)
3098 {
3099 return false;
3100 }
3101 self.platform_owned_drag = None;
3102 self.active_drag = None;
3103 true
3104 }
3105
3106 pub fn set_active_drag_cursor_style(
3108 &mut self,
3109 cursor_style: CursorStyle,
3110 window: &mut Window,
3111 ) -> bool {
3112 if let Some(ref mut drag) = self.active_drag {
3113 drag.cursor_style = Some(cursor_style);
3114 window.refresh();
3115 true
3116 } else {
3117 false
3118 }
3119 }
3120
3121 pub fn set_prompt_builder(
3124 &mut self,
3125 renderer: impl Fn(
3126 PromptLevel,
3127 &str,
3128 Option<&str>,
3129 &[PromptButton],
3130 PromptHandle,
3131 &mut Window,
3132 &mut App,
3133 ) -> RenderablePromptHandle
3134 + 'static,
3135 ) {
3136 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3137 }
3138
3139 pub fn reset_prompt_builder(&mut self) {
3141 self.prompt_builder = Some(PromptBuilder::Default);
3142 }
3143
3144 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3146 let asset_id = (TypeId::of::<A>(), hash(source));
3147 self.loading_assets.remove(&asset_id);
3148 }
3149
3150 #[cfg(any(test, feature = "test-support"))]
3153 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3154 let asset_id = (TypeId::of::<A>(), hash(source));
3155 self.loading_assets.contains_key(&asset_id)
3156 }
3157
3158 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3163 self.asset_entry::<A>(source).get()
3164 }
3165
3166 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3167 let asset_id = (TypeId::of::<A>(), hash(source));
3168 if !self.loading_assets.contains_key(&asset_id) {
3169 let future = A::load(source.clone(), self);
3170 let entry = CachedLoad::new(future, self);
3171 self.loading_assets.insert(asset_id, Box::new(entry));
3172 }
3173 self.loading_assets
3174 .get(&asset_id)
3175 .and_then(|entry| entry.downcast_ref())
3176 .expect("asset cache entries are keyed by their asset type")
3177 }
3178
3179 #[track_caller]
3182 pub fn focus_handle(&self) -> FocusHandle {
3183 FocusHandle::new(&self.focus_handles)
3184 }
3185
3186 pub fn notify(&mut self, entity_id: EntityId) {
3188 let window_invalidators = mem::take(
3189 self.window_invalidators_by_entity
3190 .entry(entity_id)
3191 .or_default(),
3192 );
3193
3194 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3199 .iter()
3200 .filter(|(window_id, _)| {
3201 self.tracked_entities
3202 .get(window_id)
3203 .is_some_and(|set| set.contains(&entity_id))
3204 })
3205 .map(|(_, invalidator)| invalidator.clone())
3206 .collect();
3207
3208 if live_invalidators.is_empty() {
3209 if self.pending_notifications.insert(entity_id) {
3210 self.pending_effects
3211 .push_back(Effect::Notify { emitter: entity_id });
3212 }
3213 } else {
3214 for invalidator in &live_invalidators {
3215 invalidator.invalidate_view(entity_id, self);
3216 }
3217 }
3218
3219 self.window_invalidators_by_entity
3220 .insert(entity_id, window_invalidators);
3221 }
3222
3223 #[cfg(any(test, feature = "test-support", debug_assertions))]
3225 pub fn get_name(&self) -> Option<&'static str> {
3226 self.name
3227 }
3228
3229 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3231 self.platform.can_select_mixed_files_and_dirs()
3232 }
3233
3234 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3239 for window in self.windows.values_mut().flatten() {
3241 _ = window.drop_image(image.clone());
3242 }
3243
3244 if let Some(window) = current_window {
3246 _ = window.drop_image(image);
3247 }
3248 }
3249
3250 #[cfg(any(feature = "inspector", debug_assertions))]
3252 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3253 self.inspector_renderer = Some(f);
3254 }
3255
3256 #[cfg(any(feature = "inspector", debug_assertions))]
3258 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3259 &mut self,
3260 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3261 ) where
3262 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3263 {
3264 self.inspector_element_registry.register(factory);
3265 }
3266
3267 pub fn init_colors(&mut self) {
3271 self.set_global(GlobalColors(Arc::new(Colors::default())));
3272 }
3273
3274 #[inline(never)]
3275 fn update_window_erased(
3276 &mut self,
3277 window_id: WindowId,
3278 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3279 ) {
3280 self.update(|cx| {
3281 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3282 update(None);
3283 return;
3284 };
3285
3286 let root_view = window.root.clone().unwrap();
3287
3288 cx.window_update_stack.push(window.handle.id);
3289 update(Some((root_view, &mut window, cx)));
3290 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3291 cx.window_update_stack.pop();
3292
3293 if window.removed {
3294 cx.end_platform_drag(window_id);
3295 cx.window_handles.remove(&window_id);
3296 cx.windows.remove(window_id);
3297 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3298 for entity_id in tracked {
3299 if let Some(windows) =
3300 cx.window_invalidators_by_entity.get_mut(&entity_id)
3301 {
3302 windows.remove(&window_id);
3303 }
3304 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3305 cx.current_window_by_entity.remove(&entity_id);
3306 }
3307 }
3308 }
3309
3310 cx.window_closed_observers.clone().retain(&(), |callback| {
3311 callback(cx, window_id);
3312 true
3313 });
3314
3315 let quit_on_empty = match cx.quit_mode {
3316 QuitMode::Explicit => false,
3317 QuitMode::LastWindowClosed => true,
3318 QuitMode::Default => cfg!(not(target_os = "macos")),
3319 };
3320
3321 if quit_on_empty && cx.windows.is_empty() {
3322 cx.quit();
3323 }
3324 } else {
3325 cx.windows.get_mut(window_id)?.replace(window);
3326 }
3327 Some(())
3328 }
3329 if trail(window_id, window, cx).is_none() {
3330 update(None);
3331 }
3332 });
3333 }
3334
3335 #[inline(never)]
3336 fn update_entity_erased(
3337 &mut self,
3338 handle: &AnyEntity,
3339 entity_type: &str,
3340 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3341 ) {
3342 self.update(|cx| {
3343 let mut lease = cx.entities.lease_erased(handle, entity_type);
3344 update(lease.entity.as_deref_mut().unwrap(), cx);
3345 cx.entities.end_lease_erased(handle.entity_id, lease);
3346 });
3347 }
3348
3349 #[inline(never)]
3350 #[track_caller]
3351 fn prepare_spawn(&self) -> AsyncApp {
3352 if self.quitting {
3353 debug_panic!("Can't spawn on main thread after on_app_quit")
3354 };
3355 self.to_async()
3356 }
3357}
3358
3359impl AppContext for App {
3360 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3365 self.update(|cx| {
3366 let slot = cx.entities.reserve();
3367 let handle = slot.clone();
3368 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3369
3370 cx.push_effect(Effect::EntityCreated {
3371 entity: handle.into_any(),
3372 tid: TypeId::of::<T>(),
3373 window: cx.window_update_stack.last().cloned(),
3374 });
3375
3376 cx.entities.insert(slot, entity)
3377 })
3378 }
3379
3380 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3381 Reservation(self.entities.reserve())
3382 }
3383
3384 fn insert_entity<T: 'static>(
3385 &mut self,
3386 reservation: Reservation<T>,
3387 build_entity: impl FnOnce(&mut Context<T>) -> T,
3388 ) -> Entity<T> {
3389 self.update(|cx| {
3390 let slot = reservation.0;
3391 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3392 cx.entities.insert(slot, entity)
3393 })
3394 }
3395
3396 #[inline(always)]
3399 fn update_entity<T: 'static, R>(
3400 &mut self,
3401 handle: &Entity<T>,
3402 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3403 ) -> R {
3404 let mut update = Some(update);
3405 let mut result = None;
3406 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3407 let value = update.take().unwrap()(
3408 entity.downcast_mut::<T>().unwrap(),
3409 &mut Context::new_context(cx, handle.downgrade()),
3410 );
3411 result = Some(value);
3412 });
3413 result.unwrap()
3414 }
3415
3416 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3417 where
3418 T: 'static,
3419 {
3420 GpuiBorrow::new(handle.clone(), self)
3421 }
3422
3423 #[inline(always)]
3424 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3425 where
3426 T: 'static,
3427 {
3428 let entity = self.entities.read(handle);
3429 read(entity, self)
3430 }
3431
3432 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3433 where
3434 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3435 {
3436 self.update_window_id(handle.id, update)
3437 }
3438
3439 fn with_window<R>(
3440 &mut self,
3441 entity_id: EntityId,
3442 f: impl FnOnce(&mut Window, &mut App) -> R,
3443 ) -> Option<R> {
3444 App::with_window(self, entity_id, f)
3445 }
3446
3447 fn read_window<T, R>(
3448 &self,
3449 window: &WindowHandle<T>,
3450 read: impl FnOnce(Entity<T>, &App) -> R,
3451 ) -> Result<R>
3452 where
3453 T: 'static,
3454 {
3455 let window = self
3456 .windows
3457 .get(window.id)
3458 .context("window not found")?
3459 .as_deref()
3460 .expect("attempted to read a window that is already on the stack");
3461
3462 let root_view = window.root.clone().unwrap();
3463 let view = root_view
3464 .downcast::<T>()
3465 .map_err(|_| anyhow!("root view's type has changed"))?;
3466
3467 Ok(read(view, self))
3468 }
3469
3470 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3471 where
3472 R: Send + 'static,
3473 {
3474 self.background_executor.spawn(future)
3475 }
3476
3477 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3478 where
3479 G: Global,
3480 {
3481 let mut g = self.global::<G>();
3482 callback(g, self)
3483 }
3484}
3485
3486pub(crate) enum Effect {
3488 Notify {
3489 emitter: EntityId,
3490 },
3491 Emit {
3492 emitter: EntityId,
3493 event_type: TypeId,
3494 event: ArenaBox<dyn Any>,
3495 },
3496 RefreshWindows,
3497 NotifyGlobalObservers {
3498 global_type: TypeId,
3499 },
3500 Defer {
3501 callback: Box<dyn FnOnce(&mut App) + 'static>,
3502 },
3503 EntityCreated {
3504 entity: AnyEntity,
3505 tid: TypeId,
3506 window: Option<WindowId>,
3507 },
3508}
3509
3510impl std::fmt::Debug for Effect {
3511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3512 match self {
3513 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3514 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3515 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3516 Effect::NotifyGlobalObservers { global_type } => {
3517 write!(f, "NotifyGlobalObservers({:?})", global_type)
3518 }
3519 Effect::Defer { .. } => write!(f, "Defer(..)"),
3520 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3521 }
3522 }
3523}
3524
3525pub(crate) struct GlobalLease<G: Global> {
3527 global: Box<dyn Any>,
3528 global_type: PhantomData<G>,
3529}
3530
3531impl<G: Global> GlobalLease<G> {
3532 fn new(global: Box<dyn Any>) -> Self {
3533 GlobalLease {
3534 global,
3535 global_type: PhantomData,
3536 }
3537 }
3538}
3539
3540impl<G: Global> Deref for GlobalLease<G> {
3541 type Target = G;
3542
3543 fn deref(&self) -> &Self::Target {
3544 self.global.downcast_ref().unwrap()
3545 }
3546}
3547
3548impl<G: Global> DerefMut for GlobalLease<G> {
3549 fn deref_mut(&mut self) -> &mut Self::Target {
3550 self.global.downcast_mut().unwrap()
3551 }
3552}
3553
3554pub struct AnyDrag {
3557 pub view: AnyView,
3559
3560 pub value: Arc<dyn Any>,
3562
3563 pub cursor_offset: Point<Pixels>,
3566
3567 pub cursor_style: Option<CursorStyle>,
3569
3570 pub external_payload_source: Option<ExternalDragPayloadSource>,
3573}
3574
3575pub type ExternalDragPayloadSource =
3578 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3579
3580#[derive(Clone)]
3583pub struct AnyTooltip {
3584 pub view: AnyView,
3586
3587 pub mouse_position: Point<Pixels>,
3589
3590 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3594}
3595
3596#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3598pub enum InputPreference {
3599 CharacterInput,
3601 KeyBindings,
3603}
3604
3605#[derive(Debug)]
3607pub struct KeystrokeEvent {
3608 pub keystroke: Keystroke,
3610
3611 pub input_preference: InputPreference,
3619
3620 pub action: Option<Box<dyn Action>>,
3622
3623 pub context_stack: Vec<KeyContext>,
3625}
3626
3627struct NullHttpClient;
3628
3629impl HttpClient for NullHttpClient {
3630 fn send(
3631 &self,
3632 _req: http_client::Request<http_client::AsyncBody>,
3633 ) -> futures::future::BoxFuture<
3634 'static,
3635 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3636 > {
3637 async move {
3638 anyhow::bail!("No HttpClient available");
3639 }
3640 .boxed()
3641 }
3642
3643 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3644 None
3645 }
3646
3647 fn proxy(&self) -> Option<&Url> {
3648 None
3649 }
3650}
3651
3652pub struct GpuiBorrow<'a, T> {
3654 inner: Option<Lease<T>>,
3655 app: &'a mut App,
3656}
3657
3658impl<'a, T: 'static> GpuiBorrow<'a, T> {
3659 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3660 app.start_update();
3661 let lease = app.entities.lease(&inner);
3662 Self {
3663 inner: Some(lease),
3664 app,
3665 }
3666 }
3667}
3668
3669impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3670 fn borrow(&self) -> &T {
3671 self.inner.as_ref().unwrap().borrow()
3672 }
3673}
3674
3675impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3676 fn borrow_mut(&mut self) -> &mut T {
3677 self.inner.as_mut().unwrap().borrow_mut()
3678 }
3679}
3680
3681impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3682 type Target = T;
3683
3684 fn deref(&self) -> &Self::Target {
3685 self.inner.as_ref().unwrap()
3686 }
3687}
3688
3689impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3690 fn deref_mut(&mut self) -> &mut T {
3691 self.inner.as_mut().unwrap()
3692 }
3693}
3694
3695impl<'a, T> Drop for GpuiBorrow<'a, T> {
3696 fn drop(&mut self) {
3697 let lease = self.inner.take().unwrap();
3698 self.app.notify(lease.id);
3699 self.app.entities.end_lease(lease);
3700 self.app.finish_update();
3701 }
3702}
3703
3704#[cfg(test)]
3705mod test {
3706 use std::{
3707 cell::{Cell, RefCell},
3708 ffi::OsString,
3709 path::PathBuf,
3710 rc::Rc,
3711 };
3712
3713 #[cfg(unix)]
3714 use std::os::unix::ffi::OsStringExt;
3715
3716 use crate::{
3717 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3718 TestAppContext, Window,
3719 };
3720
3721 #[gpui::test]
3722 fn app_borrow_diagnostics(cx: &mut TestAppContext) {
3723 use std::panic::{AssertUnwindSafe, catch_unwind};
3724
3725 let app = cx.app.clone();
3726 let first_line = line!() + 1;
3727 let first = app.borrow();
3728 let second = app.borrow();
3729 drop(first);
3730 assert!(app.try_borrow_mut().is_err());
3731 let attempted_line = line!() + 1;
3732 let panic = catch_unwind(AssertUnwindSafe(|| drop(app.borrow_mut())));
3733 let message = *panic
3734 .expect_err("conflicting borrow")
3735 .downcast::<String>()
3736 .unwrap();
3737 assert!(message.contains(&format!(
3738 "mutable App borrow at {}:{attempted_line}:",
3739 file!()
3740 )));
3741 assert!(message.contains(&format!(
3742 "shared borrow group began at {}:{first_line}:",
3743 file!()
3744 )));
3745 drop(second);
3746
3747 let origin_line = line!() + 2;
3748 let panic = catch_unwind(AssertUnwindSafe(|| {
3749 let _borrow = app.try_borrow_mut().expect("initial borrow");
3750 drop(app.borrow());
3751 }));
3752 let message = *panic
3753 .expect_err("conflicting borrow")
3754 .downcast::<String>()
3755 .unwrap();
3756 assert!(message.contains("attempted shared App borrow"));
3757 assert!(message.contains(&format!(
3758 "mutable borrow group began at {}:{origin_line}:",
3759 file!()
3760 )));
3761
3762 let next_line = line!() + 1;
3763 let _borrow = app.borrow();
3764 assert_eq!(
3765 app.borrow_origin.get().expect("new origin").0.line(),
3766 next_line
3767 );
3768 }
3769
3770 struct RenderCounter(Rc<Cell<usize>>);
3771
3772 impl Render for RenderCounter {
3773 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3774 self.0.set(self.0.get() + 1);
3775 Empty
3776 }
3777 }
3778
3779 #[gpui::test]
3780 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3781 let render_count = Rc::new(Cell::new(0));
3782
3783 let _window = cx.add_window({
3784 let render_count = render_count.clone();
3785 move |_, _| RenderCounter(render_count)
3786 });
3787
3788 cx.run_until_parked();
3789 let render_count_before_refresh = render_count.get();
3790
3791 cx.to_async().refresh();
3792
3793 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3794 }
3795
3796 #[gpui::test]
3797 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3798 let observed = Rc::new(RefCell::new(Vec::new()));
3799 let subscription = cx.update(|cx| {
3800 let observed = observed.clone();
3801 cx.on_missing_glyphs(move |missing_glyphs, _| {
3802 observed.borrow_mut().extend_from_slice(missing_glyphs);
3803 })
3804 });
3805 cx.update(|cx| {
3806 cx.text_system()
3807 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3808 });
3809 cx.run_until_parked();
3810 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3811
3812 let second_observed = Rc::new(RefCell::new(Vec::new()));
3813 let second_subscription = cx.update(|cx| {
3814 let second_observed = second_observed.clone();
3815 cx.on_missing_glyphs(move |missing_glyphs, _| {
3816 second_observed
3817 .borrow_mut()
3818 .extend_from_slice(missing_glyphs);
3819 })
3820 });
3821 cx.update(|cx| {
3822 cx.text_system()
3823 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3824 });
3825 cx.run_until_parked();
3826 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3827 assert_eq!(
3828 second_observed.borrow().as_slice(),
3829 &[missing_glyph("replacement")]
3830 );
3831
3832 drop(subscription);
3833 cx.update(|cx| {
3834 cx.text_system()
3835 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3836 });
3837 cx.run_until_parked();
3838 assert_eq!(
3839 second_observed.borrow().as_slice(),
3840 &[
3841 missing_glyph("replacement"),
3842 missing_glyph("after old drop")
3843 ]
3844 );
3845
3846 drop(second_subscription);
3847 cx.update(|cx| {
3848 cx.text_system()
3849 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3850 });
3851 cx.run_until_parked();
3852 assert_eq!(second_observed.borrow().len(), 2);
3853 }
3854
3855 #[test]
3856 fn test_gpui_borrow() {
3857 let cx = TestAppContext::single();
3858 let observation_count = Rc::new(RefCell::new(0));
3859
3860 let state = cx.update(|cx| {
3861 let state = cx.new(|_| false);
3862 cx.observe(&state, {
3863 let observation_count = observation_count.clone();
3864 move |_, _| {
3865 let mut count = observation_count.borrow_mut();
3866 *count += 1;
3867 }
3868 })
3869 .detach();
3870
3871 state
3872 });
3873
3874 cx.update(|cx| {
3875 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3877 });
3878
3879 cx.update(|cx| {
3880 state.write(cx, false);
3881 });
3882
3883 assert_eq!(*observation_count.borrow(), 2);
3884 }
3885
3886 #[gpui::test]
3887 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3888 #[cfg(unix)]
3889 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3890 #[cfg(not(unix))]
3891 let user_data_dir = OsString::from("C:\\zed data");
3892 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3893 let restart_path = PathBuf::from("updated-zed");
3894 let _application =
3895 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3896 let restart = cx.expect_restart();
3897
3898 cx.update(|cx| {
3899 cx.set_restart_path(restart_path.clone());
3900 cx.restart();
3901 });
3902
3903 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3904 assert_eq!(path, Some(restart_path));
3905 assert_eq!(restart_arguments, arguments);
3906 }
3907
3908 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3909 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3910 }
3911}