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