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, WindowBounds, WindowButtonLayout, WindowHandle,
60 WindowId, 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<WindowUpdateEntry>,
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
996#[derive(Clone, Copy)]
997pub(crate) struct WindowUpdateEntry {
998 window_id: WindowId,
999 bounds: WindowBounds,
1000 display_id: Option<DisplayId>,
1001}
1002
1003impl App {
1004 #[allow(clippy::new_ret_no_self)]
1005 pub(crate) fn new_app(
1006 platform: Rc<dyn Platform>,
1007 asset_source: Arc<dyn AssetSource>,
1008 http_client: Arc<dyn HttpClient>,
1009 ) -> Rc<AppCell> {
1010 let background_executor = platform.background_executor();
1011 let foreground_executor = platform.foreground_executor();
1012 assert!(
1013 background_executor.is_main_thread(),
1014 "must construct App on main thread"
1015 );
1016 #[cfg(feature = "profiler")]
1017 let foreground_journal = crate::profiler::journal::install_foreground_journal();
1018 let synced_animation_epoch = background_executor.now();
1019
1020 let text_system = Arc::new(TextSystem::new(platform.text_system()));
1021 let entities = EntityMap::new();
1022 let keyboard_layout = platform.keyboard_layout();
1023 let keyboard_mapper = platform.keyboard_mapper();
1024 let power_mode = platform.power_mode();
1025
1026 #[cfg(any(test, gpui_leak_detection))]
1027 let _ref_counts = entities.ref_counts_drop_handle();
1028
1029 let app = Rc::new_cyclic(|this| AppCell {
1030 borrow_origin: Cell::new(None),
1031 app: RefCell::new(App {
1032 this: this.clone(),
1033 platform: platform.clone(),
1034 text_system,
1035 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
1036 mode: GpuiMode::Production,
1037 actions: Rc::new(ActionRegistry::default()),
1038 pending_updates: 0,
1039 active_drag: None,
1040 platform_owned_drag: None,
1041 background_executor,
1042 foreground_executor,
1043 #[cfg(feature = "profiler")]
1044 foreground_journal,
1045 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1046 hang_monitor: None,
1047 svg_renderer: SvgRenderer::new(asset_source.clone()),
1048 loading_assets: Default::default(),
1049 asset_source,
1050 http_client,
1051 globals_by_type: Default::default(),
1052 entities,
1053 new_entity_observers: SubscriberSet::new(),
1054 windows: SlotMap::with_key(),
1055 window_update_stack: Vec::new(),
1056 window_handles: FxHashMap::default(),
1057 focus_handles: Arc::new(RwLock::new(FocusMap::default())),
1058 keymap: Rc::new(RefCell::new(Keymap::default())),
1059 keyboard_layout,
1060 keyboard_mapper,
1061 global_action_listeners: Default::default(),
1062 pending_effects: VecDeque::new(),
1063 pending_notifications: FxHashSet::default(),
1064 pending_global_notifications: Default::default(),
1065 dependencies: crate::fast::dependencies::AppDependencies::default(),
1066 observers: SubscriberSet::new(),
1067 tracked_entities: FxHashMap::default(),
1068 window_invalidators_by_entity: FxHashMap::default(),
1069 current_window_by_entity: FxHashMap::default(),
1070 event_listeners: SubscriberSet::new(),
1071 release_listeners: SubscriberSet::new(),
1072 keystroke_observers: SingleSubscriberSet::new(),
1073 keystroke_interceptors: SingleSubscriberSet::new(),
1074 keyboard_layout_observers: SingleSubscriberSet::new(),
1075 missing_glyph_callback: Rc::default(),
1076 thermal_state_observers: SingleSubscriberSet::new(),
1077 display_observers: SingleSubscriberSet::new(),
1078 displays: read_displays(platform.as_ref()),
1079 system_sleep_observers: SingleSubscriberSet::new(),
1080 system_wake_observers: SingleSubscriberSet::new(),
1081 app_lifecycle_observers: SingleSubscriberSet::new(),
1082 memory_warning_observers: SingleSubscriberSet::new(),
1083 global_observers: SubscriberSet::new(),
1084 quit_observers: SingleSubscriberSet::new(),
1085 restart_observers: SingleSubscriberSet::new(),
1086 restart_path: None,
1087 restart_arguments: Vec::new(),
1088 window_closed_observers: SingleSubscriberSet::new(),
1089 layout_id_buffer: Default::default(),
1090 propagate_event: true,
1091 prompt_builder: Some(PromptBuilder::Default),
1092 #[cfg(any(feature = "inspector", debug_assertions))]
1093 inspector_renderer: None,
1094 #[cfg(any(feature = "inspector", debug_assertions))]
1095 inspector_element_registry: InspectorElementRegistry::default(),
1096 quit_mode: QuitMode::default(),
1097 quitting: false,
1098 cursor_hide_mode: CursorHideMode::default(),
1099 reduce_motion: false,
1100 synced_animation_epoch,
1101 power_mode,
1102 accessibility_force_disabled: false,
1103
1104 #[cfg(any(test, feature = "test-support", debug_assertions))]
1105 name: None,
1106 element_arena: Rc::new(RefCell::new(Arena::new(1024 * 1024))),
1107 event_arena: Arena::new(1024 * 1024),
1108
1109 #[cfg(any(test, gpui_leak_detection))]
1110 _ref_counts,
1111 }),
1112 });
1113
1114 init_app_menus(platform.as_ref(), &app.borrow());
1115 SystemWindowTabController::init(&mut app.borrow_mut());
1116 #[cfg(feature = "profiler")]
1117 crate::profiler::journal::observe_power(&app.borrow());
1118
1119 platform.on_keyboard_layout_change(Box::new({
1120 let app = Rc::downgrade(&app);
1121 move || {
1122 if let Some(app) = app.upgrade() {
1123 let cx = &mut app.borrow_mut();
1124 cx.keyboard_layout = cx.platform.keyboard_layout();
1125 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1126 cx.keyboard_layout_observers
1127 .clone()
1128 .retain(move |callback| (callback)(cx));
1129 }
1130 }
1131 }));
1132
1133 platform.on_thermal_state_change(Box::new({
1134 let app = Rc::downgrade(&app);
1135 move || {
1136 if let Some(app) = app.upgrade() {
1137 let cx = &mut app.borrow_mut();
1138 cx.thermal_state_observers
1139 .clone()
1140 .retain(move |callback| (callback)(cx));
1141 }
1142 }
1143 }));
1144
1145 platform.on_displays_changed(Box::new({
1146 let app = Rc::downgrade(&app);
1147 move || {
1148 if let Some(app) = app.upgrade() {
1149 app.borrow_mut().displays_changed();
1150 }
1151 }
1152 }));
1153
1154 let fast_power = crate::fast::misc::system_power::PowerNotifications::new(
1155 platform.foreground_executor(),
1156 );
1157 platform.on_system_sleep(Box::new({
1158 let app = Rc::downgrade(&app);
1159 let fast_power = Rc::clone(&fast_power);
1160 move || {
1161 if let Some(app) = app.upgrade() {
1162 let Some(cx) =
1163 &mut crate::fast::misc::system_power::PowerNotifications::borrow_for_sleep(
1164 &fast_power,
1165 &app,
1166 )
1167 else {
1168 return;
1169 };
1170 cx.system_sleep_observers
1171 .clone()
1172 .retain(move |callback| (callback)(cx));
1173 }
1174 }
1175 }));
1176
1177 platform.on_system_wake(Box::new({
1178 let app = Rc::downgrade(&app);
1179 move || {
1180 if let Some(app) = app.upgrade() {
1181 let Some(cx) =
1182 &mut crate::fast::misc::system_power::PowerNotifications::borrow_for_wake(
1183 &fast_power,
1184 &app,
1185 )
1186 else {
1187 return;
1188 };
1189 cx.system_wake_observers
1190 .clone()
1191 .retain(move |callback| (callback)(cx));
1192 }
1193 }
1194 }));
1195
1196 platform.on_app_lifecycle(Box::new({
1197 let app = Rc::downgrade(&app);
1198 move |phase| {
1199 if let Some(app) = app.upgrade() {
1200 app.borrow_mut().update(|cx| {
1201 cx.app_lifecycle_observers
1202 .clone()
1203 .retain(|callback| callback(phase, cx));
1204 });
1205 }
1206 }
1207 }));
1208
1209 platform.on_memory_warning(Box::new({
1210 let app = Rc::downgrade(&app);
1211 move || {
1212 if let Some(app) = app.upgrade() {
1213 app.borrow_mut().update(|cx| {
1214 cx.memory_warning_observers
1215 .clone()
1216 .retain(|callback| callback(cx));
1217 });
1218 }
1219 }
1220 }));
1221
1222 platform.on_power_mode_change(Box::new({
1223 let app = Rc::downgrade(&app);
1224 move || {
1225 if let Some(app) = app.upgrade() {
1226 let power_mode = app.borrow().platform.power_mode();
1227 app.borrow_mut().power_mode = power_mode;
1228 }
1229 }
1230 }));
1231
1232 platform.on_quit(Box::new({
1233 let cx = Rc::downgrade(&app);
1234 move || {
1235 let Some(cx) = cx.upgrade() else {
1236 return true;
1237 };
1238 match cx.try_borrow_mut() {
1239 Ok(mut cx) => {
1240 cx.shutdown();
1241 true
1242 }
1243 Err(_) => {
1244 false
1247 }
1248 }
1249 }
1250 }));
1251
1252 app
1253 }
1254
1255 #[doc(hidden)]
1256 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1257 self.entities.ref_counts_drop_handle()
1258 }
1259
1260 #[cfg(any(test, gpui_leak_detection))]
1266 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1267 self.entities.leak_detector_snapshot()
1268 }
1269
1270 #[cfg(any(test, gpui_leak_detection))]
1282 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1283 self.entities.assert_no_new_leaks(snapshot)
1284 }
1285
1286 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1288 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1289 LeakDetectorSnapshot::default()
1290 }
1291
1292 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1295 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1296
1297 pub fn shutdown(&mut self) {
1303 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1306 let hang_monitor_flush = self
1307 .hang_monitor
1308 .as_ref()
1309 .and_then(|hang_monitor| hang_monitor.request_flush());
1310
1311 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1312
1313 for observer in self.quit_observers.remove() {
1314 futures.push(observer(self));
1315 }
1316
1317 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1318 if let Some(flushed) = hang_monitor_flush {
1319 futures.push(
1320 async move {
1321 if flushed.await.is_err() {
1322 log::warn!("hang monitor exited before flushing");
1323 }
1324 }
1325 .boxed_local(),
1326 );
1327 }
1328
1329 self.windows.clear();
1330 self.window_handles.clear();
1331 self.flush_effects();
1332 self.quitting = true;
1333
1334 let futures = futures::future::join_all(futures);
1335 #[cfg(not(target_family = "wasm"))]
1336 if self
1337 .foreground_executor
1338 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1339 .is_err()
1340 {
1341 log::error!("timed out waiting on app_will_quit");
1342 }
1343 #[cfg(target_family = "wasm")]
1344 self.foreground_executor.spawn(futures).detach();
1345
1346 self.quitting = false;
1347 }
1348
1349 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1351 self.keyboard_layout.as_ref()
1352 }
1353
1354 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1356 &self.keyboard_mapper
1357 }
1358
1359 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1361 where
1362 F: 'static + FnMut(&mut App),
1363 {
1364 self.keyboard_layout_observers.insert(Box::new(move |cx| {
1365 callback(cx);
1366 true
1367 }))
1368 }
1369
1370 pub fn quit(&self) {
1372 self.platform.quit();
1373 }
1374
1375 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1389 if !self.windows.is_empty() {
1390 return Task::ready(Err(anyhow::anyhow!(
1391 "cannot switch windowing modes while windows are open"
1392 )));
1393 }
1394 self.platform.request_windowing(request)
1395 }
1396
1397 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1407 self.platform.graphical_environment()
1408 }
1409
1410 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1413 self.cursor_hide_mode
1414 }
1415
1416 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1419 self.cursor_hide_mode = mode;
1420 }
1421
1422 pub fn is_cursor_visible(&self) -> bool {
1428 self.platform.is_cursor_visible()
1429 }
1430
1431 pub fn reduce_motion(&self) -> bool {
1434 self.reduce_motion
1435 }
1436
1437 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1440 if self.reduce_motion != reduce_motion {
1441 self.reduce_motion = reduce_motion;
1442 self.refresh_windows();
1443 }
1444 }
1445
1446 pub fn refresh_windows(&mut self) {
1449 self.pending_effects.push_back(Effect::RefreshWindows);
1450 }
1451
1452 #[inline(always)]
1453 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1454 self.start_update();
1455 let result = update(self);
1456 self.finish_update();
1457 result
1458 }
1459
1460 pub(crate) fn start_update(&mut self) {
1461 self.pending_updates += 1;
1462 }
1463
1464 #[inline(never)]
1465 pub(crate) fn finish_update(&mut self) {
1466 if self.pending_updates == 1 {
1467 self.flush_effects();
1468 }
1469 self.pending_updates -= 1;
1470 }
1471
1472 pub fn observe<W>(
1474 &mut self,
1475 entity: &Entity<W>,
1476 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1477 ) -> Subscription
1478 where
1479 W: 'static,
1480 {
1481 self.observe_internal(entity, move |e, cx| {
1482 on_notify(e, cx);
1483 true
1484 })
1485 }
1486
1487 pub(crate) fn detect_accessed_entities<R>(
1488 &mut self,
1489 callback: impl FnOnce(&mut App) -> R,
1490 ) -> (R, FxHashSet<EntityId>) {
1491 self.entities.push_access_scope();
1492 let result = callback(self);
1493 (result, self.entities.pop_access_scope())
1494 }
1495
1496 pub(crate) fn record_entities_accessed(
1497 &mut self,
1498 window_handle: AnyWindowHandle,
1499 invalidator: WindowInvalidator,
1500 entities: &FxHashSet<EntityId>,
1501 ) {
1502 crate::fast::tracked_entities::record_entities_accessed(
1503 self,
1504 window_handle,
1505 invalidator,
1506 entities,
1507 );
1508 }
1509
1510 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1511 let (subscription, activate) = self.observers.insert_pending(key, value);
1512 self.defer(move |_| activate());
1513 subscription
1514 }
1515
1516 pub(crate) fn observe_internal<W>(
1517 &mut self,
1518 entity: &Entity<W>,
1519 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1520 ) -> Subscription
1521 where
1522 W: 'static,
1523 {
1524 let entity_id = entity.entity_id();
1525 let handle = entity.downgrade();
1526 self.new_observer(
1527 entity_id,
1528 Box::new(move |cx| {
1529 if let Some(entity) = handle.upgrade() {
1530 on_notify(entity, cx)
1531 } else {
1532 false
1533 }
1534 }),
1535 )
1536 }
1537
1538 pub fn subscribe<T, Event>(
1541 &mut self,
1542 entity: &Entity<T>,
1543 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1544 ) -> Subscription
1545 where
1546 T: 'static + EventEmitter<Event>,
1547 Event: 'static,
1548 {
1549 self.subscribe_internal(entity, move |entity, event, cx| {
1550 on_event(entity, event, cx);
1551 true
1552 })
1553 }
1554
1555 pub(crate) fn new_subscription(
1556 &mut self,
1557 key: EntityId,
1558 value: (TypeId, Listener),
1559 ) -> Subscription {
1560 let (subscription, activate) = self.event_listeners.insert_pending(key, value);
1561 self.defer(move |_| activate());
1562 subscription
1563 }
1564 pub(crate) fn subscribe_internal<T, Evt>(
1565 &mut self,
1566 entity: &Entity<T>,
1567 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1568 ) -> Subscription
1569 where
1570 T: 'static + EventEmitter<Evt>,
1571 Evt: 'static,
1572 {
1573 let entity_id = entity.entity_id();
1574 let handle = entity.downgrade();
1575 self.new_subscription(
1576 entity_id,
1577 (
1578 TypeId::of::<Evt>(),
1579 Box::new(move |event, cx| {
1580 let event: &Evt = event.downcast_ref().expect("invalid event type");
1581 if let Some(entity) = handle.upgrade() {
1582 on_event(entity, event, cx)
1583 } else {
1584 false
1585 }
1586 }),
1587 ),
1588 )
1589 }
1590
1591 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1595 self.windows
1596 .keys()
1597 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1598 .collect()
1599 }
1600
1601 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1607 self.platform.window_stack()
1608 }
1609
1610 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1612 self.platform.active_window()
1613 }
1614
1615 pub fn active_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1617 let (display_id, _) = self.active_window_placement()?;
1618 self.find_display(display_id?)
1619 }
1620
1621 pub(crate) fn active_window_placement(&self) -> Option<(Option<DisplayId>, WindowBounds)> {
1622 let window_id = self.active_window()?.window_id();
1623
1624 if let Some(state) = self
1625 .window_update_stack
1626 .iter()
1627 .rev()
1628 .find(|state| state.window_id == window_id)
1629 {
1630 return Some((state.display_id, state.bounds));
1631 }
1632
1633 let window = self.windows.get(window_id)?.as_ref()?;
1634 Some((window.display_id(), window.last_window_bounds()))
1635 }
1636
1637 pub(crate) fn sync_window_update_entry(&mut self, window: &Window) {
1638 if let Some(state) = self
1639 .window_update_stack
1640 .iter_mut()
1641 .rev()
1642 .find(|state| state.window_id == window.handle.id)
1643 {
1644 state.bounds = window.last_window_bounds();
1645 state.display_id = window.display_id();
1646 }
1647 }
1648
1649 pub fn open_window<V: 'static + Render>(
1653 &mut self,
1654 options: crate::WindowOptions,
1655 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1656 ) -> anyhow::Result<WindowHandle<V>> {
1657 self.update(|cx| {
1658 let id = cx.windows.insert(None);
1659 let handle = WindowHandle::new(id);
1660 match Window::new(handle.into(), options, cx) {
1661 Ok(mut window) => {
1662 cx.window_update_stack.push(WindowUpdateEntry {
1663 window_id: id,
1664 bounds: window.last_window_bounds(),
1665 display_id: window.display_id(),
1666 });
1667 let root_view = build_root_view(&mut window, cx);
1668 cx.window_update_stack.pop();
1669 window.root.replace(root_view.into());
1670 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1671
1672 let clear = window.draw(cx);
1677 clear.clear(cx);
1678
1679 cx.window_handles.insert(id, window.handle);
1680 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1681 Ok(handle)
1682 }
1683 Err(e) => {
1684 cx.windows.remove(id);
1685 Err(e)
1686 }
1687 }
1688 })
1689 }
1690
1691 pub fn activate(&self, ignoring_other_apps: bool) {
1693 self.platform.activate(ignoring_other_apps);
1694 }
1695
1696 pub fn hide(&self) {
1698 self.platform.hide();
1699 }
1700
1701 pub fn hide_other_apps(&self) {
1703 self.platform.hide_other_apps();
1704 }
1705
1706 pub fn unhide_other_apps(&self) {
1708 self.platform.unhide_other_apps();
1709 }
1710
1711 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1713 self.platform.displays()
1714 }
1715
1716 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1718 self.platform.primary_display()
1719 }
1720
1721 pub fn is_screen_capture_supported(&self) -> bool {
1723 self.platform.is_screen_capture_supported()
1724 }
1725
1726 pub fn screen_capture_sources(
1728 &self,
1729 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1730 self.platform.screen_capture_sources()
1731 }
1732
1733 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1735 self.displays()
1736 .iter()
1737 .find(|display| display.id() == id)
1738 .cloned()
1739 }
1740
1741 pub fn debug_state(&self) -> serde_json::Value {
1748 let displays = self
1749 .platform
1750 .displays()
1751 .into_iter()
1752 .map(|display| {
1753 serde_json::json!({
1754 "id": u64::from(display.id()),
1755 "uuid": display.uuid().ok().map(|uuid| uuid.to_string()),
1756 "bounds": display.bounds(),
1757 "visible_bounds": display.visible_bounds(),
1758 "refresh_interval_seconds": display
1759 .refresh_interval()
1760 .map(|interval| interval.as_secs_f64()),
1761 })
1762 })
1763 .collect::<Vec<_>>();
1764 let windows = self
1765 .windows
1766 .iter()
1767 .map(|(window_id, window)| match window {
1768 Some(window) => window.debug_state(),
1769 None => serde_json::json!({ "id": window_id.as_u64(), "updating": true }),
1770 })
1771 .collect::<Vec<_>>();
1772 serde_json::json!({
1773 "compositor": self.platform.compositor_name(),
1774 "thermal_state": format!("{:?}", self.platform.thermal_state()),
1775 "power_mode": {
1776 "cached": format!("{:?}", self.power_mode),
1777 "platform": format!("{:?}", self.platform.power_mode()),
1778 },
1779 "window_appearance": format!("{:?}", self.platform.window_appearance()),
1780 "cursor_visible": self.platform.is_cursor_visible(),
1781 "active_window_id": self
1782 .platform
1783 .active_window()
1784 .map(|handle| handle.window_id().as_u64()),
1785 "window_stack": self.platform.window_stack().map(|stack| {
1786 stack
1787 .into_iter()
1788 .map(|handle| handle.window_id().as_u64())
1789 .collect::<Vec<_>>()
1790 }),
1791 "primary_display_id": self
1792 .platform
1793 .primary_display()
1794 .map(|display| u64::from(display.id())),
1795 "displays": displays,
1796 "windows": windows,
1797 "platform": self.platform.debug_state(),
1798 })
1799 }
1800
1801 pub fn thermal_state(&self) -> ThermalState {
1803 self.platform.thermal_state()
1804 }
1805
1806 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1808 self.platform.prevent_idle_sleep(reason)
1809 }
1810
1811 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1813 where
1814 F: 'static + FnMut(&mut App),
1815 {
1816 self.thermal_state_observers.insert(Box::new(move |cx| {
1817 callback(cx);
1818 true
1819 }))
1820 }
1821
1822 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1827 where
1828 F: 'static + FnMut(&mut App),
1829 {
1830 self.system_sleep_observers.insert(Box::new(move |cx| {
1831 callback(cx);
1832 true
1833 }))
1834 }
1835
1836 pub(crate) fn displays_changed(&mut self) {
1837 let current = read_displays(self.platform.as_ref());
1838 let events = display_events(&self.displays, ¤t);
1839 self.displays = current;
1840 for event in &events {
1841 let DisplayEvent::Changed { id, .. } = *event else {
1842 continue;
1843 };
1844 for handle in self.windows() {
1845 self.update_window(handle, |_, window, cx| {
1846 if window.display_id == Some(id) {
1847 window.notify_display_observers(cx);
1848 }
1849 })
1850 .log_err();
1851 }
1852 }
1853 for event in events {
1854 self.display_observers
1855 .clone()
1856 .retain(|callback| (callback)(event, self));
1857 }
1858 }
1859
1860 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1861 self.displays.contains_key(&id)
1862 }
1863
1864 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1867 self.displays.get(&id)?.refresh_interval
1868 }
1869
1870 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1873 where
1874 F: 'static + FnMut(DisplayEvent, &mut App),
1875 {
1876 self.display_observers.insert(Box::new(move |event, cx| {
1877 callback(event, cx);
1878 true
1879 }))
1880 }
1881
1882 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1884 where
1885 F: 'static + FnMut(&mut App),
1886 {
1887 self.system_wake_observers.insert(Box::new(move |cx| {
1888 callback(cx);
1889 true
1890 }))
1891 }
1892
1893 pub fn on_app_lifecycle(
1901 &self,
1902 mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
1903 ) -> Subscription {
1904 self.app_lifecycle_observers
1905 .insert(Box::new(move |phase, cx| {
1906 callback(phase, cx);
1907 true
1908 }))
1909 }
1910
1911 pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
1914 self.memory_warning_observers.insert(Box::new(move |cx| {
1915 callback(cx);
1916 true
1917 }))
1918 }
1919
1920 pub fn window_appearance(&self) -> WindowAppearance {
1922 self.platform.window_appearance()
1923 }
1924
1925 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1936 self.platform.set_window_appearance(appearance);
1937 }
1938
1939 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1941 self.platform.button_layout()
1942 }
1943
1944 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1946 self.platform.read_from_clipboard()
1947 }
1948
1949 pub fn read_from_clipboard_async(
1957 &self,
1958 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1959 self.platform.read_from_clipboard_async()
1960 }
1961
1962 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1964 self.text_rendering_mode.set(mode);
1965 }
1966
1967 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1969 self.text_rendering_mode.get()
1970 }
1971
1972 pub fn power_mode(&self) -> PowerMode {
1975 self.power_mode
1976 }
1977
1978 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1980 self.platform.write_to_clipboard(item)
1981 }
1982
1983 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1986 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1987 self.platform.read_from_primary()
1988 }
1989
1990 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1993 pub fn write_to_primary(&self, item: ClipboardItem) {
1994 self.platform.write_to_primary(item)
1995 }
1996
1997 #[cfg(target_os = "macos")]
2003 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
2004 self.platform.read_from_find_pasteboard()
2005 }
2006
2007 #[cfg(target_os = "macos")]
2013 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
2014 self.platform.write_to_find_pasteboard(item)
2015 }
2016
2017 pub fn write_credentials(
2019 &self,
2020 url: &str,
2021 username: &str,
2022 password: &[u8],
2023 ) -> Task<Result<()>> {
2024 self.platform.write_credentials(url, username, password)
2025 }
2026
2027 #[cfg(target_os = "macos")]
2035 pub fn write_credentials_if_not_exists(
2036 &self,
2037 url: &str,
2038 username: &str,
2039 password: &[u8],
2040 ) -> Task<Result<bool>> {
2041 self.platform
2042 .write_credentials_if_not_exists(url, username, password)
2043 }
2044
2045 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
2047 self.platform.read_credentials(url)
2048 }
2049
2050 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
2052 self.platform.delete_credentials(url)
2053 }
2054
2055 pub fn open_url(&self, url: &str) {
2057 self.platform.open_url(url);
2058 }
2059
2060 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
2067 self.platform.register_url_scheme(scheme)
2068 }
2069
2070 pub fn set_app_identity(&self, identifier: &str, name: &str) {
2077 self.platform.set_app_identity(identifier, name);
2078 }
2079
2080 pub fn show_system_notification(&self, notification: SystemNotification) {
2087 self.platform.show_system_notification(notification);
2088 }
2089
2090 pub fn dismiss_system_notification(&self, tag: &str) {
2095 self.platform.dismiss_system_notification(tag);
2096 }
2097
2098 pub fn on_system_notification_response<F>(&self, mut callback: F)
2102 where
2103 F: 'static + FnMut(SystemNotificationResponse, &mut App),
2104 {
2105 let this = self.this.clone();
2106 self.platform
2107 .on_system_notification_response(Box::new(move |response| {
2108 if let Some(app) = this.upgrade() {
2109 callback(response, &mut app.borrow_mut());
2110 }
2111 }));
2112 }
2113
2114 pub fn app_path(&self) -> Result<PathBuf> {
2118 self.platform.app_path()
2119 }
2120
2121 pub fn compositor_name(&self) -> &'static str {
2125 self.platform.compositor_name()
2126 }
2127
2128 pub fn platform_info(&self) -> crate::PlatformInfo {
2130 self.platform.platform_info()
2131 }
2132
2133 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
2135 self.platform.path_for_auxiliary_executable(name)
2136 }
2137
2138 pub fn prompt_for_paths(
2144 &self,
2145 options: PathPromptOptions,
2146 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
2147 self.platform.prompt_for_paths(options)
2148 }
2149
2150 pub fn prompt_for_new_path(
2157 &self,
2158 directory: &Path,
2159 suggested_name: Option<&str>,
2160 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
2161 self.platform.prompt_for_new_path(directory, suggested_name)
2162 }
2163
2164 pub fn reveal_path(&self, path: &Path) {
2166 self.platform.reveal_path(path)
2167 }
2168
2169 pub fn open_with_system(&self, path: &Path) {
2171 self.platform.open_with_system(path)
2172 }
2173
2174 pub fn should_auto_hide_scrollbars(&self) -> bool {
2176 self.platform.should_auto_hide_scrollbars()
2177 }
2178
2179 pub fn restart(&mut self) {
2181 self.restart_observers
2182 .clone()
2183 .retain(|observer| observer(self));
2184 self.platform.restart(
2185 self.restart_path.take(),
2186 std::mem::take(&mut self.restart_arguments),
2187 )
2188 }
2189
2190 pub fn set_restart_path(&mut self, path: PathBuf) {
2192 self.restart_path = Some(path);
2193 }
2194
2195 pub fn http_client(&self) -> Arc<dyn HttpClient> {
2197 self.http_client.clone()
2198 }
2199
2200 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
2202 self.http_client = new_client;
2203 }
2204
2205 pub fn set_quit_mode(&mut self, mode: QuitMode) {
2208 self.quit_mode = mode;
2209 }
2210
2211 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
2220 self.platform.set_activation_policy(policy);
2221 }
2222
2223 pub fn svg_renderer(&self) -> SvgRenderer {
2225 self.svg_renderer.clone()
2226 }
2227
2228 pub(crate) fn push_effect(&mut self, effect: Effect) {
2229 match &effect {
2230 Effect::Notify { emitter } => {
2231 if !self.pending_notifications.insert(*emitter) {
2232 return;
2233 }
2234 }
2235 Effect::NotifyGlobalObservers { global_type } => {
2236 crate::fast::dependencies::global_changed(self, *global_type);
2237 if !self.pending_global_notifications.insert(*global_type) {
2238 return;
2239 }
2240 }
2241 _ => {}
2242 };
2243
2244 self.pending_effects.push_back(effect);
2245 }
2246
2247 fn flush_effects(&mut self) {
2251 loop {
2252 self.release_dropped_entities();
2253 self.release_dropped_focus_handles();
2254 if let Some(effect) = self.pending_effects.pop_front() {
2255 match effect {
2256 Effect::Notify { emitter } => {
2257 self.apply_notify_effect(emitter);
2258 }
2259
2260 Effect::Emit {
2261 emitter,
2262 event_type,
2263 event,
2264 } => self.apply_emit_effect(emitter, event_type, &*event),
2265
2266 Effect::RefreshWindows => {
2267 self.apply_refresh_effect();
2268 }
2269
2270 Effect::NotifyGlobalObservers { global_type } => {
2271 self.apply_notify_global_observers_effect(global_type);
2272 }
2273
2274 Effect::Defer { callback } => {
2275 self.apply_defer_effect(callback);
2276 }
2277 Effect::EntityCreated {
2278 entity,
2279 tid,
2280 window,
2281 } => {
2282 self.apply_entity_created_effect(entity, tid, window);
2283 }
2284 }
2285 } else {
2286 #[cfg(any(test, feature = "test-support"))]
2287 if matches!(self.mode, GpuiMode::Test { .. }) {
2288 for window in self
2289 .windows
2290 .values()
2291 .filter_map(|window| {
2292 let window = window.as_deref()?;
2293 window.invalidator.is_dirty().then_some(window.handle)
2294 })
2295 .collect::<Vec<_>>()
2296 {
2297 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2298 .unwrap();
2299 }
2300 }
2301
2302 if self.pending_effects.is_empty() {
2303 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2304 if window.invalidator.is_dirty()
2305 || window.needs_present.get()
2306 || !window.next_frame_callbacks.borrow().is_empty()
2307 {
2308 window.platform_window.schedule_frame();
2309 }
2310 }
2311
2312 self.event_arena.clear();
2313 break;
2314 }
2315 }
2316 }
2317 }
2318
2319 fn release_dropped_entities(&mut self) {
2323 loop {
2324 let dropped = self.entities.take_dropped();
2325 if dropped.is_empty() {
2326 break;
2327 }
2328
2329 for (entity_id, mut entity) in dropped {
2330 self.observers.remove(&entity_id);
2331 self.event_listeners.remove(&entity_id);
2332 self.window_invalidators_by_entity.remove(&entity_id);
2333 self.current_window_by_entity.remove(&entity_id);
2334 for release_callback in self.release_listeners.remove(&entity_id) {
2335 release_callback(entity.as_mut(), self);
2336 }
2337 }
2338 }
2339 }
2340
2341 fn release_dropped_focus_handles(&mut self) {
2343 let focus_handles = self.focus_handles.clone();
2344 let mut focus_handles = focus_handles.write();
2345 let FocusMap {
2346 handles,
2347 dropped_handles,
2348 } = &mut *focus_handles;
2349 if dropped_handles.is_empty() {
2350 return;
2351 }
2352
2353 let windows = self
2354 .windows
2355 .values()
2356 .filter_map(|window| {
2357 let window = window.as_ref()?;
2358 dropped_handles
2359 .contains(&window.focus?)
2360 .then_some(window.handle)
2361 })
2362 .collect::<SmallVec<[_; 1]>>();
2363 for handle_id in dropped_handles.drain(..) {
2364 handles.remove(handle_id);
2365 }
2366 drop(focus_handles);
2367
2368 for window_handle in windows {
2369 window_handle
2370 .update(self, |_, window, cx| window.blur(cx))
2371 .ok();
2372 }
2373 }
2374
2375 fn apply_notify_effect(&mut self, emitter: EntityId) {
2376 self.pending_notifications.remove(&emitter);
2377
2378 self.observers
2379 .clone()
2380 .retain(&emitter, |handler| handler(self));
2381 }
2382
2383 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2384 self.event_listeners
2385 .clone()
2386 .retain(&emitter, |(stored_type, handler)| {
2387 if *stored_type == event_type {
2388 handler(event, self)
2389 } else {
2390 true
2391 }
2392 });
2393 }
2394
2395 fn apply_refresh_effect(&mut self) {
2396 for window in self.windows.values_mut() {
2397 if let Some(window) = window.as_deref_mut() {
2398 window.refreshing = true;
2399 window.invalidator.set_dirty(true);
2400 }
2401 }
2402 }
2403
2404 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2405 self.pending_global_notifications.remove(&type_id);
2406 self.global_observers
2407 .clone()
2408 .retain(&type_id, |observer| observer(self));
2409 }
2410
2411 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2412 callback(self);
2413 }
2414
2415 fn apply_entity_created_effect(
2416 &mut self,
2417 entity: AnyEntity,
2418 tid: TypeId,
2419 window: Option<WindowId>,
2420 ) {
2421 if let Some(id) = window {
2425 self.current_window_by_entity.insert(entity.entity_id(), id);
2426 }
2427
2428 self.new_entity_observers.clone().retain(&tid, |observer| {
2429 if let Some(id) = window {
2430 self.update_window_id(id, {
2431 let entity = entity.clone();
2432 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2433 })
2434 .expect("All windows should be off the stack when flushing effects");
2435 } else {
2436 (observer)(entity.clone(), &mut None, self)
2437 }
2438 true
2439 });
2440 }
2441
2442 #[inline(always)]
2448 pub fn with_window<R>(
2449 &mut self,
2450 entity_id: EntityId,
2451 f: impl FnOnce(&mut Window, &mut App) -> R,
2452 ) -> Option<R> {
2453 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2454 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2455 .ok()
2456 }
2457
2458 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2459 self.current_window_by_entity
2460 .entry(entity_id)
2461 .or_insert(window);
2462 }
2463
2464 #[inline(always)]
2465 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2466 where
2467 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2468 {
2469 let mut update = Some(update);
2470 let mut result = None;
2471 self.update_window_erased(id, &mut |arguments| {
2472 if let Some((root_view, window, cx)) = arguments {
2473 result = Some(update.take().unwrap()(root_view, window, cx));
2474 } else {
2475 drop(update.take());
2476 drop(result.take());
2477 }
2478 });
2479 result.context("window not found")
2480 }
2481
2482 pub fn to_async(&self) -> AsyncApp {
2485 AsyncApp {
2486 app: self.this.clone(),
2487 background_executor: self.background_executor.clone(),
2488 foreground_executor: self.foreground_executor.clone(),
2489 }
2490 }
2491
2492 pub fn background_executor(&self) -> &BackgroundExecutor {
2494 &self.background_executor
2495 }
2496
2497 pub fn is_test(&self) -> bool {
2500 self.background_executor.is_test()
2501 }
2502
2503 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2505 if self.quitting {
2506 panic!("Can't spawn on main thread after on_app_quit")
2507 };
2508 &self.foreground_executor
2509 }
2510
2511 #[cfg(feature = "profiler")]
2514 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2515 self.foreground_journal.clone()
2516 }
2517
2518 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2535 pub fn start_hang_monitor(
2536 &mut self,
2537 config: crate::profiler::hang::HangMonitorConfig,
2538 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2539 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2540 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2541
2542 if self.hang_monitor.is_some() {
2543 debug_assert!(false, "the hang monitor was started twice");
2544 return Err(HangMonitorError::AlreadyStarted);
2545 }
2546 let detector = HangDetector::new(
2547 self.foreground_journal(),
2548 config.threshold,
2549 config.frame_budget,
2550 );
2551 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2552 .map_err(HangMonitorError::Spawn)?;
2553 self.hang_monitor = Some(monitor);
2554 Ok(())
2555 }
2556
2557 #[track_caller]
2560 #[inline(always)]
2561 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2562 where
2563 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2564 R: 'static,
2565 {
2566 let mut cx = self.prepare_spawn();
2567
2568 self.foreground_executor
2569 .spawn(async move { f(&mut cx).await }.boxed_local())
2570 }
2571
2572 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2576 where
2577 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2578 R: 'static,
2579 {
2580 if self.quitting {
2581 debug_panic!("Can't spawn on main thread after on_app_quit")
2582 };
2583
2584 let mut cx = self.to_async();
2585
2586 self.foreground_executor
2587 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2588 }
2589
2590 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2593 self.push_effect(Effect::Defer {
2594 callback: Box::new(f),
2595 });
2596 }
2597
2598 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2600 &self.asset_source
2601 }
2602
2603 pub fn text_system(&self) -> &Arc<TextSystem> {
2605 &self.text_system
2606 }
2607
2608 pub fn on_missing_glyphs(
2619 &self,
2620 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2621 ) -> Subscription {
2622 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2623
2624 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2625 let callback = self.missing_glyph_callback.clone();
2626 self.spawn(async move |cx| {
2627 while let Ok(missing_glyphs) = receiver.recv().await {
2628 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2629 }
2630 })
2631 .detach();
2632 }
2633 self.text_system.enable_missing_glyph_reporting();
2634
2635 let callback = self.missing_glyph_callback.clone();
2636 let text_system = self.text_system.clone();
2637 Subscription::new(move || {
2638 if callback.remove(®istration) {
2639 text_system.disable_missing_glyph_reporting();
2640 }
2641 })
2642 }
2643
2644 pub fn has_global<G: Global>(&self) -> bool {
2646 crate::fast::dependencies::note_global_presence_read::<G>(self);
2647 self.globals_by_type.contains_key(&TypeId::of::<G>())
2648 }
2649
2650 #[track_caller]
2652 pub fn global<G: Global>(&self) -> &G {
2653 crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2654 self.globals_by_type
2655 .get(&TypeId::of::<G>())
2656 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2657 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2658 }
2659
2660 pub fn try_global<G: Global>(&self) -> Option<&G> {
2662 crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2663 self.globals_by_type
2664 .get(&TypeId::of::<G>())
2665 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2666 }
2667
2668 #[track_caller]
2670 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2671 let global_type = TypeId::of::<G>();
2672 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2673 self.globals_by_type
2674 .get_mut(&global_type)
2675 .and_then(|any_state| any_state.downcast_mut::<G>())
2676 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2677 }
2678
2679 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2682 let global_type = TypeId::of::<G>();
2683 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2684 crate::fast::dependencies::note_global_inserted::<G>(self);
2685 self.globals_by_type
2686 .entry(global_type)
2687 .or_insert_with(|| Box::<G>::default())
2688 .downcast_mut::<G>()
2689 .unwrap()
2690 }
2691
2692 pub fn set_global<G: Global>(&mut self, global: G) {
2694 let global_type = TypeId::of::<G>();
2695 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2696 crate::fast::dependencies::note_global_inserted::<G>(self);
2697 self.globals_by_type.insert(global_type, Box::new(global));
2698 }
2699
2700 #[cfg(any(test, feature = "test-support"))]
2702 pub fn clear_globals(&mut self) {
2703 self.globals_by_type.drain();
2704 }
2705
2706 pub fn remove_global<G: Global>(&mut self) -> G {
2708 crate::fast::dependencies::note_global_removed::<G>(self);
2709 let global_type = TypeId::of::<G>();
2710 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2711 *self
2712 .globals_by_type
2713 .remove(&global_type)
2714 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2715 .downcast()
2716 .unwrap()
2717 }
2718
2719 pub fn observe_global<G: Global>(
2721 &mut self,
2722 mut f: impl FnMut(&mut Self) + 'static,
2723 ) -> Subscription {
2724 let (subscription, activate) = self.global_observers.insert_pending(
2725 TypeId::of::<G>(),
2726 Box::new(move |cx| {
2727 f(cx);
2728 true
2729 }),
2730 );
2731 self.defer(move |_| activate());
2732 subscription
2733 }
2734
2735 #[track_caller]
2737 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2738 GlobalLease::new(
2739 self.globals_by_type
2740 .remove(&TypeId::of::<G>())
2741 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2742 .unwrap(),
2743 )
2744 }
2745
2746 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2748 let global_type = TypeId::of::<G>();
2749
2750 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2751 self.globals_by_type.insert(global_type, lease.global);
2752 }
2753
2754 pub(crate) fn new_entity_observer(
2755 &self,
2756 key: TypeId,
2757 value: NewEntityListener,
2758 ) -> Subscription {
2759 self.new_entity_observers.insert(key, value)
2760 }
2761
2762 pub fn observe_new<T: 'static>(
2765 &self,
2766 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2767 ) -> Subscription {
2768 self.new_entity_observer(
2769 TypeId::of::<T>(),
2770 Box::new(
2771 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2772 any_entity
2773 .downcast::<T>()
2774 .unwrap()
2775 .update(cx, |entity_state, cx| {
2776 on_new(entity_state, window.as_deref_mut(), cx)
2777 })
2778 },
2779 ),
2780 )
2781 }
2782
2783 pub fn observe_release<T>(
2786 &self,
2787 handle: &Entity<T>,
2788 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2789 ) -> Subscription
2790 where
2791 T: 'static,
2792 {
2793 self.release_listeners.insert(
2794 handle.entity_id(),
2795 Box::new(move |entity, cx| {
2796 let entity = entity.downcast_mut().expect("invalid entity type");
2797 on_release(entity, cx)
2798 }),
2799 )
2800 }
2801
2802 pub fn observe_release_in<T>(
2805 &self,
2806 handle: &Entity<T>,
2807 window: &Window,
2808 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2809 ) -> Subscription
2810 where
2811 T: 'static,
2812 {
2813 let window_handle = window.handle;
2814 self.observe_release(handle, move |entity, cx| {
2815 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2816 })
2817 }
2818
2819 pub fn observe_keystrokes(
2824 &mut self,
2825 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2826 ) -> Subscription {
2827 self.keystroke_observers
2828 .insert(Box::new(move |event, window, cx| {
2829 f(event, window, cx);
2830 true
2831 }))
2832 }
2833
2834 pub fn intercept_keystrokes(
2839 &mut self,
2840 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2841 ) -> Subscription {
2842 self.keystroke_interceptors
2843 .insert(Box::new(move |event, window, cx| {
2844 f(event, window, cx);
2845 true
2846 }))
2847 }
2848
2849 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2851 self.keymap.borrow_mut().add_bindings(bindings);
2852 self.pending_effects.push_back(Effect::RefreshWindows);
2853 }
2854
2855 pub fn clear_key_bindings(&mut self) {
2857 self.keymap.borrow_mut().clear();
2858 self.pending_effects.push_back(Effect::RefreshWindows);
2859 }
2860
2861 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2863 self.keymap.clone()
2864 }
2865
2866 pub fn on_action<A: Action>(
2870 &mut self,
2871 listener: impl Fn(&A, &mut Self) + 'static,
2872 ) -> &mut Self {
2873 self.global_action_listeners
2874 .entry(TypeId::of::<A>())
2875 .or_default()
2876 .push(Rc::new(move |action, phase, cx| {
2877 if phase == DispatchPhase::Bubble {
2878 let action = action.downcast_ref().unwrap();
2879 listener(action, cx)
2880 }
2881 }));
2882 self
2883 }
2884
2885 pub fn stop_propagation(&mut self) {
2890 self.propagate_event = false;
2891 }
2892
2893 pub fn propagate(&mut self) {
2898 self.propagate_event = true;
2899 }
2900
2901 pub fn build_action(
2903 &self,
2904 name: &str,
2905 data: Option<serde_json::Value>,
2906 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2907 self.actions.build_action(name, data)
2908 }
2909
2910 pub fn all_action_names(&self) -> &[&'static str] {
2913 self.actions.all_action_names()
2914 }
2915
2916 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2920 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2921 }
2922
2923 pub fn action_schemas(
2925 &self,
2926 generator: &mut schemars::SchemaGenerator,
2927 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2928 self.actions.action_schemas(generator)
2929 }
2930
2931 pub fn action_schema_by_name(
2936 &self,
2937 name: &str,
2938 generator: &mut schemars::SchemaGenerator,
2939 ) -> Option<Option<schemars::Schema>> {
2940 self.actions.action_schema_by_name(name, generator)
2941 }
2942
2943 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2945 self.actions.deprecated_aliases()
2946 }
2947
2948 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2950 self.actions.deprecation_messages()
2951 }
2952
2953 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2955 self.actions.documentation()
2956 }
2957
2958 pub fn on_app_quit<Fut>(
2961 &self,
2962 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2963 ) -> Subscription
2964 where
2965 Fut: 'static + Future<Output = ()>,
2966 {
2967 self.quit_observers.insert(Box::new(move |cx| {
2968 let future = on_quit(cx);
2969 future.boxed_local()
2970 }))
2971 }
2972
2973 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2977 self.restart_observers.insert(Box::new(move |cx| {
2978 on_restart(cx);
2979 true
2980 }))
2981 }
2982
2983 pub fn on_window_closed(
2986 &self,
2987 on_closed: impl FnMut(&mut App, WindowId) + 'static,
2988 ) -> Subscription {
2989 self.window_closed_observers.insert(Box::new(on_closed))
2990 }
2991
2992 pub(crate) fn clear_pending_keystrokes(&mut self) {
2993 for window in self.windows() {
2994 window
2995 .update(self, |_, window, cx| {
2996 window.clear_pending_keystrokes(cx);
2997 })
2998 .ok();
2999 }
3000 }
3001
3002 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
3005 let mut action_available = false;
3006 if let Some(window) = self.active_window()
3007 && let Ok(window_action_available) =
3008 window.update(self, |_, window, cx| window.is_action_available(action, cx))
3009 {
3010 action_available = window_action_available;
3011 }
3012
3013 action_available
3014 || self
3015 .global_action_listeners
3016 .contains_key(&action.as_any().type_id())
3017 }
3018
3019 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
3021 let menus: Vec<Menu> = menus.into_iter().collect();
3022 self.platform.set_menus(menus, &self.keymap.borrow());
3023 }
3024
3025 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
3027 self.platform.get_menus()
3028 }
3029
3030 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
3032 self.platform.set_dock_menu(menus, &self.keymap.borrow())
3033 }
3034
3035 pub fn perform_dock_menu_action(&self, action: usize) {
3037 self.platform.perform_dock_menu_action(action);
3038 }
3039
3040 pub fn add_recent_document(&self, path: &Path) {
3045 self.platform.add_recent_document(path);
3046 }
3047
3048 pub fn update_jump_list(
3051 &self,
3052 menus: Vec<MenuItem>,
3053 entries: Vec<SmallVec<[PathBuf; 2]>>,
3054 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
3055 self.platform.update_jump_list(menus, entries)
3056 }
3057
3058 pub fn dispatch_action(&mut self, action: &dyn Action) {
3061 if let Some(active_window) = self.active_window() {
3062 active_window
3063 .update(self, |_, window, cx| {
3064 window.dispatch_action(action.boxed_clone(), cx)
3065 })
3066 .log_err();
3067 } else {
3068 self.dispatch_global_action(action);
3069 }
3070 }
3071
3072 fn dispatch_global_action(&mut self, action: &dyn Action) {
3073 self.propagate_event = true;
3074
3075 if let Some(mut global_listeners) = self
3076 .global_action_listeners
3077 .remove(&action.as_any().type_id())
3078 {
3079 for listener in &global_listeners {
3080 listener(action.as_any(), DispatchPhase::Capture, self);
3081 if !self.propagate_event {
3082 break;
3083 }
3084 }
3085
3086 global_listeners.extend(
3087 self.global_action_listeners
3088 .remove(&action.as_any().type_id())
3089 .unwrap_or_default(),
3090 );
3091
3092 self.global_action_listeners
3093 .insert(action.as_any().type_id(), global_listeners);
3094 }
3095
3096 if self.propagate_event
3097 && let Some(mut global_listeners) = self
3098 .global_action_listeners
3099 .remove(&action.as_any().type_id())
3100 {
3101 for listener in global_listeners.iter().rev() {
3102 listener(action.as_any(), DispatchPhase::Bubble, self);
3103 if !self.propagate_event {
3104 break;
3105 }
3106 }
3107
3108 global_listeners.extend(
3109 self.global_action_listeners
3110 .remove(&action.as_any().type_id())
3111 .unwrap_or_default(),
3112 );
3113
3114 self.global_action_listeners
3115 .insert(action.as_any().type_id(), global_listeners);
3116 }
3117 }
3118
3119 pub fn has_active_drag(&self) -> bool {
3121 self.active_drag.is_some()
3122 }
3123
3124 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3126 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3127 }
3128
3129 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3131 if self.active_drag.is_some() {
3132 self.active_drag = None;
3133 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
3134 drag.source_window == window.window_handle().window_id()
3135 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3136 }) {
3137 self.platform_owned_drag = None;
3138 }
3139 window.refresh();
3140 true
3141 } else {
3142 false
3143 }
3144 }
3145
3146 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3147 let Some(drag) = self.active_drag.take() else {
3148 return false;
3149 };
3150 self.platform_owned_drag = Some(PlatformOwnedDrag {
3151 source_window,
3152 state: PlatformOwnedDragState::Suspended(drag),
3153 });
3154 true
3155 }
3156
3157 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
3158 let Some(platform_drag) = self
3159 .platform_owned_drag
3160 .as_mut()
3161 .filter(|drag| drag.source_window == source_window)
3162 else {
3163 return false;
3164 };
3165 let state = std::mem::replace(
3166 &mut platform_drag.state,
3167 PlatformOwnedDragState::RestoredInSourceWindow,
3168 );
3169 let PlatformOwnedDragState::Suspended(drag) = state else {
3170 return false;
3171 };
3172 self.active_drag = Some(drag);
3173 true
3174 }
3175
3176 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3177 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
3178 drag.source_window == source_window
3179 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3180 }) else {
3181 return false;
3182 };
3183 let Some(drag) = self.active_drag.take() else {
3184 return false;
3185 };
3186 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
3187 true
3188 }
3189
3190 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
3191 if !self
3192 .platform_owned_drag
3193 .as_ref()
3194 .is_some_and(|drag| drag.source_window == source_window)
3195 {
3196 return false;
3197 }
3198 self.platform_owned_drag = None;
3199 self.active_drag = None;
3200 true
3201 }
3202
3203 pub fn set_active_drag_cursor_style(
3205 &mut self,
3206 cursor_style: CursorStyle,
3207 window: &mut Window,
3208 ) -> bool {
3209 if let Some(ref mut drag) = self.active_drag {
3210 drag.cursor_style = Some(cursor_style);
3211 window.refresh();
3212 true
3213 } else {
3214 false
3215 }
3216 }
3217
3218 pub fn set_prompt_builder(
3221 &mut self,
3222 renderer: impl Fn(
3223 PromptLevel,
3224 &str,
3225 Option<&str>,
3226 &[PromptButton],
3227 PromptHandle,
3228 &mut Window,
3229 &mut App,
3230 ) -> RenderablePromptHandle
3231 + 'static,
3232 ) {
3233 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3234 }
3235
3236 pub fn reset_prompt_builder(&mut self) {
3238 self.prompt_builder = Some(PromptBuilder::Default);
3239 }
3240
3241 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3243 let asset_id = (TypeId::of::<A>(), hash(source));
3244 self.loading_assets.remove(&asset_id);
3245 }
3246
3247 #[cfg(any(test, feature = "test-support"))]
3250 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3251 let asset_id = (TypeId::of::<A>(), hash(source));
3252 self.loading_assets.contains_key(&asset_id)
3253 }
3254
3255 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3260 self.asset_entry::<A>(source).get()
3261 }
3262
3263 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3264 let asset_id = (TypeId::of::<A>(), hash(source));
3265 if !self.loading_assets.contains_key(&asset_id) {
3266 let future = A::load(source.clone(), self);
3267 let entry = CachedLoad::new(future, self);
3268 self.loading_assets.insert(asset_id, Box::new(entry));
3269 }
3270 self.loading_assets
3271 .get(&asset_id)
3272 .and_then(|entry| entry.downcast_ref())
3273 .expect("asset cache entries are keyed by their asset type")
3274 }
3275
3276 #[track_caller]
3279 pub fn focus_handle(&self) -> FocusHandle {
3280 FocusHandle::new(&self.focus_handles)
3281 }
3282
3283 pub fn notify(&mut self, entity_id: EntityId) {
3285 crate::fast::dependencies::note_notify(&mut self.entities, entity_id);
3286 let window_invalidators = mem::take(
3287 self.window_invalidators_by_entity
3288 .entry(entity_id)
3289 .or_default(),
3290 );
3291
3292 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3297 .iter()
3298 .filter(|(window_id, _)| {
3299 self.tracked_entities
3300 .get(window_id)
3301 .is_some_and(|set| set.contains(&entity_id))
3302 })
3303 .map(|(_, invalidator)| invalidator.clone())
3304 .collect();
3305
3306 if live_invalidators.is_empty() {
3307 if self.pending_notifications.insert(entity_id) {
3308 self.pending_effects
3309 .push_back(Effect::Notify { emitter: entity_id });
3310 }
3311 } else {
3312 for invalidator in &live_invalidators {
3313 invalidator.invalidate_view(entity_id, self);
3314 }
3315 }
3316
3317 self.window_invalidators_by_entity
3318 .insert(entity_id, window_invalidators);
3319 }
3320
3321 #[cfg(any(test, feature = "test-support", debug_assertions))]
3323 pub fn get_name(&self) -> Option<&'static str> {
3324 self.name
3325 }
3326
3327 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3329 self.platform.can_select_mixed_files_and_dirs()
3330 }
3331
3332 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3337 for window in self.windows.values_mut().flatten() {
3339 _ = window.drop_image(image.clone());
3340 }
3341
3342 if let Some(window) = current_window {
3344 _ = window.drop_image(image);
3345 }
3346 }
3347
3348 #[cfg(any(feature = "inspector", debug_assertions))]
3350 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3351 self.inspector_renderer = Some(f);
3352 }
3353
3354 #[cfg(any(feature = "inspector", debug_assertions))]
3356 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3357 &mut self,
3358 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3359 ) where
3360 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3361 {
3362 self.inspector_element_registry.register(factory);
3363 }
3364
3365 pub fn init_colors(&mut self) {
3369 self.set_global(GlobalColors(Arc::new(Colors::default())));
3370 }
3371
3372 #[inline(never)]
3373 fn update_window_erased(
3374 &mut self,
3375 window_id: WindowId,
3376 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3377 ) {
3378 self.update(|cx| {
3379 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3380 update(None);
3381 return;
3382 };
3383
3384 let root_view = window.root.clone().unwrap();
3385
3386 cx.window_update_stack.push(WindowUpdateEntry {
3387 window_id: window.handle.id,
3388 bounds: window.last_window_bounds(),
3389 display_id: window.display_id(),
3390 });
3391 update(Some((root_view, &mut window, cx)));
3392 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3393 cx.window_update_stack.pop();
3394
3395 if window.removed {
3396 cx.end_platform_drag(window_id);
3397 cx.window_handles.remove(&window_id);
3398 cx.windows.remove(window_id);
3399 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3400 for entity_id in tracked {
3401 if let Some(windows) =
3402 cx.window_invalidators_by_entity.get_mut(&entity_id)
3403 {
3404 windows.remove(&window_id);
3405 }
3406 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3407 cx.current_window_by_entity.remove(&entity_id);
3408 }
3409 }
3410 }
3411
3412 cx.window_closed_observers.clone().retain(|callback| {
3413 callback(cx, window_id);
3414 true
3415 });
3416
3417 let quit_on_empty = match cx.quit_mode {
3418 QuitMode::Explicit => false,
3419 QuitMode::LastWindowClosed => true,
3420 QuitMode::Default => cfg!(not(target_os = "macos")),
3421 };
3422
3423 if quit_on_empty && cx.windows.is_empty() {
3424 cx.quit();
3425 }
3426 } else {
3427 cx.windows.get_mut(window_id)?.replace(window);
3428 }
3429 Some(())
3430 }
3431 if trail(window_id, window, cx).is_none() {
3432 update(None);
3433 }
3434 });
3435 }
3436
3437 #[inline(never)]
3438 fn update_entity_erased(
3439 &mut self,
3440 handle: &AnyEntity,
3441 entity_type: &str,
3442 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3443 ) {
3444 self.update(|cx| {
3445 let mut lease = cx.entities.lease_erased(handle, entity_type);
3446 update(lease.entity.as_deref_mut().unwrap(), cx);
3447 cx.entities.end_lease_erased(handle.entity_id, lease);
3448 });
3449 }
3450
3451 #[inline(never)]
3452 #[track_caller]
3453 fn prepare_spawn(&self) -> AsyncApp {
3454 if self.quitting {
3455 debug_panic!("Can't spawn on main thread after on_app_quit")
3456 };
3457 self.to_async()
3458 }
3459}
3460
3461impl AppContext for App {
3462 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3467 self.update(|cx| {
3468 let slot = cx.entities.reserve();
3469 let handle = slot.clone();
3470 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3471
3472 cx.push_effect(Effect::EntityCreated {
3473 entity: handle.into_any(),
3474 tid: TypeId::of::<T>(),
3475 window: cx.window_update_stack.last().map(|state| state.window_id),
3476 });
3477
3478 cx.entities.insert(slot, entity)
3479 })
3480 }
3481
3482 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3483 Reservation(self.entities.reserve())
3484 }
3485
3486 fn insert_entity<T: 'static>(
3487 &mut self,
3488 reservation: Reservation<T>,
3489 build_entity: impl FnOnce(&mut Context<T>) -> T,
3490 ) -> Entity<T> {
3491 self.update(|cx| {
3492 let slot = reservation.0;
3493 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3494 cx.entities.insert(slot, entity)
3495 })
3496 }
3497
3498 #[inline(always)]
3501 fn update_entity<T: 'static, R>(
3502 &mut self,
3503 handle: &Entity<T>,
3504 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3505 ) -> R {
3506 let mut update = Some(update);
3507 let mut result = None;
3508 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3509 let value = update.take().unwrap()(
3510 entity.downcast_mut::<T>().unwrap(),
3511 &mut Context::new_context(cx, handle.downgrade()),
3512 );
3513 result = Some(value);
3514 });
3515 result.unwrap()
3516 }
3517
3518 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3519 where
3520 T: 'static,
3521 {
3522 GpuiBorrow::new(handle.clone(), self)
3523 }
3524
3525 #[inline(always)]
3526 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3527 where
3528 T: 'static,
3529 {
3530 let entity = self.entities.read(handle);
3531 read(entity, self)
3532 }
3533
3534 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3535 where
3536 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3537 {
3538 self.update_window_id(handle.id, update)
3539 }
3540
3541 fn with_window<R>(
3542 &mut self,
3543 entity_id: EntityId,
3544 f: impl FnOnce(&mut Window, &mut App) -> R,
3545 ) -> Option<R> {
3546 App::with_window(self, entity_id, f)
3547 }
3548
3549 fn read_window<T, R>(
3550 &self,
3551 window: &WindowHandle<T>,
3552 read: impl FnOnce(Entity<T>, &App) -> R,
3553 ) -> Result<R>
3554 where
3555 T: 'static,
3556 {
3557 let window = self
3558 .windows
3559 .get(window.id)
3560 .context("window not found")?
3561 .as_deref()
3562 .expect("attempted to read a window that is already on the stack");
3563
3564 let root_view = window.root.clone().unwrap();
3565 let view = root_view
3566 .downcast::<T>()
3567 .map_err(|_| anyhow!("root view's type has changed"))?;
3568
3569 Ok(read(view, self))
3570 }
3571
3572 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3573 where
3574 R: Send + 'static,
3575 {
3576 self.background_executor.spawn(future)
3577 }
3578
3579 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3580 where
3581 G: Global,
3582 {
3583 let g = self.global::<G>();
3584 callback(g, self)
3585 }
3586}
3587
3588pub(crate) enum Effect {
3590 Notify {
3591 emitter: EntityId,
3592 },
3593 Emit {
3594 emitter: EntityId,
3595 event_type: TypeId,
3596 event: ArenaBox<dyn Any>,
3597 },
3598 RefreshWindows,
3599 NotifyGlobalObservers {
3600 global_type: TypeId,
3601 },
3602 Defer {
3603 callback: Box<dyn FnOnce(&mut App) + 'static>,
3604 },
3605 EntityCreated {
3606 entity: AnyEntity,
3607 tid: TypeId,
3608 window: Option<WindowId>,
3609 },
3610}
3611
3612impl std::fmt::Debug for Effect {
3613 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3614 match self {
3615 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3616 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3617 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3618 Effect::NotifyGlobalObservers { global_type } => {
3619 write!(f, "NotifyGlobalObservers({:?})", global_type)
3620 }
3621 Effect::Defer { .. } => write!(f, "Defer(..)"),
3622 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3623 }
3624 }
3625}
3626
3627pub(crate) struct GlobalLease<G: Global> {
3629 global: Box<dyn Any>,
3630 global_type: PhantomData<G>,
3631}
3632
3633impl<G: Global> GlobalLease<G> {
3634 fn new(global: Box<dyn Any>) -> Self {
3635 GlobalLease {
3636 global,
3637 global_type: PhantomData,
3638 }
3639 }
3640}
3641
3642impl<G: Global> Deref for GlobalLease<G> {
3643 type Target = G;
3644
3645 fn deref(&self) -> &Self::Target {
3646 self.global.downcast_ref().unwrap()
3647 }
3648}
3649
3650impl<G: Global> DerefMut for GlobalLease<G> {
3651 fn deref_mut(&mut self) -> &mut Self::Target {
3652 self.global.downcast_mut().unwrap()
3653 }
3654}
3655
3656pub struct AnyDrag {
3659 pub view: AnyView,
3661
3662 pub value: Arc<dyn Any>,
3664
3665 pub cursor_offset: Point<Pixels>,
3668
3669 pub cursor_style: Option<CursorStyle>,
3671
3672 pub external_payload_source: Option<ExternalDragPayloadSource>,
3675}
3676
3677pub type ExternalDragPayloadSource =
3680 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3681
3682#[derive(Clone)]
3685pub struct AnyTooltip {
3686 pub view: AnyView,
3688
3689 pub mouse_position: Point<Pixels>,
3691
3692 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3696}
3697
3698#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3700pub enum InputPreference {
3701 CharacterInput,
3703 KeyBindings,
3705}
3706
3707#[derive(Debug)]
3709pub struct KeystrokeEvent {
3710 pub keystroke: Keystroke,
3712
3713 pub input_preference: InputPreference,
3721
3722 pub action: Option<Box<dyn Action>>,
3724
3725 pub context_stack: Vec<KeyContext>,
3727}
3728
3729struct NullHttpClient;
3730
3731impl HttpClient for NullHttpClient {
3732 fn send(
3733 &self,
3734 _req: http_client::Request<http_client::AsyncBody>,
3735 ) -> futures::future::BoxFuture<
3736 'static,
3737 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3738 > {
3739 async move {
3740 anyhow::bail!("No HttpClient available");
3741 }
3742 .boxed()
3743 }
3744
3745 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3746 None
3747 }
3748
3749 fn proxy(&self) -> Option<&Url> {
3750 None
3751 }
3752}
3753
3754pub struct GpuiBorrow<'a, T> {
3756 inner: Option<Lease<T>>,
3757 app: &'a mut App,
3758}
3759
3760impl<'a, T: 'static> GpuiBorrow<'a, T> {
3761 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3762 app.start_update();
3763 let lease = app.entities.lease(&inner);
3764 Self {
3765 inner: Some(lease),
3766 app,
3767 }
3768 }
3769}
3770
3771impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3772 fn borrow(&self) -> &T {
3773 self.inner.as_ref().unwrap().borrow()
3774 }
3775}
3776
3777impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3778 fn borrow_mut(&mut self) -> &mut T {
3779 self.inner.as_mut().unwrap().borrow_mut()
3780 }
3781}
3782
3783impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3784 type Target = T;
3785
3786 fn deref(&self) -> &Self::Target {
3787 self.inner.as_ref().unwrap()
3788 }
3789}
3790
3791impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3792 fn deref_mut(&mut self) -> &mut T {
3793 self.inner.as_mut().unwrap()
3794 }
3795}
3796
3797impl<'a, T> Drop for GpuiBorrow<'a, T> {
3798 fn drop(&mut self) {
3799 let lease = self.inner.take().unwrap();
3800 self.app.notify(lease.id);
3801 self.app.entities.end_lease(lease);
3802 self.app.finish_update();
3803 }
3804}
3805
3806#[cfg(test)]
3807mod test {
3808 use std::{
3809 cell::{Cell, RefCell},
3810 ffi::OsString,
3811 path::PathBuf,
3812 rc::Rc,
3813 };
3814
3815 #[cfg(unix)]
3816 use std::os::unix::ffi::OsStringExt;
3817
3818 use crate::{
3819 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3820 TestAppContext, Window,
3821 };
3822
3823 #[gpui::test]
3824 fn app_borrow_diagnostics(cx: &mut TestAppContext) {
3825 use std::panic::{AssertUnwindSafe, catch_unwind};
3826
3827 let app = cx.app.clone();
3828 let first_line = line!() + 1;
3829 let first = app.borrow();
3830 let second = app.borrow();
3831 drop(first);
3832 assert!(app.try_borrow_mut().is_err());
3833 let attempted_line = line!() + 1;
3834 let panic = catch_unwind(AssertUnwindSafe(|| drop(app.borrow_mut())));
3835 let message = *panic
3836 .expect_err("conflicting borrow")
3837 .downcast::<String>()
3838 .unwrap();
3839 assert!(message.contains(&format!(
3840 "mutable App borrow at {}:{attempted_line}:",
3841 file!()
3842 )));
3843 assert!(message.contains(&format!(
3844 "shared borrow group began at {}:{first_line}:",
3845 file!()
3846 )));
3847 drop(second);
3848
3849 let origin_line = line!() + 2;
3850 let panic = catch_unwind(AssertUnwindSafe(|| {
3851 let _borrow = app.try_borrow_mut().expect("initial borrow");
3852 drop(app.borrow());
3853 }));
3854 let message = *panic
3855 .expect_err("conflicting borrow")
3856 .downcast::<String>()
3857 .unwrap();
3858 assert!(message.contains("attempted shared App borrow"));
3859 assert!(message.contains(&format!(
3860 "mutable borrow group began at {}:{origin_line}:",
3861 file!()
3862 )));
3863
3864 let next_line = line!() + 1;
3865 let _borrow = app.borrow();
3866 assert_eq!(
3867 app.borrow_origin.get().expect("new origin").0.line(),
3868 next_line
3869 );
3870 }
3871
3872 struct RenderCounter(Rc<Cell<usize>>);
3873
3874 impl Render for RenderCounter {
3875 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3876 self.0.set(self.0.get() + 1);
3877 Empty
3878 }
3879 }
3880
3881 #[gpui::test]
3882 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3883 let render_count = Rc::new(Cell::new(0));
3884
3885 let _window = cx.add_window({
3886 let render_count = render_count.clone();
3887 move |_, _| RenderCounter(render_count)
3888 });
3889
3890 cx.run_until_parked();
3891 let render_count_before_refresh = render_count.get();
3892
3893 cx.to_async().refresh();
3894
3895 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3896 }
3897
3898 #[gpui::test]
3899 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3900 let observed = Rc::new(RefCell::new(Vec::new()));
3901 let subscription = cx.update(|cx| {
3902 let observed = observed.clone();
3903 cx.on_missing_glyphs(move |missing_glyphs, _| {
3904 observed.borrow_mut().extend_from_slice(missing_glyphs);
3905 })
3906 });
3907 cx.update(|cx| {
3908 cx.text_system()
3909 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3910 });
3911 cx.run_until_parked();
3912 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3913
3914 let second_observed = Rc::new(RefCell::new(Vec::new()));
3915 let second_subscription = cx.update(|cx| {
3916 let second_observed = second_observed.clone();
3917 cx.on_missing_glyphs(move |missing_glyphs, _| {
3918 second_observed
3919 .borrow_mut()
3920 .extend_from_slice(missing_glyphs);
3921 })
3922 });
3923 cx.update(|cx| {
3924 cx.text_system()
3925 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3926 });
3927 cx.run_until_parked();
3928 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3929 assert_eq!(
3930 second_observed.borrow().as_slice(),
3931 &[missing_glyph("replacement")]
3932 );
3933
3934 drop(subscription);
3935 cx.update(|cx| {
3936 cx.text_system()
3937 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3938 });
3939 cx.run_until_parked();
3940 assert_eq!(
3941 second_observed.borrow().as_slice(),
3942 &[
3943 missing_glyph("replacement"),
3944 missing_glyph("after old drop")
3945 ]
3946 );
3947
3948 drop(second_subscription);
3949 cx.update(|cx| {
3950 cx.text_system()
3951 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3952 });
3953 cx.run_until_parked();
3954 assert_eq!(second_observed.borrow().len(), 2);
3955 }
3956
3957 #[test]
3958 fn test_gpui_borrow() {
3959 let cx = TestAppContext::single();
3960 let observation_count = Rc::new(RefCell::new(0));
3961
3962 let state = cx.update(|cx| {
3963 let state = cx.new(|_| false);
3964 cx.observe(&state, {
3965 let observation_count = observation_count.clone();
3966 move |_, _| {
3967 let mut count = observation_count.borrow_mut();
3968 *count += 1;
3969 }
3970 })
3971 .detach();
3972
3973 state
3974 });
3975
3976 cx.update(|cx| {
3977 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3979 });
3980
3981 cx.update(|cx| {
3982 state.write(cx, false);
3983 });
3984
3985 assert_eq!(*observation_count.borrow(), 2);
3986 }
3987
3988 #[gpui::test]
3989 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3990 #[cfg(unix)]
3991 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3992 #[cfg(not(unix))]
3993 let user_data_dir = OsString::from("C:\\zed data");
3994 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3995 let restart_path = PathBuf::from("updated-zed");
3996 let _application =
3997 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3998 let restart = cx.expect_restart();
3999
4000 cx.update(|cx| {
4001 cx.set_restart_path(restart_path.clone());
4002 cx.restart();
4003 });
4004
4005 let (path, restart_arguments) = restart.await.expect("restart was not requested");
4006 assert_eq!(path, Some(restart_path));
4007 assert_eq!(restart_arguments, arguments);
4008 }
4009
4010 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
4011 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
4012 }
4013}