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