1use scheduler::Instant;
2use std::{
3 any::{TypeId, type_name},
4 cell::{Cell, Ref, RefCell, RefMut},
5 ffi::OsString,
6 marker::PhantomData,
7 mem,
8 ops::{Deref, DerefMut},
9 path::{Path, PathBuf},
10 rc::{Rc, Weak},
11 sync::Arc,
12 time::Duration,
13};
14
15use crate::util::impl_deref;
16use anyhow::{Context as _, Result, anyhow};
17use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
18use itertools::Itertools;
19use parking_lot::RwLock;
20use slotmap::SlotMap;
21
22pub use async_context::*;
23#[cfg(feature = "bench-support")]
24pub use bench_context::{
25 BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
26 MetricReport, bench_platform,
27};
28use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
29pub use context::*;
30pub use entity_map::*;
31use gpui_util::{ResultExt, debug_panic};
32#[cfg(any(test, feature = "test-support"))]
33pub use headless_app_context::*;
34use http_client::{HttpClient, Url};
35use smallvec::SmallVec;
36#[cfg(any(test, feature = "test-support"))]
37pub use test_app::*;
38#[cfg(any(test, feature = "test-support"))]
39pub use test_context::*;
40#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
41pub use visual_test_context::*;
42
43#[cfg(any(feature = "inspector", debug_assertions))]
44use crate::InspectorElementRegistry;
45use crate::asset_cache::CachedLoad;
46use crate::subscription::SingleSubscriberSet;
47use crate::{
48 Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
49 AnyWindowHandle, AppContext, AppLifecyclePhase, Arena, ArenaBox, Asset, AssetSource,
50 BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase,
51 DisplayChanges, DisplayEvent, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle,
52 FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId,
53 Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
54 PlatformKeyboardLayout, PlatformKeyboardMapper, Point, PowerMode, Priority, PromptBuilder,
55 PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle,
56 Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
57 SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
58 ThermalState, Window, WindowAppearance, WindowBounds, WindowButtonLayout, WindowHandle,
59 WindowId, WindowInvalidator, WindowingRequest,
60 colors::{Colors, GlobalColors},
61 hash, init_app_menus,
62};
63
64mod async_context;
65#[cfg(feature = "bench-support")]
66mod bench_context;
67mod context;
68mod entity_map;
69#[cfg(any(test, feature = "test-support"))]
70mod headless_app_context;
71#[cfg(any(test, feature = "test-support"))]
72mod test_app;
73#[cfg(any(test, feature = "test-support"))]
74mod test_context;
75#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
76mod visual_test_context;
77
78pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
81
82#[doc(hidden)]
85pub struct AppCell {
86 app: RefCell<App>,
87 borrow_origin: Cell<Option<(&'static std::panic::Location<'static>, &'static str)>>,
88}
89
90struct AppBorrowError {
91 attempted: &'static std::panic::Location<'static>,
92 kind: &'static str,
93 origin: Option<(&'static std::panic::Location<'static>, &'static str)>,
94}
95
96impl std::fmt::Display for AppBorrowError {
97 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 let Self {
99 attempted,
100 kind,
101 origin,
102 } = self;
103 write!(
104 formatter,
105 "RefCell already borrowed: attempted {kind} App borrow at {attempted}; "
106 )?;
107 match origin {
108 Some((origin, existing_kind)) => write!(
109 formatter,
110 "existing {existing_kind} borrow group began at {origin}"
111 ),
112 None => write!(formatter, "origin unavailable"),
113 }
114 }
115}
116
117impl std::fmt::Debug for AppBorrowError {
118 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 std::fmt::Display::fmt(self, formatter)
120 }
121}
122
123impl std::error::Error for AppBorrowError {}
124
125impl AppCell {
126 #[doc(hidden)]
127 #[track_caller]
128 pub fn borrow(&self) -> AppRef<'_> {
129 if option_env!("TRACK_THREAD_BORROWS").is_some() {
130 let thread_id = std::thread::current().id();
131 eprintln!("borrowed {thread_id:?}");
132 }
133 let starts_borrow_group = self.app.try_borrow_mut().is_ok();
136 let attempted = std::panic::Location::caller();
137 let borrow = self
138 .app
139 .try_borrow()
140 .map_err(|_error| AppBorrowError {
141 attempted,
142 kind: "shared",
143 origin: self.borrow_origin.get(),
144 })
145 .unwrap();
146 if starts_borrow_group {
147 self.borrow_origin
148 .set(Some((std::panic::Location::caller(), "shared")));
149 }
150 AppRef(borrow)
151 }
152
153 pub(crate) fn is_borrowed(&self) -> bool {
155 self.app.try_borrow_mut().is_err()
156 }
157
158 #[doc(hidden)]
159 #[track_caller]
160 pub fn borrow_mut(&self) -> AppRefMut<'_> {
161 self.try_borrow_mut().unwrap()
162 }
163
164 #[doc(hidden)]
165 #[track_caller]
166 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>> {
167 if option_env!("TRACK_THREAD_BORROWS").is_some() {
168 let thread_id = std::thread::current().id();
169 eprintln!("borrowed {thread_id:?}");
170 }
171 let borrow = match self.app.try_borrow_mut() {
172 Ok(borrow) => borrow,
173 Err(_error) => {
174 return Err(AppBorrowError {
175 attempted: std::panic::Location::caller(),
176 kind: "mutable",
177 origin: self.borrow_origin.get(),
178 }
179 .into());
180 }
181 };
182 self.borrow_origin
183 .set(Some((std::panic::Location::caller(), "mutable")));
184 Ok(AppRefMut(borrow))
185 }
186}
187
188#[doc(hidden)]
189pub struct AppRef<'a>(Ref<'a, App>);
190
191impl_deref!(['a] AppRef<'a> => mut 0: Ref<'a, App>);
192
193impl Drop for AppRef<'_> {
194 fn drop(&mut self) {
195 if option_env!("TRACK_THREAD_BORROWS").is_some() {
196 let thread_id = std::thread::current().id();
197 eprintln!("dropped borrow from {thread_id:?}");
198 }
199 }
200}
201
202#[doc(hidden)]
203pub struct AppRefMut<'a>(RefMut<'a, App>);
204
205impl_deref!(['a] AppRefMut<'a> => mut 0: RefMut<'a, App>);
206
207impl Drop for AppRefMut<'_> {
208 fn drop(&mut self) {
209 if option_env!("TRACK_THREAD_BORROWS").is_some() {
210 let thread_id = std::thread::current().id();
211 eprintln!("dropped {thread_id:?}");
212 }
213 }
214}
215
216pub struct Application(Rc<AppCell>);
219
220pub struct ApplicationHandle {
226 app: Rc<AppCell>,
227}
228
229impl ApplicationHandle {
230 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
234 let cx = &mut *self.app.borrow_mut();
235 f(cx)
236 }
237
238 pub fn to_async(&self) -> AsyncApp {
241 self.update(|cx| cx.to_async())
242 }
243}
244
245impl Application {
248 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
250 Self(App::new_app(
251 platform,
252 Arc::new(()),
253 Arc::new(NullHttpClient),
254 ))
255 }
256
257 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
267 let this = Self::with_platform(platform);
268 this.0.borrow_mut().accessibility_force_disabled = true;
269 this
270 }
271
272 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
274 let mut context_lock = self.0.borrow_mut();
275 let asset_source = Arc::new(asset_source);
276 context_lock.asset_source = asset_source.clone();
277 context_lock.svg_renderer = SvgRenderer::new(asset_source);
278 drop(context_lock);
279 self
280 }
281
282 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
284 self.0.borrow_mut().restart_arguments = arguments;
285 self
286 }
287
288 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
290 let mut context_lock = self.0.borrow_mut();
291 context_lock.http_client = http_client;
292 drop(context_lock);
293 self
294 }
295
296 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
299 self.0.borrow_mut().quit_mode = mode;
300 self
301 }
302
303 pub fn with_windowing(self, request: WindowingRequest) -> Self {
310 self.0.borrow().platform.set_initial_windowing(request);
311 self
312 }
313
314 pub fn run<F>(self, on_finish_launching: F)
320 where
321 F: 'static + FnOnce(&mut App),
322 {
323 let this = self.0.clone();
324 let platform = self.0.borrow().platform.clone();
325 platform.run(Box::new(move || {
326 let cx = &mut *this.borrow_mut();
327 cx.displays_changed();
329 #[cfg(gpui_hot_reload)]
330 crate::hot_reload::init(cx);
331 on_finish_launching(cx);
332 }));
333
334 #[cfg(target_family = "wasm")]
335 std::mem::forget(self);
336 }
337
338 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
348 where
349 F: 'static + FnOnce(&mut App),
350 {
351 let this = self.0.clone();
352 let platform = self.0.borrow().platform.clone();
353 platform.run(Box::new(move || {
354 let cx = &mut *this.borrow_mut();
355 cx.displays_changed();
357 #[cfg(gpui_hot_reload)]
358 crate::hot_reload::init(cx);
359 on_finish_launching(cx);
360 }));
361 ApplicationHandle { app: self.0 }
362 }
363
364 pub fn on_open_urls<F>(&self, callback: F) -> &Self
367 where
368 F: 'static + FnMut(Vec<String>),
369 {
370 self.0.borrow().platform.on_open_urls(Box::new(callback));
371 self
372 }
373
374 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
377 where
378 F: 'static + FnMut(&mut App),
379 {
380 let this = Rc::downgrade(&self.0);
381 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
382 if let Some(app) = this.upgrade() {
383 callback(&mut app.borrow_mut());
384 }
385 }));
386 self
387 }
388
389 pub fn background_executor(&self) -> BackgroundExecutor {
391 self.0.borrow().background_executor.clone()
392 }
393
394 pub fn foreground_executor(&self) -> ForegroundExecutor {
396 self.0.borrow().foreground_executor.clone()
397 }
398
399 pub fn text_system(&self) -> Arc<TextSystem> {
401 self.0.borrow().text_system.clone()
402 }
403
404 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
406 self.0.borrow().path_for_auxiliary_executable(name)
407 }
408}
409
410type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
411type AppLifecycleHandler = Box<dyn FnMut(AppLifecyclePhase, &mut App) -> bool + 'static>;
412type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
413
414#[derive(Clone, Copy, PartialEq)]
416struct DisplayState {
417 bounds: Bounds<Pixels>,
418 refresh_interval: Option<Duration>,
419}
420
421impl DisplayState {
422 fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
423 let mut changes = DisplayChanges::empty();
424 changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
425 changes.set(
426 DisplayChanges::REFRESH_INTERVAL,
427 self.refresh_interval != previous.refresh_interval,
428 );
429 changes
430 }
431}
432
433fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
434 platform
435 .displays()
436 .into_iter()
437 .map(|display| {
438 let state = DisplayState {
439 bounds: display.bounds(),
440 refresh_interval: display.refresh_interval(),
441 };
442 (display.id(), state)
443 })
444 .collect()
445}
446
447fn display_events(
449 previous: &HashMap<DisplayId, DisplayState>,
450 current: &HashMap<DisplayId, DisplayState>,
451) -> Vec<DisplayEvent> {
452 let removed = previous
453 .keys()
454 .filter(|id| !current.contains_key(id))
455 .map(|id| DisplayEvent::Removed(*id));
456 let added_or_changed = current.iter().filter_map(|(id, state)| {
457 let Some(previous_state) = previous.get(id) else {
458 return Some(DisplayEvent::Added(*id));
459 };
460 let changes = state.changes_from(previous_state);
461 (!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
462 });
463 removed.chain(added_or_changed).collect()
464}
465type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
466type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
467pub(crate) type KeystrokeObserver =
468 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
469type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
470type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
471type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
472type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
473
474struct MissingGlyphCallbackEntry {
475 registration: Rc<()>,
476 callback: Option<MissingGlyphCallback>,
477}
478
479#[derive(Default)]
480struct MissingGlyphCallbackSlot {
481 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
482}
483
484impl MissingGlyphCallbackSlot {
485 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
486 let registration = Rc::new(());
487 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
488 registration: registration.clone(),
489 callback: Some(callback),
490 });
491 registration
492 }
493
494 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
495 let Some((registration, mut callback)) =
496 self.entry.borrow_mut().as_mut().and_then(|entry| {
497 entry
498 .callback
499 .take()
500 .map(|callback| (entry.registration.clone(), callback))
501 })
502 else {
503 return;
504 };
505 callback(missing_glyphs, cx);
506
507 let mut entry = self.entry.borrow_mut();
508 let is_current = entry
509 .as_ref()
510 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
511 if is_current {
512 let Some(entry) = entry.as_mut() else {
513 return;
514 };
515 entry.callback = Some(callback);
516 }
517 }
518
519 fn remove(&self, registration: &Rc<()>) -> bool {
520 let mut entry = self.entry.borrow_mut();
521 let is_current = entry
522 .as_ref()
523 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
524 if is_current {
525 entry.take();
526 }
527 is_current
528 }
529}
530
531#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
533pub enum QuitMode {
534 #[default]
536 Default,
537 LastWindowClosed,
539 Explicit,
541}
542
543#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
548pub enum CursorHideMode {
549 Never,
551 OnTyping,
553 #[default]
556 OnTypingAndAction,
557}
558
559#[doc(hidden)]
560#[derive(Clone, PartialEq, Eq)]
561pub struct SystemWindowTab {
562 pub id: WindowId,
563 pub title: SharedString,
564 pub handle: AnyWindowHandle,
565 pub last_active_at: Instant,
566}
567
568impl SystemWindowTab {
569 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
571 Self {
572 id: handle.id,
573 title,
574 handle,
575 last_active_at: Instant::now(),
576 }
577 }
578}
579
580#[derive(Default)]
582pub struct SystemWindowTabController {
583 visible: Option<bool>,
584 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
585}
586
587impl Global for SystemWindowTabController {}
588
589impl SystemWindowTabController {
590 pub fn new() -> Self {
592 Self {
593 visible: None,
594 tab_groups: FxHashMap::default(),
595 }
596 }
597
598 pub fn init(cx: &mut App) {
600 cx.set_global(SystemWindowTabController::new());
601 }
602
603 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
605 &self.tab_groups
606 }
607
608 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
610 let controller = cx.global::<SystemWindowTabController>();
611 let current_group = controller
612 .tab_groups
613 .iter()
614 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
615
616 let current_group = current_group?;
617 let group_ids: Vec<_> = controller.tab_groups.keys().collect();
619 let idx = group_ids.iter().position(|g| *g == current_group)?;
620 let next_idx = (idx + 1) % group_ids.len();
621
622 controller
623 .tab_groups
624 .get(group_ids[next_idx])
625 .and_then(|tabs| {
626 tabs.iter()
627 .max_by_key(|tab| tab.last_active_at)
628 .or_else(|| tabs.first())
629 .map(|tab| &tab.handle)
630 })
631 }
632
633 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
635 let controller = cx.global::<SystemWindowTabController>();
636 let current_group = controller
637 .tab_groups
638 .iter()
639 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
640
641 let current_group = current_group?;
642 let group_ids: Vec<_> = controller.tab_groups.keys().collect();
644 let idx = group_ids.iter().position(|g| *g == current_group)?;
645 let prev_idx = if idx == 0 {
646 group_ids.len() - 1
647 } else {
648 idx - 1
649 };
650
651 controller
652 .tab_groups
653 .get(group_ids[prev_idx])
654 .and_then(|tabs| {
655 tabs.iter()
656 .max_by_key(|tab| tab.last_active_at)
657 .or_else(|| tabs.first())
658 .map(|tab| &tab.handle)
659 })
660 }
661
662 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
664 self.tab_groups
665 .values()
666 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
667 }
668
669 pub fn init_visible(cx: &mut App, visible: bool) {
671 let controller = cx.global_mut::<SystemWindowTabController>();
672 if controller.visible.is_none() {
673 controller.visible = Some(visible);
674 }
675 }
676
677 pub fn is_visible(&self) -> bool {
679 self.visible.unwrap_or(false)
680 }
681
682 pub fn set_visible(cx: &mut App, visible: bool) {
684 let controller = cx.global_mut::<SystemWindowTabController>();
685 controller.visible = Some(visible);
686 }
687
688 pub fn update_last_active(cx: &mut App, id: WindowId) {
690 let controller = cx.global_mut::<SystemWindowTabController>();
691 for windows in controller.tab_groups.values_mut() {
692 for tab in windows.iter_mut() {
693 if tab.id == id {
694 tab.last_active_at = Instant::now();
695 }
696 }
697 }
698 }
699
700 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
702 let controller = cx.global_mut::<SystemWindowTabController>();
703 for (_, windows) in controller.tab_groups.iter_mut() {
704 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
705 if ix < windows.len() && current_pos != ix {
706 let window_tab = windows.remove(current_pos);
707 windows.insert(ix, window_tab);
708 }
709 break;
710 }
711 }
712 }
713
714 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
716 let controller = cx.global::<SystemWindowTabController>();
717 let tab = controller
718 .tab_groups
719 .values()
720 .flat_map(|windows| windows.iter())
721 .find(|tab| tab.id == id);
722
723 if tab.map_or(true, |t| t.title == title) {
724 return;
725 }
726
727 let controller = cx.global_mut::<SystemWindowTabController>();
728 for windows in controller.tab_groups.values_mut() {
729 for tab in windows.iter_mut() {
730 if tab.id == id {
731 tab.title = title;
732 return;
733 }
734 }
735 }
736 }
737
738 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
740 let controller = cx.global_mut::<SystemWindowTabController>();
741 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
742 return;
743 };
744
745 let expected_tab_ids: Vec<_> = tabs
746 .iter()
747 .filter(|tab| tab.id != id)
748 .map(|tab| tab.id)
749 .sorted()
750 .collect();
751
752 let mut tab_group_id = None;
753 for (group_id, group_tabs) in &controller.tab_groups {
754 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
755 if tab_ids == expected_tab_ids {
756 tab_group_id = Some(*group_id);
757 break;
758 }
759 }
760
761 if let Some(tab_group_id) = tab_group_id {
762 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
763 tabs.push(tab);
764 }
765 } else {
766 let new_group_id = controller.tab_groups.len();
767 controller.tab_groups.insert(new_group_id, tabs);
768 }
769 }
770
771 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
773 let controller = cx.global_mut::<SystemWindowTabController>();
774 let mut removed_tab = None;
775
776 controller.tab_groups.retain(|_, tabs| {
777 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
778 removed_tab = Some(tabs.remove(pos));
779 }
780 !tabs.is_empty()
781 });
782
783 removed_tab
784 }
785
786 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
788 let removed_tab = Self::remove_tab(cx, id);
789 let controller = cx.global_mut::<SystemWindowTabController>();
790
791 if let Some(tab) = removed_tab {
792 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
793 controller.tab_groups.insert(new_group_id, vec![tab]);
794 }
795 }
796
797 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
799 let controller = cx.global_mut::<SystemWindowTabController>();
800 let Some(initial_tabs) = controller.tabs(id) else {
801 return;
802 };
803
804 let initial_tabs_len = initial_tabs.len();
805 let mut all_tabs = initial_tabs.clone();
806
807 for (_, mut tabs) in controller.tab_groups.drain() {
808 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
809 all_tabs.extend(tabs);
810 }
811
812 controller.tab_groups.insert(0, all_tabs);
813 }
814
815 pub fn select_next_tab(cx: &mut App, id: WindowId) {
817 let controller = cx.global_mut::<SystemWindowTabController>();
818 let Some(tabs) = controller.tabs(id) else {
819 return;
820 };
821
822 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
823 let next_index = (current_index + 1) % tabs.len();
824
825 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
826 window.activate_window();
827 });
828 }
829
830 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
832 let controller = cx.global_mut::<SystemWindowTabController>();
833 let Some(tabs) = controller.tabs(id) else {
834 return;
835 };
836
837 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
838 let previous_index = if current_index == 0 {
839 tabs.len() - 1
840 } else {
841 current_index - 1
842 };
843
844 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
845 window.activate_window();
846 });
847 }
848}
849
850pub(crate) enum GpuiMode {
851 #[cfg(any(test, feature = "test-support"))]
852 Test {
853 skip_drawing: bool,
854 },
855 Production,
856}
857
858impl GpuiMode {
859 #[cfg(any(test, feature = "test-support"))]
860 pub fn test() -> Self {
861 GpuiMode::Test {
862 skip_drawing: false,
863 }
864 }
865
866 #[inline]
867 pub(crate) fn skip_drawing(&self) -> bool {
868 match self {
869 #[cfg(any(test, feature = "test-support"))]
870 GpuiMode::Test { skip_drawing } => *skip_drawing,
871 GpuiMode::Production => false,
872 }
873 }
874}
875
876struct PlatformOwnedDrag {
877 source_window: WindowId,
878 state: PlatformOwnedDragState,
879}
880
881enum PlatformOwnedDragState {
882 Suspended(AnyDrag),
883 RestoredInSourceWindow,
886}
887
888pub struct App {
892 pub(crate) this: Weak<AppCell>,
893 pub(crate) platform: Rc<dyn Platform>,
894 text_system: Arc<TextSystem>,
895
896 pub(crate) actions: Rc<ActionRegistry>,
897 pub(crate) active_drag: Option<AnyDrag>,
898 platform_owned_drag: Option<PlatformOwnedDrag>,
899 pub(crate) background_executor: BackgroundExecutor,
900 pub(crate) foreground_executor: ForegroundExecutor,
901 #[cfg(feature = "profiler")]
902 foreground_journal: crate::profiler::journal::ForegroundJournal,
903 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
904 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
905 pub(crate) entities: EntityMap,
906 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
907 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
908 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
909 pub(crate) focus_handles: Arc<RwLock<FocusMap>>,
910 pub(crate) keymap: Rc<RefCell<Keymap>>,
911 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
912 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
913 pub(crate) global_action_listeners:
914 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
915 pending_effects: VecDeque<Effect>,
916
917 pub(crate) observers: SubscriberSet<EntityId, Handler>,
918 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
919 pub(crate) keystroke_observers: SingleSubscriberSet<KeystrokeObserver>,
920 pub(crate) keystroke_interceptors: SingleSubscriberSet<KeystrokeObserver>,
921 pub(crate) keyboard_layout_observers: SingleSubscriberSet<Handler>,
922 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
923 pub(crate) thermal_state_observers: SingleSubscriberSet<Handler>,
924 pub(crate) display_observers: SingleSubscriberSet<DisplayHandler>,
925 displays: HashMap<DisplayId, DisplayState>,
928 pub(crate) system_sleep_observers: SingleSubscriberSet<Handler>,
929 pub(crate) system_wake_observers: SingleSubscriberSet<Handler>,
930 app_lifecycle_observers: SingleSubscriberSet<AppLifecycleHandler>,
931 memory_warning_observers: SingleSubscriberSet<Handler>,
932 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
933 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
934 pub(crate) quit_observers: SingleSubscriberSet<QuitHandler>,
935 pub(crate) restart_observers: SingleSubscriberSet<Handler>,
936 pub(crate) window_closed_observers: SingleSubscriberSet<WindowClosedHandler>,
937
938 pub(crate) element_arena: Rc<RefCell<Arena>>,
946 pub(crate) event_arena: Arena,
948
949 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
954
955 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
957 asset_source: Arc<dyn AssetSource>,
958 pub(crate) svg_renderer: SvgRenderer,
959 http_client: Arc<dyn HttpClient>,
960
961 pub(crate) pending_notifications: FxHashSet<EntityId>,
963 pub(crate) pending_global_notifications: TypeIdHashSet,
964 pub(crate) restart_path: Option<PathBuf>,
965 pub(crate) restart_arguments: Vec<OsString>,
966 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
968 pub(crate) prompt_builder: Option<PromptBuilder>,
969 pub(crate) window_invalidators_by_entity:
970 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
971 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
972 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
973 #[cfg(any(feature = "inspector", debug_assertions))]
974 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
975 #[cfg(any(feature = "inspector", debug_assertions))]
976 pub(crate) inspector_element_registry: InspectorElementRegistry,
977 #[cfg(any(test, feature = "test-support", debug_assertions))]
978 pub(crate) name: Option<&'static str>,
979 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
980
981 pub(crate) window_update_stack: Vec<WindowUpdateEntry>,
982 pub(crate) mode: GpuiMode,
983 pub(crate) cursor_hide_mode: CursorHideMode,
984 pub(crate) reduce_motion: bool,
985 pub(crate) synced_animation_epoch: Instant,
987 power_mode: PowerMode,
988 pub(crate) accessibility_force_disabled: bool,
991 pending_updates: usize,
992 quit_mode: QuitMode,
993 quitting: bool,
994
995 #[cfg(any(test, gpui_leak_detection))]
998 _ref_counts: Arc<RwLock<EntityRefCounts>>,
999}
1000
1001#[derive(Clone, Copy)]
1002pub(crate) struct WindowUpdateEntry {
1003 window_id: WindowId,
1004 bounds: WindowBounds,
1005 display_id: Option<DisplayId>,
1006}
1007
1008impl App {
1009 #[allow(clippy::new_ret_no_self)]
1010 pub(crate) fn new_app(
1011 platform: Rc<dyn Platform>,
1012 asset_source: Arc<dyn AssetSource>,
1013 http_client: Arc<dyn HttpClient>,
1014 ) -> Rc<AppCell> {
1015 let background_executor = platform.background_executor();
1016 let foreground_executor = platform.foreground_executor();
1017 assert!(
1018 background_executor.is_main_thread(),
1019 "must construct App on main thread"
1020 );
1021 #[cfg(feature = "profiler")]
1022 let foreground_journal = crate::profiler::journal::install_foreground_journal();
1023 let synced_animation_epoch = background_executor.now();
1024
1025 let text_system = Arc::new(TextSystem::new(platform.text_system()));
1026 let entities = EntityMap::new();
1027 let keyboard_layout = platform.keyboard_layout();
1028 let keyboard_mapper = platform.keyboard_mapper();
1029 let power_mode = platform.power_mode();
1030
1031 #[cfg(any(test, gpui_leak_detection))]
1032 let _ref_counts = entities.ref_counts_drop_handle();
1033
1034 let app = Rc::new_cyclic(|this| AppCell {
1035 borrow_origin: Cell::new(None),
1036 app: RefCell::new(App {
1037 this: this.clone(),
1038 platform: platform.clone(),
1039 text_system,
1040 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
1041 mode: GpuiMode::Production,
1042 actions: Rc::new(ActionRegistry::default()),
1043 pending_updates: 0,
1044 active_drag: None,
1045 platform_owned_drag: None,
1046 background_executor,
1047 foreground_executor,
1048 #[cfg(feature = "profiler")]
1049 foreground_journal,
1050 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1051 hang_monitor: None,
1052 svg_renderer: SvgRenderer::new(asset_source.clone()),
1053 loading_assets: Default::default(),
1054 asset_source,
1055 http_client,
1056 globals_by_type: Default::default(),
1057 entities,
1058 new_entity_observers: SubscriberSet::new(),
1059 windows: SlotMap::with_key(),
1060 window_update_stack: Vec::new(),
1061 window_handles: FxHashMap::default(),
1062 focus_handles: Arc::new(RwLock::new(FocusMap::default())),
1063 keymap: Rc::new(RefCell::new(Keymap::default())),
1064 keyboard_layout,
1065 keyboard_mapper,
1066 global_action_listeners: Default::default(),
1067 pending_effects: VecDeque::new(),
1068 pending_notifications: FxHashSet::default(),
1069 pending_global_notifications: Default::default(),
1070 observers: SubscriberSet::new(),
1071 tracked_entities: FxHashMap::default(),
1072 window_invalidators_by_entity: FxHashMap::default(),
1073 current_window_by_entity: FxHashMap::default(),
1074 event_listeners: SubscriberSet::new(),
1075 release_listeners: SubscriberSet::new(),
1076 keystroke_observers: SingleSubscriberSet::new(),
1077 keystroke_interceptors: SingleSubscriberSet::new(),
1078 keyboard_layout_observers: SingleSubscriberSet::new(),
1079 missing_glyph_callback: Rc::default(),
1080 thermal_state_observers: SingleSubscriberSet::new(),
1081 display_observers: SingleSubscriberSet::new(),
1082 displays: read_displays(platform.as_ref()),
1083 system_sleep_observers: SingleSubscriberSet::new(),
1084 system_wake_observers: SingleSubscriberSet::new(),
1085 app_lifecycle_observers: SingleSubscriberSet::new(),
1086 memory_warning_observers: SingleSubscriberSet::new(),
1087 global_observers: SubscriberSet::new(),
1088 quit_observers: SingleSubscriberSet::new(),
1089 restart_observers: SingleSubscriberSet::new(),
1090 restart_path: None,
1091 restart_arguments: Vec::new(),
1092 window_closed_observers: SingleSubscriberSet::new(),
1093 layout_id_buffer: Default::default(),
1094 propagate_event: true,
1095 prompt_builder: Some(PromptBuilder::Default),
1096 #[cfg(any(feature = "inspector", debug_assertions))]
1097 inspector_renderer: None,
1098 #[cfg(any(feature = "inspector", debug_assertions))]
1099 inspector_element_registry: InspectorElementRegistry::default(),
1100 quit_mode: QuitMode::default(),
1101 quitting: false,
1102 cursor_hide_mode: CursorHideMode::default(),
1103 reduce_motion: false,
1104 synced_animation_epoch,
1105 power_mode,
1106 accessibility_force_disabled: false,
1107
1108 #[cfg(any(test, feature = "test-support", debug_assertions))]
1109 name: None,
1110 element_arena: Rc::new(RefCell::new(Arena::new(1024 * 1024))),
1111 event_arena: Arena::new(1024 * 1024),
1112
1113 #[cfg(any(test, gpui_leak_detection))]
1114 _ref_counts,
1115 }),
1116 });
1117
1118 init_app_menus(platform.as_ref(), &app.borrow());
1119 SystemWindowTabController::init(&mut app.borrow_mut());
1120 #[cfg(feature = "profiler")]
1121 crate::profiler::journal::observe_power(&app.borrow());
1122
1123 platform.on_keyboard_layout_change(Box::new({
1124 let app = Rc::downgrade(&app);
1125 move || {
1126 if let Some(app) = app.upgrade() {
1127 let cx = &mut app.borrow_mut();
1128 cx.keyboard_layout = cx.platform.keyboard_layout();
1129 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1130 cx.keyboard_layout_observers
1131 .clone()
1132 .retain(move |callback| (callback)(cx));
1133 }
1134 }
1135 }));
1136
1137 platform.on_thermal_state_change(Box::new({
1138 let app = Rc::downgrade(&app);
1139 move || {
1140 if let Some(app) = app.upgrade() {
1141 let cx = &mut app.borrow_mut();
1142 cx.thermal_state_observers
1143 .clone()
1144 .retain(move |callback| (callback)(cx));
1145 }
1146 }
1147 }));
1148
1149 platform.on_displays_changed(Box::new({
1150 let app = Rc::downgrade(&app);
1151 move || {
1152 if let Some(app) = app.upgrade() {
1153 app.borrow_mut().displays_changed();
1154 }
1155 }
1156 }));
1157
1158 platform.on_system_sleep(Box::new({
1159 let app = Rc::downgrade(&app);
1160 move || {
1161 if let Some(app) = app.upgrade() {
1162 let cx = &mut app.borrow_mut();
1163 cx.system_sleep_observers
1164 .clone()
1165 .retain(move |callback| (callback)(cx));
1166 }
1167 }
1168 }));
1169
1170 platform.on_system_wake(Box::new({
1171 let app = Rc::downgrade(&app);
1172 move || {
1173 if let Some(app) = app.upgrade() {
1174 let cx = &mut app.borrow_mut();
1175 cx.system_wake_observers
1176 .clone()
1177 .retain(move |callback| (callback)(cx));
1178 }
1179 }
1180 }));
1181
1182 platform.on_app_lifecycle(Box::new({
1183 let app = Rc::downgrade(&app);
1184 move |phase| {
1185 if let Some(app) = app.upgrade() {
1186 app.borrow_mut().update(|cx| {
1187 cx.app_lifecycle_observers
1188 .clone()
1189 .retain(|callback| callback(phase, cx));
1190 });
1191 }
1192 }
1193 }));
1194
1195 platform.on_memory_warning(Box::new({
1196 let app = Rc::downgrade(&app);
1197 move || {
1198 if let Some(app) = app.upgrade() {
1199 app.borrow_mut().update(|cx| {
1200 cx.memory_warning_observers
1201 .clone()
1202 .retain(|callback| callback(cx));
1203 });
1204 }
1205 }
1206 }));
1207
1208 platform.on_power_mode_change(Box::new({
1209 let app = Rc::downgrade(&app);
1210 move || {
1211 if let Some(app) = app.upgrade() {
1212 let power_mode = app.borrow().platform.power_mode();
1213 app.borrow_mut().power_mode = power_mode;
1214 }
1215 }
1216 }));
1217
1218 platform.on_quit(Box::new({
1219 let cx = Rc::downgrade(&app);
1220 move || {
1221 let Some(cx) = cx.upgrade() else {
1222 return true;
1223 };
1224 match cx.try_borrow_mut() {
1225 Ok(mut cx) => {
1226 cx.shutdown();
1227 true
1228 }
1229 Err(_) => {
1230 false
1233 }
1234 }
1235 }
1236 }));
1237
1238 app
1239 }
1240
1241 #[doc(hidden)]
1242 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1243 self.entities.ref_counts_drop_handle()
1244 }
1245
1246 #[cfg(any(test, gpui_leak_detection))]
1252 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1253 self.entities.leak_detector_snapshot()
1254 }
1255
1256 #[cfg(any(test, gpui_leak_detection))]
1268 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1269 self.entities.assert_no_new_leaks(snapshot)
1270 }
1271
1272 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1274 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1275 LeakDetectorSnapshot::default()
1276 }
1277
1278 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1281 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1282
1283 pub fn shutdown(&mut self) {
1289 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1292 let hang_monitor_flush = self
1293 .hang_monitor
1294 .as_ref()
1295 .and_then(|hang_monitor| hang_monitor.request_flush());
1296
1297 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1298
1299 for observer in self.quit_observers.remove() {
1300 futures.push(observer(self));
1301 }
1302
1303 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1304 if let Some(flushed) = hang_monitor_flush {
1305 futures.push(
1306 async move {
1307 if flushed.await.is_err() {
1308 log::warn!("hang monitor exited before flushing");
1309 }
1310 }
1311 .boxed_local(),
1312 );
1313 }
1314
1315 self.windows.clear();
1316 self.window_handles.clear();
1317 self.flush_effects();
1318 self.quitting = true;
1319
1320 let futures = futures::future::join_all(futures);
1321 #[cfg(not(target_family = "wasm"))]
1322 if self
1323 .foreground_executor
1324 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1325 .is_err()
1326 {
1327 log::error!("timed out waiting on app_will_quit");
1328 }
1329 #[cfg(target_family = "wasm")]
1330 self.foreground_executor.spawn(futures).detach();
1331
1332 self.quitting = false;
1333 }
1334
1335 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1337 self.keyboard_layout.as_ref()
1338 }
1339
1340 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1342 &self.keyboard_mapper
1343 }
1344
1345 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1347 where
1348 F: 'static + FnMut(&mut App),
1349 {
1350 self.keyboard_layout_observers.insert(Box::new(move |cx| {
1351 callback(cx);
1352 true
1353 }))
1354 }
1355
1356 pub fn quit(&self) {
1358 self.platform.quit();
1359 }
1360
1361 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1375 if !self.windows.is_empty() {
1376 return Task::ready(Err(anyhow::anyhow!(
1377 "cannot switch windowing modes while windows are open"
1378 )));
1379 }
1380 self.platform.request_windowing(request)
1381 }
1382
1383 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1393 self.platform.graphical_environment()
1394 }
1395
1396 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1399 self.cursor_hide_mode
1400 }
1401
1402 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1405 self.cursor_hide_mode = mode;
1406 }
1407
1408 pub fn is_cursor_visible(&self) -> bool {
1414 self.platform.is_cursor_visible()
1415 }
1416
1417 pub fn reduce_motion(&self) -> bool {
1420 self.reduce_motion
1421 }
1422
1423 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1426 if self.reduce_motion != reduce_motion {
1427 self.reduce_motion = reduce_motion;
1428 self.refresh_windows();
1429 }
1430 }
1431
1432 pub fn refresh_windows(&mut self) {
1435 self.pending_effects.push_back(Effect::RefreshWindows);
1436 }
1437
1438 #[inline(always)]
1439 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1440 self.start_update();
1441 let result = update(self);
1442 self.finish_update();
1443 result
1444 }
1445
1446 pub(crate) fn start_update(&mut self) {
1447 self.pending_updates += 1;
1448 }
1449
1450 #[inline(never)]
1451 pub(crate) fn finish_update(&mut self) {
1452 if self.pending_updates == 1 {
1453 self.flush_effects();
1454 }
1455 self.pending_updates -= 1;
1456 }
1457
1458 pub fn observe<W>(
1460 &mut self,
1461 entity: &Entity<W>,
1462 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1463 ) -> Subscription
1464 where
1465 W: 'static,
1466 {
1467 self.observe_internal(entity, move |e, cx| {
1468 on_notify(e, cx);
1469 true
1470 })
1471 }
1472
1473 pub(crate) fn detect_accessed_entities<R>(
1474 &mut self,
1475 callback: impl FnOnce(&mut App) -> R,
1476 ) -> (R, FxHashSet<EntityId>) {
1477 self.entities.push_access_scope();
1478 let result = callback(self);
1479 (result, self.entities.pop_access_scope())
1480 }
1481
1482 pub(crate) fn record_entities_accessed(
1483 &mut self,
1484 window_handle: AnyWindowHandle,
1485 invalidator: WindowInvalidator,
1486 entities: &FxHashSet<EntityId>,
1487 ) {
1488 let mut tracked_entities =
1489 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1490 for entity in tracked_entities.iter() {
1491 self.window_invalidators_by_entity
1492 .entry(*entity)
1493 .and_modify(|windows| {
1494 windows.remove(&window_handle.id);
1495 });
1496 }
1497 for entity in entities.iter() {
1498 self.window_invalidators_by_entity
1499 .entry(*entity)
1500 .or_default()
1501 .insert(window_handle.id, invalidator.clone());
1502 self.current_window_by_entity
1503 .insert(*entity, window_handle.id);
1504 }
1505 tracked_entities.clear();
1506 tracked_entities.extend(entities.iter().copied());
1507 self.tracked_entities
1508 .insert(window_handle.id, tracked_entities);
1509 }
1510
1511 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1512 let (subscription, activate) = self.observers.insert_pending(key, value);
1513 self.defer(move |_| activate());
1514 subscription
1515 }
1516
1517 pub(crate) fn observe_internal<W>(
1518 &mut self,
1519 entity: &Entity<W>,
1520 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1521 ) -> Subscription
1522 where
1523 W: 'static,
1524 {
1525 let entity_id = entity.entity_id();
1526 let handle = entity.downgrade();
1527 self.new_observer(
1528 entity_id,
1529 Box::new(move |cx| {
1530 if let Some(entity) = handle.upgrade() {
1531 on_notify(entity, cx)
1532 } else {
1533 false
1534 }
1535 }),
1536 )
1537 }
1538
1539 pub fn subscribe<T, Event>(
1542 &mut self,
1543 entity: &Entity<T>,
1544 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1545 ) -> Subscription
1546 where
1547 T: 'static + EventEmitter<Event>,
1548 Event: 'static,
1549 {
1550 self.subscribe_internal(entity, move |entity, event, cx| {
1551 on_event(entity, event, cx);
1552 true
1553 })
1554 }
1555
1556 pub(crate) fn new_subscription(
1557 &mut self,
1558 key: EntityId,
1559 value: (TypeId, Listener),
1560 ) -> Subscription {
1561 let (subscription, activate) = self.event_listeners.insert_pending(key, value);
1562 self.defer(move |_| activate());
1563 subscription
1564 }
1565 pub(crate) fn subscribe_internal<T, Evt>(
1566 &mut self,
1567 entity: &Entity<T>,
1568 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1569 ) -> Subscription
1570 where
1571 T: 'static + EventEmitter<Evt>,
1572 Evt: 'static,
1573 {
1574 let entity_id = entity.entity_id();
1575 let handle = entity.downgrade();
1576 self.new_subscription(
1577 entity_id,
1578 (
1579 TypeId::of::<Evt>(),
1580 Box::new(move |event, cx| {
1581 let event: &Evt = event.downcast_ref().expect("invalid event type");
1582 if let Some(entity) = handle.upgrade() {
1583 on_event(entity, event, cx)
1584 } else {
1585 false
1586 }
1587 }),
1588 ),
1589 )
1590 }
1591
1592 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1596 self.windows
1597 .keys()
1598 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1599 .collect()
1600 }
1601
1602 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1608 self.platform.window_stack()
1609 }
1610
1611 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1613 self.platform.active_window()
1614 }
1615
1616 pub fn active_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1618 let (display_id, _) = self.active_window_placement()?;
1619 self.find_display(display_id?)
1620 }
1621
1622 pub(crate) fn active_window_placement(&self) -> Option<(Option<DisplayId>, WindowBounds)> {
1623 let window_id = self.active_window()?.window_id();
1624
1625 if let Some(state) = self
1626 .window_update_stack
1627 .iter()
1628 .rev()
1629 .find(|state| state.window_id == window_id)
1630 {
1631 return Some((state.display_id, state.bounds));
1632 }
1633
1634 let window = self.windows.get(window_id)?.as_ref()?;
1635 Some((window.display_id(), window.last_window_bounds()))
1636 }
1637
1638 pub(crate) fn sync_window_update_entry(&mut self, window: &Window) {
1639 if let Some(state) = self
1640 .window_update_stack
1641 .iter_mut()
1642 .rev()
1643 .find(|state| state.window_id == window.handle.id)
1644 {
1645 state.bounds = window.last_window_bounds();
1646 state.display_id = window.display_id();
1647 }
1648 }
1649
1650 pub fn open_window<V: 'static + Render>(
1654 &mut self,
1655 options: crate::WindowOptions,
1656 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1657 ) -> anyhow::Result<WindowHandle<V>> {
1658 self.update(|cx| {
1659 let id = cx.windows.insert(None);
1660 let handle = WindowHandle::new(id);
1661 match Window::new(handle.into(), options, cx) {
1662 Ok(mut window) => {
1663 cx.window_update_stack.push(WindowUpdateEntry {
1664 window_id: id,
1665 bounds: window.last_window_bounds(),
1666 display_id: window.display_id(),
1667 });
1668 let root_view = build_root_view(&mut window, cx);
1669 cx.window_update_stack.pop();
1670 window.root.replace(root_view.into());
1671 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1672
1673 let clear = window.draw(cx);
1678 clear.clear(cx);
1679
1680 cx.window_handles.insert(id, window.handle);
1681 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1682 Ok(handle)
1683 }
1684 Err(e) => {
1685 cx.windows.remove(id);
1686 Err(e)
1687 }
1688 }
1689 })
1690 }
1691
1692 pub fn activate(&self, ignoring_other_apps: bool) {
1694 self.platform.activate(ignoring_other_apps);
1695 }
1696
1697 pub fn hide(&self) {
1699 self.platform.hide();
1700 }
1701
1702 pub fn hide_other_apps(&self) {
1704 self.platform.hide_other_apps();
1705 }
1706
1707 pub fn unhide_other_apps(&self) {
1709 self.platform.unhide_other_apps();
1710 }
1711
1712 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1714 self.platform.displays()
1715 }
1716
1717 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1719 self.platform.primary_display()
1720 }
1721
1722 pub fn is_screen_capture_supported(&self) -> bool {
1724 self.platform.is_screen_capture_supported()
1725 }
1726
1727 pub fn screen_capture_sources(
1729 &self,
1730 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1731 self.platform.screen_capture_sources()
1732 }
1733
1734 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1736 self.displays()
1737 .iter()
1738 .find(|display| display.id() == id)
1739 .cloned()
1740 }
1741
1742 pub fn debug_state(&self) -> serde_json::Value {
1749 let displays = self
1750 .platform
1751 .displays()
1752 .into_iter()
1753 .map(|display| {
1754 serde_json::json!({
1755 "id": u64::from(display.id()),
1756 "uuid": display.uuid().ok().map(|uuid| uuid.to_string()),
1757 "bounds": display.bounds(),
1758 "visible_bounds": display.visible_bounds(),
1759 "refresh_interval_seconds": display
1760 .refresh_interval()
1761 .map(|interval| interval.as_secs_f64()),
1762 })
1763 })
1764 .collect::<Vec<_>>();
1765 let windows = self
1766 .windows
1767 .iter()
1768 .map(|(window_id, window)| match window {
1769 Some(window) => window.debug_state(),
1770 None => serde_json::json!({ "id": window_id.as_u64(), "updating": true }),
1771 })
1772 .collect::<Vec<_>>();
1773 serde_json::json!({
1774 "compositor": self.platform.compositor_name(),
1775 "thermal_state": format!("{:?}", self.platform.thermal_state()),
1776 "power_mode": {
1777 "cached": format!("{:?}", self.power_mode),
1778 "platform": format!("{:?}", self.platform.power_mode()),
1779 },
1780 "window_appearance": format!("{:?}", self.platform.window_appearance()),
1781 "cursor_visible": self.platform.is_cursor_visible(),
1782 "active_window_id": self
1783 .platform
1784 .active_window()
1785 .map(|handle| handle.window_id().as_u64()),
1786 "window_stack": self.platform.window_stack().map(|stack| {
1787 stack
1788 .into_iter()
1789 .map(|handle| handle.window_id().as_u64())
1790 .collect::<Vec<_>>()
1791 }),
1792 "primary_display_id": self
1793 .platform
1794 .primary_display()
1795 .map(|display| u64::from(display.id())),
1796 "displays": displays,
1797 "windows": windows,
1798 "platform": self.platform.debug_state(),
1799 })
1800 }
1801
1802 pub fn thermal_state(&self) -> ThermalState {
1804 self.platform.thermal_state()
1805 }
1806
1807 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1809 self.platform.prevent_idle_sleep(reason)
1810 }
1811
1812 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1814 where
1815 F: 'static + FnMut(&mut App),
1816 {
1817 self.thermal_state_observers.insert(Box::new(move |cx| {
1818 callback(cx);
1819 true
1820 }))
1821 }
1822
1823 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1828 where
1829 F: 'static + FnMut(&mut App),
1830 {
1831 self.system_sleep_observers.insert(Box::new(move |cx| {
1832 callback(cx);
1833 true
1834 }))
1835 }
1836
1837 pub(crate) fn displays_changed(&mut self) {
1838 let current = read_displays(self.platform.as_ref());
1839 let events = display_events(&self.displays, ¤t);
1840 self.displays = current;
1841 for event in &events {
1842 let DisplayEvent::Changed { id, .. } = *event else {
1843 continue;
1844 };
1845 for handle in self.windows() {
1846 self.update_window(handle, |_, window, cx| {
1847 if window.display_id == Some(id) {
1848 window.notify_display_observers(cx);
1849 }
1850 })
1851 .log_err();
1852 }
1853 }
1854 for event in events {
1855 self.display_observers
1856 .clone()
1857 .retain(|callback| (callback)(event, self));
1858 }
1859 }
1860
1861 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1862 self.displays.contains_key(&id)
1863 }
1864
1865 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1868 self.displays.get(&id)?.refresh_interval
1869 }
1870
1871 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1874 where
1875 F: 'static + FnMut(DisplayEvent, &mut App),
1876 {
1877 self.display_observers.insert(Box::new(move |event, cx| {
1878 callback(event, cx);
1879 true
1880 }))
1881 }
1882
1883 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1885 where
1886 F: 'static + FnMut(&mut App),
1887 {
1888 self.system_wake_observers.insert(Box::new(move |cx| {
1889 callback(cx);
1890 true
1891 }))
1892 }
1893
1894 pub fn on_app_lifecycle(
1902 &self,
1903 mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
1904 ) -> Subscription {
1905 self.app_lifecycle_observers
1906 .insert(Box::new(move |phase, cx| {
1907 callback(phase, cx);
1908 true
1909 }))
1910 }
1911
1912 pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
1915 self.memory_warning_observers.insert(Box::new(move |cx| {
1916 callback(cx);
1917 true
1918 }))
1919 }
1920
1921 pub fn window_appearance(&self) -> WindowAppearance {
1923 self.platform.window_appearance()
1924 }
1925
1926 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1937 self.platform.set_window_appearance(appearance);
1938 }
1939
1940 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1942 self.platform.button_layout()
1943 }
1944
1945 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1947 self.platform.read_from_clipboard()
1948 }
1949
1950 pub fn read_from_clipboard_async(
1958 &self,
1959 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1960 self.platform.read_from_clipboard_async()
1961 }
1962
1963 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1965 self.text_rendering_mode.set(mode);
1966 }
1967
1968 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1970 self.text_rendering_mode.get()
1971 }
1972
1973 pub fn power_mode(&self) -> PowerMode {
1976 self.power_mode
1977 }
1978
1979 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1981 self.platform.write_to_clipboard(item)
1982 }
1983
1984 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1987 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1988 self.platform.read_from_primary()
1989 }
1990
1991 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1994 pub fn write_to_primary(&self, item: ClipboardItem) {
1995 self.platform.write_to_primary(item)
1996 }
1997
1998 #[cfg(target_os = "macos")]
2004 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
2005 self.platform.read_from_find_pasteboard()
2006 }
2007
2008 #[cfg(target_os = "macos")]
2014 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
2015 self.platform.write_to_find_pasteboard(item)
2016 }
2017
2018 pub fn write_credentials(
2020 &self,
2021 url: &str,
2022 username: &str,
2023 password: &[u8],
2024 ) -> Task<Result<()>> {
2025 self.platform.write_credentials(url, username, password)
2026 }
2027
2028 #[cfg(target_os = "macos")]
2036 pub fn write_credentials_if_not_exists(
2037 &self,
2038 url: &str,
2039 username: &str,
2040 password: &[u8],
2041 ) -> Task<Result<bool>> {
2042 self.platform
2043 .write_credentials_if_not_exists(url, username, password)
2044 }
2045
2046 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
2048 self.platform.read_credentials(url)
2049 }
2050
2051 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
2053 self.platform.delete_credentials(url)
2054 }
2055
2056 pub fn open_url(&self, url: &str) {
2058 self.platform.open_url(url);
2059 }
2060
2061 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
2068 self.platform.register_url_scheme(scheme)
2069 }
2070
2071 pub fn set_app_identity(&self, identifier: &str, name: &str) {
2078 self.platform.set_app_identity(identifier, name);
2079 }
2080
2081 pub fn show_system_notification(&self, notification: SystemNotification) {
2088 self.platform.show_system_notification(notification);
2089 }
2090
2091 pub fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
2099 self.platform.dismiss_system_notification(tag)
2100 }
2101
2102 pub fn on_system_notification_response<F>(&self, mut callback: F)
2106 where
2107 F: 'static + FnMut(SystemNotificationResponse, &mut App),
2108 {
2109 let this = self.this.clone();
2110 self.platform
2111 .on_system_notification_response(Box::new(move |response| {
2112 if let Some(app) = this.upgrade() {
2113 callback(response, &mut app.borrow_mut());
2114 }
2115 }));
2116 }
2117
2118 pub fn app_path(&self) -> Result<PathBuf> {
2122 self.platform.app_path()
2123 }
2124
2125 pub fn compositor_name(&self) -> &'static str {
2129 self.platform.compositor_name()
2130 }
2131
2132 pub fn platform_info(&self) -> crate::PlatformInfo {
2134 self.platform.platform_info()
2135 }
2136
2137 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
2139 self.platform.path_for_auxiliary_executable(name)
2140 }
2141
2142 pub fn prompt_for_paths(
2148 &self,
2149 options: PathPromptOptions,
2150 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
2151 self.platform.prompt_for_paths(options)
2152 }
2153
2154 pub fn prompt_for_new_path(
2161 &self,
2162 directory: &Path,
2163 suggested_name: Option<&str>,
2164 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
2165 self.platform.prompt_for_new_path(directory, suggested_name)
2166 }
2167
2168 pub fn reveal_path(&self, path: &Path) {
2170 self.platform.reveal_path(path)
2171 }
2172
2173 pub fn open_with_system(&self, path: &Path) {
2175 self.platform.open_with_system(path)
2176 }
2177
2178 pub fn should_auto_hide_scrollbars(&self) -> bool {
2180 self.platform.should_auto_hide_scrollbars()
2181 }
2182
2183 pub fn restart(&mut self) {
2185 self.restart_observers
2186 .clone()
2187 .retain(|observer| observer(self));
2188 self.platform.restart(
2189 self.restart_path.take(),
2190 std::mem::take(&mut self.restart_arguments),
2191 )
2192 }
2193
2194 pub fn set_restart_path(&mut self, path: PathBuf) {
2196 self.restart_path = Some(path);
2197 }
2198
2199 pub fn http_client(&self) -> Arc<dyn HttpClient> {
2201 self.http_client.clone()
2202 }
2203
2204 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
2206 self.http_client = new_client;
2207 }
2208
2209 pub fn set_quit_mode(&mut self, mode: QuitMode) {
2212 self.quit_mode = mode;
2213 }
2214
2215 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
2224 self.platform.set_activation_policy(policy);
2225 }
2226
2227 pub fn svg_renderer(&self) -> SvgRenderer {
2229 self.svg_renderer.clone()
2230 }
2231
2232 pub(crate) fn push_effect(&mut self, effect: Effect) {
2233 match &effect {
2234 Effect::Notify { emitter } => {
2235 if !self.pending_notifications.insert(*emitter) {
2236 return;
2237 }
2238 }
2239 Effect::NotifyGlobalObservers { global_type } => {
2240 if !self.pending_global_notifications.insert(*global_type) {
2241 return;
2242 }
2243 }
2244 _ => {}
2245 };
2246
2247 self.pending_effects.push_back(effect);
2248 }
2249
2250 fn flush_effects(&mut self) {
2254 loop {
2255 self.release_dropped_entities();
2256 self.release_dropped_focus_handles();
2257 if let Some(effect) = self.pending_effects.pop_front() {
2258 match effect {
2259 Effect::Notify { emitter } => {
2260 self.apply_notify_effect(emitter);
2261 }
2262
2263 Effect::Emit {
2264 emitter,
2265 event_type,
2266 event,
2267 } => self.apply_emit_effect(emitter, event_type, &*event),
2268
2269 Effect::RefreshWindows => {
2270 self.apply_refresh_effect();
2271 }
2272
2273 Effect::NotifyGlobalObservers { global_type } => {
2274 self.apply_notify_global_observers_effect(global_type);
2275 }
2276
2277 Effect::Defer { callback } => {
2278 self.apply_defer_effect(callback);
2279 }
2280 Effect::EntityCreated {
2281 entity,
2282 tid,
2283 window,
2284 } => {
2285 self.apply_entity_created_effect(entity, tid, window);
2286 }
2287 }
2288 } else {
2289 #[cfg(any(test, feature = "test-support"))]
2290 if matches!(self.mode, GpuiMode::Test { .. }) {
2291 for window in self
2292 .windows
2293 .values()
2294 .filter_map(|window| {
2295 let window = window.as_deref()?;
2296 window.invalidator.is_dirty().then_some(window.handle)
2297 })
2298 .collect::<Vec<_>>()
2299 {
2300 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2301 .unwrap();
2302 }
2303 }
2304
2305 if self.pending_effects.is_empty() {
2306 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2307 if window.invalidator.is_dirty()
2308 || window.needs_present.get()
2309 || !window.next_frame_callbacks.borrow().is_empty()
2310 {
2311 window.platform_window.schedule_frame();
2312 }
2313 }
2314
2315 self.event_arena.clear();
2316 break;
2317 }
2318 }
2319 }
2320 }
2321
2322 fn release_dropped_entities(&mut self) {
2326 loop {
2327 let dropped = self.entities.take_dropped();
2328 if dropped.is_empty() {
2329 break;
2330 }
2331
2332 for (entity_id, mut entity) in dropped {
2333 self.observers.remove(&entity_id);
2334 self.event_listeners.remove(&entity_id);
2335 self.window_invalidators_by_entity.remove(&entity_id);
2336 self.current_window_by_entity.remove(&entity_id);
2337 for release_callback in self.release_listeners.remove(&entity_id) {
2338 release_callback(entity.as_mut(), self);
2339 }
2340 }
2341 }
2342 }
2343
2344 fn release_dropped_focus_handles(&mut self) {
2346 let focus_handles = self.focus_handles.clone();
2347 let mut focus_handles = focus_handles.write();
2348 let FocusMap {
2349 handles,
2350 dropped_handles,
2351 } = &mut *focus_handles;
2352 if dropped_handles.is_empty() {
2353 return;
2354 }
2355
2356 let windows = self
2357 .windows
2358 .values()
2359 .filter_map(|window| {
2360 let window = window.as_ref()?;
2361 dropped_handles
2362 .contains(&window.focus?)
2363 .then_some(window.handle)
2364 })
2365 .collect::<SmallVec<[_; 1]>>();
2366 for handle_id in dropped_handles.drain(..) {
2367 handles.remove(handle_id);
2368 }
2369 drop(focus_handles);
2370
2371 for window_handle in windows {
2372 window_handle
2373 .update(self, |_, window, cx| window.blur(cx))
2374 .ok();
2375 }
2376 }
2377
2378 fn apply_notify_effect(&mut self, emitter: EntityId) {
2379 self.pending_notifications.remove(&emitter);
2380
2381 self.observers
2382 .clone()
2383 .retain(&emitter, |handler| handler(self));
2384 }
2385
2386 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2387 self.event_listeners
2388 .clone()
2389 .retain(&emitter, |(stored_type, handler)| {
2390 if *stored_type == event_type {
2391 handler(event, self)
2392 } else {
2393 true
2394 }
2395 });
2396 }
2397
2398 fn apply_refresh_effect(&mut self) {
2399 for window in self.windows.values_mut() {
2400 if let Some(window) = window.as_deref_mut() {
2401 window.refreshing = true;
2402 window.invalidator.set_dirty(true);
2403 }
2404 }
2405 }
2406
2407 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2408 self.pending_global_notifications.remove(&type_id);
2409 self.global_observers
2410 .clone()
2411 .retain(&type_id, |observer| observer(self));
2412 }
2413
2414 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2415 callback(self);
2416 }
2417
2418 fn apply_entity_created_effect(
2419 &mut self,
2420 entity: AnyEntity,
2421 tid: TypeId,
2422 window: Option<WindowId>,
2423 ) {
2424 if let Some(id) = window {
2428 self.current_window_by_entity.insert(entity.entity_id(), id);
2429 }
2430
2431 self.new_entity_observers.clone().retain(&tid, |observer| {
2432 if let Some(id) = window {
2433 self.update_window_id(id, {
2434 let entity = entity.clone();
2435 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2436 })
2437 .expect("All windows should be off the stack when flushing effects");
2438 } else {
2439 (observer)(entity.clone(), &mut None, self)
2440 }
2441 true
2442 });
2443 }
2444
2445 #[inline(always)]
2451 pub fn with_window<R>(
2452 &mut self,
2453 entity_id: EntityId,
2454 f: impl FnOnce(&mut Window, &mut App) -> R,
2455 ) -> Option<R> {
2456 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2457 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2458 .ok()
2459 }
2460
2461 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2462 self.current_window_by_entity
2463 .entry(entity_id)
2464 .or_insert(window);
2465 }
2466
2467 #[inline(always)]
2468 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2469 where
2470 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2471 {
2472 let mut update = Some(update);
2473 let mut result = None;
2474 self.update_window_erased(id, &mut |arguments| {
2475 if let Some((root_view, window, cx)) = arguments {
2476 result = Some(update.take().unwrap()(root_view, window, cx));
2477 } else {
2478 drop(update.take());
2479 drop(result.take());
2480 }
2481 });
2482 result.context("window not found")
2483 }
2484
2485 pub fn to_async(&self) -> AsyncApp {
2488 AsyncApp {
2489 app: self.this.clone(),
2490 background_executor: self.background_executor.clone(),
2491 foreground_executor: self.foreground_executor.clone(),
2492 }
2493 }
2494
2495 pub fn background_executor(&self) -> &BackgroundExecutor {
2497 &self.background_executor
2498 }
2499
2500 pub fn is_test(&self) -> bool {
2503 self.background_executor.is_test()
2504 }
2505
2506 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2508 if self.quitting {
2509 panic!("Can't spawn on main thread after on_app_quit")
2510 };
2511 &self.foreground_executor
2512 }
2513
2514 #[cfg(feature = "profiler")]
2517 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2518 self.foreground_journal.clone()
2519 }
2520
2521 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2538 pub fn start_hang_monitor(
2539 &mut self,
2540 config: crate::profiler::hang::HangMonitorConfig,
2541 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2542 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2543 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2544
2545 if self.hang_monitor.is_some() {
2546 debug_assert!(false, "the hang monitor was started twice");
2547 return Err(HangMonitorError::AlreadyStarted);
2548 }
2549 let detector = HangDetector::new(
2550 self.foreground_journal(),
2551 config.threshold,
2552 config.frame_budget,
2553 );
2554 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2555 .map_err(HangMonitorError::Spawn)?;
2556 self.hang_monitor = Some(monitor);
2557 Ok(())
2558 }
2559
2560 #[track_caller]
2563 #[inline(always)]
2564 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2565 where
2566 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2567 R: 'static,
2568 {
2569 let mut cx = self.prepare_spawn();
2570
2571 self.foreground_executor
2572 .spawn(async move { f(&mut cx).await }.boxed_local())
2573 }
2574
2575 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2579 where
2580 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2581 R: 'static,
2582 {
2583 if self.quitting {
2584 debug_panic!("Can't spawn on main thread after on_app_quit")
2585 };
2586
2587 let mut cx = self.to_async();
2588
2589 self.foreground_executor
2590 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2591 }
2592
2593 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2596 self.push_effect(Effect::Defer {
2597 callback: Box::new(f),
2598 });
2599 }
2600
2601 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2603 &self.asset_source
2604 }
2605
2606 pub fn text_system(&self) -> &Arc<TextSystem> {
2608 &self.text_system
2609 }
2610
2611 pub fn on_missing_glyphs(
2622 &self,
2623 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2624 ) -> Subscription {
2625 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2626
2627 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2628 let callback = self.missing_glyph_callback.clone();
2629 self.spawn(async move |cx| {
2630 while let Ok(missing_glyphs) = receiver.recv().await {
2631 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2632 }
2633 })
2634 .detach();
2635 }
2636 self.text_system.enable_missing_glyph_reporting();
2637
2638 let callback = self.missing_glyph_callback.clone();
2639 let text_system = self.text_system.clone();
2640 Subscription::new(move || {
2641 if callback.remove(®istration) {
2642 text_system.disable_missing_glyph_reporting();
2643 }
2644 })
2645 }
2646
2647 pub fn has_global<G: Global>(&self) -> bool {
2649 self.globals_by_type.contains_key(&TypeId::of::<G>())
2650 }
2651
2652 #[track_caller]
2654 pub fn global<G: Global>(&self) -> &G {
2655 self.globals_by_type
2656 .get(&TypeId::of::<G>())
2657 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2658 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2659 }
2660
2661 pub fn try_global<G: Global>(&self) -> Option<&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 self.globals_by_type
2685 .entry(global_type)
2686 .or_insert_with(|| Box::<G>::default())
2687 .downcast_mut::<G>()
2688 .unwrap()
2689 }
2690
2691 pub fn set_global<G: Global>(&mut self, global: G) {
2693 let global_type = TypeId::of::<G>();
2694 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2695 self.globals_by_type.insert(global_type, Box::new(global));
2696 }
2697
2698 #[cfg(any(test, feature = "test-support"))]
2700 pub fn clear_globals(&mut self) {
2701 self.globals_by_type.drain();
2702 }
2703
2704 pub fn remove_global<G: Global>(&mut self) -> G {
2706 let global_type = TypeId::of::<G>();
2707 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2708 *self
2709 .globals_by_type
2710 .remove(&global_type)
2711 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2712 .downcast()
2713 .unwrap()
2714 }
2715
2716 pub fn observe_global<G: Global>(
2718 &mut self,
2719 mut f: impl FnMut(&mut Self) + 'static,
2720 ) -> Subscription {
2721 let (subscription, activate) = self.global_observers.insert_pending(
2722 TypeId::of::<G>(),
2723 Box::new(move |cx| {
2724 f(cx);
2725 true
2726 }),
2727 );
2728 self.defer(move |_| activate());
2729 subscription
2730 }
2731
2732 #[track_caller]
2734 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2735 GlobalLease::new(
2736 self.globals_by_type
2737 .remove(&TypeId::of::<G>())
2738 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2739 .unwrap(),
2740 )
2741 }
2742
2743 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2745 let global_type = TypeId::of::<G>();
2746
2747 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2748 self.globals_by_type.insert(global_type, lease.global);
2749 }
2750
2751 pub(crate) fn new_entity_observer(
2752 &self,
2753 key: TypeId,
2754 value: NewEntityListener,
2755 ) -> Subscription {
2756 self.new_entity_observers.insert(key, value)
2757 }
2758
2759 pub fn observe_new<T: 'static>(
2762 &self,
2763 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2764 ) -> Subscription {
2765 self.new_entity_observer(
2766 TypeId::of::<T>(),
2767 Box::new(
2768 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2769 any_entity
2770 .downcast::<T>()
2771 .unwrap()
2772 .update(cx, |entity_state, cx| {
2773 on_new(entity_state, window.as_deref_mut(), cx)
2774 })
2775 },
2776 ),
2777 )
2778 }
2779
2780 pub fn observe_release<T>(
2783 &self,
2784 handle: &Entity<T>,
2785 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2786 ) -> Subscription
2787 where
2788 T: 'static,
2789 {
2790 self.release_listeners.insert(
2791 handle.entity_id(),
2792 Box::new(move |entity, cx| {
2793 let entity = entity.downcast_mut().expect("invalid entity type");
2794 on_release(entity, cx)
2795 }),
2796 )
2797 }
2798
2799 pub fn observe_release_in<T>(
2802 &self,
2803 handle: &Entity<T>,
2804 window: &Window,
2805 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2806 ) -> Subscription
2807 where
2808 T: 'static,
2809 {
2810 let window_handle = window.handle;
2811 self.observe_release(handle, move |entity, cx| {
2812 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2813 })
2814 }
2815
2816 pub fn observe_keystrokes(
2821 &mut self,
2822 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2823 ) -> Subscription {
2824 self.keystroke_observers
2825 .insert(Box::new(move |event, window, cx| {
2826 f(event, window, cx);
2827 true
2828 }))
2829 }
2830
2831 pub fn intercept_keystrokes(
2836 &mut self,
2837 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2838 ) -> Subscription {
2839 self.keystroke_interceptors
2840 .insert(Box::new(move |event, window, cx| {
2841 f(event, window, cx);
2842 true
2843 }))
2844 }
2845
2846 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2848 self.keymap.borrow_mut().add_bindings(bindings);
2849 self.pending_effects.push_back(Effect::RefreshWindows);
2850 }
2851
2852 pub fn clear_key_bindings(&mut self) {
2854 self.keymap.borrow_mut().clear();
2855 self.pending_effects.push_back(Effect::RefreshWindows);
2856 }
2857
2858 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2860 self.keymap.clone()
2861 }
2862
2863 pub fn on_action<A: Action>(
2867 &mut self,
2868 listener: impl Fn(&A, &mut Self) + 'static,
2869 ) -> &mut Self {
2870 self.global_action_listeners
2871 .entry(TypeId::of::<A>())
2872 .or_default()
2873 .push(Rc::new(move |action, phase, cx| {
2874 if phase == DispatchPhase::Bubble {
2875 let action = action.downcast_ref().unwrap();
2876 listener(action, cx)
2877 }
2878 }));
2879 self
2880 }
2881
2882 pub fn stop_propagation(&mut self) {
2887 self.propagate_event = false;
2888 }
2889
2890 pub fn propagate(&mut self) {
2895 self.propagate_event = true;
2896 }
2897
2898 pub fn build_action(
2900 &self,
2901 name: &str,
2902 data: Option<serde_json::Value>,
2903 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2904 self.actions.build_action(name, data)
2905 }
2906
2907 pub fn all_action_names(&self) -> &[&'static str] {
2910 self.actions.all_action_names()
2911 }
2912
2913 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2917 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2918 }
2919
2920 #[cfg(feature = "schemars")]
2922 pub fn action_schemas(
2923 &self,
2924 generator: &mut schemars::SchemaGenerator,
2925 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2926 self.actions.action_schemas(generator)
2927 }
2928
2929 #[cfg(feature = "schemars")]
2934 pub fn action_schema_by_name(
2935 &self,
2936 name: &str,
2937 generator: &mut schemars::SchemaGenerator,
2938 ) -> Option<Option<schemars::Schema>> {
2939 self.actions.action_schema_by_name(name, generator)
2940 }
2941
2942 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2944 self.actions.deprecated_aliases()
2945 }
2946
2947 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2949 self.actions.deprecation_messages()
2950 }
2951
2952 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2954 self.actions.documentation()
2955 }
2956
2957 pub fn on_app_quit<Fut>(
2960 &self,
2961 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2962 ) -> Subscription
2963 where
2964 Fut: 'static + Future<Output = ()>,
2965 {
2966 self.quit_observers.insert(Box::new(move |cx| {
2967 let future = on_quit(cx);
2968 future.boxed_local()
2969 }))
2970 }
2971
2972 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2976 self.restart_observers.insert(Box::new(move |cx| {
2977 on_restart(cx);
2978 true
2979 }))
2980 }
2981
2982 pub fn on_window_closed(
2985 &self,
2986 on_closed: impl FnMut(&mut App, WindowId) + 'static,
2987 ) -> Subscription {
2988 self.window_closed_observers.insert(Box::new(on_closed))
2989 }
2990
2991 pub(crate) fn clear_pending_keystrokes(&mut self) {
2992 for window in self.windows() {
2993 window
2994 .update(self, |_, window, cx| {
2995 window.clear_pending_keystrokes(cx);
2996 })
2997 .ok();
2998 }
2999 }
3000
3001 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
3004 let mut action_available = false;
3005 if let Some(window) = self.active_window()
3006 && let Ok(window_action_available) =
3007 window.update(self, |_, window, cx| window.is_action_available(action, cx))
3008 {
3009 action_available = window_action_available;
3010 }
3011
3012 action_available
3013 || self
3014 .global_action_listeners
3015 .contains_key(&action.as_any().type_id())
3016 }
3017
3018 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
3020 let menus: Vec<Menu> = menus.into_iter().collect();
3021 self.platform.set_menus(menus, &self.keymap.borrow());
3022 }
3023
3024 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
3026 self.platform.get_menus()
3027 }
3028
3029 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
3031 self.platform.set_dock_menu(menus, &self.keymap.borrow())
3032 }
3033
3034 pub fn perform_dock_menu_action(&self, action: usize) {
3036 self.platform.perform_dock_menu_action(action);
3037 }
3038
3039 pub fn add_recent_document(&self, path: &Path) {
3044 self.platform.add_recent_document(path);
3045 }
3046
3047 pub fn update_jump_list(
3050 &self,
3051 menus: Vec<MenuItem>,
3052 entries: Vec<SmallVec<[PathBuf; 2]>>,
3053 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
3054 self.platform.update_jump_list(menus, entries)
3055 }
3056
3057 pub fn dispatch_action(&mut self, action: &dyn Action) {
3060 if let Some(active_window) = self.active_window() {
3061 active_window
3062 .update(self, |_, window, cx| {
3063 window.dispatch_action(action.boxed_clone(), cx)
3064 })
3065 .log_err();
3066 } else {
3067 self.dispatch_global_action(action);
3068 }
3069 }
3070
3071 fn dispatch_global_action(&mut self, action: &dyn Action) {
3072 self.propagate_event = true;
3073
3074 if let Some(mut global_listeners) = self
3075 .global_action_listeners
3076 .remove(&action.as_any().type_id())
3077 {
3078 for listener in &global_listeners {
3079 listener(action.as_any(), DispatchPhase::Capture, self);
3080 if !self.propagate_event {
3081 break;
3082 }
3083 }
3084
3085 global_listeners.extend(
3086 self.global_action_listeners
3087 .remove(&action.as_any().type_id())
3088 .unwrap_or_default(),
3089 );
3090
3091 self.global_action_listeners
3092 .insert(action.as_any().type_id(), global_listeners);
3093 }
3094
3095 if self.propagate_event
3096 && let Some(mut global_listeners) = self
3097 .global_action_listeners
3098 .remove(&action.as_any().type_id())
3099 {
3100 for listener in global_listeners.iter().rev() {
3101 listener(action.as_any(), DispatchPhase::Bubble, self);
3102 if !self.propagate_event {
3103 break;
3104 }
3105 }
3106
3107 global_listeners.extend(
3108 self.global_action_listeners
3109 .remove(&action.as_any().type_id())
3110 .unwrap_or_default(),
3111 );
3112
3113 self.global_action_listeners
3114 .insert(action.as_any().type_id(), global_listeners);
3115 }
3116 }
3117
3118 pub fn has_active_drag(&self) -> bool {
3120 self.active_drag.is_some()
3121 }
3122
3123 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3125 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3126 }
3127
3128 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3130 if self.active_drag.is_some() {
3131 self.active_drag = None;
3132 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
3133 drag.source_window == window.window_handle().window_id()
3134 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3135 }) {
3136 self.platform_owned_drag = None;
3137 }
3138 window.refresh();
3139 true
3140 } else {
3141 false
3142 }
3143 }
3144
3145 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3146 let Some(drag) = self.active_drag.take() else {
3147 return false;
3148 };
3149 self.platform_owned_drag = Some(PlatformOwnedDrag {
3150 source_window,
3151 state: PlatformOwnedDragState::Suspended(drag),
3152 });
3153 true
3154 }
3155
3156 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
3157 let Some(platform_drag) = self
3158 .platform_owned_drag
3159 .as_mut()
3160 .filter(|drag| drag.source_window == source_window)
3161 else {
3162 return false;
3163 };
3164 let state = std::mem::replace(
3165 &mut platform_drag.state,
3166 PlatformOwnedDragState::RestoredInSourceWindow,
3167 );
3168 let PlatformOwnedDragState::Suspended(drag) = state else {
3169 return false;
3170 };
3171 self.active_drag = Some(drag);
3172 true
3173 }
3174
3175 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3176 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
3177 drag.source_window == source_window
3178 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3179 }) else {
3180 return false;
3181 };
3182 let Some(drag) = self.active_drag.take() else {
3183 return false;
3184 };
3185 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
3186 true
3187 }
3188
3189 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
3190 if !self
3191 .platform_owned_drag
3192 .as_ref()
3193 .is_some_and(|drag| drag.source_window == source_window)
3194 {
3195 return false;
3196 }
3197 self.platform_owned_drag = None;
3198 self.active_drag = None;
3199 true
3200 }
3201
3202 pub fn set_active_drag_cursor_style(
3204 &mut self,
3205 cursor_style: CursorStyle,
3206 window: &mut Window,
3207 ) -> bool {
3208 if let Some(ref mut drag) = self.active_drag {
3209 drag.cursor_style = Some(cursor_style);
3210 window.refresh();
3211 true
3212 } else {
3213 false
3214 }
3215 }
3216
3217 pub fn set_prompt_builder(
3220 &mut self,
3221 renderer: impl Fn(
3222 PromptLevel,
3223 &str,
3224 Option<&str>,
3225 &[PromptButton],
3226 PromptHandle,
3227 &mut Window,
3228 &mut App,
3229 ) -> RenderablePromptHandle
3230 + 'static,
3231 ) {
3232 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3233 }
3234
3235 pub fn reset_prompt_builder(&mut self) {
3237 self.prompt_builder = Some(PromptBuilder::Default);
3238 }
3239
3240 pub fn image_asset_stats(&self) -> (usize, usize, usize, u64) {
3246 type ImageLoad = CachedLoad<Result<Arc<RenderImage>, crate::ImageCacheError>>;
3247 let (mut images, mut decoded, mut bytes) = (0, 0, 0u64);
3248 for entry in self.loading_assets.values() {
3249 let Some(load) = entry.downcast_ref::<ImageLoad>() else { continue };
3250 images += 1;
3251 if let Some(Ok(image)) = load.get() {
3252 decoded += 1;
3253 for i in 0..image.frame_count() {
3254 let size = image.size(i);
3255 bytes += (size.width.0.max(0) as u64) * (size.height.0.max(0) as u64) * 4;
3256 }
3257 }
3258 }
3259 (self.loading_assets.len(), images, decoded, bytes)
3260 }
3261
3262 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3264 let asset_id = (TypeId::of::<A>(), hash(source));
3265 self.loading_assets.remove(&asset_id);
3266 }
3267
3268 pub fn peek_asset<A: Asset>(&self, source: &A::Source) -> Option<A::Output> {
3271 let asset_id = (TypeId::of::<A>(), hash(source));
3272 self.loading_assets
3273 .get(&asset_id)?
3274 .downcast_ref::<CachedLoad<A::Output>>()?
3275 .get()
3276 }
3277
3278 pub fn replace_asset<A: Asset>(&mut self, source: &A::Source, output: A::Output) -> bool {
3282 let asset_id = (TypeId::of::<A>(), hash(source));
3283 let in_flight = self
3284 .loading_assets
3285 .get(&asset_id)
3286 .and_then(|entry| entry.downcast_ref::<CachedLoad<A::Output>>())
3287 .is_some_and(|load| !load.is_loaded());
3288 if in_flight {
3289 return false;
3290 }
3291 self.loading_assets
3292 .insert(asset_id, Box::new(CachedLoad::ready(output)));
3293 true
3294 }
3295
3296 #[cfg(any(test, feature = "test-support"))]
3299 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3300 let asset_id = (TypeId::of::<A>(), hash(source));
3301 self.loading_assets.contains_key(&asset_id)
3302 }
3303
3304 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3309 self.asset_entry::<A>(source).get()
3310 }
3311
3312 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3313 let asset_id = (TypeId::of::<A>(), hash(source));
3314 if !self.loading_assets.contains_key(&asset_id) {
3315 let future = A::load(source.clone(), self);
3316 let entry = CachedLoad::new(future, self);
3317 self.loading_assets.insert(asset_id, Box::new(entry));
3318 }
3319 self.loading_assets
3320 .get(&asset_id)
3321 .and_then(|entry| entry.downcast_ref())
3322 .expect("asset cache entries are keyed by their asset type")
3323 }
3324
3325 #[track_caller]
3328 pub fn focus_handle(&self) -> FocusHandle {
3329 FocusHandle::new(&self.focus_handles)
3330 }
3331
3332 pub fn notify(&mut self, entity_id: EntityId) {
3334 let window_invalidators = mem::take(
3335 self.window_invalidators_by_entity
3336 .entry(entity_id)
3337 .or_default(),
3338 );
3339
3340 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3345 .iter()
3346 .filter(|(window_id, _)| {
3347 self.tracked_entities
3348 .get(window_id)
3349 .is_some_and(|set| set.contains(&entity_id))
3350 })
3351 .map(|(_, invalidator)| invalidator.clone())
3352 .collect();
3353
3354 if live_invalidators.is_empty() {
3355 if self.pending_notifications.insert(entity_id) {
3356 self.pending_effects
3357 .push_back(Effect::Notify { emitter: entity_id });
3358 }
3359 } else {
3360 for invalidator in &live_invalidators {
3361 invalidator.invalidate_view(entity_id, self);
3362 }
3363 }
3364
3365 self.window_invalidators_by_entity
3366 .insert(entity_id, window_invalidators);
3367 }
3368
3369 #[cfg(any(test, feature = "test-support", debug_assertions))]
3371 pub fn get_name(&self) -> Option<&'static str> {
3372 self.name
3373 }
3374
3375 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3377 self.platform.can_select_mixed_files_and_dirs()
3378 }
3379
3380 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3385 for window in self.windows.values_mut().flatten() {
3387 _ = window.drop_image(image.clone());
3388 }
3389
3390 if let Some(window) = current_window {
3392 _ = window.drop_image(image);
3393 }
3394 }
3395
3396 #[cfg(any(feature = "inspector", debug_assertions))]
3398 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3399 self.inspector_renderer = Some(f);
3400 }
3401
3402 #[cfg(any(feature = "inspector", debug_assertions))]
3404 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3405 &mut self,
3406 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3407 ) where
3408 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3409 {
3410 self.inspector_element_registry.register(factory);
3411 }
3412
3413 pub fn init_colors(&mut self) {
3417 self.set_global(GlobalColors(Arc::new(Colors::default())));
3418 }
3419
3420 #[inline(never)]
3421 fn update_window_erased(
3422 &mut self,
3423 window_id: WindowId,
3424 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3425 ) {
3426 self.update(|cx| {
3427 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3428 update(None);
3429 return;
3430 };
3431
3432 let root_view = window.root.clone().unwrap();
3433
3434 cx.window_update_stack.push(WindowUpdateEntry {
3435 window_id: window.handle.id,
3436 bounds: window.last_window_bounds(),
3437 display_id: window.display_id(),
3438 });
3439 update(Some((root_view, &mut window, cx)));
3440 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3441 cx.window_update_stack.pop();
3442
3443 if window.removed {
3444 cx.end_platform_drag(window_id);
3445 cx.window_handles.remove(&window_id);
3446 cx.windows.remove(window_id);
3447 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3448 for entity_id in tracked {
3449 if let Some(windows) =
3450 cx.window_invalidators_by_entity.get_mut(&entity_id)
3451 {
3452 windows.remove(&window_id);
3453 }
3454 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3455 cx.current_window_by_entity.remove(&entity_id);
3456 }
3457 }
3458 }
3459
3460 cx.window_closed_observers.clone().retain(|callback| {
3461 callback(cx, window_id);
3462 true
3463 });
3464
3465 let quit_on_empty = match cx.quit_mode {
3466 QuitMode::Explicit => false,
3467 QuitMode::LastWindowClosed => true,
3468 QuitMode::Default => cfg!(not(target_os = "macos")),
3469 };
3470
3471 if quit_on_empty && cx.windows.is_empty() {
3472 cx.quit();
3473 }
3474 } else {
3475 cx.windows.get_mut(window_id)?.replace(window);
3476 }
3477 Some(())
3478 }
3479 if trail(window_id, window, cx).is_none() {
3480 update(None);
3481 }
3482 });
3483 }
3484
3485 #[inline(never)]
3486 fn update_entity_erased(
3487 &mut self,
3488 handle: &AnyEntity,
3489 entity_type: &str,
3490 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3491 ) {
3492 self.update(|cx| {
3493 let mut lease = cx.entities.lease_erased(handle, entity_type);
3494 update(lease.entity.as_deref_mut().unwrap(), cx);
3495 cx.entities.end_lease_erased(handle.entity_id, lease);
3496 });
3497 }
3498
3499 #[inline(never)]
3500 #[track_caller]
3501 fn prepare_spawn(&self) -> AsyncApp {
3502 if self.quitting {
3503 debug_panic!("Can't spawn on main thread after on_app_quit")
3504 };
3505 self.to_async()
3506 }
3507}
3508
3509impl AppContext for App {
3510 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3515 self.update(|cx| {
3516 let slot = cx.entities.reserve();
3517 let handle = slot.clone();
3518 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3519
3520 cx.push_effect(Effect::EntityCreated {
3521 entity: handle.into_any(),
3522 tid: TypeId::of::<T>(),
3523 window: cx.window_update_stack.last().map(|state| state.window_id),
3524 });
3525
3526 cx.entities.insert(slot, entity)
3527 })
3528 }
3529
3530 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3531 Reservation(self.entities.reserve())
3532 }
3533
3534 fn insert_entity<T: 'static>(
3535 &mut self,
3536 reservation: Reservation<T>,
3537 build_entity: impl FnOnce(&mut Context<T>) -> T,
3538 ) -> Entity<T> {
3539 self.update(|cx| {
3540 let slot = reservation.0;
3541 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3542 cx.entities.insert(slot, entity)
3543 })
3544 }
3545
3546 #[inline(always)]
3549 fn update_entity<T: 'static, R>(
3550 &mut self,
3551 handle: &Entity<T>,
3552 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3553 ) -> R {
3554 let mut update = Some(update);
3555 let mut result = None;
3556 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3557 let value = update.take().unwrap()(
3558 entity.downcast_mut::<T>().unwrap(),
3559 &mut Context::new_context(cx, handle.downgrade()),
3560 );
3561 result = Some(value);
3562 });
3563 result.unwrap()
3564 }
3565
3566 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3567 where
3568 T: 'static,
3569 {
3570 GpuiBorrow::new(handle.clone(), self)
3571 }
3572
3573 #[inline(always)]
3574 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3575 where
3576 T: 'static,
3577 {
3578 let entity = self.entities.read(handle);
3579 read(entity, self)
3580 }
3581
3582 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3583 where
3584 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3585 {
3586 self.update_window_id(handle.id, update)
3587 }
3588
3589 fn with_window<R>(
3590 &mut self,
3591 entity_id: EntityId,
3592 f: impl FnOnce(&mut Window, &mut App) -> R,
3593 ) -> Option<R> {
3594 App::with_window(self, entity_id, f)
3595 }
3596
3597 fn read_window<T, R>(
3598 &self,
3599 window: &WindowHandle<T>,
3600 read: impl FnOnce(Entity<T>, &App) -> R,
3601 ) -> Result<R>
3602 where
3603 T: 'static,
3604 {
3605 let window = self
3606 .windows
3607 .get(window.id)
3608 .context("window not found")?
3609 .as_deref()
3610 .expect("attempted to read a window that is already on the stack");
3611
3612 let root_view = window.root.clone().unwrap();
3613 let view = root_view
3614 .downcast::<T>()
3615 .map_err(|_| anyhow!("root view's type has changed"))?;
3616
3617 Ok(read(view, self))
3618 }
3619
3620 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3621 where
3622 R: Send + 'static,
3623 {
3624 self.background_executor.spawn(future)
3625 }
3626
3627 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3628 where
3629 G: Global,
3630 {
3631 let g = self.global::<G>();
3632 callback(g, self)
3633 }
3634}
3635
3636pub(crate) enum Effect {
3638 Notify {
3639 emitter: EntityId,
3640 },
3641 Emit {
3642 emitter: EntityId,
3643 event_type: TypeId,
3644 event: ArenaBox<dyn Any>,
3645 },
3646 RefreshWindows,
3647 NotifyGlobalObservers {
3648 global_type: TypeId,
3649 },
3650 Defer {
3651 callback: Box<dyn FnOnce(&mut App) + 'static>,
3652 },
3653 EntityCreated {
3654 entity: AnyEntity,
3655 tid: TypeId,
3656 window: Option<WindowId>,
3657 },
3658}
3659
3660impl std::fmt::Debug for Effect {
3661 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3662 match self {
3663 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3664 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3665 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3666 Effect::NotifyGlobalObservers { global_type } => {
3667 write!(f, "NotifyGlobalObservers({:?})", global_type)
3668 }
3669 Effect::Defer { .. } => write!(f, "Defer(..)"),
3670 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3671 }
3672 }
3673}
3674
3675pub(crate) struct GlobalLease<G: Global> {
3677 global: Box<dyn Any>,
3678 global_type: PhantomData<G>,
3679}
3680
3681impl<G: Global> GlobalLease<G> {
3682 fn new(global: Box<dyn Any>) -> Self {
3683 GlobalLease {
3684 global,
3685 global_type: PhantomData,
3686 }
3687 }
3688}
3689
3690impl<G: Global> Deref for GlobalLease<G> {
3691 type Target = G;
3692
3693 fn deref(&self) -> &Self::Target {
3694 self.global.downcast_ref().unwrap()
3695 }
3696}
3697
3698impl<G: Global> DerefMut for GlobalLease<G> {
3699 fn deref_mut(&mut self) -> &mut Self::Target {
3700 self.global.downcast_mut().unwrap()
3701 }
3702}
3703
3704pub struct AnyDrag {
3707 pub view: AnyView,
3709
3710 pub value: Arc<dyn Any>,
3712
3713 pub cursor_offset: Point<Pixels>,
3716
3717 pub cursor_style: Option<CursorStyle>,
3719
3720 pub external_payload_source: Option<ExternalDragPayloadSource>,
3723}
3724
3725pub type ExternalDragPayloadSource =
3728 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3729
3730#[derive(Clone)]
3733pub struct AnyTooltip {
3734 pub view: AnyView,
3736
3737 pub mouse_position: Point<Pixels>,
3739
3740 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3744}
3745
3746#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3748pub enum InputPreference {
3749 CharacterInput,
3751 KeyBindings,
3753}
3754
3755#[derive(Debug)]
3757pub struct KeystrokeEvent {
3758 pub keystroke: Keystroke,
3760
3761 pub input_preference: InputPreference,
3769
3770 pub action: Option<Box<dyn Action>>,
3772
3773 pub context_stack: Vec<KeyContext>,
3775}
3776
3777struct NullHttpClient;
3778
3779impl HttpClient for NullHttpClient {
3780 fn send(
3781 &self,
3782 _req: http_client::Request<http_client::AsyncBody>,
3783 ) -> futures::future::BoxFuture<
3784 'static,
3785 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3786 > {
3787 async move {
3788 anyhow::bail!("No HttpClient available");
3789 }
3790 .boxed()
3791 }
3792
3793 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3794 None
3795 }
3796
3797 fn proxy(&self) -> Option<&Url> {
3798 None
3799 }
3800}
3801
3802pub struct GpuiBorrow<'a, T> {
3804 inner: Option<Lease<T>>,
3805 app: &'a mut App,
3806}
3807
3808impl<'a, T: 'static> GpuiBorrow<'a, T> {
3809 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3810 app.start_update();
3811 let lease = app.entities.lease(&inner);
3812 Self {
3813 inner: Some(lease),
3814 app,
3815 }
3816 }
3817}
3818
3819impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3820 fn borrow(&self) -> &T {
3821 self.inner.as_ref().unwrap().borrow()
3822 }
3823}
3824
3825impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3826 fn borrow_mut(&mut self) -> &mut T {
3827 self.inner.as_mut().unwrap().borrow_mut()
3828 }
3829}
3830
3831impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3832 type Target = T;
3833
3834 fn deref(&self) -> &Self::Target {
3835 self.inner.as_ref().unwrap()
3836 }
3837}
3838
3839impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3840 fn deref_mut(&mut self) -> &mut T {
3841 self.inner.as_mut().unwrap()
3842 }
3843}
3844
3845impl<'a, T> Drop for GpuiBorrow<'a, T> {
3846 fn drop(&mut self) {
3847 let lease = self.inner.take().unwrap();
3848 self.app.notify(lease.id);
3849 self.app.entities.end_lease(lease);
3850 self.app.finish_update();
3851 }
3852}
3853
3854#[cfg(test)]
3855mod test {
3856 use std::{
3857 cell::{Cell, RefCell},
3858 ffi::OsString,
3859 path::PathBuf,
3860 rc::Rc,
3861 };
3862
3863 #[cfg(unix)]
3864 use std::os::unix::ffi::OsStringExt;
3865
3866 use crate::{
3867 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3868 TestAppContext, Window,
3869 };
3870
3871 #[gpui::test]
3872 fn app_borrow_diagnostics(cx: &mut TestAppContext) {
3873 use std::panic::{AssertUnwindSafe, catch_unwind};
3874
3875 let app = cx.app.clone();
3876 let first_line = line!() + 1;
3877 let first = app.borrow();
3878 let second = app.borrow();
3879 drop(first);
3880 assert!(app.try_borrow_mut().is_err());
3881 let attempted_line = line!() + 1;
3882 let panic = catch_unwind(AssertUnwindSafe(|| drop(app.borrow_mut())));
3883 let message = *panic
3884 .expect_err("conflicting borrow")
3885 .downcast::<String>()
3886 .unwrap();
3887 assert!(message.contains(&format!(
3888 "mutable App borrow at {}:{attempted_line}:",
3889 file!()
3890 )));
3891 assert!(message.contains(&format!(
3892 "shared borrow group began at {}:{first_line}:",
3893 file!()
3894 )));
3895 drop(second);
3896
3897 let origin_line = line!() + 2;
3898 let panic = catch_unwind(AssertUnwindSafe(|| {
3899 let _borrow = app.try_borrow_mut().expect("initial borrow");
3900 drop(app.borrow());
3901 }));
3902 let message = *panic
3903 .expect_err("conflicting borrow")
3904 .downcast::<String>()
3905 .unwrap();
3906 assert!(message.contains("attempted shared App borrow"));
3907 assert!(message.contains(&format!(
3908 "mutable borrow group began at {}:{origin_line}:",
3909 file!()
3910 )));
3911
3912 let next_line = line!() + 1;
3913 let _borrow = app.borrow();
3914 assert_eq!(
3915 app.borrow_origin.get().expect("new origin").0.line(),
3916 next_line
3917 );
3918 }
3919
3920 struct RenderCounter(Rc<Cell<usize>>);
3921
3922 impl Render for RenderCounter {
3923 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3924 self.0.set(self.0.get() + 1);
3925 Empty
3926 }
3927 }
3928
3929 #[gpui::test]
3930 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3931 let render_count = Rc::new(Cell::new(0));
3932
3933 let _window = cx.add_window({
3934 let render_count = render_count.clone();
3935 move |_, _| RenderCounter(render_count)
3936 });
3937
3938 cx.run_until_parked();
3939 let render_count_before_refresh = render_count.get();
3940
3941 cx.to_async().refresh();
3942
3943 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3944 }
3945
3946 #[gpui::test]
3947 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3948 let observed = Rc::new(RefCell::new(Vec::new()));
3949 let subscription = cx.update(|cx| {
3950 let observed = observed.clone();
3951 cx.on_missing_glyphs(move |missing_glyphs, _| {
3952 observed.borrow_mut().extend_from_slice(missing_glyphs);
3953 })
3954 });
3955 cx.update(|cx| {
3956 cx.text_system()
3957 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3958 });
3959 cx.run_until_parked();
3960 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3961
3962 let second_observed = Rc::new(RefCell::new(Vec::new()));
3963 let second_subscription = cx.update(|cx| {
3964 let second_observed = second_observed.clone();
3965 cx.on_missing_glyphs(move |missing_glyphs, _| {
3966 second_observed
3967 .borrow_mut()
3968 .extend_from_slice(missing_glyphs);
3969 })
3970 });
3971 cx.update(|cx| {
3972 cx.text_system()
3973 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3974 });
3975 cx.run_until_parked();
3976 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3977 assert_eq!(
3978 second_observed.borrow().as_slice(),
3979 &[missing_glyph("replacement")]
3980 );
3981
3982 drop(subscription);
3983 cx.update(|cx| {
3984 cx.text_system()
3985 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3986 });
3987 cx.run_until_parked();
3988 assert_eq!(
3989 second_observed.borrow().as_slice(),
3990 &[
3991 missing_glyph("replacement"),
3992 missing_glyph("after old drop")
3993 ]
3994 );
3995
3996 drop(second_subscription);
3997 cx.update(|cx| {
3998 cx.text_system()
3999 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
4000 });
4001 cx.run_until_parked();
4002 assert_eq!(second_observed.borrow().len(), 2);
4003 }
4004
4005 #[test]
4006 fn test_gpui_borrow() {
4007 let cx = TestAppContext::single();
4008 let observation_count = Rc::new(RefCell::new(0));
4009
4010 let state = cx.update(|cx| {
4011 let state = cx.new(|_| false);
4012 cx.observe(&state, {
4013 let observation_count = observation_count.clone();
4014 move |_, _| {
4015 let mut count = observation_count.borrow_mut();
4016 *count += 1;
4017 }
4018 })
4019 .detach();
4020
4021 state
4022 });
4023
4024 cx.update(|cx| {
4025 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
4027 });
4028
4029 cx.update(|cx| {
4030 state.write(cx, false);
4031 });
4032
4033 assert_eq!(*observation_count.borrow(), 2);
4034 }
4035
4036 #[gpui::test]
4037 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
4038 #[cfg(unix)]
4039 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
4040 #[cfg(not(unix))]
4041 let user_data_dir = OsString::from("C:\\zed data");
4042 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
4043 let restart_path = PathBuf::from("updated-zed");
4044 let _application =
4045 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
4046 let restart = cx.expect_restart();
4047
4048 cx.update(|cx| {
4049 cx.set_restart_path(restart_path.clone());
4050 cx.restart();
4051 });
4052
4053 let (path, restart_arguments) = restart.await.expect("restart was not requested");
4054 assert_eq!(path, Some(restart_path));
4055 assert_eq!(restart_arguments, arguments);
4056 }
4057
4058 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
4059 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
4060 }
4061}