1use scheduler::Instant;
3use std::{
4 any::{TypeId, type_name},
5 cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
6 ffi::OsString,
7 marker::PhantomData,
8 mem,
9 ops::{Deref, DerefMut},
10 path::{Path, PathBuf},
11 rc::{Rc, Weak},
12 sync::{Arc, atomic::Ordering::SeqCst},
13 time::Duration,
14};
15
16use anyhow::{Context as _, Result, anyhow};
17use derive_more::{Deref, DerefMut};
18use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
19use itertools::Itertools;
20use parking_lot::RwLock;
21use slotmap::SlotMap;
22
23pub use async_context::*;
24#[cfg(feature = "bench-support")]
25pub use bench_context::{
26 BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
27 MetricReport, bench_platform,
28};
29use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
30pub use context::*;
31pub use entity_map::*;
32use gpui_util::{ResultExt, debug_panic};
33#[cfg(any(test, feature = "test-support"))]
34pub use headless_app_context::*;
35use http_client::{HttpClient, Url};
36use smallvec::SmallVec;
37#[cfg(any(test, feature = "test-support"))]
38pub use test_app::*;
39#[cfg(any(test, feature = "test-support"))]
40pub use test_context::*;
41#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
42pub use visual_test_context::*;
43
44#[cfg(any(feature = "inspector", debug_assertions))]
45use crate::InspectorElementRegistry;
46use crate::asset_cache::CachedLoad;
47use crate::{
48 Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
49 AnyWindowHandle, AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds,
50 ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase, DisplayChanges, DisplayEvent,
51 DisplayId, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap, ForegroundExecutor,
52 Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu, MenuItem, MissingGlyph,
53 OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
54 PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton, PromptHandle,
55 PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource,
56 SharedString, SubscriberSet, Subscription, SvgRenderer, SystemNotification,
57 SystemNotificationResponse, Task, TextRenderingMode, TextSystem, ThermalState, Window,
58 WindowAppearance, WindowButtonLayout, WindowHandle, WindowId, WindowInvalidator,
59 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}
88
89impl AppCell {
90 #[doc(hidden)]
91 #[track_caller]
92 pub fn borrow(&self) -> AppRef<'_> {
93 if option_env!("TRACK_THREAD_BORROWS").is_some() {
94 let thread_id = std::thread::current().id();
95 eprintln!("borrowed {thread_id:?}");
96 }
97 AppRef(self.app.borrow())
98 }
99
100 #[doc(hidden)]
101 #[track_caller]
102 pub fn borrow_mut(&self) -> AppRefMut<'_> {
103 if option_env!("TRACK_THREAD_BORROWS").is_some() {
104 let thread_id = std::thread::current().id();
105 eprintln!("borrowed {thread_id:?}");
106 }
107 AppRefMut(self.app.borrow_mut())
108 }
109
110 #[doc(hidden)]
111 #[track_caller]
112 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
113 if option_env!("TRACK_THREAD_BORROWS").is_some() {
114 let thread_id = std::thread::current().id();
115 eprintln!("borrowed {thread_id:?}");
116 }
117 Ok(AppRefMut(self.app.try_borrow_mut()?))
118 }
119}
120
121#[doc(hidden)]
122#[derive(Deref, DerefMut)]
123pub struct AppRef<'a>(Ref<'a, App>);
124
125impl Drop for AppRef<'_> {
126 fn drop(&mut self) {
127 if option_env!("TRACK_THREAD_BORROWS").is_some() {
128 let thread_id = std::thread::current().id();
129 eprintln!("dropped borrow from {thread_id:?}");
130 }
131 }
132}
133
134#[doc(hidden)]
135#[derive(Deref, DerefMut)]
136pub struct AppRefMut<'a>(RefMut<'a, App>);
137
138impl Drop for AppRefMut<'_> {
139 fn drop(&mut self) {
140 if option_env!("TRACK_THREAD_BORROWS").is_some() {
141 let thread_id = std::thread::current().id();
142 eprintln!("dropped {thread_id:?}");
143 }
144 }
145}
146
147pub struct Application(Rc<AppCell>);
150
151pub struct ApplicationHandle {
157 app: Rc<AppCell>,
158}
159
160impl ApplicationHandle {
161 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
165 let cx = &mut *self.app.borrow_mut();
166 f(cx)
167 }
168
169 pub fn to_async(&self) -> AsyncApp {
172 self.update(|cx| cx.to_async())
173 }
174}
175
176impl Application {
179 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
181 Self(App::new_app(
182 platform,
183 Arc::new(()),
184 Arc::new(NullHttpClient),
185 ))
186 }
187
188 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
198 let this = Self::with_platform(platform);
199 this.0.borrow_mut().accessibility_force_disabled = true;
200 this
201 }
202
203 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
205 let mut context_lock = self.0.borrow_mut();
206 let asset_source = Arc::new(asset_source);
207 context_lock.asset_source = asset_source.clone();
208 context_lock.svg_renderer = SvgRenderer::new(asset_source);
209 drop(context_lock);
210 self
211 }
212
213 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
215 self.0.borrow_mut().restart_arguments = arguments;
216 self
217 }
218
219 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
221 let mut context_lock = self.0.borrow_mut();
222 context_lock.http_client = http_client;
223 drop(context_lock);
224 self
225 }
226
227 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
230 self.0.borrow_mut().quit_mode = mode;
231 self
232 }
233
234 pub fn with_windowing(self, request: WindowingRequest) -> Self {
241 self.0.borrow().platform.set_initial_windowing(request);
242 self
243 }
244
245 pub fn run<F>(self, on_finish_launching: F)
251 where
252 F: 'static + FnOnce(&mut App),
253 {
254 let this = self.0.clone();
255 let platform = self.0.borrow().platform.clone();
256 platform.run(Box::new(move || {
257 let cx = &mut *this.borrow_mut();
258 cx.displays_changed();
260 on_finish_launching(cx);
261 }));
262
263 #[cfg(target_family = "wasm")]
264 std::mem::forget(self);
265 }
266
267 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
277 where
278 F: 'static + FnOnce(&mut App),
279 {
280 let this = self.0.clone();
281 let platform = self.0.borrow().platform.clone();
282 platform.run(Box::new(move || {
283 let cx = &mut *this.borrow_mut();
284 cx.displays_changed();
286 on_finish_launching(cx);
287 }));
288 ApplicationHandle { app: self.0 }
289 }
290
291 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
294 where
295 F: 'static + FnMut(Vec<String>),
296 {
297 self.0.borrow().platform.on_open_urls(Box::new(callback));
298 self
299 }
300
301 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
304 where
305 F: 'static + FnMut(&mut App),
306 {
307 let this = Rc::downgrade(&self.0);
308 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
309 if let Some(app) = this.upgrade() {
310 callback(&mut app.borrow_mut());
311 }
312 }));
313 self
314 }
315
316 pub fn background_executor(&self) -> BackgroundExecutor {
318 self.0.borrow().background_executor.clone()
319 }
320
321 pub fn foreground_executor(&self) -> ForegroundExecutor {
323 self.0.borrow().foreground_executor.clone()
324 }
325
326 pub fn text_system(&self) -> Arc<TextSystem> {
328 self.0.borrow().text_system.clone()
329 }
330
331 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
333 self.0.borrow().path_for_auxiliary_executable(name)
334 }
335}
336
337type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
338type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
339
340#[derive(Clone, Copy, PartialEq)]
342struct DisplayState {
343 bounds: Bounds<Pixels>,
344 refresh_interval: Option<Duration>,
345}
346
347impl DisplayState {
348 fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
349 let mut changes = DisplayChanges::empty();
350 changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
351 changes.set(
352 DisplayChanges::REFRESH_INTERVAL,
353 self.refresh_interval != previous.refresh_interval,
354 );
355 changes
356 }
357}
358
359fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
360 platform
361 .displays()
362 .into_iter()
363 .map(|display| {
364 let state = DisplayState {
365 bounds: display.bounds(),
366 refresh_interval: display.refresh_interval(),
367 };
368 (display.id(), state)
369 })
370 .collect()
371}
372
373fn display_events(
375 previous: &HashMap<DisplayId, DisplayState>,
376 current: &HashMap<DisplayId, DisplayState>,
377) -> Vec<DisplayEvent> {
378 let removed = previous
379 .keys()
380 .filter(|id| !current.contains_key(id))
381 .map(|id| DisplayEvent::Removed(*id));
382 let added_or_changed = current.iter().filter_map(|(id, state)| {
383 let Some(previous_state) = previous.get(id) else {
384 return Some(DisplayEvent::Added(*id));
385 };
386 let changes = state.changes_from(previous_state);
387 (!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
388 });
389 removed.chain(added_or_changed).collect()
390}
391type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
392type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
393pub(crate) type KeystrokeObserver =
394 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
395type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
396type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
397type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
398type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
399
400struct MissingGlyphCallbackEntry {
401 registration: Rc<()>,
402 callback: Option<MissingGlyphCallback>,
403}
404
405#[derive(Default)]
406struct MissingGlyphCallbackSlot {
407 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
408}
409
410impl MissingGlyphCallbackSlot {
411 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
412 let registration = Rc::new(());
413 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
414 registration: registration.clone(),
415 callback: Some(callback),
416 });
417 registration
418 }
419
420 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
421 let Some((registration, mut callback)) =
422 self.entry.borrow_mut().as_mut().and_then(|entry| {
423 entry
424 .callback
425 .take()
426 .map(|callback| (entry.registration.clone(), callback))
427 })
428 else {
429 return;
430 };
431 callback(missing_glyphs, cx);
432
433 let mut entry = self.entry.borrow_mut();
434 let is_current = entry
435 .as_ref()
436 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
437 if is_current {
438 let Some(entry) = entry.as_mut() else {
439 return;
440 };
441 entry.callback = Some(callback);
442 }
443 }
444
445 fn remove(&self, registration: &Rc<()>) -> bool {
446 let mut entry = self.entry.borrow_mut();
447 let is_current = entry
448 .as_ref()
449 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
450 if is_current {
451 entry.take();
452 }
453 is_current
454 }
455}
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
459pub enum QuitMode {
460 #[default]
462 Default,
463 LastWindowClosed,
465 Explicit,
467}
468
469#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
474pub enum CursorHideMode {
475 Never,
477 OnTyping,
479 #[default]
482 OnTypingAndAction,
483}
484
485#[doc(hidden)]
486#[derive(Clone, PartialEq, Eq)]
487pub struct SystemWindowTab {
488 pub id: WindowId,
489 pub title: SharedString,
490 pub handle: AnyWindowHandle,
491 pub last_active_at: Instant,
492}
493
494impl SystemWindowTab {
495 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
497 Self {
498 id: handle.id,
499 title,
500 handle,
501 last_active_at: Instant::now(),
502 }
503 }
504}
505
506#[derive(Default)]
508pub struct SystemWindowTabController {
509 visible: Option<bool>,
510 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
511}
512
513impl Global for SystemWindowTabController {}
514
515impl SystemWindowTabController {
516 pub fn new() -> Self {
518 Self {
519 visible: None,
520 tab_groups: FxHashMap::default(),
521 }
522 }
523
524 pub fn init(cx: &mut App) {
526 cx.set_global(SystemWindowTabController::new());
527 }
528
529 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
531 &self.tab_groups
532 }
533
534 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
536 let controller = cx.global::<SystemWindowTabController>();
537 let current_group = controller
538 .tab_groups
539 .iter()
540 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
541
542 let current_group = current_group?;
543 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
545 let idx = group_ids.iter().position(|g| *g == current_group)?;
546 let next_idx = (idx + 1) % group_ids.len();
547
548 controller
549 .tab_groups
550 .get(group_ids[next_idx])
551 .and_then(|tabs| {
552 tabs.iter()
553 .max_by_key(|tab| tab.last_active_at)
554 .or_else(|| tabs.first())
555 .map(|tab| &tab.handle)
556 })
557 }
558
559 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
561 let controller = cx.global::<SystemWindowTabController>();
562 let current_group = controller
563 .tab_groups
564 .iter()
565 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
566
567 let current_group = current_group?;
568 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
570 let idx = group_ids.iter().position(|g| *g == current_group)?;
571 let prev_idx = if idx == 0 {
572 group_ids.len() - 1
573 } else {
574 idx - 1
575 };
576
577 controller
578 .tab_groups
579 .get(group_ids[prev_idx])
580 .and_then(|tabs| {
581 tabs.iter()
582 .max_by_key(|tab| tab.last_active_at)
583 .or_else(|| tabs.first())
584 .map(|tab| &tab.handle)
585 })
586 }
587
588 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
590 self.tab_groups
591 .values()
592 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
593 }
594
595 pub fn init_visible(cx: &mut App, visible: bool) {
597 let mut controller = cx.global_mut::<SystemWindowTabController>();
598 if controller.visible.is_none() {
599 controller.visible = Some(visible);
600 }
601 }
602
603 pub fn is_visible(&self) -> bool {
605 self.visible.unwrap_or(false)
606 }
607
608 pub fn set_visible(cx: &mut App, visible: bool) {
610 let mut controller = cx.global_mut::<SystemWindowTabController>();
611 controller.visible = Some(visible);
612 }
613
614 pub fn update_last_active(cx: &mut App, id: WindowId) {
616 let mut controller = cx.global_mut::<SystemWindowTabController>();
617 for windows in controller.tab_groups.values_mut() {
618 for tab in windows.iter_mut() {
619 if tab.id == id {
620 tab.last_active_at = Instant::now();
621 }
622 }
623 }
624 }
625
626 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
628 let mut controller = cx.global_mut::<SystemWindowTabController>();
629 for (_, windows) in controller.tab_groups.iter_mut() {
630 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
631 if ix < windows.len() && current_pos != ix {
632 let window_tab = windows.remove(current_pos);
633 windows.insert(ix, window_tab);
634 }
635 break;
636 }
637 }
638 }
639
640 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
642 let controller = cx.global::<SystemWindowTabController>();
643 let tab = controller
644 .tab_groups
645 .values()
646 .flat_map(|windows| windows.iter())
647 .find(|tab| tab.id == id);
648
649 if tab.map_or(true, |t| t.title == title) {
650 return;
651 }
652
653 let mut controller = cx.global_mut::<SystemWindowTabController>();
654 for windows in controller.tab_groups.values_mut() {
655 for tab in windows.iter_mut() {
656 if tab.id == id {
657 tab.title = title;
658 return;
659 }
660 }
661 }
662 }
663
664 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
666 let mut controller = cx.global_mut::<SystemWindowTabController>();
667 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
668 return;
669 };
670
671 let mut expected_tab_ids: Vec<_> = tabs
672 .iter()
673 .filter(|tab| tab.id != id)
674 .map(|tab| tab.id)
675 .sorted()
676 .collect();
677
678 let mut tab_group_id = None;
679 for (group_id, group_tabs) in &controller.tab_groups {
680 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
681 if tab_ids == expected_tab_ids {
682 tab_group_id = Some(*group_id);
683 break;
684 }
685 }
686
687 if let Some(tab_group_id) = tab_group_id {
688 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
689 tabs.push(tab);
690 }
691 } else {
692 let new_group_id = controller.tab_groups.len();
693 controller.tab_groups.insert(new_group_id, tabs);
694 }
695 }
696
697 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
699 let mut controller = cx.global_mut::<SystemWindowTabController>();
700 let mut removed_tab = None;
701
702 controller.tab_groups.retain(|_, tabs| {
703 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
704 removed_tab = Some(tabs.remove(pos));
705 }
706 !tabs.is_empty()
707 });
708
709 removed_tab
710 }
711
712 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
714 let mut removed_tab = Self::remove_tab(cx, id);
715 let mut controller = cx.global_mut::<SystemWindowTabController>();
716
717 if let Some(tab) = removed_tab {
718 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
719 controller.tab_groups.insert(new_group_id, vec![tab]);
720 }
721 }
722
723 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
725 let mut controller = cx.global_mut::<SystemWindowTabController>();
726 let Some(initial_tabs) = controller.tabs(id) else {
727 return;
728 };
729
730 let initial_tabs_len = initial_tabs.len();
731 let mut all_tabs = initial_tabs.clone();
732
733 for (_, mut tabs) in controller.tab_groups.drain() {
734 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
735 all_tabs.extend(tabs);
736 }
737
738 controller.tab_groups.insert(0, all_tabs);
739 }
740
741 pub fn select_next_tab(cx: &mut App, id: WindowId) {
743 let mut controller = cx.global_mut::<SystemWindowTabController>();
744 let Some(tabs) = controller.tabs(id) else {
745 return;
746 };
747
748 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
749 let next_index = (current_index + 1) % tabs.len();
750
751 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
752 window.activate_window();
753 });
754 }
755
756 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
758 let mut controller = cx.global_mut::<SystemWindowTabController>();
759 let Some(tabs) = controller.tabs(id) else {
760 return;
761 };
762
763 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
764 let previous_index = if current_index == 0 {
765 tabs.len() - 1
766 } else {
767 current_index - 1
768 };
769
770 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
771 window.activate_window();
772 });
773 }
774}
775
776pub(crate) enum GpuiMode {
777 #[cfg(any(test, feature = "test-support"))]
778 Test {
779 skip_drawing: bool,
780 },
781 Production,
782}
783
784impl GpuiMode {
785 #[cfg(any(test, feature = "test-support"))]
786 pub fn test() -> Self {
787 GpuiMode::Test {
788 skip_drawing: false,
789 }
790 }
791
792 #[inline]
793 pub(crate) fn skip_drawing(&self) -> bool {
794 match self {
795 #[cfg(any(test, feature = "test-support"))]
796 GpuiMode::Test { skip_drawing } => *skip_drawing,
797 GpuiMode::Production => false,
798 }
799 }
800}
801
802struct PlatformOwnedDrag {
803 source_window: WindowId,
804 state: PlatformOwnedDragState,
805}
806
807enum PlatformOwnedDragState {
808 Suspended(AnyDrag),
809 RestoredInSourceWindow,
812}
813
814pub struct App {
818 pub(crate) this: Weak<AppCell>,
819 pub(crate) platform: Rc<dyn Platform>,
820 text_system: Arc<TextSystem>,
821
822 pub(crate) actions: Rc<ActionRegistry>,
823 pub(crate) active_drag: Option<AnyDrag>,
824 platform_owned_drag: Option<PlatformOwnedDrag>,
825 pub(crate) background_executor: BackgroundExecutor,
826 pub(crate) foreground_executor: ForegroundExecutor,
827 #[cfg(feature = "profiler")]
828 foreground_journal: crate::profiler::journal::ForegroundJournal,
829 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
830 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
831 pub(crate) entities: EntityMap,
832 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
833 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
834 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
835 pub(crate) focus_handles: Arc<FocusMap>,
836 pub(crate) keymap: Rc<RefCell<Keymap>>,
837 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
838 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
839 pub(crate) global_action_listeners:
840 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
841 pending_effects: VecDeque<Effect>,
842
843 pub(crate) observers: SubscriberSet<EntityId, Handler>,
844 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
845 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
846 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
847 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
848 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
849 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
850 pub(crate) display_observers: SubscriberSet<(), DisplayHandler>,
851 displays: HashMap<DisplayId, DisplayState>,
854 pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
855 pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
856 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
857 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
858 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
859 pub(crate) restart_observers: SubscriberSet<(), Handler>,
860 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
861
862 pub(crate) element_arena: RefCell<Arena>,
865 pub(crate) event_arena: Arena,
867
868 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
873
874 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
876 asset_source: Arc<dyn AssetSource>,
877 pub(crate) svg_renderer: SvgRenderer,
878 http_client: Arc<dyn HttpClient>,
879
880 pub(crate) pending_notifications: FxHashSet<EntityId>,
882 pub(crate) pending_global_notifications: TypeIdHashSet,
883 pub(crate) dependencies: crate::fast::dependencies::AppDependencies,
884 pub(crate) restart_path: Option<PathBuf>,
885 pub(crate) restart_arguments: Vec<OsString>,
886 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
888 pub(crate) prompt_builder: Option<PromptBuilder>,
889 pub(crate) window_invalidators_by_entity:
890 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
891 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
892 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
893 #[cfg(any(feature = "inspector", debug_assertions))]
894 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
895 #[cfg(any(feature = "inspector", debug_assertions))]
896 pub(crate) inspector_element_registry: InspectorElementRegistry,
897 #[cfg(any(test, feature = "test-support", debug_assertions))]
898 pub(crate) name: Option<&'static str>,
899 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
900
901 pub(crate) window_update_stack: Vec<WindowId>,
902 pub(crate) mode: GpuiMode,
903 pub(crate) cursor_hide_mode: CursorHideMode,
904 pub(crate) reduce_motion: bool,
905 pub(crate) synced_animation_epoch: Instant,
907 pub(crate) accessibility_force_disabled: bool,
910 pending_updates: usize,
911 quit_mode: QuitMode,
912 quitting: bool,
913
914 #[cfg(any(test, gpui_leak_detection))]
917 _ref_counts: Arc<RwLock<EntityRefCounts>>,
918}
919
920impl App {
921 #[allow(clippy::new_ret_no_self)]
922 pub(crate) fn new_app(
923 platform: Rc<dyn Platform>,
924 asset_source: Arc<dyn AssetSource>,
925 http_client: Arc<dyn HttpClient>,
926 ) -> Rc<AppCell> {
927 let background_executor = platform.background_executor();
928 let foreground_executor = platform.foreground_executor();
929 assert!(
930 background_executor.is_main_thread(),
931 "must construct App on main thread"
932 );
933 #[cfg(feature = "profiler")]
934 let foreground_journal = crate::profiler::journal::install_foreground_journal();
935 let synced_animation_epoch = background_executor.now();
936
937 let text_system = Arc::new(TextSystem::new(platform.text_system()));
938 let entities = EntityMap::new();
939 let keyboard_layout = platform.keyboard_layout();
940 let keyboard_mapper = platform.keyboard_mapper();
941
942 #[cfg(any(test, gpui_leak_detection))]
943 let _ref_counts = entities.ref_counts_drop_handle();
944
945 let app = Rc::new_cyclic(|this| AppCell {
946 app: RefCell::new(App {
947 this: this.clone(),
948 platform: platform.clone(),
949 text_system,
950 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
951 mode: GpuiMode::Production,
952 actions: Rc::new(ActionRegistry::default()),
953 pending_updates: 0,
954 active_drag: None,
955 platform_owned_drag: None,
956 background_executor,
957 foreground_executor,
958 #[cfg(feature = "profiler")]
959 foreground_journal,
960 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
961 hang_monitor: None,
962 svg_renderer: SvgRenderer::new(asset_source.clone()),
963 loading_assets: Default::default(),
964 asset_source,
965 http_client,
966 globals_by_type: Default::default(),
967 entities,
968 new_entity_observers: SubscriberSet::new(),
969 windows: SlotMap::with_key(),
970 window_update_stack: Vec::new(),
971 window_handles: FxHashMap::default(),
972 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
973 keymap: Rc::new(RefCell::new(Keymap::default())),
974 keyboard_layout,
975 keyboard_mapper,
976 global_action_listeners: Default::default(),
977 pending_effects: VecDeque::new(),
978 pending_notifications: FxHashSet::default(),
979 pending_global_notifications: Default::default(),
980 dependencies: crate::fast::dependencies::AppDependencies::default(),
981 observers: SubscriberSet::new(),
982 tracked_entities: FxHashMap::default(),
983 window_invalidators_by_entity: FxHashMap::default(),
984 current_window_by_entity: FxHashMap::default(),
985 event_listeners: SubscriberSet::new(),
986 release_listeners: SubscriberSet::new(),
987 keystroke_observers: SubscriberSet::new(),
988 keystroke_interceptors: SubscriberSet::new(),
989 keyboard_layout_observers: SubscriberSet::new(),
990 missing_glyph_callback: Rc::default(),
991 thermal_state_observers: SubscriberSet::new(),
992 display_observers: SubscriberSet::new(),
993 displays: read_displays(platform.as_ref()),
994 system_sleep_observers: SubscriberSet::new(),
995 system_wake_observers: SubscriberSet::new(),
996 global_observers: SubscriberSet::new(),
997 quit_observers: SubscriberSet::new(),
998 restart_observers: SubscriberSet::new(),
999 restart_path: None,
1000 restart_arguments: Vec::new(),
1001 window_closed_observers: SubscriberSet::new(),
1002 layout_id_buffer: Default::default(),
1003 propagate_event: true,
1004 prompt_builder: Some(PromptBuilder::Default),
1005 #[cfg(any(feature = "inspector", debug_assertions))]
1006 inspector_renderer: None,
1007 #[cfg(any(feature = "inspector", debug_assertions))]
1008 inspector_element_registry: InspectorElementRegistry::default(),
1009 quit_mode: QuitMode::default(),
1010 quitting: false,
1011 cursor_hide_mode: CursorHideMode::default(),
1012 reduce_motion: false,
1013 synced_animation_epoch,
1014 accessibility_force_disabled: false,
1015
1016 #[cfg(any(test, feature = "test-support", debug_assertions))]
1017 name: None,
1018 element_arena: RefCell::new(Arena::new(1024 * 1024)),
1019 event_arena: Arena::new(1024 * 1024),
1020
1021 #[cfg(any(test, gpui_leak_detection))]
1022 _ref_counts,
1023 }),
1024 });
1025
1026 init_app_menus(platform.as_ref(), &app.borrow());
1027 SystemWindowTabController::init(&mut app.borrow_mut());
1028 #[cfg(feature = "profiler")]
1029 crate::profiler::journal::observe_power(&app.borrow());
1030
1031 platform.on_keyboard_layout_change(Box::new({
1032 let app = Rc::downgrade(&app);
1033 move || {
1034 if let Some(app) = app.upgrade() {
1035 let cx = &mut app.borrow_mut();
1036 cx.keyboard_layout = cx.platform.keyboard_layout();
1037 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1038 cx.keyboard_layout_observers
1039 .clone()
1040 .retain(&(), move |callback| (callback)(cx));
1041 }
1042 }
1043 }));
1044
1045 platform.on_thermal_state_change(Box::new({
1046 let app = Rc::downgrade(&app);
1047 move || {
1048 if let Some(app) = app.upgrade() {
1049 let cx = &mut app.borrow_mut();
1050 cx.thermal_state_observers
1051 .clone()
1052 .retain(&(), move |callback| (callback)(cx));
1053 }
1054 }
1055 }));
1056
1057 platform.on_displays_changed(Box::new({
1058 let app = Rc::downgrade(&app);
1059 move || {
1060 if let Some(app) = app.upgrade() {
1061 app.borrow_mut().displays_changed();
1062 }
1063 }
1064 }));
1065
1066 platform.on_system_sleep(Box::new({
1067 let app = Rc::downgrade(&app);
1068 move || {
1069 if let Some(app) = app.upgrade() {
1070 let cx = &mut app.borrow_mut();
1071 cx.system_sleep_observers
1072 .clone()
1073 .retain(&(), move |callback| (callback)(cx));
1074 }
1075 }
1076 }));
1077
1078 platform.on_system_wake(Box::new({
1079 let app = Rc::downgrade(&app);
1080 move || {
1081 if let Some(app) = app.upgrade() {
1082 let cx = &mut app.borrow_mut();
1083 cx.system_wake_observers
1084 .clone()
1085 .retain(&(), move |callback| (callback)(cx));
1086 }
1087 }
1088 }));
1089
1090 platform.on_quit(Box::new({
1091 let cx = Rc::downgrade(&app);
1092 move || {
1093 let Some(cx) = cx.upgrade() else {
1094 return true;
1095 };
1096 match cx.try_borrow_mut() {
1097 Ok(mut cx) => {
1098 cx.shutdown();
1099 true
1100 }
1101 Err(_) => {
1102 false
1105 }
1106 }
1107 }
1108 }));
1109
1110 app
1111 }
1112
1113 #[doc(hidden)]
1114 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1115 self.entities.ref_counts_drop_handle()
1116 }
1117
1118 #[cfg(any(test, gpui_leak_detection))]
1124 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1125 self.entities.leak_detector_snapshot()
1126 }
1127
1128 #[cfg(any(test, gpui_leak_detection))]
1140 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1141 self.entities.assert_no_new_leaks(snapshot)
1142 }
1143
1144 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1146 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1147 LeakDetectorSnapshot::default()
1148 }
1149
1150 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1153 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1154
1155 pub fn shutdown(&mut self) {
1161 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1164 let hang_monitor_flush = self
1165 .hang_monitor
1166 .as_ref()
1167 .and_then(|hang_monitor| hang_monitor.request_flush());
1168
1169 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1170
1171 for observer in self.quit_observers.remove(&()) {
1172 futures.push(observer(self));
1173 }
1174
1175 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1176 if let Some(flushed) = hang_monitor_flush {
1177 futures.push(
1178 async move {
1179 if flushed.await.is_err() {
1180 log::warn!("hang monitor exited before flushing");
1181 }
1182 }
1183 .boxed_local(),
1184 );
1185 }
1186
1187 self.windows.clear();
1188 self.window_handles.clear();
1189 self.flush_effects();
1190 self.quitting = true;
1191
1192 let futures = futures::future::join_all(futures);
1193 #[cfg(not(target_family = "wasm"))]
1194 if self
1195 .foreground_executor
1196 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1197 .is_err()
1198 {
1199 log::error!("timed out waiting on app_will_quit");
1200 }
1201 #[cfg(target_family = "wasm")]
1202 self.foreground_executor.spawn(futures).detach();
1203
1204 self.quitting = false;
1205 }
1206
1207 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1209 self.keyboard_layout.as_ref()
1210 }
1211
1212 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1214 &self.keyboard_mapper
1215 }
1216
1217 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1219 where
1220 F: 'static + FnMut(&mut App),
1221 {
1222 let (subscription, activate) = self.keyboard_layout_observers.insert(
1223 (),
1224 Box::new(move |cx| {
1225 callback(cx);
1226 true
1227 }),
1228 );
1229 activate();
1230 subscription
1231 }
1232
1233 pub fn quit(&self) {
1235 self.platform.quit();
1236 }
1237
1238 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1252 if !self.windows.is_empty() {
1253 return Task::ready(Err(anyhow::anyhow!(
1254 "cannot switch windowing modes while windows are open"
1255 )));
1256 }
1257 self.platform.request_windowing(request)
1258 }
1259
1260 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1270 self.platform.graphical_environment()
1271 }
1272
1273 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1276 self.cursor_hide_mode
1277 }
1278
1279 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1282 self.cursor_hide_mode = mode;
1283 }
1284
1285 pub fn is_cursor_visible(&self) -> bool {
1291 self.platform.is_cursor_visible()
1292 }
1293
1294 pub fn reduce_motion(&self) -> bool {
1297 self.reduce_motion
1298 }
1299
1300 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1303 if self.reduce_motion != reduce_motion {
1304 self.reduce_motion = reduce_motion;
1305 self.refresh_windows();
1306 }
1307 }
1308
1309 pub fn refresh_windows(&mut self) {
1312 self.pending_effects.push_back(Effect::RefreshWindows);
1313 }
1314
1315 #[inline(always)]
1316 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1317 self.start_update();
1318 let result = update(self);
1319 self.finish_update();
1320 result
1321 }
1322
1323 pub(crate) fn start_update(&mut self) {
1324 self.pending_updates += 1;
1325 }
1326
1327 #[inline(never)]
1328 pub(crate) fn finish_update(&mut self) {
1329 if self.pending_updates == 1 {
1330 self.flush_effects();
1331 }
1332 self.pending_updates -= 1;
1333 }
1334
1335 pub fn observe<W>(
1337 &mut self,
1338 entity: &Entity<W>,
1339 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1340 ) -> Subscription
1341 where
1342 W: 'static,
1343 {
1344 self.observe_internal(entity, move |e, cx| {
1345 on_notify(e, cx);
1346 true
1347 })
1348 }
1349
1350 pub(crate) fn record_entities_accessed(
1351 &mut self,
1352 window_handle: AnyWindowHandle,
1353 invalidator: WindowInvalidator,
1354 entities: &FxHashSet<EntityId>,
1355 ) {
1356 let mut tracked_entities =
1357 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1358 for entity in tracked_entities.iter() {
1359 self.window_invalidators_by_entity
1360 .entry(*entity)
1361 .and_modify(|windows| {
1362 windows.remove(&window_handle.id);
1363 });
1364 }
1365 for entity in entities.iter() {
1366 self.window_invalidators_by_entity
1367 .entry(*entity)
1368 .or_default()
1369 .insert(window_handle.id, invalidator.clone());
1370 self.current_window_by_entity
1371 .insert(*entity, window_handle.id);
1372 }
1373 tracked_entities.clear();
1374 tracked_entities.extend(entities.iter().copied());
1375 self.tracked_entities
1376 .insert(window_handle.id, tracked_entities);
1377 }
1378
1379 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1380 let (subscription, activate) = self.observers.insert(key, value);
1381 self.defer(move |_| activate());
1382 subscription
1383 }
1384
1385 pub(crate) fn observe_internal<W>(
1386 &mut self,
1387 entity: &Entity<W>,
1388 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1389 ) -> Subscription
1390 where
1391 W: 'static,
1392 {
1393 let entity_id = entity.entity_id();
1394 let handle = entity.downgrade();
1395 self.new_observer(
1396 entity_id,
1397 Box::new(move |cx| {
1398 if let Some(entity) = handle.upgrade() {
1399 on_notify(entity, cx)
1400 } else {
1401 false
1402 }
1403 }),
1404 )
1405 }
1406
1407 pub fn subscribe<T, Event>(
1410 &mut self,
1411 entity: &Entity<T>,
1412 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1413 ) -> Subscription
1414 where
1415 T: 'static + EventEmitter<Event>,
1416 Event: 'static,
1417 {
1418 self.subscribe_internal(entity, move |entity, event, cx| {
1419 on_event(entity, event, cx);
1420 true
1421 })
1422 }
1423
1424 pub(crate) fn new_subscription(
1425 &mut self,
1426 key: EntityId,
1427 value: (TypeId, Listener),
1428 ) -> Subscription {
1429 let (subscription, activate) = self.event_listeners.insert(key, value);
1430 self.defer(move |_| activate());
1431 subscription
1432 }
1433 pub(crate) fn subscribe_internal<T, Evt>(
1434 &mut self,
1435 entity: &Entity<T>,
1436 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1437 ) -> Subscription
1438 where
1439 T: 'static + EventEmitter<Evt>,
1440 Evt: 'static,
1441 {
1442 let entity_id = entity.entity_id();
1443 let handle = entity.downgrade();
1444 self.new_subscription(
1445 entity_id,
1446 (
1447 TypeId::of::<Evt>(),
1448 Box::new(move |event, cx| {
1449 let event: &Evt = event.downcast_ref().expect("invalid event type");
1450 if let Some(entity) = handle.upgrade() {
1451 on_event(entity, event, cx)
1452 } else {
1453 false
1454 }
1455 }),
1456 ),
1457 )
1458 }
1459
1460 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1464 self.windows
1465 .keys()
1466 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1467 .collect()
1468 }
1469
1470 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1476 self.platform.window_stack()
1477 }
1478
1479 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1481 self.platform.active_window()
1482 }
1483
1484 pub fn open_window<V: 'static + Render>(
1488 &mut self,
1489 options: crate::WindowOptions,
1490 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1491 ) -> anyhow::Result<WindowHandle<V>> {
1492 self.update(|cx| {
1493 let id = cx.windows.insert(None);
1494 let handle = WindowHandle::new(id);
1495 match Window::new(handle.into(), options, cx) {
1496 Ok(mut window) => {
1497 cx.window_update_stack.push(id);
1498 let root_view = build_root_view(&mut window, cx);
1499 cx.window_update_stack.pop();
1500 window.root.replace(root_view.into());
1501 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1502
1503 let clear = window.draw(cx);
1508 clear.clear(cx);
1509
1510 cx.window_handles.insert(id, window.handle);
1511 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1512 Ok(handle)
1513 }
1514 Err(e) => {
1515 cx.windows.remove(id);
1516 Err(e)
1517 }
1518 }
1519 })
1520 }
1521
1522 pub fn activate(&self, ignoring_other_apps: bool) {
1524 self.platform.activate(ignoring_other_apps);
1525 }
1526
1527 pub fn hide(&self) {
1529 self.platform.hide();
1530 }
1531
1532 pub fn hide_other_apps(&self) {
1534 self.platform.hide_other_apps();
1535 }
1536
1537 pub fn unhide_other_apps(&self) {
1539 self.platform.unhide_other_apps();
1540 }
1541
1542 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1544 self.platform.displays()
1545 }
1546
1547 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1549 self.platform.primary_display()
1550 }
1551
1552 pub fn is_screen_capture_supported(&self) -> bool {
1554 self.platform.is_screen_capture_supported()
1555 }
1556
1557 pub fn screen_capture_sources(
1559 &self,
1560 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1561 self.platform.screen_capture_sources()
1562 }
1563
1564 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1566 self.displays()
1567 .iter()
1568 .find(|display| display.id() == id)
1569 .cloned()
1570 }
1571
1572 pub fn thermal_state(&self) -> ThermalState {
1574 self.platform.thermal_state()
1575 }
1576
1577 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1579 self.platform.prevent_idle_sleep(reason)
1580 }
1581
1582 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1584 where
1585 F: 'static + FnMut(&mut App),
1586 {
1587 let (subscription, activate) = self.thermal_state_observers.insert(
1588 (),
1589 Box::new(move |cx| {
1590 callback(cx);
1591 true
1592 }),
1593 );
1594 activate();
1595 subscription
1596 }
1597
1598 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1603 where
1604 F: 'static + FnMut(&mut App),
1605 {
1606 let (subscription, activate) = self.system_sleep_observers.insert(
1607 (),
1608 Box::new(move |cx| {
1609 callback(cx);
1610 true
1611 }),
1612 );
1613 activate();
1614 subscription
1615 }
1616
1617 pub(crate) fn displays_changed(&mut self) {
1618 let current = read_displays(self.platform.as_ref());
1619 let events = display_events(&self.displays, ¤t);
1620 self.displays = current;
1621 for event in &events {
1622 let DisplayEvent::Changed { id, .. } = *event else {
1623 continue;
1624 };
1625 for handle in self.windows() {
1626 self.update_window(handle, |_, window, cx| {
1627 if window.display_id == Some(id) {
1628 window.notify_display_observers(cx);
1629 }
1630 })
1631 .log_err();
1632 }
1633 }
1634 for event in events {
1635 self.display_observers
1636 .clone()
1637 .retain(&(), |callback| (callback)(event, self));
1638 }
1639 }
1640
1641 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1642 self.displays.contains_key(&id)
1643 }
1644
1645 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1648 self.displays.get(&id)?.refresh_interval
1649 }
1650
1651 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1654 where
1655 F: 'static + FnMut(DisplayEvent, &mut App),
1656 {
1657 let (subscription, activate) = self.display_observers.insert(
1658 (),
1659 Box::new(move |event, cx| {
1660 callback(event, cx);
1661 true
1662 }),
1663 );
1664 activate();
1665 subscription
1666 }
1667
1668 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1670 where
1671 F: 'static + FnMut(&mut App),
1672 {
1673 let (subscription, activate) = self.system_wake_observers.insert(
1674 (),
1675 Box::new(move |cx| {
1676 callback(cx);
1677 true
1678 }),
1679 );
1680 activate();
1681 subscription
1682 }
1683
1684 pub fn window_appearance(&self) -> WindowAppearance {
1686 self.platform.window_appearance()
1687 }
1688
1689 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1700 self.platform.set_window_appearance(appearance);
1701 }
1702
1703 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1705 self.platform.button_layout()
1706 }
1707
1708 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1710 self.platform.read_from_clipboard()
1711 }
1712
1713 pub fn read_from_clipboard_async(
1721 &self,
1722 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1723 self.platform.read_from_clipboard_async()
1724 }
1725
1726 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1728 self.text_rendering_mode.set(mode);
1729 }
1730
1731 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1733 self.text_rendering_mode.get()
1734 }
1735
1736 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1738 self.platform.write_to_clipboard(item)
1739 }
1740
1741 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1744 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1745 self.platform.read_from_primary()
1746 }
1747
1748 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1751 pub fn write_to_primary(&self, item: ClipboardItem) {
1752 self.platform.write_to_primary(item)
1753 }
1754
1755 #[cfg(target_os = "macos")]
1761 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1762 self.platform.read_from_find_pasteboard()
1763 }
1764
1765 #[cfg(target_os = "macos")]
1771 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1772 self.platform.write_to_find_pasteboard(item)
1773 }
1774
1775 pub fn write_credentials(
1777 &self,
1778 url: &str,
1779 username: &str,
1780 password: &[u8],
1781 ) -> Task<Result<()>> {
1782 self.platform.write_credentials(url, username, password)
1783 }
1784
1785 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1787 self.platform.read_credentials(url)
1788 }
1789
1790 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1792 self.platform.delete_credentials(url)
1793 }
1794
1795 pub fn open_url(&self, url: &str) {
1797 self.platform.open_url(url);
1798 }
1799
1800 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1807 self.platform.register_url_scheme(scheme)
1808 }
1809
1810 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1817 self.platform.set_app_identity(identifier, name);
1818 }
1819
1820 pub fn show_system_notification(&self, notification: SystemNotification) {
1827 self.platform.show_system_notification(notification);
1828 }
1829
1830 pub fn dismiss_system_notification(&self, tag: &str) {
1835 self.platform.dismiss_system_notification(tag);
1836 }
1837
1838 pub fn on_system_notification_response<F>(&self, mut callback: F)
1842 where
1843 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1844 {
1845 let this = self.this.clone();
1846 self.platform
1847 .on_system_notification_response(Box::new(move |response| {
1848 if let Some(app) = this.upgrade() {
1849 callback(response, &mut app.borrow_mut());
1850 }
1851 }));
1852 }
1853
1854 pub fn app_path(&self) -> Result<PathBuf> {
1858 self.platform.app_path()
1859 }
1860
1861 pub fn compositor_name(&self) -> &'static str {
1865 self.platform.compositor_name()
1866 }
1867
1868 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1870 self.platform.path_for_auxiliary_executable(name)
1871 }
1872
1873 pub fn prompt_for_paths(
1879 &self,
1880 options: PathPromptOptions,
1881 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1882 self.platform.prompt_for_paths(options)
1883 }
1884
1885 pub fn prompt_for_new_path(
1892 &self,
1893 directory: &Path,
1894 suggested_name: Option<&str>,
1895 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1896 self.platform.prompt_for_new_path(directory, suggested_name)
1897 }
1898
1899 pub fn reveal_path(&self, path: &Path) {
1901 self.platform.reveal_path(path)
1902 }
1903
1904 pub fn open_with_system(&self, path: &Path) {
1906 self.platform.open_with_system(path)
1907 }
1908
1909 pub fn should_auto_hide_scrollbars(&self) -> bool {
1911 self.platform.should_auto_hide_scrollbars()
1912 }
1913
1914 pub fn restart(&mut self) {
1916 self.restart_observers
1917 .clone()
1918 .retain(&(), |observer| observer(self));
1919 self.platform.restart(
1920 self.restart_path.take(),
1921 std::mem::take(&mut self.restart_arguments),
1922 )
1923 }
1924
1925 pub fn set_restart_path(&mut self, path: PathBuf) {
1927 self.restart_path = Some(path);
1928 }
1929
1930 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1932 self.http_client.clone()
1933 }
1934
1935 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1937 self.http_client = new_client;
1938 }
1939
1940 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1943 self.quit_mode = mode;
1944 }
1945
1946 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
1955 self.platform.set_activation_policy(policy);
1956 }
1957
1958 pub fn svg_renderer(&self) -> SvgRenderer {
1960 self.svg_renderer.clone()
1961 }
1962
1963 pub(crate) fn push_effect(&mut self, effect: Effect) {
1964 match &effect {
1965 Effect::Notify { emitter } => {
1966 if !self.pending_notifications.insert(*emitter) {
1967 return;
1968 }
1969 }
1970 Effect::NotifyGlobalObservers { global_type } => {
1971 crate::fast::dependencies::global_changed(self, *global_type);
1972 if !self.pending_global_notifications.insert(*global_type) {
1973 return;
1974 }
1975 }
1976 _ => {}
1977 };
1978
1979 self.pending_effects.push_back(effect);
1980 }
1981
1982 fn flush_effects(&mut self) {
1986 loop {
1987 self.release_dropped_entities();
1988 self.release_dropped_focus_handles();
1989 if let Some(effect) = self.pending_effects.pop_front() {
1990 match effect {
1991 Effect::Notify { emitter } => {
1992 self.apply_notify_effect(emitter);
1993 }
1994
1995 Effect::Emit {
1996 emitter,
1997 event_type,
1998 event,
1999 } => self.apply_emit_effect(emitter, event_type, &*event),
2000
2001 Effect::RefreshWindows => {
2002 self.apply_refresh_effect();
2003 }
2004
2005 Effect::NotifyGlobalObservers { global_type } => {
2006 self.apply_notify_global_observers_effect(global_type);
2007 }
2008
2009 Effect::Defer { callback } => {
2010 self.apply_defer_effect(callback);
2011 }
2012 Effect::EntityCreated {
2013 entity,
2014 tid,
2015 window,
2016 } => {
2017 self.apply_entity_created_effect(entity, tid, window);
2018 }
2019 }
2020 } else {
2021 #[cfg(any(test, feature = "test-support"))]
2022 if matches!(self.mode, GpuiMode::Test { .. }) {
2023 for window in self
2024 .windows
2025 .values()
2026 .filter_map(|window| {
2027 let window = window.as_deref()?;
2028 window.invalidator.is_dirty().then_some(window.handle)
2029 })
2030 .collect::<Vec<_>>()
2031 {
2032 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2033 .unwrap();
2034 }
2035 }
2036
2037 if self.pending_effects.is_empty() {
2038 for window in self.windows.values().filter_map(|window| window.as_deref()) {
2039 if window.invalidator.is_dirty()
2040 || window.needs_present.get()
2041 || !window.next_frame_callbacks.borrow().is_empty()
2042 {
2043 window.platform_window.schedule_frame();
2044 }
2045 }
2046
2047 self.event_arena.clear();
2048 break;
2049 }
2050 }
2051 }
2052 }
2053
2054 fn release_dropped_entities(&mut self) {
2058 loop {
2059 let dropped = self.entities.take_dropped();
2060 if dropped.is_empty() {
2061 break;
2062 }
2063
2064 for (entity_id, mut entity) in dropped {
2065 self.observers.remove(&entity_id);
2066 self.event_listeners.remove(&entity_id);
2067 self.window_invalidators_by_entity.remove(&entity_id);
2068 self.current_window_by_entity.remove(&entity_id);
2069 for release_callback in self.release_listeners.remove(&entity_id) {
2070 release_callback(entity.as_mut(), self);
2071 }
2072 }
2073 }
2074 }
2075
2076 fn release_dropped_focus_handles(&mut self) {
2078 self.focus_handles
2079 .clone()
2080 .write()
2081 .retain(|handle_id, focus| {
2082 if focus.ref_count.load(SeqCst) == 0 {
2083 for window_handle in self.windows() {
2084 window_handle
2085 .update(self, |_, window, cx| {
2086 if window.focus == Some(handle_id) {
2087 window.blur(cx);
2088 }
2089 })
2090 .unwrap();
2091 }
2092 false
2093 } else {
2094 true
2095 }
2096 });
2097 }
2098
2099 fn apply_notify_effect(&mut self, emitter: EntityId) {
2100 self.pending_notifications.remove(&emitter);
2101
2102 self.observers
2103 .clone()
2104 .retain(&emitter, |handler| handler(self));
2105 }
2106
2107 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2108 self.event_listeners
2109 .clone()
2110 .retain(&emitter, |(stored_type, handler)| {
2111 if *stored_type == event_type {
2112 handler(event, self)
2113 } else {
2114 true
2115 }
2116 });
2117 }
2118
2119 fn apply_refresh_effect(&mut self) {
2120 for window in self.windows.values_mut() {
2121 if let Some(window) = window.as_deref_mut() {
2122 window.refreshing = true;
2123 window.invalidator.set_dirty(true);
2124 }
2125 }
2126 }
2127
2128 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2129 self.pending_global_notifications.remove(&type_id);
2130 self.global_observers
2131 .clone()
2132 .retain(&type_id, |observer| observer(self));
2133 }
2134
2135 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2136 callback(self);
2137 }
2138
2139 fn apply_entity_created_effect(
2140 &mut self,
2141 entity: AnyEntity,
2142 tid: TypeId,
2143 window: Option<WindowId>,
2144 ) {
2145 if let Some(id) = window {
2149 self.current_window_by_entity.insert(entity.entity_id(), id);
2150 }
2151
2152 self.new_entity_observers.clone().retain(&tid, |observer| {
2153 if let Some(id) = window {
2154 self.update_window_id(id, {
2155 let entity = entity.clone();
2156 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2157 })
2158 .expect("All windows should be off the stack when flushing effects");
2159 } else {
2160 (observer)(entity.clone(), &mut None, self)
2161 }
2162 true
2163 });
2164 }
2165
2166 #[inline(always)]
2172 pub fn with_window<R>(
2173 &mut self,
2174 entity_id: EntityId,
2175 f: impl FnOnce(&mut Window, &mut App) -> R,
2176 ) -> Option<R> {
2177 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2178 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2179 .ok()
2180 }
2181
2182 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2183 self.current_window_by_entity
2184 .entry(entity_id)
2185 .or_insert(window);
2186 }
2187
2188 #[inline(always)]
2189 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2190 where
2191 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2192 {
2193 let mut update = Some(update);
2194 let mut result = None;
2195 self.update_window_erased(id, &mut |arguments| {
2196 if let Some((root_view, window, cx)) = arguments {
2197 result = Some(update.take().unwrap()(root_view, window, cx));
2198 } else {
2199 drop(update.take());
2200 drop(result.take());
2201 }
2202 });
2203 result.context("window not found")
2204 }
2205
2206 pub fn to_async(&self) -> AsyncApp {
2209 AsyncApp {
2210 app: self.this.clone(),
2211 background_executor: self.background_executor.clone(),
2212 foreground_executor: self.foreground_executor.clone(),
2213 }
2214 }
2215
2216 pub fn background_executor(&self) -> &BackgroundExecutor {
2218 &self.background_executor
2219 }
2220
2221 pub fn is_test(&self) -> bool {
2224 self.background_executor.is_test()
2225 }
2226
2227 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2229 if self.quitting {
2230 panic!("Can't spawn on main thread after on_app_quit")
2231 };
2232 &self.foreground_executor
2233 }
2234
2235 #[cfg(feature = "profiler")]
2238 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2239 self.foreground_journal.clone()
2240 }
2241
2242 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2259 pub fn start_hang_monitor(
2260 &mut self,
2261 config: crate::profiler::hang::HangMonitorConfig,
2262 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2263 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2264 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2265
2266 if self.hang_monitor.is_some() {
2267 debug_assert!(false, "the hang monitor was started twice");
2268 return Err(HangMonitorError::AlreadyStarted);
2269 }
2270 let detector = HangDetector::new(
2271 self.foreground_journal(),
2272 config.threshold,
2273 config.frame_budget,
2274 );
2275 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2276 .map_err(HangMonitorError::Spawn)?;
2277 self.hang_monitor = Some(monitor);
2278 Ok(())
2279 }
2280
2281 #[track_caller]
2284 #[inline(always)]
2285 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2286 where
2287 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2288 R: 'static,
2289 {
2290 let mut cx = self.prepare_spawn();
2291
2292 self.foreground_executor
2293 .spawn(async move { f(&mut cx).await }.boxed_local())
2294 }
2295
2296 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2300 where
2301 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2302 R: 'static,
2303 {
2304 if self.quitting {
2305 debug_panic!("Can't spawn on main thread after on_app_quit")
2306 };
2307
2308 let mut cx = self.to_async();
2309
2310 self.foreground_executor
2311 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2312 }
2313
2314 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2317 self.push_effect(Effect::Defer {
2318 callback: Box::new(f),
2319 });
2320 }
2321
2322 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2324 &self.asset_source
2325 }
2326
2327 pub fn text_system(&self) -> &Arc<TextSystem> {
2329 &self.text_system
2330 }
2331
2332 pub fn on_missing_glyphs(
2343 &self,
2344 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2345 ) -> Subscription {
2346 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2347
2348 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2349 let callback = self.missing_glyph_callback.clone();
2350 self.spawn(async move |cx| {
2351 while let Ok(missing_glyphs) = receiver.recv().await {
2352 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2353 }
2354 })
2355 .detach();
2356 }
2357 self.text_system.enable_missing_glyph_reporting();
2358
2359 let callback = self.missing_glyph_callback.clone();
2360 let text_system = self.text_system.clone();
2361 Subscription::new(move || {
2362 if callback.remove(®istration) {
2363 text_system.disable_missing_glyph_reporting();
2364 }
2365 })
2366 }
2367
2368 pub fn has_global<G: Global>(&self) -> bool {
2370 crate::fast::dependencies::note_global_presence_read::<G>(self);
2371 self.globals_by_type.contains_key(&TypeId::of::<G>())
2372 }
2373
2374 #[track_caller]
2376 pub fn global<G: Global>(&self) -> &G {
2377 crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2378 self.globals_by_type
2379 .get(&TypeId::of::<G>())
2380 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2381 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2382 }
2383
2384 pub fn try_global<G: Global>(&self) -> Option<&G> {
2386 crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2387 self.globals_by_type
2388 .get(&TypeId::of::<G>())
2389 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2390 }
2391
2392 #[track_caller]
2394 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2395 let global_type = TypeId::of::<G>();
2396 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2397 self.globals_by_type
2398 .get_mut(&global_type)
2399 .and_then(|any_state| any_state.downcast_mut::<G>())
2400 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2401 }
2402
2403 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2406 let global_type = TypeId::of::<G>();
2407 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2408 crate::fast::dependencies::note_global_inserted::<G>(self);
2409 self.globals_by_type
2410 .entry(global_type)
2411 .or_insert_with(|| Box::<G>::default())
2412 .downcast_mut::<G>()
2413 .unwrap()
2414 }
2415
2416 pub fn set_global<G: Global>(&mut self, global: G) {
2418 let global_type = TypeId::of::<G>();
2419 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2420 crate::fast::dependencies::note_global_inserted::<G>(self);
2421 self.globals_by_type.insert(global_type, Box::new(global));
2422 }
2423
2424 #[cfg(any(test, feature = "test-support"))]
2426 pub fn clear_globals(&mut self) {
2427 self.globals_by_type.drain();
2428 }
2429
2430 pub fn remove_global<G: Global>(&mut self) -> G {
2432 crate::fast::dependencies::note_global_removed::<G>(self);
2433 let global_type = TypeId::of::<G>();
2434 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2435 *self
2436 .globals_by_type
2437 .remove(&global_type)
2438 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2439 .downcast()
2440 .unwrap()
2441 }
2442
2443 pub fn observe_global<G: Global>(
2445 &mut self,
2446 mut f: impl FnMut(&mut Self) + 'static,
2447 ) -> Subscription {
2448 let (subscription, activate) = self.global_observers.insert(
2449 TypeId::of::<G>(),
2450 Box::new(move |cx| {
2451 f(cx);
2452 true
2453 }),
2454 );
2455 self.defer(move |_| activate());
2456 subscription
2457 }
2458
2459 #[track_caller]
2461 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2462 GlobalLease::new(
2463 self.globals_by_type
2464 .remove(&TypeId::of::<G>())
2465 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2466 .unwrap(),
2467 )
2468 }
2469
2470 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2472 let global_type = TypeId::of::<G>();
2473
2474 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2475 self.globals_by_type.insert(global_type, lease.global);
2476 }
2477
2478 pub(crate) fn new_entity_observer(
2479 &self,
2480 key: TypeId,
2481 value: NewEntityListener,
2482 ) -> Subscription {
2483 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2484 activate();
2485 subscription
2486 }
2487
2488 pub fn observe_new<T: 'static>(
2491 &self,
2492 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2493 ) -> Subscription {
2494 self.new_entity_observer(
2495 TypeId::of::<T>(),
2496 Box::new(
2497 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2498 any_entity
2499 .downcast::<T>()
2500 .unwrap()
2501 .update(cx, |entity_state, cx| {
2502 on_new(entity_state, window.as_deref_mut(), cx)
2503 })
2504 },
2505 ),
2506 )
2507 }
2508
2509 pub fn observe_release<T>(
2512 &self,
2513 handle: &Entity<T>,
2514 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2515 ) -> Subscription
2516 where
2517 T: 'static,
2518 {
2519 let (subscription, activate) = self.release_listeners.insert(
2520 handle.entity_id(),
2521 Box::new(move |entity, cx| {
2522 let entity = entity.downcast_mut().expect("invalid entity type");
2523 on_release(entity, cx)
2524 }),
2525 );
2526 activate();
2527 subscription
2528 }
2529
2530 pub fn observe_release_in<T>(
2533 &self,
2534 handle: &Entity<T>,
2535 window: &Window,
2536 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2537 ) -> Subscription
2538 where
2539 T: 'static,
2540 {
2541 let window_handle = window.handle;
2542 self.observe_release(handle, move |entity, cx| {
2543 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2544 })
2545 }
2546
2547 pub fn observe_keystrokes(
2552 &mut self,
2553 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2554 ) -> Subscription {
2555 fn inner(
2556 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2557 handler: KeystrokeObserver,
2558 ) -> Subscription {
2559 let (subscription, activate) = keystroke_observers.insert((), handler);
2560 activate();
2561 subscription
2562 }
2563
2564 inner(
2565 &self.keystroke_observers,
2566 Box::new(move |event, window, cx| {
2567 f(event, window, cx);
2568 true
2569 }),
2570 )
2571 }
2572
2573 pub fn intercept_keystrokes(
2578 &mut self,
2579 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2580 ) -> Subscription {
2581 fn inner(
2582 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2583 handler: KeystrokeObserver,
2584 ) -> Subscription {
2585 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2586 activate();
2587 subscription
2588 }
2589
2590 inner(
2591 &self.keystroke_interceptors,
2592 Box::new(move |event, window, cx| {
2593 f(event, window, cx);
2594 true
2595 }),
2596 )
2597 }
2598
2599 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2601 self.keymap.borrow_mut().add_bindings(bindings);
2602 self.pending_effects.push_back(Effect::RefreshWindows);
2603 }
2604
2605 pub fn clear_key_bindings(&mut self) {
2607 self.keymap.borrow_mut().clear();
2608 self.pending_effects.push_back(Effect::RefreshWindows);
2609 }
2610
2611 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2613 self.keymap.clone()
2614 }
2615
2616 pub fn on_action<A: Action>(
2620 &mut self,
2621 listener: impl Fn(&A, &mut Self) + 'static,
2622 ) -> &mut Self {
2623 self.global_action_listeners
2624 .entry(TypeId::of::<A>())
2625 .or_default()
2626 .push(Rc::new(move |action, phase, cx| {
2627 if phase == DispatchPhase::Bubble {
2628 let action = action.downcast_ref().unwrap();
2629 listener(action, cx)
2630 }
2631 }));
2632 self
2633 }
2634
2635 pub fn stop_propagation(&mut self) {
2640 self.propagate_event = false;
2641 }
2642
2643 pub fn propagate(&mut self) {
2648 self.propagate_event = true;
2649 }
2650
2651 pub fn build_action(
2653 &self,
2654 name: &str,
2655 data: Option<serde_json::Value>,
2656 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2657 self.actions.build_action(name, data)
2658 }
2659
2660 pub fn all_action_names(&self) -> &[&'static str] {
2663 self.actions.all_action_names()
2664 }
2665
2666 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2670 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2671 }
2672
2673 pub fn action_schemas(
2675 &self,
2676 generator: &mut schemars::SchemaGenerator,
2677 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2678 self.actions.action_schemas(generator)
2679 }
2680
2681 pub fn action_schema_by_name(
2686 &self,
2687 name: &str,
2688 generator: &mut schemars::SchemaGenerator,
2689 ) -> Option<Option<schemars::Schema>> {
2690 self.actions.action_schema_by_name(name, generator)
2691 }
2692
2693 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2695 self.actions.deprecated_aliases()
2696 }
2697
2698 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2700 self.actions.deprecation_messages()
2701 }
2702
2703 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2705 self.actions.documentation()
2706 }
2707
2708 pub fn on_app_quit<Fut>(
2711 &self,
2712 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2713 ) -> Subscription
2714 where
2715 Fut: 'static + Future<Output = ()>,
2716 {
2717 let (subscription, activate) = self.quit_observers.insert(
2718 (),
2719 Box::new(move |cx| {
2720 let future = on_quit(cx);
2721 future.boxed_local()
2722 }),
2723 );
2724 activate();
2725 subscription
2726 }
2727
2728 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2732 let (subscription, activate) = self.restart_observers.insert(
2733 (),
2734 Box::new(move |cx| {
2735 on_restart(cx);
2736 true
2737 }),
2738 );
2739 activate();
2740 subscription
2741 }
2742
2743 pub fn on_window_closed(
2746 &self,
2747 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2748 ) -> Subscription {
2749 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2750 activate();
2751 subscription
2752 }
2753
2754 pub(crate) fn clear_pending_keystrokes(&mut self) {
2755 for window in self.windows() {
2756 window
2757 .update(self, |_, window, cx| {
2758 window.clear_pending_keystrokes(cx);
2759 })
2760 .ok();
2761 }
2762 }
2763
2764 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2767 let mut action_available = false;
2768 if let Some(window) = self.active_window()
2769 && let Ok(window_action_available) =
2770 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2771 {
2772 action_available = window_action_available;
2773 }
2774
2775 action_available
2776 || self
2777 .global_action_listeners
2778 .contains_key(&action.as_any().type_id())
2779 }
2780
2781 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2783 let menus: Vec<Menu> = menus.into_iter().collect();
2784 self.platform.set_menus(menus, &self.keymap.borrow());
2785 }
2786
2787 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2789 self.platform.get_menus()
2790 }
2791
2792 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2794 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2795 }
2796
2797 pub fn perform_dock_menu_action(&self, action: usize) {
2799 self.platform.perform_dock_menu_action(action);
2800 }
2801
2802 pub fn add_recent_document(&self, path: &Path) {
2807 self.platform.add_recent_document(path);
2808 }
2809
2810 pub fn update_jump_list(
2813 &self,
2814 menus: Vec<MenuItem>,
2815 entries: Vec<SmallVec<[PathBuf; 2]>>,
2816 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2817 self.platform.update_jump_list(menus, entries)
2818 }
2819
2820 pub fn dispatch_action(&mut self, action: &dyn Action) {
2823 if let Some(active_window) = self.active_window() {
2824 active_window
2825 .update(self, |_, window, cx| {
2826 window.dispatch_action(action.boxed_clone(), cx)
2827 })
2828 .log_err();
2829 } else {
2830 self.dispatch_global_action(action);
2831 }
2832 }
2833
2834 fn dispatch_global_action(&mut self, action: &dyn Action) {
2835 self.propagate_event = true;
2836
2837 if let Some(mut global_listeners) = self
2838 .global_action_listeners
2839 .remove(&action.as_any().type_id())
2840 {
2841 for listener in &global_listeners {
2842 listener(action.as_any(), DispatchPhase::Capture, self);
2843 if !self.propagate_event {
2844 break;
2845 }
2846 }
2847
2848 global_listeners.extend(
2849 self.global_action_listeners
2850 .remove(&action.as_any().type_id())
2851 .unwrap_or_default(),
2852 );
2853
2854 self.global_action_listeners
2855 .insert(action.as_any().type_id(), global_listeners);
2856 }
2857
2858 if self.propagate_event
2859 && let Some(mut global_listeners) = self
2860 .global_action_listeners
2861 .remove(&action.as_any().type_id())
2862 {
2863 for listener in global_listeners.iter().rev() {
2864 listener(action.as_any(), DispatchPhase::Bubble, self);
2865 if !self.propagate_event {
2866 break;
2867 }
2868 }
2869
2870 global_listeners.extend(
2871 self.global_action_listeners
2872 .remove(&action.as_any().type_id())
2873 .unwrap_or_default(),
2874 );
2875
2876 self.global_action_listeners
2877 .insert(action.as_any().type_id(), global_listeners);
2878 }
2879 }
2880
2881 pub fn has_active_drag(&self) -> bool {
2883 self.active_drag.is_some()
2884 }
2885
2886 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2888 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2889 }
2890
2891 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2893 if self.active_drag.is_some() {
2894 self.active_drag = None;
2895 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2896 drag.source_window == window.window_handle().window_id()
2897 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2898 }) {
2899 self.platform_owned_drag = None;
2900 }
2901 window.refresh();
2902 true
2903 } else {
2904 false
2905 }
2906 }
2907
2908 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2909 let Some(drag) = self.active_drag.take() else {
2910 return false;
2911 };
2912 self.platform_owned_drag = Some(PlatformOwnedDrag {
2913 source_window,
2914 state: PlatformOwnedDragState::Suspended(drag),
2915 });
2916 true
2917 }
2918
2919 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2920 let Some(platform_drag) = self
2921 .platform_owned_drag
2922 .as_mut()
2923 .filter(|drag| drag.source_window == source_window)
2924 else {
2925 return false;
2926 };
2927 let state = std::mem::replace(
2928 &mut platform_drag.state,
2929 PlatformOwnedDragState::RestoredInSourceWindow,
2930 );
2931 let PlatformOwnedDragState::Suspended(drag) = state else {
2932 return false;
2933 };
2934 self.active_drag = Some(drag);
2935 true
2936 }
2937
2938 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2939 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2940 drag.source_window == source_window
2941 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2942 }) else {
2943 return false;
2944 };
2945 let Some(drag) = self.active_drag.take() else {
2946 return false;
2947 };
2948 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2949 true
2950 }
2951
2952 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2953 if !self
2954 .platform_owned_drag
2955 .as_ref()
2956 .is_some_and(|drag| drag.source_window == source_window)
2957 {
2958 return false;
2959 }
2960 self.platform_owned_drag = None;
2961 self.active_drag = None;
2962 true
2963 }
2964
2965 pub fn set_active_drag_cursor_style(
2967 &mut self,
2968 cursor_style: CursorStyle,
2969 window: &mut Window,
2970 ) -> bool {
2971 if let Some(ref mut drag) = self.active_drag {
2972 drag.cursor_style = Some(cursor_style);
2973 window.refresh();
2974 true
2975 } else {
2976 false
2977 }
2978 }
2979
2980 pub fn set_prompt_builder(
2983 &mut self,
2984 renderer: impl Fn(
2985 PromptLevel,
2986 &str,
2987 Option<&str>,
2988 &[PromptButton],
2989 PromptHandle,
2990 &mut Window,
2991 &mut App,
2992 ) -> RenderablePromptHandle
2993 + 'static,
2994 ) {
2995 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2996 }
2997
2998 pub fn reset_prompt_builder(&mut self) {
3000 self.prompt_builder = Some(PromptBuilder::Default);
3001 }
3002
3003 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3005 let asset_id = (TypeId::of::<A>(), hash(source));
3006 self.loading_assets.remove(&asset_id);
3007 }
3008
3009 #[cfg(any(test, feature = "test-support"))]
3012 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3013 let asset_id = (TypeId::of::<A>(), hash(source));
3014 self.loading_assets.contains_key(&asset_id)
3015 }
3016
3017 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3022 self.asset_entry::<A>(source).get()
3023 }
3024
3025 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3026 let asset_id = (TypeId::of::<A>(), hash(source));
3027 if !self.loading_assets.contains_key(&asset_id) {
3028 let future = A::load(source.clone(), self);
3029 let entry = CachedLoad::new(future, self);
3030 self.loading_assets.insert(asset_id, Box::new(entry));
3031 }
3032 self.loading_assets
3033 .get(&asset_id)
3034 .and_then(|entry| entry.downcast_ref())
3035 .expect("asset cache entries are keyed by their asset type")
3036 }
3037
3038 #[track_caller]
3041 pub fn focus_handle(&self) -> FocusHandle {
3042 FocusHandle::new(&self.focus_handles)
3043 }
3044
3045 pub fn notify(&mut self, entity_id: EntityId) {
3047 crate::fast::dependencies::note_notify(&mut self.entities, entity_id);
3048 let window_invalidators = mem::take(
3049 self.window_invalidators_by_entity
3050 .entry(entity_id)
3051 .or_default(),
3052 );
3053
3054 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3059 .iter()
3060 .filter(|(window_id, _)| {
3061 self.tracked_entities
3062 .get(window_id)
3063 .is_some_and(|set| set.contains(&entity_id))
3064 })
3065 .map(|(_, invalidator)| invalidator.clone())
3066 .collect();
3067
3068 if live_invalidators.is_empty() {
3069 if self.pending_notifications.insert(entity_id) {
3070 self.pending_effects
3071 .push_back(Effect::Notify { emitter: entity_id });
3072 }
3073 } else {
3074 for invalidator in &live_invalidators {
3075 invalidator.invalidate_view(entity_id, self);
3076 }
3077 }
3078
3079 self.window_invalidators_by_entity
3080 .insert(entity_id, window_invalidators);
3081 }
3082
3083 #[cfg(any(test, feature = "test-support", debug_assertions))]
3085 pub fn get_name(&self) -> Option<&'static str> {
3086 self.name
3087 }
3088
3089 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3091 self.platform.can_select_mixed_files_and_dirs()
3092 }
3093
3094 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3099 for window in self.windows.values_mut().flatten() {
3101 _ = window.drop_image(image.clone());
3102 }
3103
3104 if let Some(window) = current_window {
3106 _ = window.drop_image(image);
3107 }
3108 }
3109
3110 #[cfg(any(feature = "inspector", debug_assertions))]
3112 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3113 self.inspector_renderer = Some(f);
3114 }
3115
3116 #[cfg(any(feature = "inspector", debug_assertions))]
3118 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3119 &mut self,
3120 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3121 ) where
3122 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3123 {
3124 self.inspector_element_registry.register(factory);
3125 }
3126
3127 pub fn init_colors(&mut self) {
3131 self.set_global(GlobalColors(Arc::new(Colors::default())));
3132 }
3133
3134 #[inline(never)]
3135 fn update_window_erased(
3136 &mut self,
3137 window_id: WindowId,
3138 update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3139 ) {
3140 self.update(|cx| {
3141 let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3142 update(None);
3143 return;
3144 };
3145
3146 let root_view = window.root.clone().unwrap();
3147
3148 cx.window_update_stack.push(window.handle.id);
3149 update(Some((root_view, &mut window, cx)));
3150 fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3151 cx.window_update_stack.pop();
3152
3153 if window.removed {
3154 cx.end_platform_drag(window_id);
3155 cx.window_handles.remove(&window_id);
3156 cx.windows.remove(window_id);
3157 if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3158 for entity_id in tracked {
3159 if let Some(windows) =
3160 cx.window_invalidators_by_entity.get_mut(&entity_id)
3161 {
3162 windows.remove(&window_id);
3163 }
3164 if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3165 cx.current_window_by_entity.remove(&entity_id);
3166 }
3167 }
3168 }
3169
3170 cx.window_closed_observers.clone().retain(&(), |callback| {
3171 callback(cx, window_id);
3172 true
3173 });
3174
3175 let quit_on_empty = match cx.quit_mode {
3176 QuitMode::Explicit => false,
3177 QuitMode::LastWindowClosed => true,
3178 QuitMode::Default => cfg!(not(target_os = "macos")),
3179 };
3180
3181 if quit_on_empty && cx.windows.is_empty() {
3182 cx.quit();
3183 }
3184 } else {
3185 cx.windows.get_mut(window_id)?.replace(window);
3186 }
3187 Some(())
3188 }
3189 if trail(window_id, window, cx).is_none() {
3190 update(None);
3191 }
3192 });
3193 }
3194
3195 #[inline(never)]
3196 fn update_entity_erased(
3197 &mut self,
3198 handle: &AnyEntity,
3199 entity_type: &str,
3200 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3201 ) {
3202 self.update(|cx| {
3203 let mut lease = cx.entities.lease_erased(handle, entity_type);
3204 update(lease.entity.as_deref_mut().unwrap(), cx);
3205 cx.entities.end_lease_erased(handle.entity_id, lease);
3206 });
3207 }
3208
3209 #[inline(never)]
3210 #[track_caller]
3211 fn prepare_spawn(&self) -> AsyncApp {
3212 if self.quitting {
3213 debug_panic!("Can't spawn on main thread after on_app_quit")
3214 };
3215 self.to_async()
3216 }
3217}
3218
3219impl AppContext for App {
3220 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3225 self.update(|cx| {
3226 let slot = cx.entities.reserve();
3227 let handle = slot.clone();
3228 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3229
3230 cx.push_effect(Effect::EntityCreated {
3231 entity: handle.into_any(),
3232 tid: TypeId::of::<T>(),
3233 window: cx.window_update_stack.last().cloned(),
3234 });
3235
3236 cx.entities.insert(slot, entity)
3237 })
3238 }
3239
3240 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3241 Reservation(self.entities.reserve())
3242 }
3243
3244 fn insert_entity<T: 'static>(
3245 &mut self,
3246 reservation: Reservation<T>,
3247 build_entity: impl FnOnce(&mut Context<T>) -> T,
3248 ) -> Entity<T> {
3249 self.update(|cx| {
3250 let slot = reservation.0;
3251 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3252 cx.entities.insert(slot, entity)
3253 })
3254 }
3255
3256 #[inline(always)]
3259 fn update_entity<T: 'static, R>(
3260 &mut self,
3261 handle: &Entity<T>,
3262 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3263 ) -> R {
3264 let mut update = Some(update);
3265 let mut result = None;
3266 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3267 let value = update.take().unwrap()(
3268 entity.downcast_mut::<T>().unwrap(),
3269 &mut Context::new_context(cx, handle.downgrade()),
3270 );
3271 result = Some(value);
3272 });
3273 result.unwrap()
3274 }
3275
3276 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3277 where
3278 T: 'static,
3279 {
3280 GpuiBorrow::new(handle.clone(), self)
3281 }
3282
3283 #[inline(always)]
3284 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3285 where
3286 T: 'static,
3287 {
3288 let entity = self.entities.read(handle);
3289 read(entity, self)
3290 }
3291
3292 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3293 where
3294 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3295 {
3296 self.update_window_id(handle.id, update)
3297 }
3298
3299 fn with_window<R>(
3300 &mut self,
3301 entity_id: EntityId,
3302 f: impl FnOnce(&mut Window, &mut App) -> R,
3303 ) -> Option<R> {
3304 App::with_window(self, entity_id, f)
3305 }
3306
3307 fn read_window<T, R>(
3308 &self,
3309 window: &WindowHandle<T>,
3310 read: impl FnOnce(Entity<T>, &App) -> R,
3311 ) -> Result<R>
3312 where
3313 T: 'static,
3314 {
3315 let window = self
3316 .windows
3317 .get(window.id)
3318 .context("window not found")?
3319 .as_deref()
3320 .expect("attempted to read a window that is already on the stack");
3321
3322 let root_view = window.root.clone().unwrap();
3323 let view = root_view
3324 .downcast::<T>()
3325 .map_err(|_| anyhow!("root view's type has changed"))?;
3326
3327 Ok(read(view, self))
3328 }
3329
3330 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3331 where
3332 R: Send + 'static,
3333 {
3334 self.background_executor.spawn(future)
3335 }
3336
3337 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3338 where
3339 G: Global,
3340 {
3341 let mut g = self.global::<G>();
3342 callback(g, self)
3343 }
3344}
3345
3346pub(crate) enum Effect {
3348 Notify {
3349 emitter: EntityId,
3350 },
3351 Emit {
3352 emitter: EntityId,
3353 event_type: TypeId,
3354 event: ArenaBox<dyn Any>,
3355 },
3356 RefreshWindows,
3357 NotifyGlobalObservers {
3358 global_type: TypeId,
3359 },
3360 Defer {
3361 callback: Box<dyn FnOnce(&mut App) + 'static>,
3362 },
3363 EntityCreated {
3364 entity: AnyEntity,
3365 tid: TypeId,
3366 window: Option<WindowId>,
3367 },
3368}
3369
3370impl std::fmt::Debug for Effect {
3371 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3372 match self {
3373 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3374 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3375 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3376 Effect::NotifyGlobalObservers { global_type } => {
3377 write!(f, "NotifyGlobalObservers({:?})", global_type)
3378 }
3379 Effect::Defer { .. } => write!(f, "Defer(..)"),
3380 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3381 }
3382 }
3383}
3384
3385pub(crate) struct GlobalLease<G: Global> {
3387 global: Box<dyn Any>,
3388 global_type: PhantomData<G>,
3389}
3390
3391impl<G: Global> GlobalLease<G> {
3392 fn new(global: Box<dyn Any>) -> Self {
3393 GlobalLease {
3394 global,
3395 global_type: PhantomData,
3396 }
3397 }
3398}
3399
3400impl<G: Global> Deref for GlobalLease<G> {
3401 type Target = G;
3402
3403 fn deref(&self) -> &Self::Target {
3404 self.global.downcast_ref().unwrap()
3405 }
3406}
3407
3408impl<G: Global> DerefMut for GlobalLease<G> {
3409 fn deref_mut(&mut self) -> &mut Self::Target {
3410 self.global.downcast_mut().unwrap()
3411 }
3412}
3413
3414pub struct AnyDrag {
3417 pub view: AnyView,
3419
3420 pub value: Arc<dyn Any>,
3422
3423 pub cursor_offset: Point<Pixels>,
3426
3427 pub cursor_style: Option<CursorStyle>,
3429
3430 pub external_payload_source: Option<ExternalDragPayloadSource>,
3433}
3434
3435pub type ExternalDragPayloadSource =
3438 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3439
3440#[derive(Clone)]
3443pub struct AnyTooltip {
3444 pub view: AnyView,
3446
3447 pub mouse_position: Point<Pixels>,
3449
3450 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3454}
3455
3456#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3458pub enum InputPreference {
3459 CharacterInput,
3461 KeyBindings,
3463}
3464
3465#[derive(Debug)]
3467pub struct KeystrokeEvent {
3468 pub keystroke: Keystroke,
3470
3471 pub input_preference: InputPreference,
3479
3480 pub action: Option<Box<dyn Action>>,
3482
3483 pub context_stack: Vec<KeyContext>,
3485}
3486
3487struct NullHttpClient;
3488
3489impl HttpClient for NullHttpClient {
3490 fn send(
3491 &self,
3492 _req: http_client::Request<http_client::AsyncBody>,
3493 ) -> futures::future::BoxFuture<
3494 'static,
3495 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3496 > {
3497 async move {
3498 anyhow::bail!("No HttpClient available");
3499 }
3500 .boxed()
3501 }
3502
3503 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3504 None
3505 }
3506
3507 fn proxy(&self) -> Option<&Url> {
3508 None
3509 }
3510}
3511
3512pub struct GpuiBorrow<'a, T> {
3514 inner: Option<Lease<T>>,
3515 app: &'a mut App,
3516}
3517
3518impl<'a, T: 'static> GpuiBorrow<'a, T> {
3519 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3520 app.start_update();
3521 let lease = app.entities.lease(&inner);
3522 Self {
3523 inner: Some(lease),
3524 app,
3525 }
3526 }
3527}
3528
3529impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3530 fn borrow(&self) -> &T {
3531 self.inner.as_ref().unwrap().borrow()
3532 }
3533}
3534
3535impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3536 fn borrow_mut(&mut self) -> &mut T {
3537 self.inner.as_mut().unwrap().borrow_mut()
3538 }
3539}
3540
3541impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3542 type Target = T;
3543
3544 fn deref(&self) -> &Self::Target {
3545 self.inner.as_ref().unwrap()
3546 }
3547}
3548
3549impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3550 fn deref_mut(&mut self) -> &mut T {
3551 self.inner.as_mut().unwrap()
3552 }
3553}
3554
3555impl<'a, T> Drop for GpuiBorrow<'a, T> {
3556 fn drop(&mut self) {
3557 let lease = self.inner.take().unwrap();
3558 self.app.notify(lease.id);
3559 self.app.entities.end_lease(lease);
3560 self.app.finish_update();
3561 }
3562}
3563
3564#[cfg(test)]
3565mod test {
3566 use std::{
3567 cell::{Cell, RefCell},
3568 ffi::OsString,
3569 path::PathBuf,
3570 rc::Rc,
3571 };
3572
3573 #[cfg(unix)]
3574 use std::os::unix::ffi::OsStringExt;
3575
3576 use crate::{
3577 AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3578 TestAppContext, Window,
3579 };
3580
3581 struct RenderCounter(Rc<Cell<usize>>);
3582
3583 impl Render for RenderCounter {
3584 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3585 self.0.set(self.0.get() + 1);
3586 Empty
3587 }
3588 }
3589
3590 #[gpui::test]
3591 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3592 let render_count = Rc::new(Cell::new(0));
3593
3594 let _window = cx.add_window({
3595 let render_count = render_count.clone();
3596 move |_, _| RenderCounter(render_count)
3597 });
3598
3599 cx.run_until_parked();
3600 let render_count_before_refresh = render_count.get();
3601
3602 cx.to_async().refresh();
3603
3604 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3605 }
3606
3607 #[gpui::test]
3608 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3609 let observed = Rc::new(RefCell::new(Vec::new()));
3610 let subscription = cx.update(|cx| {
3611 let observed = observed.clone();
3612 cx.on_missing_glyphs(move |missing_glyphs, _| {
3613 observed.borrow_mut().extend_from_slice(missing_glyphs);
3614 })
3615 });
3616 cx.update(|cx| {
3617 cx.text_system()
3618 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3619 });
3620 cx.run_until_parked();
3621 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3622
3623 let second_observed = Rc::new(RefCell::new(Vec::new()));
3624 let second_subscription = cx.update(|cx| {
3625 let second_observed = second_observed.clone();
3626 cx.on_missing_glyphs(move |missing_glyphs, _| {
3627 second_observed
3628 .borrow_mut()
3629 .extend_from_slice(missing_glyphs);
3630 })
3631 });
3632 cx.update(|cx| {
3633 cx.text_system()
3634 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3635 });
3636 cx.run_until_parked();
3637 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3638 assert_eq!(
3639 second_observed.borrow().as_slice(),
3640 &[missing_glyph("replacement")]
3641 );
3642
3643 drop(subscription);
3644 cx.update(|cx| {
3645 cx.text_system()
3646 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3647 });
3648 cx.run_until_parked();
3649 assert_eq!(
3650 second_observed.borrow().as_slice(),
3651 &[
3652 missing_glyph("replacement"),
3653 missing_glyph("after old drop")
3654 ]
3655 );
3656
3657 drop(second_subscription);
3658 cx.update(|cx| {
3659 cx.text_system()
3660 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3661 });
3662 cx.run_until_parked();
3663 assert_eq!(second_observed.borrow().len(), 2);
3664 }
3665
3666 #[test]
3667 fn test_gpui_borrow() {
3668 let cx = TestAppContext::single();
3669 let observation_count = Rc::new(RefCell::new(0));
3670
3671 let state = cx.update(|cx| {
3672 let state = cx.new(|_| false);
3673 cx.observe(&state, {
3674 let observation_count = observation_count.clone();
3675 move |_, _| {
3676 let mut count = observation_count.borrow_mut();
3677 *count += 1;
3678 }
3679 })
3680 .detach();
3681
3682 state
3683 });
3684
3685 cx.update(|cx| {
3686 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3688 });
3689
3690 cx.update(|cx| {
3691 state.write(cx, false);
3692 });
3693
3694 assert_eq!(*observation_count.borrow(), 2);
3695 }
3696
3697 #[gpui::test]
3698 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3699 #[cfg(unix)]
3700 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3701 #[cfg(not(unix))]
3702 let user_data_dir = OsString::from("C:\\zed data");
3703 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3704 let restart_path = PathBuf::from("updated-zed");
3705 let _application =
3706 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3707 let restart = cx.expect_restart();
3708
3709 cx.update(|cx| {
3710 cx.set_restart_path(restart_path.clone());
3711 cx.restart();
3712 });
3713
3714 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3715 assert_eq!(path, Some(restart_path));
3716 assert_eq!(restart_arguments, arguments);
3717 }
3718
3719 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3720 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3721 }
3722}