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