1use scheduler::Instant;
2use std::{
3 any::{TypeId, type_name},
4 cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
5 marker::PhantomData,
6 mem,
7 ops::{Deref, DerefMut},
8 path::{Path, PathBuf},
9 rc::{Rc, Weak},
10 sync::{Arc, atomic::Ordering::SeqCst},
11 time::Duration,
12};
13
14use anyhow::{Context as _, Result, anyhow};
15use derive_more::{Deref, DerefMut};
16use futures::{
17 Future, FutureExt,
18 channel::oneshot,
19 future::{LocalBoxFuture, Shared},
20};
21use itertools::Itertools;
22use parking_lot::RwLock;
23use slotmap::SlotMap;
24
25use crate::http_client::{HttpClient, NullHttpClient};
26pub use async_context::*;
27#[cfg(feature = "bench")]
28pub use bench_context::{BenchAppContext, BenchReport, BenchWindowContext, bench_platform};
29use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
30pub use context::*;
31pub use entity_map::*;
32use gpui_util::{ResultExt, debug_panic};
33#[cfg(any(test, feature = "test-support"))]
34pub use headless_app_context::*;
35use smallvec::SmallVec;
36#[cfg(any(test, feature = "test-support"))]
37pub use test_app::*;
38#[cfg(any(test, feature = "test-support"))]
39pub use test_context::*;
40#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
41pub use visual_test_context::*;
42
43#[cfg(any(feature = "inspector", debug_assertions))]
44use crate::InspectorElementRegistry;
45#[cfg(target_os = "macos")]
46use crate::MacActivationPolicy;
47use crate::{
48 Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
49 ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle,
50 DispatchPhase, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap,
51 ForegroundExecutor, Global, HapticFeedbackStyle, KeyBinding, KeyContext, Keymap, Keystroke,
52 LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
53 PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
54 PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
55 ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
56 SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
57 ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
58 WindowInvalidator,
59 colors::{Colors, GlobalColors},
60 hash, init_app_menus,
61};
62
63mod async_context;
64#[cfg(feature = "bench")]
65mod bench_context;
66mod context;
67mod entity_map;
68#[cfg(any(test, feature = "test-support"))]
69mod headless_app_context;
70#[cfg(any(test, feature = "test-support"))]
71mod test_app;
72#[cfg(any(test, feature = "test-support"))]
73mod test_context;
74#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
75mod visual_test_context;
76
77pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
79
80#[doc(hidden)]
83pub struct AppCell {
84 app: RefCell<App>,
85}
86
87impl AppCell {
88 #[doc(hidden)]
89 #[track_caller]
90 pub fn borrow(&self) -> AppRef<'_> {
91 if option_env!("TRACK_THREAD_BORROWS").is_some() {
92 let thread_id = std::thread::current().id();
93 eprintln!("borrowed {thread_id:?}");
94 }
95 AppRef(self.app.borrow())
96 }
97
98 #[doc(hidden)]
99 #[track_caller]
100 pub fn borrow_mut(&self) -> AppRefMut<'_> {
101 if option_env!("TRACK_THREAD_BORROWS").is_some() {
102 let thread_id = std::thread::current().id();
103 eprintln!("borrowed {thread_id:?}");
104 }
105 AppRefMut(self.app.borrow_mut())
106 }
107
108 #[doc(hidden)]
109 #[track_caller]
110 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
111 if option_env!("TRACK_THREAD_BORROWS").is_some() {
112 let thread_id = std::thread::current().id();
113 eprintln!("borrowed {thread_id:?}");
114 }
115 Ok(AppRefMut(self.app.try_borrow_mut()?))
116 }
117}
118
119#[doc(hidden)]
120#[derive(Deref, DerefMut)]
121pub struct AppRef<'a>(Ref<'a, App>);
122
123impl Drop for AppRef<'_> {
124 fn drop(&mut self) {
125 if option_env!("TRACK_THREAD_BORROWS").is_some() {
126 let thread_id = std::thread::current().id();
127 eprintln!("dropped borrow from {thread_id:?}");
128 }
129 }
130}
131
132#[doc(hidden)]
133#[derive(Deref, DerefMut)]
134pub struct AppRefMut<'a>(RefMut<'a, App>);
135
136impl Drop for AppRefMut<'_> {
137 fn drop(&mut self) {
138 if option_env!("TRACK_THREAD_BORROWS").is_some() {
139 let thread_id = std::thread::current().id();
140 eprintln!("dropped {thread_id:?}");
141 }
142 }
143}
144
145pub struct Application(Rc<AppCell>);
148
149pub struct ApplicationHandle {
155 app: Rc<AppCell>,
156}
157
158impl ApplicationHandle {
159 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
163 let cx = &mut *self.app.borrow_mut();
164 f(cx)
165 }
166
167 pub fn to_async(&self) -> AsyncApp {
170 self.update(|cx| cx.to_async())
171 }
172}
173
174impl Application {
177 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
179 Self(App::new_app(
180 platform,
181 Arc::new(()),
182 Arc::new(NullHttpClient),
183 ))
184 }
185
186 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
196 let this = Self::with_platform(platform);
197 this.0.borrow_mut().accessibility_force_disabled = true;
198 this
199 }
200
201 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
203 let mut context_lock = self.0.borrow_mut();
204 let asset_source = Arc::new(asset_source);
205 context_lock.asset_source = asset_source.clone();
206 context_lock.svg_renderer = SvgRenderer::new(asset_source);
207 drop(context_lock);
208 self
209 }
210
211 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
213 let mut context_lock = self.0.borrow_mut();
214 context_lock.http_client = http_client;
215 drop(context_lock);
216 self
217 }
218
219 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
222 self.0.borrow_mut().quit_mode = mode;
223 self
224 }
225
226 #[cfg(target_os = "macos")]
243 pub fn with_activation_policy(self, policy: MacActivationPolicy) -> Self {
244 self.0.borrow().platform.set_mac_activation_policy(policy);
245 self
246 }
247
248 pub fn run<F>(self, on_finish_launching: F)
251 where
252 F: 'static + FnOnce(&mut App),
253 {
254 let this = self.0.clone();
255 let platform = self.0.borrow().platform.clone();
256 platform.run(Box::new(move || {
257 let cx = &mut *this.borrow_mut();
258 on_finish_launching(cx);
259 }));
260 }
261
262 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
272 where
273 F: 'static + FnOnce(&mut App),
274 {
275 let this = self.0.clone();
276 let platform = self.0.borrow().platform.clone();
277 platform.run(Box::new(move || {
278 let cx = &mut *this.borrow_mut();
279 on_finish_launching(cx);
280 }));
281 ApplicationHandle { app: self.0 }
282 }
283
284 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
287 where
288 F: 'static + FnMut(Vec<String>),
289 {
290 self.0.borrow().platform.on_open_urls(Box::new(callback));
291 self
292 }
293
294 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
297 where
298 F: 'static + FnMut(&mut App),
299 {
300 let this = Rc::downgrade(&self.0);
301 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
302 if let Some(app) = this.upgrade() {
303 callback(&mut app.borrow_mut());
304 }
305 }));
306 self
307 }
308
309 pub fn on_system_wake<F>(&self, mut callback: F) -> &Self
311 where
312 F: 'static + FnMut(&mut App),
313 {
314 let this = Rc::downgrade(&self.0);
315 self.0
316 .borrow_mut()
317 .platform
318 .on_system_wake(Box::new(move || {
319 if let Some(app) = this.upgrade() {
320 callback(&mut app.borrow_mut());
321 }
322 }));
323 self
324 }
325
326 pub fn background_executor(&self) -> BackgroundExecutor {
328 self.0.borrow().background_executor.clone()
329 }
330
331 pub fn foreground_executor(&self) -> ForegroundExecutor {
333 self.0.borrow().foreground_executor.clone()
334 }
335
336 pub fn text_system(&self) -> Arc<TextSystem> {
338 self.0.borrow().text_system.clone()
339 }
340
341 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
343 self.0.borrow().path_for_auxiliary_executable(name)
344 }
345}
346
347type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
348type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
349pub(crate) type KeystrokeObserver =
350 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
351type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
352type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
353type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
354type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
355
356#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
358pub enum QuitMode {
359 #[default]
361 Default,
362 LastWindowClosed,
364 Explicit,
366}
367
368#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
373pub enum CursorHideMode {
374 Never,
376 OnTyping,
378 #[default]
381 OnTypingAndAction,
382}
383
384#[doc(hidden)]
385#[derive(Clone, PartialEq, Eq)]
386pub struct SystemWindowTab {
387 pub id: WindowId,
388 pub title: SharedString,
389 pub handle: AnyWindowHandle,
390 pub last_active_at: Instant,
391}
392
393impl SystemWindowTab {
394 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
396 Self {
397 id: handle.id,
398 title,
399 handle,
400 last_active_at: Instant::now(),
401 }
402 }
403}
404
405#[derive(Default)]
407pub struct SystemWindowTabController {
408 visible: Option<bool>,
409 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
410}
411
412impl Global for SystemWindowTabController {}
413
414impl SystemWindowTabController {
415 pub fn new() -> Self {
417 Self {
418 visible: None,
419 tab_groups: FxHashMap::default(),
420 }
421 }
422
423 pub fn init(cx: &mut App) {
425 cx.set_global(SystemWindowTabController::new());
426 }
427
428 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
430 &self.tab_groups
431 }
432
433 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
435 let controller = cx.global::<SystemWindowTabController>();
436 let current_group = controller
437 .tab_groups
438 .iter()
439 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
440
441 let current_group = current_group?;
442 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
444 let idx = group_ids.iter().position(|g| *g == current_group)?;
445 let next_idx = (idx + 1) % group_ids.len();
446
447 controller
448 .tab_groups
449 .get(group_ids[next_idx])
450 .and_then(|tabs| {
451 tabs.iter()
452 .max_by_key(|tab| tab.last_active_at)
453 .or_else(|| tabs.first())
454 .map(|tab| &tab.handle)
455 })
456 }
457
458 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
460 let controller = cx.global::<SystemWindowTabController>();
461 let current_group = controller
462 .tab_groups
463 .iter()
464 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
465
466 let current_group = current_group?;
467 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
469 let idx = group_ids.iter().position(|g| *g == current_group)?;
470 let prev_idx = if idx == 0 {
471 group_ids.len() - 1
472 } else {
473 idx - 1
474 };
475
476 controller
477 .tab_groups
478 .get(group_ids[prev_idx])
479 .and_then(|tabs| {
480 tabs.iter()
481 .max_by_key(|tab| tab.last_active_at)
482 .or_else(|| tabs.first())
483 .map(|tab| &tab.handle)
484 })
485 }
486
487 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
489 self.tab_groups
490 .values()
491 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
492 }
493
494 pub fn init_visible(cx: &mut App, visible: bool) {
496 let mut controller = cx.global_mut::<SystemWindowTabController>();
497 if controller.visible.is_none() {
498 controller.visible = Some(visible);
499 }
500 }
501
502 pub fn is_visible(&self) -> bool {
504 self.visible.unwrap_or(false)
505 }
506
507 pub fn set_visible(cx: &mut App, visible: bool) {
509 let mut controller = cx.global_mut::<SystemWindowTabController>();
510 controller.visible = Some(visible);
511 }
512
513 pub fn update_last_active(cx: &mut App, id: WindowId) {
515 let mut controller = cx.global_mut::<SystemWindowTabController>();
516 for windows in controller.tab_groups.values_mut() {
517 for tab in windows.iter_mut() {
518 if tab.id == id {
519 tab.last_active_at = Instant::now();
520 }
521 }
522 }
523 }
524
525 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
527 let mut controller = cx.global_mut::<SystemWindowTabController>();
528 for (_, windows) in controller.tab_groups.iter_mut() {
529 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
530 if ix < windows.len() && current_pos != ix {
531 let window_tab = windows.remove(current_pos);
532 windows.insert(ix, window_tab);
533 }
534 break;
535 }
536 }
537 }
538
539 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
541 let controller = cx.global::<SystemWindowTabController>();
542 let tab = controller
543 .tab_groups
544 .values()
545 .flat_map(|windows| windows.iter())
546 .find(|tab| tab.id == id);
547
548 if tab.map_or(true, |t| t.title == title) {
549 return;
550 }
551
552 let mut controller = cx.global_mut::<SystemWindowTabController>();
553 for windows in controller.tab_groups.values_mut() {
554 for tab in windows.iter_mut() {
555 if tab.id == id {
556 tab.title = title;
557 return;
558 }
559 }
560 }
561 }
562
563 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
565 let mut controller = cx.global_mut::<SystemWindowTabController>();
566 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
567 return;
568 };
569
570 let mut expected_tab_ids: Vec<_> = tabs
571 .iter()
572 .filter(|tab| tab.id != id)
573 .map(|tab| tab.id)
574 .sorted()
575 .collect();
576
577 let mut tab_group_id = None;
578 for (group_id, group_tabs) in &controller.tab_groups {
579 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
580 if tab_ids == expected_tab_ids {
581 tab_group_id = Some(*group_id);
582 break;
583 }
584 }
585
586 if let Some(tab_group_id) = tab_group_id {
587 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
588 tabs.push(tab);
589 }
590 } else {
591 let new_group_id = controller.tab_groups.len();
592 controller.tab_groups.insert(new_group_id, tabs);
593 }
594 }
595
596 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
598 let mut controller = cx.global_mut::<SystemWindowTabController>();
599 let mut removed_tab = None;
600
601 controller.tab_groups.retain(|_, tabs| {
602 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
603 removed_tab = Some(tabs.remove(pos));
604 }
605 !tabs.is_empty()
606 });
607
608 removed_tab
609 }
610
611 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
613 let mut removed_tab = Self::remove_tab(cx, id);
614 let mut controller = cx.global_mut::<SystemWindowTabController>();
615
616 if let Some(tab) = removed_tab {
617 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
618 controller.tab_groups.insert(new_group_id, vec![tab]);
619 }
620 }
621
622 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
624 let mut controller = cx.global_mut::<SystemWindowTabController>();
625 let Some(initial_tabs) = controller.tabs(id) else {
626 return;
627 };
628
629 let initial_tabs_len = initial_tabs.len();
630 let mut all_tabs = initial_tabs.clone();
631
632 for (_, mut tabs) in controller.tab_groups.drain() {
633 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
634 all_tabs.extend(tabs);
635 }
636
637 controller.tab_groups.insert(0, all_tabs);
638 }
639
640 pub fn select_next_tab(cx: &mut App, id: WindowId) {
642 let mut controller = cx.global_mut::<SystemWindowTabController>();
643 let Some(tabs) = controller.tabs(id) else {
644 return;
645 };
646
647 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
648 let next_index = (current_index + 1) % tabs.len();
649
650 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
651 window.activate_window();
652 });
653 }
654
655 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
657 let mut controller = cx.global_mut::<SystemWindowTabController>();
658 let Some(tabs) = controller.tabs(id) else {
659 return;
660 };
661
662 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
663 let previous_index = if current_index == 0 {
664 tabs.len() - 1
665 } else {
666 current_index - 1
667 };
668
669 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
670 window.activate_window();
671 });
672 }
673}
674
675pub(crate) enum GpuiMode {
676 #[cfg(any(test, feature = "test-support"))]
677 Test {
678 skip_drawing: bool,
679 },
680 Production,
681}
682
683impl GpuiMode {
684 #[cfg(any(test, feature = "test-support"))]
685 pub fn test() -> Self {
686 GpuiMode::Test {
687 skip_drawing: false,
688 }
689 }
690
691 #[inline]
692 pub(crate) fn skip_drawing(&self) -> bool {
693 match self {
694 #[cfg(any(test, feature = "test-support"))]
695 GpuiMode::Test { skip_drawing } => *skip_drawing,
696 GpuiMode::Production => false,
697 }
698 }
699}
700
701struct PlatformOwnedDrag {
702 source_window: WindowId,
703 state: PlatformOwnedDragState,
704}
705
706enum PlatformOwnedDragState {
707 Suspended(AnyDrag),
708 RestoredInSourceWindow,
711}
712
713pub struct App {
717 pub(crate) this: Weak<AppCell>,
718 pub(crate) platform: Rc<dyn Platform>,
719 text_system: Arc<TextSystem>,
720
721 pub(crate) actions: Rc<ActionRegistry>,
722 pub(crate) active_drag: Option<AnyDrag>,
723 platform_owned_drag: Option<PlatformOwnedDrag>,
724 pub(crate) background_executor: BackgroundExecutor,
725 pub(crate) foreground_executor: ForegroundExecutor,
726 pub(crate) entities: EntityMap,
727 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
728 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
729 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
730 pub(crate) focus_handles: Arc<FocusMap>,
731 pub(crate) keymap: Rc<RefCell<Keymap>>,
732 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
733 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
734 pub(crate) global_action_listeners:
735 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
736 pending_effects: VecDeque<Effect>,
737
738 pub(crate) observers: SubscriberSet<EntityId, Handler>,
739 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
740 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
741 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
742 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
743 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
744 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
745 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
746 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
747 pub(crate) restart_observers: SubscriberSet<(), Handler>,
748 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
749
750 pub(crate) element_arena: RefCell<Arena>,
753 pub(crate) event_arena: Arena,
755
756 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
761 global_entities: Vec<AnyEntity>,
765
766 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
768 asset_source: Arc<dyn AssetSource>,
769 pub(crate) svg_renderer: SvgRenderer,
770 http_client: Arc<dyn HttpClient>,
771
772 pub(crate) pending_notifications: FxHashSet<EntityId>,
774 pub(crate) pending_global_notifications: TypeIdHashSet,
775 pub(crate) restart_path: Option<PathBuf>,
776 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
778 pub(crate) prompt_builder: Option<PromptBuilder>,
779 pub(crate) window_invalidators_by_entity:
780 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
781 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
782 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
783 #[cfg(any(feature = "inspector", debug_assertions))]
784 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
785 #[cfg(any(feature = "inspector", debug_assertions))]
786 pub(crate) inspector_element_registry: InspectorElementRegistry,
787 #[cfg(any(test, feature = "test-support", debug_assertions))]
788 pub(crate) name: Option<&'static str>,
789 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
790
791 pub(crate) window_update_stack: Vec<WindowId>,
792 pub(crate) mode: GpuiMode,
793 pub(crate) cursor_hide_mode: CursorHideMode,
794 pub(crate) reduce_motion: bool,
795 pub(crate) accessibility_force_disabled: bool,
798 flushing_effects: bool,
799 pending_updates: usize,
800 quit_mode: QuitMode,
801 quitting: bool,
802
803 #[cfg(any(test, feature = "leak-detection"))]
806 _ref_counts: Arc<RwLock<EntityRefCounts>>,
807}
808
809impl App {
810 #[allow(clippy::new_ret_no_self)]
811 pub(crate) fn new_app(
812 platform: Rc<dyn Platform>,
813 asset_source: Arc<dyn AssetSource>,
814 http_client: Arc<dyn HttpClient>,
815 ) -> Rc<AppCell> {
816 let background_executor = platform.background_executor();
817 let foreground_executor = platform.foreground_executor();
818 assert!(
819 background_executor.is_main_thread(),
820 "must construct App on main thread"
821 );
822
823 let text_system = Arc::new(TextSystem::new(platform.text_system()));
824 let entities = EntityMap::new();
825 let keyboard_layout = platform.keyboard_layout();
826 let keyboard_mapper = platform.keyboard_mapper();
827
828 #[cfg(any(test, feature = "leak-detection"))]
829 let _ref_counts = entities.ref_counts_drop_handle();
830
831 let app = Rc::new_cyclic(|this| AppCell {
832 app: RefCell::new(App {
833 this: this.clone(),
834 platform: platform.clone(),
835 text_system,
836 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
837 mode: GpuiMode::Production,
838 actions: Rc::new(ActionRegistry::default()),
839 flushing_effects: false,
840 pending_updates: 0,
841 active_drag: None,
842 platform_owned_drag: None,
843 background_executor,
844 foreground_executor,
845 svg_renderer: SvgRenderer::new(asset_source.clone()),
846 loading_assets: Default::default(),
847 asset_source,
848 http_client,
849 globals_by_type: Default::default(),
850 global_entities: Default::default(),
851 entities,
852 new_entity_observers: SubscriberSet::new(),
853 windows: SlotMap::with_key(),
854 window_update_stack: Vec::new(),
855 window_handles: FxHashMap::default(),
856 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
857 keymap: Rc::new(RefCell::new(Keymap::default())),
858 keyboard_layout,
859 keyboard_mapper,
860 global_action_listeners: Default::default(),
861 pending_effects: VecDeque::new(),
862 pending_notifications: FxHashSet::default(),
863 pending_global_notifications: Default::default(),
864 observers: SubscriberSet::new(),
865 tracked_entities: FxHashMap::default(),
866 window_invalidators_by_entity: FxHashMap::default(),
867 current_window_by_entity: FxHashMap::default(),
868 event_listeners: SubscriberSet::new(),
869 release_listeners: SubscriberSet::new(),
870 keystroke_observers: SubscriberSet::new(),
871 keystroke_interceptors: SubscriberSet::new(),
872 keyboard_layout_observers: SubscriberSet::new(),
873 thermal_state_observers: SubscriberSet::new(),
874 global_observers: SubscriberSet::new(),
875 quit_observers: SubscriberSet::new(),
876 restart_observers: SubscriberSet::new(),
877 restart_path: None,
878 window_closed_observers: SubscriberSet::new(),
879 layout_id_buffer: Default::default(),
880 propagate_event: true,
881 prompt_builder: Some(PromptBuilder::Default),
882 #[cfg(any(feature = "inspector", debug_assertions))]
883 inspector_renderer: None,
884 #[cfg(any(feature = "inspector", debug_assertions))]
885 inspector_element_registry: InspectorElementRegistry::default(),
886 quit_mode: QuitMode::default(),
887 quitting: false,
888 cursor_hide_mode: CursorHideMode::default(),
889 reduce_motion: false,
890 accessibility_force_disabled: false,
891
892 #[cfg(any(test, feature = "test-support", debug_assertions))]
893 name: None,
894 element_arena: RefCell::new(Arena::new(1024 * 1024)),
895 event_arena: Arena::new(1024 * 1024),
896
897 #[cfg(any(test, feature = "leak-detection"))]
898 _ref_counts,
899 }),
900 });
901
902 init_app_menus(platform.as_ref(), &app.borrow());
903 SystemWindowTabController::init(&mut app.borrow_mut());
904
905 platform.on_keyboard_layout_change(Box::new({
906 let app = Rc::downgrade(&app);
907 move || {
908 if let Some(app) = app.upgrade() {
909 let cx = &mut app.borrow_mut();
910 cx.keyboard_layout = cx.platform.keyboard_layout();
911 cx.keyboard_mapper = cx.platform.keyboard_mapper();
912 cx.keyboard_layout_observers
913 .clone()
914 .retain(&(), move |callback| (callback)(cx));
915 }
916 }
917 }));
918
919 platform.on_thermal_state_change(Box::new({
920 let app = Rc::downgrade(&app);
921 move || {
922 if let Some(app) = app.upgrade() {
923 let cx = &mut app.borrow_mut();
924 cx.thermal_state_observers
925 .clone()
926 .retain(&(), move |callback| (callback)(cx));
927 }
928 }
929 }));
930
931 platform.on_quit(Box::new({
932 let cx = Rc::downgrade(&app);
933 move || {
934 if let Some(cx) = cx.upgrade() {
935 cx.borrow_mut().shutdown();
936 }
937 }
938 }));
939
940 app
941 }
942
943 #[doc(hidden)]
944 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
945 self.entities.ref_counts_drop_handle()
946 }
947
948 #[cfg(any(test, feature = "leak-detection"))]
954 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
955 self.entities.leak_detector_snapshot()
956 }
957
958 #[cfg(any(test, feature = "leak-detection"))]
970 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
971 self.entities.assert_no_new_leaks(snapshot)
972 }
973
974 pub fn shutdown(&mut self) {
977 let mut futures = Vec::new();
978
979 for observer in self.quit_observers.remove(&()) {
980 futures.push(observer(self));
981 }
982
983 self.windows.clear();
984 self.window_handles.clear();
985 self.flush_effects();
986 self.quitting = true;
987
988 let futures = futures::future::join_all(futures);
989 if self
990 .foreground_executor
991 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
992 .is_err()
993 {
994 log::error!("timed out waiting on app_will_quit");
995 }
996
997 self.quitting = false;
998 }
999
1000 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1002 self.keyboard_layout.as_ref()
1003 }
1004
1005 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1007 &self.keyboard_mapper
1008 }
1009
1010 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1012 where
1013 F: 'static + FnMut(&mut App),
1014 {
1015 let (subscription, activate) = self.keyboard_layout_observers.insert(
1016 (),
1017 Box::new(move |cx| {
1018 callback(cx);
1019 true
1020 }),
1021 );
1022 activate();
1023 subscription
1024 }
1025
1026 pub fn quit(&self) {
1028 self.platform.quit();
1029 }
1030
1031 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1034 self.cursor_hide_mode
1035 }
1036
1037 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1040 self.cursor_hide_mode = mode;
1041 }
1042
1043 pub fn is_cursor_visible(&self) -> bool {
1049 self.platform.is_cursor_visible()
1050 }
1051
1052 pub fn reduce_motion(&self) -> bool {
1055 self.reduce_motion
1056 }
1057
1058 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1061 if self.reduce_motion != reduce_motion {
1062 self.reduce_motion = reduce_motion;
1063 self.refresh_windows();
1064 }
1065 }
1066
1067 pub fn refresh_windows(&mut self) {
1070 self.pending_effects.push_back(Effect::RefreshWindows);
1071 }
1072
1073 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1074 self.start_update();
1075 let result = update(self);
1076 self.finish_update();
1077 result
1078 }
1079
1080 pub(crate) fn start_update(&mut self) {
1081 self.pending_updates += 1;
1082 }
1083
1084 pub(crate) fn finish_update(&mut self) {
1085 if !self.flushing_effects && self.pending_updates == 1 {
1086 self.flushing_effects = true;
1087 self.flush_effects();
1088 self.flushing_effects = false;
1089 }
1090 self.pending_updates -= 1;
1091 }
1092
1093 pub fn emit<EntityType, EventType>(&mut self, entity: &Entity<EntityType>, event: EventType)
1096 where
1097 EntityType: EventEmitter<EventType>,
1098 EventType: 'static,
1099 {
1100 let event = self
1101 .event_arena
1102 .alloc(|| event)
1103 .map(|it| it as &mut dyn Any);
1104 self.pending_effects.push_back(Effect::Emit {
1105 emitter: entity.entity_id(),
1106 event_type: TypeId::of::<EventType>(),
1107 event,
1108 });
1109 }
1110
1111 pub fn observe<W>(
1113 &mut self,
1114 entity: &Entity<W>,
1115 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1116 ) -> Subscription
1117 where
1118 W: 'static,
1119 {
1120 self.observe_internal(entity, move |e, cx| {
1121 on_notify(e, cx);
1122 true
1123 })
1124 }
1125
1126 pub(crate) fn detect_accessed_entities<R>(
1127 &mut self,
1128 callback: impl FnOnce(&mut App) -> R,
1129 ) -> (R, FxHashSet<EntityId>) {
1130 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1131 let result = callback(self);
1132 let entities_accessed_in_callback = self
1133 .entities
1134 .accessed_entities
1135 .get_mut()
1136 .difference(&accessed_entities_start)
1137 .copied()
1138 .collect::<FxHashSet<EntityId>>();
1139 (result, entities_accessed_in_callback)
1140 }
1141
1142 pub(crate) fn record_entities_accessed(
1143 &mut self,
1144 window_handle: AnyWindowHandle,
1145 invalidator: WindowInvalidator,
1146 entities: &FxHashSet<EntityId>,
1147 ) {
1148 let mut tracked_entities =
1149 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1150 for entity in tracked_entities.iter() {
1151 self.window_invalidators_by_entity
1152 .entry(*entity)
1153 .and_modify(|windows| {
1154 windows.remove(&window_handle.id);
1155 });
1156 }
1157 for entity in entities.iter() {
1158 self.window_invalidators_by_entity
1159 .entry(*entity)
1160 .or_default()
1161 .insert(window_handle.id, invalidator.clone());
1162 self.current_window_by_entity
1163 .insert(*entity, window_handle.id);
1164 }
1165 tracked_entities.clear();
1166 tracked_entities.extend(entities.iter().copied());
1167 self.tracked_entities
1168 .insert(window_handle.id, tracked_entities);
1169 }
1170
1171 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1172 let (subscription, activate) = self.observers.insert(key, value);
1173 self.defer(move |_| activate());
1174 subscription
1175 }
1176
1177 pub(crate) fn observe_internal<W>(
1178 &mut self,
1179 entity: &Entity<W>,
1180 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1181 ) -> Subscription
1182 where
1183 W: 'static,
1184 {
1185 let entity_id = entity.entity_id();
1186 let handle = entity.downgrade();
1187 self.new_observer(
1188 entity_id,
1189 Box::new(move |cx| {
1190 if let Some(entity) = handle.upgrade() {
1191 on_notify(entity, cx)
1192 } else {
1193 false
1194 }
1195 }),
1196 )
1197 }
1198
1199 pub fn subscribe<T, Event>(
1202 &mut self,
1203 entity: &Entity<T>,
1204 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1205 ) -> Subscription
1206 where
1207 T: 'static + EventEmitter<Event>,
1208 Event: 'static,
1209 {
1210 self.subscribe_internal(entity, move |entity, event, cx| {
1211 on_event(entity, event, cx);
1212 true
1213 })
1214 }
1215
1216 pub(crate) fn new_subscription(
1217 &mut self,
1218 key: EntityId,
1219 value: (TypeId, Listener),
1220 ) -> Subscription {
1221 let (subscription, activate) = self.event_listeners.insert(key, value);
1222 self.defer(move |_| activate());
1223 subscription
1224 }
1225 pub(crate) fn subscribe_internal<T, Evt>(
1226 &mut self,
1227 entity: &Entity<T>,
1228 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1229 ) -> Subscription
1230 where
1231 T: 'static + EventEmitter<Evt>,
1232 Evt: 'static,
1233 {
1234 let entity_id = entity.entity_id();
1235 let handle = entity.downgrade();
1236 self.new_subscription(
1237 entity_id,
1238 (
1239 TypeId::of::<Evt>(),
1240 Box::new(move |event, cx| {
1241 let event: &Evt = event.downcast_ref().expect("invalid event type");
1242 if let Some(entity) = handle.upgrade() {
1243 on_event(entity, event, cx)
1244 } else {
1245 false
1246 }
1247 }),
1248 ),
1249 )
1250 }
1251
1252 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1256 self.windows
1257 .keys()
1258 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1259 .collect()
1260 }
1261
1262 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1268 self.platform.window_stack()
1269 }
1270
1271 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1275 pub fn set_gpu_requirements(&self, requirements: Box<dyn std::any::Any>) {
1276 self.platform.set_gpu_requirements(requirements);
1277 }
1278
1279 pub fn set_keyring_label(&self, label: impl Into<SharedString>) {
1282 self.platform.set_keyring_label(label.into());
1283 }
1284
1285 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1287 self.platform.active_window()
1288 }
1289
1290 pub fn open_window<V: 'static + Render>(
1294 &mut self,
1295 options: crate::WindowOptions,
1296 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1297 ) -> anyhow::Result<WindowHandle<V>> {
1298 self.update(|cx| {
1299 let id = cx.windows.insert(None);
1300 let handle = WindowHandle::new(id);
1301 match Window::new(handle.into(), options, cx) {
1302 Ok(mut window) => {
1303 cx.window_update_stack.push(id);
1304 let root_view = build_root_view(&mut window, cx);
1305 cx.window_update_stack.pop();
1306 window.root.replace(root_view.into());
1307 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1308
1309 let clear = window.draw(cx);
1314 clear.clear(cx);
1315
1316 cx.window_handles.insert(id, window.handle);
1317 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1318 Ok(handle)
1319 }
1320 Err(e) => {
1321 cx.windows.remove(id);
1322 Err(e)
1323 }
1324 }
1325 })
1326 }
1327
1328 pub fn activate(&self, ignoring_other_apps: bool) {
1330 self.platform.activate(ignoring_other_apps);
1331 }
1332
1333 pub fn hide(&self) {
1335 self.platform.hide();
1336 }
1337
1338 pub fn hide_other_apps(&self) {
1340 self.platform.hide_other_apps();
1341 }
1342
1343 pub fn unhide_other_apps(&self) {
1345 self.platform.unhide_other_apps();
1346 }
1347
1348 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1350 self.platform.displays()
1351 }
1352
1353 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1355 self.platform.primary_display()
1356 }
1357
1358 pub fn is_screen_capture_supported(&self) -> bool {
1360 self.platform.is_screen_capture_supported()
1361 }
1362
1363 pub fn screen_capture_sources(
1365 &self,
1366 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1367 self.platform.screen_capture_sources()
1368 }
1369
1370 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1372 self.displays()
1373 .iter()
1374 .find(|display| display.id() == id)
1375 .cloned()
1376 }
1377
1378 pub fn thermal_state(&self) -> ThermalState {
1380 self.platform.thermal_state()
1381 }
1382
1383 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1385 where
1386 F: 'static + FnMut(&mut App),
1387 {
1388 let (subscription, activate) = self.thermal_state_observers.insert(
1389 (),
1390 Box::new(move |cx| {
1391 callback(cx);
1392 true
1393 }),
1394 );
1395 activate();
1396 subscription
1397 }
1398
1399 pub fn window_appearance(&self) -> WindowAppearance {
1401 self.platform.window_appearance()
1402 }
1403
1404 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1415 self.platform.set_window_appearance(appearance);
1416 }
1417
1418 pub fn supports_haptic_feedback(&self) -> bool {
1420 self.platform.supports_haptic_feedback()
1421 }
1422
1423 pub fn play_haptic_feedback(&self, style: HapticFeedbackStyle) {
1430 self.platform.play_haptic_feedback(style)
1431 }
1432
1433 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1435 self.platform.button_layout()
1436 }
1437
1438 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1440 self.platform.read_from_clipboard()
1441 }
1442
1443 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1445 self.text_rendering_mode.set(mode);
1446 }
1447
1448 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1450 self.text_rendering_mode.get()
1451 }
1452
1453 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1455 self.platform.write_to_clipboard(item)
1456 }
1457
1458 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1461 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1462 self.platform.read_from_primary()
1463 }
1464
1465 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1468 pub fn write_to_primary(&self, item: ClipboardItem) {
1469 self.platform.write_to_primary(item)
1470 }
1471
1472 #[cfg(target_os = "macos")]
1478 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1479 self.platform.read_from_find_pasteboard()
1480 }
1481
1482 #[cfg(target_os = "macos")]
1488 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1489 self.platform.write_to_find_pasteboard(item)
1490 }
1491
1492 pub fn write_credentials(
1494 &self,
1495 url: &str,
1496 username: &str,
1497 password: &[u8],
1498 ) -> Task<Result<()>> {
1499 self.platform.write_credentials(url, username, password)
1500 }
1501
1502 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1504 self.platform.read_credentials(url)
1505 }
1506
1507 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1509 self.platform.delete_credentials(url)
1510 }
1511
1512 pub fn open_url(&self, url: &str) {
1514 self.platform.open_url(url);
1515 }
1516
1517 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1524 self.platform.register_url_scheme(scheme)
1525 }
1526
1527 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1534 self.platform.set_app_identity(identifier, name);
1535 }
1536
1537 pub fn show_system_notification(&self, notification: SystemNotification) {
1544 self.platform.show_system_notification(notification);
1545 }
1546
1547 pub fn dismiss_system_notification(&self, tag: &str) {
1552 self.platform.dismiss_system_notification(tag);
1553 }
1554
1555 pub fn on_system_notification_response<F>(&self, mut callback: F)
1559 where
1560 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1561 {
1562 let this = self.this.clone();
1563 self.platform
1564 .on_system_notification_response(Box::new(move |response| {
1565 if let Some(app) = this.upgrade() {
1566 callback(response, &mut app.borrow_mut());
1567 }
1568 }));
1569 }
1570
1571 pub fn app_path(&self) -> Result<PathBuf> {
1575 self.platform.app_path()
1576 }
1577
1578 pub fn compositor_name(&self) -> &'static str {
1582 self.platform.compositor_name()
1583 }
1584
1585 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1587 self.platform.path_for_auxiliary_executable(name)
1588 }
1589
1590 pub fn prompt_for_paths(
1596 &self,
1597 options: PathPromptOptions,
1598 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1599 self.platform.prompt_for_paths(options)
1600 }
1601
1602 pub fn prompt_for_new_path(
1609 &self,
1610 directory: &Path,
1611 suggested_name: Option<&str>,
1612 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1613 self.platform.prompt_for_new_path(directory, suggested_name)
1614 }
1615
1616 pub fn reveal_path(&self, path: &Path) {
1618 self.platform.reveal_path(path)
1619 }
1620
1621 pub fn open_with_system(&self, path: &Path) {
1623 self.platform.open_with_system(path)
1624 }
1625
1626 pub fn should_auto_hide_scrollbars(&self) -> bool {
1628 self.platform.should_auto_hide_scrollbars()
1629 }
1630
1631 pub fn restart(&mut self) {
1633 self.restart_observers
1634 .clone()
1635 .retain(&(), |observer| observer(self));
1636 self.platform.restart(self.restart_path.take())
1637 }
1638
1639 pub fn set_restart_path(&mut self, path: PathBuf) {
1641 self.restart_path = Some(path);
1642 }
1643
1644 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1646 self.http_client.clone()
1647 }
1648
1649 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1651 self.http_client = new_client;
1652 }
1653
1654 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1657 self.quit_mode = mode;
1658 }
1659
1660 pub fn svg_renderer(&self) -> SvgRenderer {
1662 self.svg_renderer.clone()
1663 }
1664
1665 pub(crate) fn push_effect(&mut self, effect: Effect) {
1666 match &effect {
1667 Effect::Notify { emitter } => {
1668 if !self.pending_notifications.insert(*emitter) {
1669 return;
1670 }
1671 }
1672 Effect::NotifyGlobalObservers { global_type } => {
1673 if !self.pending_global_notifications.insert(*global_type) {
1674 return;
1675 }
1676 }
1677 _ => {}
1678 };
1679
1680 self.pending_effects.push_back(effect);
1681 }
1682
1683 fn flush_effects(&mut self) {
1687 loop {
1688 self.release_dropped_entities();
1689 self.release_dropped_focus_handles();
1690 if let Some(effect) = self.pending_effects.pop_front() {
1691 match effect {
1692 Effect::Notify { emitter } => {
1693 self.apply_notify_effect(emitter);
1694 }
1695
1696 Effect::Emit {
1697 emitter,
1698 event_type,
1699 event,
1700 } => self.apply_emit_effect(emitter, event_type, &*event),
1701
1702 Effect::RefreshWindows => {
1703 self.apply_refresh_effect();
1704 }
1705
1706 Effect::NotifyGlobalObservers { global_type } => {
1707 self.apply_notify_global_observers_effect(global_type);
1708 }
1709
1710 Effect::Defer { callback } => {
1711 self.apply_defer_effect(callback);
1712 }
1713 Effect::EntityCreated {
1714 entity,
1715 tid,
1716 window,
1717 } => {
1718 self.apply_entity_created_effect(entity, tid, window);
1719 }
1720 }
1721 } else {
1722 #[cfg(any(test, feature = "test-support", feature = "bench"))]
1723 for window in self
1724 .windows
1725 .values()
1726 .filter_map(|window| {
1727 let window = window.as_deref()?;
1728 window.invalidator.is_dirty().then_some(window.handle)
1729 })
1730 .collect::<Vec<_>>()
1731 {
1732 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1733 .unwrap();
1734 }
1735
1736 if self.pending_effects.is_empty() {
1737 self.event_arena.clear();
1738 break;
1739 }
1740 }
1741 }
1742 }
1743
1744 fn release_dropped_entities(&mut self) {
1748 loop {
1749 let dropped = self.entities.take_dropped();
1750 if dropped.is_empty() {
1751 break;
1752 }
1753
1754 for (entity_id, mut entity) in dropped {
1755 self.observers.remove(&entity_id);
1756 self.event_listeners.remove(&entity_id);
1757 self.window_invalidators_by_entity.remove(&entity_id);
1758 self.current_window_by_entity.remove(&entity_id);
1759 for release_callback in self.release_listeners.remove(&entity_id) {
1760 release_callback(entity.as_mut(), self);
1761 }
1762 }
1763 }
1764 }
1765
1766 fn release_dropped_focus_handles(&mut self) {
1768 self.focus_handles
1769 .clone()
1770 .write()
1771 .retain(|handle_id, focus| {
1772 if focus.ref_count.load(SeqCst) == 0 {
1773 for window_handle in self.windows() {
1774 window_handle
1775 .update(self, |_, window, _| {
1776 if window.focus == Some(handle_id) {
1777 window.blur();
1778 }
1779 })
1780 .unwrap();
1781 }
1782 false
1783 } else {
1784 true
1785 }
1786 });
1787 }
1788
1789 fn apply_notify_effect(&mut self, emitter: EntityId) {
1790 self.pending_notifications.remove(&emitter);
1791
1792 self.observers
1793 .clone()
1794 .retain(&emitter, |handler| handler(self));
1795 }
1796
1797 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1798 self.event_listeners
1799 .clone()
1800 .retain(&emitter, |(stored_type, handler)| {
1801 if *stored_type == event_type {
1802 handler(event, self)
1803 } else {
1804 true
1805 }
1806 });
1807 }
1808
1809 fn apply_refresh_effect(&mut self) {
1810 for window in self.windows.values_mut() {
1811 if let Some(window) = window.as_deref_mut() {
1812 window.refreshing = true;
1813 window.invalidator.set_dirty(true);
1814 }
1815 }
1816 }
1817
1818 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1819 self.pending_global_notifications.remove(&type_id);
1820 self.global_observers
1821 .clone()
1822 .retain(&type_id, |observer| observer(self));
1823 }
1824
1825 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1826 callback(self);
1827 }
1828
1829 fn apply_entity_created_effect(
1830 &mut self,
1831 entity: AnyEntity,
1832 tid: TypeId,
1833 window: Option<WindowId>,
1834 ) {
1835 if let Some(id) = window {
1839 self.current_window_by_entity.insert(entity.entity_id(), id);
1840 }
1841
1842 self.new_entity_observers.clone().retain(&tid, |observer| {
1843 if let Some(id) = window {
1844 self.update_window_id(id, {
1845 let entity = entity.clone();
1846 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1847 })
1848 .expect("All windows should be off the stack when flushing effects");
1849 } else {
1850 (observer)(entity.clone(), &mut None, self)
1851 }
1852 true
1853 });
1854 }
1855
1856 pub fn with_window<R>(
1862 &mut self,
1863 entity_id: EntityId,
1864 f: impl FnOnce(&mut Window, &mut App) -> R,
1865 ) -> Option<R> {
1866 let window_id = *self.current_window_by_entity.get(&entity_id)?;
1867 self.update_window_id(window_id, |_, window, cx| f(window, cx))
1868 .ok()
1869 }
1870
1871 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1872 self.current_window_by_entity
1873 .entry(entity_id)
1874 .or_insert(window);
1875 }
1876
1877 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1878 where
1879 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1880 {
1881 self.update(|cx| {
1882 let mut window = cx.windows.get_mut(id)?.take()?;
1883
1884 let root_view = window.root.clone().unwrap();
1885
1886 cx.window_update_stack.push(window.handle.id);
1887 let result = update(root_view, &mut window, cx);
1888 fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1889 cx.window_update_stack.pop();
1890
1891 if window.removed {
1892 cx.end_platform_drag(id);
1893 cx.window_handles.remove(&id);
1894 cx.windows.remove(id);
1895 if let Some(tracked) = cx.tracked_entities.remove(&id) {
1896 for entity_id in tracked {
1897 if let Some(windows) =
1898 cx.window_invalidators_by_entity.get_mut(&entity_id)
1899 {
1900 windows.remove(&id);
1901 }
1902 if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1903 cx.current_window_by_entity.remove(&entity_id);
1904 }
1905 }
1906 }
1907
1908 cx.window_closed_observers.clone().retain(&(), |callback| {
1909 callback(cx, id);
1910 true
1911 });
1912
1913 let quit_on_empty = match cx.quit_mode {
1914 QuitMode::Explicit => false,
1915 QuitMode::LastWindowClosed => true,
1916 QuitMode::Default => cfg!(not(target_os = "macos")),
1917 };
1918
1919 if quit_on_empty && cx.windows.is_empty() {
1920 cx.quit();
1921 }
1922 } else {
1923 cx.windows.get_mut(id)?.replace(window);
1924 }
1925 Some(())
1926 }
1927 trail(id, window, cx)?;
1928
1929 Some(result)
1930 })
1931 .context("window not found")
1932 }
1933
1934 pub fn to_async(&self) -> AsyncApp {
1937 AsyncApp {
1938 app: self.this.clone(),
1939 background_executor: self.background_executor.clone(),
1940 foreground_executor: self.foreground_executor.clone(),
1941 }
1942 }
1943
1944 pub fn background_executor(&self) -> &BackgroundExecutor {
1946 &self.background_executor
1947 }
1948
1949 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1951 if self.quitting {
1952 panic!("Can't spawn on main thread after on_app_quit")
1953 };
1954 &self.foreground_executor
1955 }
1956
1957 #[track_caller]
1960 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1961 where
1962 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1963 R: 'static,
1964 {
1965 if self.quitting {
1966 debug_panic!("Can't spawn on main thread after on_app_quit")
1967 };
1968
1969 let mut cx = self.to_async();
1970
1971 self.foreground_executor
1972 .spawn(async move { f(&mut cx).await }.boxed_local())
1973 }
1974
1975 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1979 where
1980 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1981 R: 'static,
1982 {
1983 if self.quitting {
1984 debug_panic!("Can't spawn on main thread after on_app_quit")
1985 };
1986
1987 let mut cx = self.to_async();
1988
1989 self.foreground_executor
1990 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
1991 }
1992
1993 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1996 self.push_effect(Effect::Defer {
1997 callback: Box::new(f),
1998 });
1999 }
2000
2001 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2003 &self.asset_source
2004 }
2005
2006 pub fn text_system(&self) -> &Arc<TextSystem> {
2008 &self.text_system
2009 }
2010
2011 pub fn has_global<G: Global>(&self) -> bool {
2013 self.globals_by_type.contains_key(&TypeId::of::<G>())
2014 }
2015
2016 #[track_caller]
2018 pub fn global<G: Global>(&self) -> &G {
2019 self.globals_by_type
2020 .get(&TypeId::of::<G>())
2021 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2022 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2023 }
2024
2025 pub fn try_global<G: Global>(&self) -> Option<&G> {
2027 self.globals_by_type
2028 .get(&TypeId::of::<G>())
2029 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2030 }
2031
2032 #[track_caller]
2034 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2035 let global_type = TypeId::of::<G>();
2036 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2037 self.globals_by_type
2038 .get_mut(&global_type)
2039 .and_then(|any_state| any_state.downcast_mut::<G>())
2040 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2041 }
2042
2043 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2046 let global_type = TypeId::of::<G>();
2047 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2048 self.globals_by_type
2049 .entry(global_type)
2050 .or_insert_with(|| Box::<G>::default())
2051 .downcast_mut::<G>()
2052 .unwrap()
2053 }
2054
2055 pub fn set_global<G: Global>(&mut self, global: G) {
2057 let global_type = TypeId::of::<G>();
2058 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2059 self.globals_by_type.insert(global_type, Box::new(global));
2060 }
2061
2062 #[cfg(any(test, feature = "test-support"))]
2064 pub fn clear_globals(&mut self) {
2065 self.globals_by_type.drain();
2066 }
2067
2068 pub fn remove_global<G: Global>(&mut self) -> G {
2070 let global_type = TypeId::of::<G>();
2071 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2072 *self
2073 .globals_by_type
2074 .remove(&global_type)
2075 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2076 .downcast()
2077 .unwrap()
2078 }
2079
2080 pub fn observe_global<G: Global>(
2082 &mut self,
2083 mut f: impl FnMut(&mut Self) + 'static,
2084 ) -> Subscription {
2085 let (subscription, activate) = self.global_observers.insert(
2086 TypeId::of::<G>(),
2087 Box::new(move |cx| {
2088 f(cx);
2089 true
2090 }),
2091 );
2092 self.defer(move |_| activate());
2093 subscription
2094 }
2095
2096 #[track_caller]
2098 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2099 GlobalLease::new(
2100 self.globals_by_type
2101 .remove(&TypeId::of::<G>())
2102 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2103 .unwrap(),
2104 )
2105 }
2106
2107 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2109 let global_type = TypeId::of::<G>();
2110
2111 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2112 self.globals_by_type.insert(global_type, lease.global);
2113 }
2114
2115 pub fn insert_global_entity<T: 'static>(&mut self, entity: Entity<T>) {
2118 let any = entity.into_any();
2119 if !self.global_entities.contains(&any) {
2120 self.global_entities.push(any);
2121 }
2122 }
2123
2124 pub fn remove_global_entity<T: 'static>(&mut self, entity: &Entity<T>) {
2127 self.global_entities
2128 .retain(|any| any.entity_id() != entity.entity_id());
2129 }
2130
2131 pub fn global_entities<T: 'static>(&self) -> impl Iterator<Item = Entity<T>> {
2133 let mut iter = self.global_entities.iter();
2134 iter.filter_map(|any| any.clone().downcast::<T>().ok())
2135 }
2136
2137 pub(crate) fn new_entity_observer(
2138 &self,
2139 key: TypeId,
2140 value: NewEntityListener,
2141 ) -> Subscription {
2142 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2143 activate();
2144 subscription
2145 }
2146
2147 pub fn observe_new<T: 'static>(
2150 &self,
2151 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2152 ) -> Subscription {
2153 self.new_entity_observer(
2154 TypeId::of::<T>(),
2155 Box::new(
2156 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2157 any_entity
2158 .downcast::<T>()
2159 .unwrap()
2160 .update(cx, |entity_state, cx| {
2161 on_new(entity_state, window.as_deref_mut(), cx)
2162 })
2163 },
2164 ),
2165 )
2166 }
2167
2168 pub fn observe_release<T>(
2171 &self,
2172 handle: &Entity<T>,
2173 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2174 ) -> Subscription
2175 where
2176 T: 'static,
2177 {
2178 let (subscription, activate) = self.release_listeners.insert(
2179 handle.entity_id(),
2180 Box::new(move |entity, cx| {
2181 let entity = entity.downcast_mut().expect("invalid entity type");
2182 on_release(entity, cx)
2183 }),
2184 );
2185 activate();
2186 subscription
2187 }
2188
2189 pub fn observe_release_in<T>(
2192 &self,
2193 handle: &Entity<T>,
2194 window: &Window,
2195 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2196 ) -> Subscription
2197 where
2198 T: 'static,
2199 {
2200 let window_handle = window.handle;
2201 self.observe_release(handle, move |entity, cx| {
2202 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2203 })
2204 }
2205
2206 pub fn observe_keystrokes(
2210 &mut self,
2211 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2212 ) -> Subscription {
2213 fn inner(
2214 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2215 handler: KeystrokeObserver,
2216 ) -> Subscription {
2217 let (subscription, activate) = keystroke_observers.insert((), handler);
2218 activate();
2219 subscription
2220 }
2221
2222 inner(
2223 &self.keystroke_observers,
2224 Box::new(move |event, window, cx| {
2225 f(event, window, cx);
2226 true
2227 }),
2228 )
2229 }
2230
2231 pub fn intercept_keystrokes(
2236 &mut self,
2237 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2238 ) -> Subscription {
2239 fn inner(
2240 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2241 handler: KeystrokeObserver,
2242 ) -> Subscription {
2243 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2244 activate();
2245 subscription
2246 }
2247
2248 inner(
2249 &self.keystroke_interceptors,
2250 Box::new(move |event, window, cx| {
2251 f(event, window, cx);
2252 true
2253 }),
2254 )
2255 }
2256
2257 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2259 self.keymap.borrow_mut().add_bindings(bindings);
2260 self.pending_effects.push_back(Effect::RefreshWindows);
2261 }
2262
2263 pub fn clear_key_bindings(&mut self) {
2265 self.keymap.borrow_mut().clear();
2266 self.pending_effects.push_back(Effect::RefreshWindows);
2267 }
2268
2269 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2271 self.keymap.clone()
2272 }
2273
2274 pub fn on_action<A: Action>(
2278 &mut self,
2279 listener: impl Fn(&A, &mut Self) + 'static,
2280 ) -> &mut Self {
2281 self.global_action_listeners
2282 .entry(TypeId::of::<A>())
2283 .or_default()
2284 .push(Rc::new(move |action, phase, cx| {
2285 if phase == DispatchPhase::Bubble {
2286 let action = action.downcast_ref().unwrap();
2287 listener(action, cx)
2288 }
2289 }));
2290 self
2291 }
2292
2293 pub fn stop_propagation(&mut self) {
2298 self.propagate_event = false;
2299 }
2300
2301 pub fn propagate(&mut self) {
2306 self.propagate_event = true;
2307 }
2308
2309 pub fn build_action(
2311 &self,
2312 name: &str,
2313 data: Option<serde_json::Value>,
2314 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2315 self.actions.build_action(name, data)
2316 }
2317
2318 pub fn all_action_names(&self) -> &[&'static str] {
2321 self.actions.all_action_names()
2322 }
2323
2324 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2328 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2329 }
2330
2331 pub fn action_schemas(
2333 &self,
2334 generator: &mut schemars::SchemaGenerator,
2335 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2336 self.actions.action_schemas(generator)
2337 }
2338
2339 pub fn action_schema_by_name(
2344 &self,
2345 name: &str,
2346 generator: &mut schemars::SchemaGenerator,
2347 ) -> Option<Option<schemars::Schema>> {
2348 self.actions.action_schema_by_name(name, generator)
2349 }
2350
2351 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2353 self.actions.deprecated_aliases()
2354 }
2355
2356 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2358 self.actions.deprecation_messages()
2359 }
2360
2361 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2363 self.actions.documentation()
2364 }
2365
2366 pub fn on_app_quit<Fut>(
2369 &self,
2370 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2371 ) -> Subscription
2372 where
2373 Fut: 'static + Future<Output = ()>,
2374 {
2375 let (subscription, activate) = self.quit_observers.insert(
2376 (),
2377 Box::new(move |cx| {
2378 let future = on_quit(cx);
2379 future.boxed_local()
2380 }),
2381 );
2382 activate();
2383 subscription
2384 }
2385
2386 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2390 let (subscription, activate) = self.restart_observers.insert(
2391 (),
2392 Box::new(move |cx| {
2393 on_restart(cx);
2394 true
2395 }),
2396 );
2397 activate();
2398 subscription
2399 }
2400
2401 pub fn on_window_closed(
2404 &self,
2405 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2406 ) -> Subscription {
2407 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2408 activate();
2409 subscription
2410 }
2411
2412 pub(crate) fn clear_pending_keystrokes(&mut self) {
2413 for window in self.windows() {
2414 window
2415 .update(self, |_, window, cx| {
2416 if window.pending_input_keystrokes().is_some() {
2417 window.clear_pending_keystrokes();
2418 window.pending_input_changed(cx);
2419 }
2420 })
2421 .ok();
2422 }
2423 }
2424
2425 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2428 let mut action_available = false;
2429 if let Some(window) = self.active_window()
2430 && let Ok(window_action_available) =
2431 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2432 {
2433 action_available = window_action_available;
2434 }
2435
2436 action_available
2437 || self
2438 .global_action_listeners
2439 .contains_key(&action.as_any().type_id())
2440 }
2441
2442 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2444 let menus: Vec<Menu> = menus.into_iter().collect();
2445 self.platform.set_menus(menus, &self.keymap.borrow());
2446 }
2447
2448 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2450 self.platform.get_menus()
2451 }
2452
2453 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2455 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2456 }
2457
2458 pub fn perform_dock_menu_action(&self, action: usize) {
2460 self.platform.perform_dock_menu_action(action);
2461 }
2462
2463 pub fn add_recent_document(&self, path: &Path) {
2468 self.platform.add_recent_document(path);
2469 }
2470
2471 pub fn update_jump_list(
2474 &self,
2475 menus: Vec<MenuItem>,
2476 entries: Vec<SmallVec<[PathBuf; 2]>>,
2477 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2478 self.platform.update_jump_list(menus, entries)
2479 }
2480
2481 pub fn dispatch_action(&mut self, action: &dyn Action) {
2484 if let Some(active_window) = self.active_window() {
2485 active_window
2486 .update(self, |_, window, cx| {
2487 window.dispatch_action(action.boxed_clone(), cx)
2488 })
2489 .log_err();
2490 } else {
2491 self.dispatch_global_action(action);
2492 }
2493 }
2494
2495 fn dispatch_global_action(&mut self, action: &dyn Action) {
2496 self.propagate_event = true;
2497
2498 if let Some(mut global_listeners) = self
2499 .global_action_listeners
2500 .remove(&action.as_any().type_id())
2501 {
2502 for listener in &global_listeners {
2503 listener(action.as_any(), DispatchPhase::Capture, self);
2504 if !self.propagate_event {
2505 break;
2506 }
2507 }
2508
2509 global_listeners.extend(
2510 self.global_action_listeners
2511 .remove(&action.as_any().type_id())
2512 .unwrap_or_default(),
2513 );
2514
2515 self.global_action_listeners
2516 .insert(action.as_any().type_id(), global_listeners);
2517 }
2518
2519 if self.propagate_event
2520 && let Some(mut global_listeners) = self
2521 .global_action_listeners
2522 .remove(&action.as_any().type_id())
2523 {
2524 for listener in global_listeners.iter().rev() {
2525 listener(action.as_any(), DispatchPhase::Bubble, self);
2526 if !self.propagate_event {
2527 break;
2528 }
2529 }
2530
2531 global_listeners.extend(
2532 self.global_action_listeners
2533 .remove(&action.as_any().type_id())
2534 .unwrap_or_default(),
2535 );
2536
2537 self.global_action_listeners
2538 .insert(action.as_any().type_id(), global_listeners);
2539 }
2540 }
2541
2542 pub fn has_active_drag(&self) -> bool {
2544 self.active_drag.is_some()
2545 }
2546
2547 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2549 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2550 }
2551
2552 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2554 if self.active_drag.is_some() {
2555 self.active_drag = None;
2556 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2557 drag.source_window == window.window_handle().window_id()
2558 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2559 }) {
2560 self.platform_owned_drag = None;
2561 }
2562 window.refresh();
2563 true
2564 } else {
2565 false
2566 }
2567 }
2568
2569 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2570 let Some(drag) = self.active_drag.take() else {
2571 return false;
2572 };
2573 self.platform_owned_drag = Some(PlatformOwnedDrag {
2574 source_window,
2575 state: PlatformOwnedDragState::Suspended(drag),
2576 });
2577 true
2578 }
2579
2580 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2581 let Some(platform_drag) = self
2582 .platform_owned_drag
2583 .as_mut()
2584 .filter(|drag| drag.source_window == source_window)
2585 else {
2586 return false;
2587 };
2588 let state = std::mem::replace(
2589 &mut platform_drag.state,
2590 PlatformOwnedDragState::RestoredInSourceWindow,
2591 );
2592 let PlatformOwnedDragState::Suspended(drag) = state else {
2593 return false;
2594 };
2595 self.active_drag = Some(drag);
2596 true
2597 }
2598
2599 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2600 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2601 drag.source_window == source_window
2602 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2603 }) else {
2604 return false;
2605 };
2606 let Some(drag) = self.active_drag.take() else {
2607 return false;
2608 };
2609 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2610 true
2611 }
2612
2613 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2614 if !self
2615 .platform_owned_drag
2616 .as_ref()
2617 .is_some_and(|drag| drag.source_window == source_window)
2618 {
2619 return false;
2620 }
2621 self.platform_owned_drag = None;
2622 self.active_drag = None;
2623 true
2624 }
2625
2626 pub fn set_active_drag_cursor_style(
2628 &mut self,
2629 cursor_style: CursorStyle,
2630 window: &mut Window,
2631 ) -> bool {
2632 if let Some(ref mut drag) = self.active_drag {
2633 drag.cursor_style = Some(cursor_style);
2634 window.refresh();
2635 true
2636 } else {
2637 false
2638 }
2639 }
2640
2641 pub fn set_prompt_builder(
2644 &mut self,
2645 renderer: impl Fn(
2646 PromptLevel,
2647 &str,
2648 Option<&str>,
2649 &[PromptButton],
2650 PromptHandle,
2651 &mut Window,
2652 &mut App,
2653 ) -> RenderablePromptHandle
2654 + 'static,
2655 ) {
2656 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2657 }
2658
2659 pub fn reset_prompt_builder(&mut self) {
2661 self.prompt_builder = Some(PromptBuilder::Default);
2662 }
2663
2664 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2666 let asset_id = (TypeId::of::<A>(), hash(source));
2667 self.loading_assets.remove(&asset_id);
2668 }
2669
2670 #[cfg(any(test, feature = "test-support"))]
2673 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
2674 let asset_id = (TypeId::of::<A>(), hash(source));
2675 self.loading_assets.contains_key(&asset_id)
2676 }
2677
2678 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2683 let asset_id = (TypeId::of::<A>(), hash(source));
2684 let mut is_first = false;
2685 let task = self
2686 .loading_assets
2687 .remove(&asset_id)
2688 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2689 .unwrap_or_else(|| {
2690 is_first = true;
2691 let future = A::load(source.clone(), self);
2692
2693 self.background_executor().spawn(future).shared()
2694 });
2695
2696 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2697
2698 (task, is_first)
2699 }
2700
2701 #[track_caller]
2704 pub fn focus_handle(&self) -> FocusHandle {
2705 FocusHandle::new(&self.focus_handles)
2706 }
2707
2708 pub fn notify(&mut self, entity_id: EntityId) {
2710 let window_invalidators = mem::take(
2711 self.window_invalidators_by_entity
2712 .entry(entity_id)
2713 .or_default(),
2714 );
2715
2716 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2721 .iter()
2722 .filter(|(window_id, _)| {
2723 self.tracked_entities
2724 .get(window_id)
2725 .is_some_and(|set| set.contains(&entity_id))
2726 })
2727 .map(|(_, invalidator)| invalidator.clone())
2728 .collect();
2729
2730 if live_invalidators.is_empty() {
2731 if self.pending_notifications.insert(entity_id) {
2732 self.pending_effects
2733 .push_back(Effect::Notify { emitter: entity_id });
2734 }
2735 } else {
2736 for invalidator in &live_invalidators {
2737 invalidator.invalidate_view(entity_id, self);
2738 }
2739 }
2740
2741 self.window_invalidators_by_entity
2742 .insert(entity_id, window_invalidators);
2743 }
2744
2745 #[cfg(any(test, feature = "test-support", debug_assertions))]
2747 pub fn get_name(&self) -> Option<&'static str> {
2748 self.name
2749 }
2750
2751 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2753 self.platform.can_select_mixed_files_and_dirs()
2754 }
2755
2756 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2761 for window in self.windows.values_mut().flatten() {
2763 _ = window.drop_image(image.clone());
2764 }
2765
2766 if let Some(window) = current_window {
2768 _ = window.drop_image(image);
2769 }
2770 }
2771
2772 #[cfg(any(feature = "inspector", debug_assertions))]
2774 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2775 self.inspector_renderer = Some(f);
2776 }
2777
2778 #[cfg(any(feature = "inspector", debug_assertions))]
2780 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2781 &mut self,
2782 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2783 ) {
2784 self.inspector_element_registry.register(f);
2785 }
2786
2787 pub fn init_colors(&mut self) {
2791 self.set_global(GlobalColors(Arc::new(Colors::default())));
2792 }
2793}
2794
2795impl AppContext for App {
2796 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2801 self.update(|cx| {
2802 let slot = cx.entities.reserve();
2803 let handle = slot.clone();
2804 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2805
2806 cx.push_effect(Effect::EntityCreated {
2807 entity: handle.into_any(),
2808 tid: TypeId::of::<T>(),
2809 window: cx.window_update_stack.last().cloned(),
2810 });
2811
2812 cx.entities.insert(slot, entity)
2813 })
2814 }
2815
2816 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
2817 Reservation(self.entities.reserve())
2818 }
2819
2820 fn insert_entity<T: 'static>(
2821 &mut self,
2822 reservation: Reservation<T>,
2823 build_entity: impl FnOnce(&mut Context<T>) -> T,
2824 ) -> Entity<T> {
2825 self.update(|cx| {
2826 let slot = reservation.0;
2827 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2828 cx.entities.insert(slot, entity)
2829 })
2830 }
2831
2832 fn update_entity<T: 'static, R>(
2835 &mut self,
2836 handle: &Entity<T>,
2837 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2838 ) -> R {
2839 self.update(|cx| {
2840 let mut entity = cx.entities.lease(handle);
2841 let result = update(
2842 &mut entity,
2843 &mut Context::new_context(cx, handle.downgrade()),
2844 );
2845 cx.entities.end_lease(entity);
2846 result
2847 })
2848 }
2849
2850 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2851 where
2852 T: 'static,
2853 {
2854 GpuiBorrow::new(handle.clone(), self)
2855 }
2856
2857 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
2858 where
2859 T: 'static,
2860 {
2861 let entity = self.entities.read(handle);
2862 read(entity, self)
2863 }
2864
2865 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2866 where
2867 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2868 {
2869 self.update_window_id(handle.id, update)
2870 }
2871
2872 fn with_window<R>(
2873 &mut self,
2874 entity_id: EntityId,
2875 f: impl FnOnce(&mut Window, &mut App) -> R,
2876 ) -> Option<R> {
2877 App::with_window(self, entity_id, f)
2878 }
2879
2880 fn read_window<T, R>(
2881 &self,
2882 window: &WindowHandle<T>,
2883 read: impl FnOnce(Entity<T>, &App) -> R,
2884 ) -> Result<R>
2885 where
2886 T: 'static,
2887 {
2888 let window = self
2889 .windows
2890 .get(window.id)
2891 .context("window not found")?
2892 .as_deref()
2893 .expect("attempted to read a window that is already on the stack");
2894
2895 let root_view = window.root.clone().unwrap();
2896 let view = root_view
2897 .downcast::<T>()
2898 .map_err(|_| anyhow!("root view's type has changed"))?;
2899
2900 Ok(read(view, self))
2901 }
2902
2903 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2904 where
2905 R: Send + 'static,
2906 {
2907 self.background_executor.spawn(future)
2908 }
2909
2910 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
2911 where
2912 G: Global,
2913 {
2914 let mut g = self.global::<G>();
2915 callback(g, self)
2916 }
2917}
2918
2919pub(crate) enum Effect {
2921 Notify {
2922 emitter: EntityId,
2923 },
2924 Emit {
2925 emitter: EntityId,
2926 event_type: TypeId,
2927 event: ArenaBox<dyn Any>,
2928 },
2929 RefreshWindows,
2930 NotifyGlobalObservers {
2931 global_type: TypeId,
2932 },
2933 Defer {
2934 callback: Box<dyn FnOnce(&mut App) + 'static>,
2935 },
2936 EntityCreated {
2937 entity: AnyEntity,
2938 tid: TypeId,
2939 window: Option<WindowId>,
2940 },
2941}
2942
2943impl std::fmt::Debug for Effect {
2944 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2945 match self {
2946 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2947 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2948 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2949 Effect::NotifyGlobalObservers { global_type } => {
2950 write!(f, "NotifyGlobalObservers({:?})", global_type)
2951 }
2952 Effect::Defer { .. } => write!(f, "Defer(..)"),
2953 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2954 }
2955 }
2956}
2957
2958pub(crate) struct GlobalLease<G: Global> {
2960 global: Box<dyn Any>,
2961 global_type: PhantomData<G>,
2962}
2963
2964impl<G: Global> GlobalLease<G> {
2965 fn new(global: Box<dyn Any>) -> Self {
2966 GlobalLease {
2967 global,
2968 global_type: PhantomData,
2969 }
2970 }
2971}
2972
2973impl<G: Global> Deref for GlobalLease<G> {
2974 type Target = G;
2975
2976 fn deref(&self) -> &Self::Target {
2977 self.global.downcast_ref().unwrap()
2978 }
2979}
2980
2981impl<G: Global> DerefMut for GlobalLease<G> {
2982 fn deref_mut(&mut self) -> &mut Self::Target {
2983 self.global.downcast_mut().unwrap()
2984 }
2985}
2986
2987pub struct AnyDrag {
2990 pub view: AnyView,
2992
2993 pub value: Arc<dyn Any>,
2995
2996 pub cursor_offset: Point<Pixels>,
2999
3000 pub cursor_style: Option<CursorStyle>,
3002
3003 pub external_payload_source: Option<ExternalDragPayloadSource>,
3006}
3007
3008pub type ExternalDragPayloadSource =
3011 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3012
3013#[derive(Clone)]
3016pub struct AnyTooltip {
3017 pub view: AnyView,
3019
3020 pub mouse_position: Point<Pixels>,
3022
3023 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3027}
3028
3029#[derive(Debug)]
3031pub struct KeystrokeEvent {
3032 pub keystroke: Keystroke,
3034
3035 pub action: Option<Box<dyn Action>>,
3037
3038 pub context_stack: Vec<KeyContext>,
3040}
3041
3042pub struct GpuiBorrow<'a, T> {
3044 inner: Option<Lease<T>>,
3045 app: &'a mut App,
3046}
3047
3048impl<'a, T: 'static> GpuiBorrow<'a, T> {
3049 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3050 app.start_update();
3051 let lease = app.entities.lease(&inner);
3052 Self {
3053 inner: Some(lease),
3054 app,
3055 }
3056 }
3057}
3058
3059impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3060 fn borrow(&self) -> &T {
3061 self.inner.as_ref().unwrap().borrow()
3062 }
3063}
3064
3065impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3066 fn borrow_mut(&mut self) -> &mut T {
3067 self.inner.as_mut().unwrap().borrow_mut()
3068 }
3069}
3070
3071impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3072 type Target = T;
3073
3074 fn deref(&self) -> &Self::Target {
3075 self.inner.as_ref().unwrap()
3076 }
3077}
3078
3079impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3080 fn deref_mut(&mut self) -> &mut T {
3081 self.inner.as_mut().unwrap()
3082 }
3083}
3084
3085impl<'a, T> Drop for GpuiBorrow<'a, T> {
3086 fn drop(&mut self) {
3087 let lease = self.inner.take().unwrap();
3088 self.app.notify(lease.id);
3089 self.app.entities.end_lease(lease);
3090 self.app.finish_update();
3091 }
3092}
3093
3094#[cfg(test)]
3095mod test {
3096 use std::{cell::RefCell, rc::Rc};
3097
3098 use crate::{AppContext, TestAppContext};
3099
3100 #[test]
3101 fn test_gpui_borrow() {
3102 let cx = TestAppContext::single();
3103 let observation_count = Rc::new(RefCell::new(0));
3104
3105 let state = cx.update(|cx| {
3106 let state = cx.new(|_| false);
3107 cx.observe(&state, {
3108 let observation_count = observation_count.clone();
3109 move |_, _| {
3110 let mut count = observation_count.borrow_mut();
3111 *count += 1;
3112 }
3113 })
3114 .detach();
3115
3116 state
3117 });
3118
3119 cx.update(|cx| {
3120 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3122 });
3123
3124 cx.update(|cx| {
3125 state.write(cx, false);
3126 });
3127
3128 assert_eq!(*observation_count.borrow(), 2);
3129 }
3130}