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