1use scheduler::Instant;
2use std::{
3 any::{TypeId, type_name},
4 cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
5 ffi::OsString,
6 marker::PhantomData,
7 mem,
8 ops::{Deref, DerefMut},
9 path::{Path, PathBuf},
10 rc::{Rc, Weak},
11 sync::{Arc, atomic::Ordering::SeqCst},
12 time::Duration,
13};
14
15use anyhow::{Context as _, Result, anyhow};
16use derive_more::{Deref, DerefMut};
17use futures::{
18 Future, FutureExt,
19 channel::oneshot,
20 future::{LocalBoxFuture, Shared},
21};
22use itertools::Itertools;
23use parking_lot::RwLock;
24use slotmap::SlotMap;
25
26pub use async_context::*;
27#[cfg(feature = "bench-support")]
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 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::{
47 Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
48 ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError,
49 CursorStyle, DispatchPhase, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle,
50 FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId,
51 Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
52 PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
53 PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
54 ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
55 SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
56 ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
57 WindowInvalidator,
58 colors::{Colors, GlobalColors},
59 hash, init_app_menus,
60};
61
62mod async_context;
63#[cfg(feature = "bench-support")]
64mod bench_context;
65mod context;
66mod entity_map;
67#[cfg(any(test, feature = "test-support"))]
68mod headless_app_context;
69#[cfg(any(test, feature = "test-support"))]
70mod test_app;
71#[cfg(any(test, feature = "test-support"))]
72mod test_context;
73#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
74mod visual_test_context;
75
76pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
78
79#[doc(hidden)]
82pub struct AppCell {
83 app: RefCell<App>,
84}
85
86impl AppCell {
87 #[doc(hidden)]
88 #[track_caller]
89 pub fn borrow(&self) -> AppRef<'_> {
90 if option_env!("TRACK_THREAD_BORROWS").is_some() {
91 let thread_id = std::thread::current().id();
92 eprintln!("borrowed {thread_id:?}");
93 }
94 AppRef(self.app.borrow())
95 }
96
97 #[doc(hidden)]
98 #[track_caller]
99 pub fn borrow_mut(&self) -> AppRefMut<'_> {
100 if option_env!("TRACK_THREAD_BORROWS").is_some() {
101 let thread_id = std::thread::current().id();
102 eprintln!("borrowed {thread_id:?}");
103 }
104 AppRefMut(self.app.borrow_mut())
105 }
106
107 #[doc(hidden)]
108 #[track_caller]
109 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
110 if option_env!("TRACK_THREAD_BORROWS").is_some() {
111 let thread_id = std::thread::current().id();
112 eprintln!("borrowed {thread_id:?}");
113 }
114 Ok(AppRefMut(self.app.try_borrow_mut()?))
115 }
116}
117
118#[doc(hidden)]
119#[derive(Deref, DerefMut)]
120pub struct AppRef<'a>(Ref<'a, App>);
121
122impl Drop for AppRef<'_> {
123 fn drop(&mut self) {
124 if option_env!("TRACK_THREAD_BORROWS").is_some() {
125 let thread_id = std::thread::current().id();
126 eprintln!("dropped borrow from {thread_id:?}");
127 }
128 }
129}
130
131#[doc(hidden)]
132#[derive(Deref, DerefMut)]
133pub struct AppRefMut<'a>(RefMut<'a, App>);
134
135impl Drop for AppRefMut<'_> {
136 fn drop(&mut self) {
137 if option_env!("TRACK_THREAD_BORROWS").is_some() {
138 let thread_id = std::thread::current().id();
139 eprintln!("dropped {thread_id:?}");
140 }
141 }
142}
143
144pub struct Application(Rc<AppCell>);
147
148pub struct ApplicationHandle {
154 app: Rc<AppCell>,
155}
156
157impl ApplicationHandle {
158 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
162 let cx = &mut *self.app.borrow_mut();
163 f(cx)
164 }
165
166 pub fn to_async(&self) -> AsyncApp {
169 self.update(|cx| cx.to_async())
170 }
171}
172
173impl Application {
176 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
178 Self(App::new_app(
179 platform,
180 Arc::new(()),
181 Arc::new(NullHttpClient),
182 ))
183 }
184
185 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
195 let this = Self::with_platform(platform);
196 this.0.borrow_mut().accessibility_force_disabled = true;
197 this
198 }
199
200 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
202 let mut context_lock = self.0.borrow_mut();
203 let asset_source = Arc::new(asset_source);
204 context_lock.asset_source = asset_source.clone();
205 context_lock.svg_renderer = SvgRenderer::new(asset_source);
206 drop(context_lock);
207 self
208 }
209
210 pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
212 self.0.borrow_mut().restart_arguments = arguments;
213 self
214 }
215
216 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
218 let mut context_lock = self.0.borrow_mut();
219 context_lock.http_client = http_client;
220 drop(context_lock);
221 self
222 }
223
224 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
227 self.0.borrow_mut().quit_mode = mode;
228 self
229 }
230
231 pub fn run<F>(self, on_finish_launching: F)
234 where
235 F: 'static + FnOnce(&mut App),
236 {
237 let this = self.0.clone();
238 let platform = self.0.borrow().platform.clone();
239 platform.run(Box::new(move || {
240 let cx = &mut *this.borrow_mut();
241 on_finish_launching(cx);
242 }));
243 }
244
245 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
255 where
256 F: 'static + FnOnce(&mut App),
257 {
258 let this = self.0.clone();
259 let platform = self.0.borrow().platform.clone();
260 platform.run(Box::new(move || {
261 let cx = &mut *this.borrow_mut();
262 on_finish_launching(cx);
263 }));
264 ApplicationHandle { app: self.0 }
265 }
266
267 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
270 where
271 F: 'static + FnMut(Vec<String>),
272 {
273 self.0.borrow().platform.on_open_urls(Box::new(callback));
274 self
275 }
276
277 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
280 where
281 F: 'static + FnMut(&mut App),
282 {
283 let this = Rc::downgrade(&self.0);
284 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
285 if let Some(app) = this.upgrade() {
286 callback(&mut app.borrow_mut());
287 }
288 }));
289 self
290 }
291
292 pub fn background_executor(&self) -> BackgroundExecutor {
294 self.0.borrow().background_executor.clone()
295 }
296
297 pub fn foreground_executor(&self) -> ForegroundExecutor {
299 self.0.borrow().foreground_executor.clone()
300 }
301
302 pub fn text_system(&self) -> Arc<TextSystem> {
304 self.0.borrow().text_system.clone()
305 }
306
307 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
309 self.0.borrow().path_for_auxiliary_executable(name)
310 }
311}
312
313type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
314type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
315pub(crate) type KeystrokeObserver =
316 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
317type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
318type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
319type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
320type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
324pub enum QuitMode {
325 #[default]
327 Default,
328 LastWindowClosed,
330 Explicit,
332}
333
334#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
339pub enum CursorHideMode {
340 Never,
342 OnTyping,
344 #[default]
347 OnTypingAndAction,
348}
349
350#[doc(hidden)]
351#[derive(Clone, PartialEq, Eq)]
352pub struct SystemWindowTab {
353 pub id: WindowId,
354 pub title: SharedString,
355 pub handle: AnyWindowHandle,
356 pub last_active_at: Instant,
357}
358
359impl SystemWindowTab {
360 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
362 Self {
363 id: handle.id,
364 title,
365 handle,
366 last_active_at: Instant::now(),
367 }
368 }
369}
370
371#[derive(Default)]
373pub struct SystemWindowTabController {
374 visible: Option<bool>,
375 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
376}
377
378impl Global for SystemWindowTabController {}
379
380impl SystemWindowTabController {
381 pub fn new() -> Self {
383 Self {
384 visible: None,
385 tab_groups: FxHashMap::default(),
386 }
387 }
388
389 pub fn init(cx: &mut App) {
391 cx.set_global(SystemWindowTabController::new());
392 }
393
394 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
396 &self.tab_groups
397 }
398
399 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
401 let controller = cx.global::<SystemWindowTabController>();
402 let current_group = controller
403 .tab_groups
404 .iter()
405 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
406
407 let current_group = current_group?;
408 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
410 let idx = group_ids.iter().position(|g| *g == current_group)?;
411 let next_idx = (idx + 1) % group_ids.len();
412
413 controller
414 .tab_groups
415 .get(group_ids[next_idx])
416 .and_then(|tabs| {
417 tabs.iter()
418 .max_by_key(|tab| tab.last_active_at)
419 .or_else(|| tabs.first())
420 .map(|tab| &tab.handle)
421 })
422 }
423
424 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
426 let controller = cx.global::<SystemWindowTabController>();
427 let current_group = controller
428 .tab_groups
429 .iter()
430 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
431
432 let current_group = current_group?;
433 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
435 let idx = group_ids.iter().position(|g| *g == current_group)?;
436 let prev_idx = if idx == 0 {
437 group_ids.len() - 1
438 } else {
439 idx - 1
440 };
441
442 controller
443 .tab_groups
444 .get(group_ids[prev_idx])
445 .and_then(|tabs| {
446 tabs.iter()
447 .max_by_key(|tab| tab.last_active_at)
448 .or_else(|| tabs.first())
449 .map(|tab| &tab.handle)
450 })
451 }
452
453 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
455 self.tab_groups
456 .values()
457 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
458 }
459
460 pub fn init_visible(cx: &mut App, visible: bool) {
462 let mut controller = cx.global_mut::<SystemWindowTabController>();
463 if controller.visible.is_none() {
464 controller.visible = Some(visible);
465 }
466 }
467
468 pub fn is_visible(&self) -> bool {
470 self.visible.unwrap_or(false)
471 }
472
473 pub fn set_visible(cx: &mut App, visible: bool) {
475 let mut controller = cx.global_mut::<SystemWindowTabController>();
476 controller.visible = Some(visible);
477 }
478
479 pub fn update_last_active(cx: &mut App, id: WindowId) {
481 let mut controller = cx.global_mut::<SystemWindowTabController>();
482 for windows in controller.tab_groups.values_mut() {
483 for tab in windows.iter_mut() {
484 if tab.id == id {
485 tab.last_active_at = Instant::now();
486 }
487 }
488 }
489 }
490
491 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
493 let mut controller = cx.global_mut::<SystemWindowTabController>();
494 for (_, windows) in controller.tab_groups.iter_mut() {
495 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
496 if ix < windows.len() && current_pos != ix {
497 let window_tab = windows.remove(current_pos);
498 windows.insert(ix, window_tab);
499 }
500 break;
501 }
502 }
503 }
504
505 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
507 let controller = cx.global::<SystemWindowTabController>();
508 let tab = controller
509 .tab_groups
510 .values()
511 .flat_map(|windows| windows.iter())
512 .find(|tab| tab.id == id);
513
514 if tab.map_or(true, |t| t.title == title) {
515 return;
516 }
517
518 let mut controller = cx.global_mut::<SystemWindowTabController>();
519 for windows in controller.tab_groups.values_mut() {
520 for tab in windows.iter_mut() {
521 if tab.id == id {
522 tab.title = title;
523 return;
524 }
525 }
526 }
527 }
528
529 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
531 let mut controller = cx.global_mut::<SystemWindowTabController>();
532 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
533 return;
534 };
535
536 let mut expected_tab_ids: Vec<_> = tabs
537 .iter()
538 .filter(|tab| tab.id != id)
539 .map(|tab| tab.id)
540 .sorted()
541 .collect();
542
543 let mut tab_group_id = None;
544 for (group_id, group_tabs) in &controller.tab_groups {
545 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
546 if tab_ids == expected_tab_ids {
547 tab_group_id = Some(*group_id);
548 break;
549 }
550 }
551
552 if let Some(tab_group_id) = tab_group_id {
553 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
554 tabs.push(tab);
555 }
556 } else {
557 let new_group_id = controller.tab_groups.len();
558 controller.tab_groups.insert(new_group_id, tabs);
559 }
560 }
561
562 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
564 let mut controller = cx.global_mut::<SystemWindowTabController>();
565 let mut removed_tab = None;
566
567 controller.tab_groups.retain(|_, tabs| {
568 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
569 removed_tab = Some(tabs.remove(pos));
570 }
571 !tabs.is_empty()
572 });
573
574 removed_tab
575 }
576
577 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
579 let mut removed_tab = Self::remove_tab(cx, id);
580 let mut controller = cx.global_mut::<SystemWindowTabController>();
581
582 if let Some(tab) = removed_tab {
583 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
584 controller.tab_groups.insert(new_group_id, vec![tab]);
585 }
586 }
587
588 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
590 let mut controller = cx.global_mut::<SystemWindowTabController>();
591 let Some(initial_tabs) = controller.tabs(id) else {
592 return;
593 };
594
595 let initial_tabs_len = initial_tabs.len();
596 let mut all_tabs = initial_tabs.clone();
597
598 for (_, mut tabs) in controller.tab_groups.drain() {
599 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
600 all_tabs.extend(tabs);
601 }
602
603 controller.tab_groups.insert(0, all_tabs);
604 }
605
606 pub fn select_next_tab(cx: &mut App, id: WindowId) {
608 let mut controller = cx.global_mut::<SystemWindowTabController>();
609 let Some(tabs) = controller.tabs(id) else {
610 return;
611 };
612
613 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
614 let next_index = (current_index + 1) % tabs.len();
615
616 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
617 window.activate_window();
618 });
619 }
620
621 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
623 let mut controller = cx.global_mut::<SystemWindowTabController>();
624 let Some(tabs) = controller.tabs(id) else {
625 return;
626 };
627
628 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
629 let previous_index = if current_index == 0 {
630 tabs.len() - 1
631 } else {
632 current_index - 1
633 };
634
635 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
636 window.activate_window();
637 });
638 }
639}
640
641pub(crate) enum GpuiMode {
642 #[cfg(any(test, feature = "test-support"))]
643 Test {
644 skip_drawing: bool,
645 },
646 Production,
647}
648
649impl GpuiMode {
650 #[cfg(any(test, feature = "test-support"))]
651 pub fn test() -> Self {
652 GpuiMode::Test {
653 skip_drawing: false,
654 }
655 }
656
657 #[inline]
658 pub(crate) fn skip_drawing(&self) -> bool {
659 match self {
660 #[cfg(any(test, feature = "test-support"))]
661 GpuiMode::Test { skip_drawing } => *skip_drawing,
662 GpuiMode::Production => false,
663 }
664 }
665}
666
667struct PlatformOwnedDrag {
668 source_window: WindowId,
669 state: PlatformOwnedDragState,
670}
671
672enum PlatformOwnedDragState {
673 Suspended(AnyDrag),
674 RestoredInSourceWindow,
677}
678
679pub struct App {
683 pub(crate) this: Weak<AppCell>,
684 pub(crate) platform: Rc<dyn Platform>,
685 text_system: Arc<TextSystem>,
686
687 pub(crate) actions: Rc<ActionRegistry>,
688 pub(crate) active_drag: Option<AnyDrag>,
689 platform_owned_drag: Option<PlatformOwnedDrag>,
690 pub(crate) background_executor: BackgroundExecutor,
691 pub(crate) foreground_executor: ForegroundExecutor,
692 #[cfg(feature = "profiler")]
693 foreground_journal: crate::profiler::journal::ForegroundJournal,
694 pub(crate) entities: EntityMap,
695 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
696 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
697 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
698 pub(crate) focus_handles: Arc<FocusMap>,
699 pub(crate) keymap: Rc<RefCell<Keymap>>,
700 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
701 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
702 pub(crate) global_action_listeners:
703 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
704 pending_effects: VecDeque<Effect>,
705
706 pub(crate) observers: SubscriberSet<EntityId, Handler>,
707 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
708 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
709 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
710 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
711 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
712 pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
713 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
714 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
715 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
716 pub(crate) restart_observers: SubscriberSet<(), Handler>,
717 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
718
719 pub(crate) element_arena: RefCell<Arena>,
722 pub(crate) event_arena: Arena,
724
725 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
730
731 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
733 asset_source: Arc<dyn AssetSource>,
734 pub(crate) svg_renderer: SvgRenderer,
735 http_client: Arc<dyn HttpClient>,
736
737 pub(crate) pending_notifications: FxHashSet<EntityId>,
739 pub(crate) pending_global_notifications: TypeIdHashSet,
740 pub(crate) restart_path: Option<PathBuf>,
741 pub(crate) restart_arguments: Vec<OsString>,
742 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
744 pub(crate) prompt_builder: Option<PromptBuilder>,
745 pub(crate) window_invalidators_by_entity:
746 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
747 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
748 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
749 #[cfg(any(feature = "inspector", debug_assertions))]
750 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
751 #[cfg(any(feature = "inspector", debug_assertions))]
752 pub(crate) inspector_element_registry: InspectorElementRegistry,
753 #[cfg(any(test, feature = "test-support", debug_assertions))]
754 pub(crate) name: Option<&'static str>,
755 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
756
757 pub(crate) window_update_stack: Vec<WindowId>,
758 pub(crate) mode: GpuiMode,
759 pub(crate) cursor_hide_mode: CursorHideMode,
760 pub(crate) reduce_motion: bool,
761 pub(crate) synced_animation_epoch: Instant,
763 pub(crate) accessibility_force_disabled: bool,
766 flushing_effects: bool,
767 pending_updates: usize,
768 quit_mode: QuitMode,
769 quitting: bool,
770
771 #[cfg(any(test, feature = "leak-detection"))]
774 _ref_counts: Arc<RwLock<EntityRefCounts>>,
775}
776
777impl App {
778 #[allow(clippy::new_ret_no_self)]
779 pub(crate) fn new_app(
780 platform: Rc<dyn Platform>,
781 asset_source: Arc<dyn AssetSource>,
782 http_client: Arc<dyn HttpClient>,
783 ) -> Rc<AppCell> {
784 let background_executor = platform.background_executor();
785 let foreground_executor = platform.foreground_executor();
786 assert!(
787 background_executor.is_main_thread(),
788 "must construct App on main thread"
789 );
790 #[cfg(feature = "profiler")]
791 let foreground_journal = crate::profiler::journal::install_foreground_journal();
792 let synced_animation_epoch = background_executor.now();
793
794 let text_system = Arc::new(TextSystem::new(platform.text_system()));
795 let entities = EntityMap::new();
796 let keyboard_layout = platform.keyboard_layout();
797 let keyboard_mapper = platform.keyboard_mapper();
798
799 #[cfg(any(test, feature = "leak-detection"))]
800 let _ref_counts = entities.ref_counts_drop_handle();
801
802 let app = Rc::new_cyclic(|this| AppCell {
803 app: RefCell::new(App {
804 this: this.clone(),
805 platform: platform.clone(),
806 text_system,
807 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
808 mode: GpuiMode::Production,
809 actions: Rc::new(ActionRegistry::default()),
810 flushing_effects: false,
811 pending_updates: 0,
812 active_drag: None,
813 platform_owned_drag: None,
814 background_executor,
815 foreground_executor,
816 #[cfg(feature = "profiler")]
817 foreground_journal,
818 svg_renderer: SvgRenderer::new(asset_source.clone()),
819 loading_assets: Default::default(),
820 asset_source,
821 http_client,
822 globals_by_type: Default::default(),
823 entities,
824 new_entity_observers: SubscriberSet::new(),
825 windows: SlotMap::with_key(),
826 window_update_stack: Vec::new(),
827 window_handles: FxHashMap::default(),
828 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
829 keymap: Rc::new(RefCell::new(Keymap::default())),
830 keyboard_layout,
831 keyboard_mapper,
832 global_action_listeners: Default::default(),
833 pending_effects: VecDeque::new(),
834 pending_notifications: FxHashSet::default(),
835 pending_global_notifications: Default::default(),
836 observers: SubscriberSet::new(),
837 tracked_entities: FxHashMap::default(),
838 window_invalidators_by_entity: FxHashMap::default(),
839 current_window_by_entity: FxHashMap::default(),
840 event_listeners: SubscriberSet::new(),
841 release_listeners: SubscriberSet::new(),
842 keystroke_observers: SubscriberSet::new(),
843 keystroke_interceptors: SubscriberSet::new(),
844 keyboard_layout_observers: SubscriberSet::new(),
845 thermal_state_observers: SubscriberSet::new(),
846 system_wake_observers: SubscriberSet::new(),
847 global_observers: SubscriberSet::new(),
848 quit_observers: SubscriberSet::new(),
849 restart_observers: SubscriberSet::new(),
850 restart_path: None,
851 restart_arguments: Vec::new(),
852 window_closed_observers: SubscriberSet::new(),
853 layout_id_buffer: Default::default(),
854 propagate_event: true,
855 prompt_builder: Some(PromptBuilder::Default),
856 #[cfg(any(feature = "inspector", debug_assertions))]
857 inspector_renderer: None,
858 #[cfg(any(feature = "inspector", debug_assertions))]
859 inspector_element_registry: InspectorElementRegistry::default(),
860 quit_mode: QuitMode::default(),
861 quitting: false,
862 cursor_hide_mode: CursorHideMode::default(),
863 reduce_motion: false,
864 synced_animation_epoch,
865 accessibility_force_disabled: false,
866
867 #[cfg(any(test, feature = "test-support", debug_assertions))]
868 name: None,
869 element_arena: RefCell::new(Arena::new(1024 * 1024)),
870 event_arena: Arena::new(1024 * 1024),
871
872 #[cfg(any(test, feature = "leak-detection"))]
873 _ref_counts,
874 }),
875 });
876
877 init_app_menus(platform.as_ref(), &app.borrow());
878 SystemWindowTabController::init(&mut app.borrow_mut());
879
880 platform.on_keyboard_layout_change(Box::new({
881 let app = Rc::downgrade(&app);
882 move || {
883 if let Some(app) = app.upgrade() {
884 let cx = &mut app.borrow_mut();
885 cx.keyboard_layout = cx.platform.keyboard_layout();
886 cx.keyboard_mapper = cx.platform.keyboard_mapper();
887 cx.keyboard_layout_observers
888 .clone()
889 .retain(&(), move |callback| (callback)(cx));
890 }
891 }
892 }));
893
894 platform.on_thermal_state_change(Box::new({
895 let app = Rc::downgrade(&app);
896 move || {
897 if let Some(app) = app.upgrade() {
898 let cx = &mut app.borrow_mut();
899 cx.thermal_state_observers
900 .clone()
901 .retain(&(), move |callback| (callback)(cx));
902 }
903 }
904 }));
905
906 platform.on_system_wake(Box::new({
907 let app = Rc::downgrade(&app);
908 move || {
909 if let Some(app) = app.upgrade() {
910 let cx = &mut app.borrow_mut();
911 cx.system_wake_observers
912 .clone()
913 .retain(&(), move |callback| (callback)(cx));
914 }
915 }
916 }));
917
918 platform.on_quit(Box::new({
919 let cx = Rc::downgrade(&app);
920 move || {
921 let Some(cx) = cx.upgrade() else {
922 return true;
923 };
924 match cx.try_borrow_mut() {
925 Ok(mut cx) => {
926 cx.shutdown();
927 true
928 }
929 Err(_) => {
930 false
933 }
934 }
935 }
936 }));
937
938 app
939 }
940
941 #[doc(hidden)]
942 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
943 self.entities.ref_counts_drop_handle()
944 }
945
946 #[cfg(any(test, feature = "leak-detection"))]
952 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
953 self.entities.leak_detector_snapshot()
954 }
955
956 #[cfg(any(test, feature = "leak-detection"))]
968 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
969 self.entities.assert_no_new_leaks(snapshot)
970 }
971
972 pub fn shutdown(&mut self) {
975 let mut futures = Vec::new();
976
977 for observer in self.quit_observers.remove(&()) {
978 futures.push(observer(self));
979 }
980
981 self.windows.clear();
982 self.window_handles.clear();
983 self.flush_effects();
984 self.quitting = true;
985
986 let futures = futures::future::join_all(futures);
987 if self
988 .foreground_executor
989 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
990 .is_err()
991 {
992 log::error!("timed out waiting on app_will_quit");
993 }
994
995 self.quitting = false;
996 }
997
998 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1000 self.keyboard_layout.as_ref()
1001 }
1002
1003 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1005 &self.keyboard_mapper
1006 }
1007
1008 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1010 where
1011 F: 'static + FnMut(&mut App),
1012 {
1013 let (subscription, activate) = self.keyboard_layout_observers.insert(
1014 (),
1015 Box::new(move |cx| {
1016 callback(cx);
1017 true
1018 }),
1019 );
1020 activate();
1021 subscription
1022 }
1023
1024 pub fn quit(&self) {
1026 self.platform.quit();
1027 }
1028
1029 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1032 self.cursor_hide_mode
1033 }
1034
1035 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1038 self.cursor_hide_mode = mode;
1039 }
1040
1041 pub fn is_cursor_visible(&self) -> bool {
1047 self.platform.is_cursor_visible()
1048 }
1049
1050 pub fn reduce_motion(&self) -> bool {
1053 self.reduce_motion
1054 }
1055
1056 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1059 if self.reduce_motion != reduce_motion {
1060 self.reduce_motion = reduce_motion;
1061 self.refresh_windows();
1062 }
1063 }
1064
1065 pub fn refresh_windows(&mut self) {
1068 self.pending_effects.push_back(Effect::RefreshWindows);
1069 }
1070
1071 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1072 self.start_update();
1073 let result = update(self);
1074 self.finish_update();
1075 result
1076 }
1077
1078 pub(crate) fn start_update(&mut self) {
1079 self.pending_updates += 1;
1080 }
1081
1082 pub(crate) fn finish_update(&mut self) {
1083 if !self.flushing_effects && self.pending_updates == 1 {
1084 self.flushing_effects = true;
1085 self.flush_effects();
1086 self.flushing_effects = false;
1087 }
1088 self.pending_updates -= 1;
1089 }
1090
1091 pub fn observe<W>(
1093 &mut self,
1094 entity: &Entity<W>,
1095 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1096 ) -> Subscription
1097 where
1098 W: 'static,
1099 {
1100 self.observe_internal(entity, move |e, cx| {
1101 on_notify(e, cx);
1102 true
1103 })
1104 }
1105
1106 pub(crate) fn detect_accessed_entities<R>(
1107 &mut self,
1108 callback: impl FnOnce(&mut App) -> R,
1109 ) -> (R, FxHashSet<EntityId>) {
1110 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1111 let result = callback(self);
1112 let entities_accessed_in_callback = self
1113 .entities
1114 .accessed_entities
1115 .get_mut()
1116 .difference(&accessed_entities_start)
1117 .copied()
1118 .collect::<FxHashSet<EntityId>>();
1119 (result, entities_accessed_in_callback)
1120 }
1121
1122 pub(crate) fn record_entities_accessed(
1123 &mut self,
1124 window_handle: AnyWindowHandle,
1125 invalidator: WindowInvalidator,
1126 entities: &FxHashSet<EntityId>,
1127 ) {
1128 let mut tracked_entities =
1129 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1130 for entity in tracked_entities.iter() {
1131 self.window_invalidators_by_entity
1132 .entry(*entity)
1133 .and_modify(|windows| {
1134 windows.remove(&window_handle.id);
1135 });
1136 }
1137 for entity in entities.iter() {
1138 self.window_invalidators_by_entity
1139 .entry(*entity)
1140 .or_default()
1141 .insert(window_handle.id, invalidator.clone());
1142 self.current_window_by_entity
1143 .insert(*entity, window_handle.id);
1144 }
1145 tracked_entities.clear();
1146 tracked_entities.extend(entities.iter().copied());
1147 self.tracked_entities
1148 .insert(window_handle.id, tracked_entities);
1149 }
1150
1151 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1152 let (subscription, activate) = self.observers.insert(key, value);
1153 self.defer(move |_| activate());
1154 subscription
1155 }
1156
1157 pub(crate) fn observe_internal<W>(
1158 &mut self,
1159 entity: &Entity<W>,
1160 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1161 ) -> Subscription
1162 where
1163 W: 'static,
1164 {
1165 let entity_id = entity.entity_id();
1166 let handle = entity.downgrade();
1167 self.new_observer(
1168 entity_id,
1169 Box::new(move |cx| {
1170 if let Some(entity) = handle.upgrade() {
1171 on_notify(entity, cx)
1172 } else {
1173 false
1174 }
1175 }),
1176 )
1177 }
1178
1179 pub fn subscribe<T, Event>(
1182 &mut self,
1183 entity: &Entity<T>,
1184 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1185 ) -> Subscription
1186 where
1187 T: 'static + EventEmitter<Event>,
1188 Event: 'static,
1189 {
1190 self.subscribe_internal(entity, move |entity, event, cx| {
1191 on_event(entity, event, cx);
1192 true
1193 })
1194 }
1195
1196 pub(crate) fn new_subscription(
1197 &mut self,
1198 key: EntityId,
1199 value: (TypeId, Listener),
1200 ) -> Subscription {
1201 let (subscription, activate) = self.event_listeners.insert(key, value);
1202 self.defer(move |_| activate());
1203 subscription
1204 }
1205 pub(crate) fn subscribe_internal<T, Evt>(
1206 &mut self,
1207 entity: &Entity<T>,
1208 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1209 ) -> Subscription
1210 where
1211 T: 'static + EventEmitter<Evt>,
1212 Evt: 'static,
1213 {
1214 let entity_id = entity.entity_id();
1215 let handle = entity.downgrade();
1216 self.new_subscription(
1217 entity_id,
1218 (
1219 TypeId::of::<Evt>(),
1220 Box::new(move |event, cx| {
1221 let event: &Evt = event.downcast_ref().expect("invalid event type");
1222 if let Some(entity) = handle.upgrade() {
1223 on_event(entity, event, cx)
1224 } else {
1225 false
1226 }
1227 }),
1228 ),
1229 )
1230 }
1231
1232 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1236 self.windows
1237 .keys()
1238 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1239 .collect()
1240 }
1241
1242 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1248 self.platform.window_stack()
1249 }
1250
1251 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1253 self.platform.active_window()
1254 }
1255
1256 pub fn open_window<V: 'static + Render>(
1260 &mut self,
1261 options: crate::WindowOptions,
1262 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1263 ) -> anyhow::Result<WindowHandle<V>> {
1264 self.update(|cx| {
1265 let id = cx.windows.insert(None);
1266 let handle = WindowHandle::new(id);
1267 match Window::new(handle.into(), options, cx) {
1268 Ok(mut window) => {
1269 cx.window_update_stack.push(id);
1270 let root_view = build_root_view(&mut window, cx);
1271 cx.window_update_stack.pop();
1272 window.root.replace(root_view.into());
1273 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1274
1275 let clear = window.draw(cx);
1280 clear.clear(cx);
1281
1282 cx.window_handles.insert(id, window.handle);
1283 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1284 Ok(handle)
1285 }
1286 Err(e) => {
1287 cx.windows.remove(id);
1288 Err(e)
1289 }
1290 }
1291 })
1292 }
1293
1294 pub fn activate(&self, ignoring_other_apps: bool) {
1296 self.platform.activate(ignoring_other_apps);
1297 }
1298
1299 pub fn hide(&self) {
1301 self.platform.hide();
1302 }
1303
1304 pub fn hide_other_apps(&self) {
1306 self.platform.hide_other_apps();
1307 }
1308
1309 pub fn unhide_other_apps(&self) {
1311 self.platform.unhide_other_apps();
1312 }
1313
1314 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1316 self.platform.displays()
1317 }
1318
1319 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1321 self.platform.primary_display()
1322 }
1323
1324 pub fn is_screen_capture_supported(&self) -> bool {
1326 self.platform.is_screen_capture_supported()
1327 }
1328
1329 pub fn screen_capture_sources(
1331 &self,
1332 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1333 self.platform.screen_capture_sources()
1334 }
1335
1336 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1338 self.displays()
1339 .iter()
1340 .find(|display| display.id() == id)
1341 .cloned()
1342 }
1343
1344 pub fn thermal_state(&self) -> ThermalState {
1346 self.platform.thermal_state()
1347 }
1348
1349 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1351 where
1352 F: 'static + FnMut(&mut App),
1353 {
1354 let (subscription, activate) = self.thermal_state_observers.insert(
1355 (),
1356 Box::new(move |cx| {
1357 callback(cx);
1358 true
1359 }),
1360 );
1361 activate();
1362 subscription
1363 }
1364
1365 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1367 where
1368 F: 'static + FnMut(&mut App),
1369 {
1370 let (subscription, activate) = self.system_wake_observers.insert(
1371 (),
1372 Box::new(move |cx| {
1373 callback(cx);
1374 true
1375 }),
1376 );
1377 activate();
1378 subscription
1379 }
1380
1381 pub fn window_appearance(&self) -> WindowAppearance {
1383 self.platform.window_appearance()
1384 }
1385
1386 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1397 self.platform.set_window_appearance(appearance);
1398 }
1399
1400 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1402 self.platform.button_layout()
1403 }
1404
1405 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1407 self.platform.read_from_clipboard()
1408 }
1409
1410 pub fn read_from_clipboard_async(
1418 &self,
1419 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1420 self.platform.read_from_clipboard_async()
1421 }
1422
1423 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1425 self.text_rendering_mode.set(mode);
1426 }
1427
1428 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1430 self.text_rendering_mode.get()
1431 }
1432
1433 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1435 self.platform.write_to_clipboard(item)
1436 }
1437
1438 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1441 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1442 self.platform.read_from_primary()
1443 }
1444
1445 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1448 pub fn write_to_primary(&self, item: ClipboardItem) {
1449 self.platform.write_to_primary(item)
1450 }
1451
1452 #[cfg(target_os = "macos")]
1458 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1459 self.platform.read_from_find_pasteboard()
1460 }
1461
1462 #[cfg(target_os = "macos")]
1468 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1469 self.platform.write_to_find_pasteboard(item)
1470 }
1471
1472 pub fn write_credentials(
1474 &self,
1475 url: &str,
1476 username: &str,
1477 password: &[u8],
1478 ) -> Task<Result<()>> {
1479 self.platform.write_credentials(url, username, password)
1480 }
1481
1482 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1484 self.platform.read_credentials(url)
1485 }
1486
1487 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1489 self.platform.delete_credentials(url)
1490 }
1491
1492 pub fn open_url(&self, url: &str) {
1494 self.platform.open_url(url);
1495 }
1496
1497 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1504 self.platform.register_url_scheme(scheme)
1505 }
1506
1507 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1514 self.platform.set_app_identity(identifier, name);
1515 }
1516
1517 pub fn show_system_notification(&self, notification: SystemNotification) {
1524 self.platform.show_system_notification(notification);
1525 }
1526
1527 pub fn dismiss_system_notification(&self, tag: &str) {
1532 self.platform.dismiss_system_notification(tag);
1533 }
1534
1535 pub fn on_system_notification_response<F>(&self, mut callback: F)
1539 where
1540 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1541 {
1542 let this = self.this.clone();
1543 self.platform
1544 .on_system_notification_response(Box::new(move |response| {
1545 if let Some(app) = this.upgrade() {
1546 callback(response, &mut app.borrow_mut());
1547 }
1548 }));
1549 }
1550
1551 pub fn app_path(&self) -> Result<PathBuf> {
1555 self.platform.app_path()
1556 }
1557
1558 pub fn compositor_name(&self) -> &'static str {
1562 self.platform.compositor_name()
1563 }
1564
1565 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1567 self.platform.path_for_auxiliary_executable(name)
1568 }
1569
1570 pub fn prompt_for_paths(
1576 &self,
1577 options: PathPromptOptions,
1578 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1579 self.platform.prompt_for_paths(options)
1580 }
1581
1582 pub fn prompt_for_new_path(
1589 &self,
1590 directory: &Path,
1591 suggested_name: Option<&str>,
1592 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1593 self.platform.prompt_for_new_path(directory, suggested_name)
1594 }
1595
1596 pub fn reveal_path(&self, path: &Path) {
1598 self.platform.reveal_path(path)
1599 }
1600
1601 pub fn open_with_system(&self, path: &Path) {
1603 self.platform.open_with_system(path)
1604 }
1605
1606 pub fn should_auto_hide_scrollbars(&self) -> bool {
1608 self.platform.should_auto_hide_scrollbars()
1609 }
1610
1611 pub fn restart(&mut self) {
1613 self.restart_observers
1614 .clone()
1615 .retain(&(), |observer| observer(self));
1616 self.platform.restart(
1617 self.restart_path.take(),
1618 std::mem::take(&mut self.restart_arguments),
1619 )
1620 }
1621
1622 pub fn set_restart_path(&mut self, path: PathBuf) {
1624 self.restart_path = Some(path);
1625 }
1626
1627 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1629 self.http_client.clone()
1630 }
1631
1632 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1634 self.http_client = new_client;
1635 }
1636
1637 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1640 self.quit_mode = mode;
1641 }
1642
1643 pub fn svg_renderer(&self) -> SvgRenderer {
1645 self.svg_renderer.clone()
1646 }
1647
1648 pub(crate) fn push_effect(&mut self, effect: Effect) {
1649 match &effect {
1650 Effect::Notify { emitter } => {
1651 if !self.pending_notifications.insert(*emitter) {
1652 return;
1653 }
1654 }
1655 Effect::NotifyGlobalObservers { global_type } => {
1656 if !self.pending_global_notifications.insert(*global_type) {
1657 return;
1658 }
1659 }
1660 _ => {}
1661 };
1662
1663 self.pending_effects.push_back(effect);
1664 }
1665
1666 fn flush_effects(&mut self) {
1670 loop {
1671 self.release_dropped_entities();
1672 self.release_dropped_focus_handles();
1673 if let Some(effect) = self.pending_effects.pop_front() {
1674 match effect {
1675 Effect::Notify { emitter } => {
1676 self.apply_notify_effect(emitter);
1677 }
1678
1679 Effect::Emit {
1680 emitter,
1681 event_type,
1682 event,
1683 } => self.apply_emit_effect(emitter, event_type, &*event),
1684
1685 Effect::RefreshWindows => {
1686 self.apply_refresh_effect();
1687 }
1688
1689 Effect::NotifyGlobalObservers { global_type } => {
1690 self.apply_notify_global_observers_effect(global_type);
1691 }
1692
1693 Effect::Defer { callback } => {
1694 self.apply_defer_effect(callback);
1695 }
1696 Effect::EntityCreated {
1697 entity,
1698 tid,
1699 window,
1700 } => {
1701 self.apply_entity_created_effect(entity, tid, window);
1702 }
1703 }
1704 } else {
1705 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1706 for window in self
1707 .windows
1708 .values()
1709 .filter_map(|window| {
1710 let window = window.as_deref()?;
1711 window.invalidator.is_dirty().then_some(window.handle)
1712 })
1713 .collect::<Vec<_>>()
1714 {
1715 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1716 .unwrap();
1717 }
1718
1719 if self.pending_effects.is_empty() {
1720 for window in self.windows.values().filter_map(|window| window.as_deref()) {
1721 if window.invalidator.is_dirty()
1722 || window.needs_present.get()
1723 || !window.next_frame_callbacks.borrow().is_empty()
1724 {
1725 window.platform_window.schedule_frame();
1726 }
1727 }
1728
1729 self.event_arena.clear();
1730 break;
1731 }
1732 }
1733 }
1734 }
1735
1736 fn release_dropped_entities(&mut self) {
1740 loop {
1741 let dropped = self.entities.take_dropped();
1742 if dropped.is_empty() {
1743 break;
1744 }
1745
1746 for (entity_id, mut entity) in dropped {
1747 self.observers.remove(&entity_id);
1748 self.event_listeners.remove(&entity_id);
1749 self.window_invalidators_by_entity.remove(&entity_id);
1750 self.current_window_by_entity.remove(&entity_id);
1751 for release_callback in self.release_listeners.remove(&entity_id) {
1752 release_callback(entity.as_mut(), self);
1753 }
1754 }
1755 }
1756 }
1757
1758 fn release_dropped_focus_handles(&mut self) {
1760 self.focus_handles
1761 .clone()
1762 .write()
1763 .retain(|handle_id, focus| {
1764 if focus.ref_count.load(SeqCst) == 0 {
1765 for window_handle in self.windows() {
1766 window_handle
1767 .update(self, |_, window, cx| {
1768 if window.focus == Some(handle_id) {
1769 window.blur(cx);
1770 }
1771 })
1772 .unwrap();
1773 }
1774 false
1775 } else {
1776 true
1777 }
1778 });
1779 }
1780
1781 fn apply_notify_effect(&mut self, emitter: EntityId) {
1782 self.pending_notifications.remove(&emitter);
1783
1784 self.observers
1785 .clone()
1786 .retain(&emitter, |handler| handler(self));
1787 }
1788
1789 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1790 self.event_listeners
1791 .clone()
1792 .retain(&emitter, |(stored_type, handler)| {
1793 if *stored_type == event_type {
1794 handler(event, self)
1795 } else {
1796 true
1797 }
1798 });
1799 }
1800
1801 fn apply_refresh_effect(&mut self) {
1802 for window in self.windows.values_mut() {
1803 if let Some(window) = window.as_deref_mut() {
1804 window.refreshing = true;
1805 window.invalidator.set_dirty(true);
1806 }
1807 }
1808 }
1809
1810 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1811 self.pending_global_notifications.remove(&type_id);
1812 self.global_observers
1813 .clone()
1814 .retain(&type_id, |observer| observer(self));
1815 }
1816
1817 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1818 callback(self);
1819 }
1820
1821 fn apply_entity_created_effect(
1822 &mut self,
1823 entity: AnyEntity,
1824 tid: TypeId,
1825 window: Option<WindowId>,
1826 ) {
1827 if let Some(id) = window {
1831 self.current_window_by_entity.insert(entity.entity_id(), id);
1832 }
1833
1834 self.new_entity_observers.clone().retain(&tid, |observer| {
1835 if let Some(id) = window {
1836 self.update_window_id(id, {
1837 let entity = entity.clone();
1838 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1839 })
1840 .expect("All windows should be off the stack when flushing effects");
1841 } else {
1842 (observer)(entity.clone(), &mut None, self)
1843 }
1844 true
1845 });
1846 }
1847
1848 pub fn with_window<R>(
1854 &mut self,
1855 entity_id: EntityId,
1856 f: impl FnOnce(&mut Window, &mut App) -> R,
1857 ) -> Option<R> {
1858 let window_id = *self.current_window_by_entity.get(&entity_id)?;
1859 self.update_window_id(window_id, |_, window, cx| f(window, cx))
1860 .ok()
1861 }
1862
1863 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1864 self.current_window_by_entity
1865 .entry(entity_id)
1866 .or_insert(window);
1867 }
1868
1869 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1870 where
1871 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1872 {
1873 self.update(|cx| {
1874 let mut window = cx.windows.get_mut(id)?.take()?;
1875
1876 let root_view = window.root.clone().unwrap();
1877
1878 cx.window_update_stack.push(window.handle.id);
1879 let result = update(root_view, &mut window, cx);
1880 fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1881 cx.window_update_stack.pop();
1882
1883 if window.removed {
1884 cx.end_platform_drag(id);
1885 cx.window_handles.remove(&id);
1886 cx.windows.remove(id);
1887 if let Some(tracked) = cx.tracked_entities.remove(&id) {
1888 for entity_id in tracked {
1889 if let Some(windows) =
1890 cx.window_invalidators_by_entity.get_mut(&entity_id)
1891 {
1892 windows.remove(&id);
1893 }
1894 if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1895 cx.current_window_by_entity.remove(&entity_id);
1896 }
1897 }
1898 }
1899
1900 cx.window_closed_observers.clone().retain(&(), |callback| {
1901 callback(cx, id);
1902 true
1903 });
1904
1905 let quit_on_empty = match cx.quit_mode {
1906 QuitMode::Explicit => false,
1907 QuitMode::LastWindowClosed => true,
1908 QuitMode::Default => cfg!(not(target_os = "macos")),
1909 };
1910
1911 if quit_on_empty && cx.windows.is_empty() {
1912 cx.quit();
1913 }
1914 } else {
1915 cx.windows.get_mut(id)?.replace(window);
1916 }
1917 Some(())
1918 }
1919 trail(id, window, cx)?;
1920
1921 Some(result)
1922 })
1923 .context("window not found")
1924 }
1925
1926 pub fn to_async(&self) -> AsyncApp {
1929 AsyncApp {
1930 app: self.this.clone(),
1931 background_executor: self.background_executor.clone(),
1932 foreground_executor: self.foreground_executor.clone(),
1933 }
1934 }
1935
1936 pub fn background_executor(&self) -> &BackgroundExecutor {
1938 &self.background_executor
1939 }
1940
1941 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1943 if self.quitting {
1944 panic!("Can't spawn on main thread after on_app_quit")
1945 };
1946 &self.foreground_executor
1947 }
1948
1949 #[cfg(feature = "profiler")]
1952 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
1953 self.foreground_journal.clone()
1954 }
1955
1956 #[track_caller]
1959 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1960 where
1961 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1962 R: 'static,
1963 {
1964 if self.quitting {
1965 debug_panic!("Can't spawn on main thread after on_app_quit")
1966 };
1967
1968 let mut cx = self.to_async();
1969
1970 self.foreground_executor
1971 .spawn(async move { f(&mut cx).await }.boxed_local())
1972 }
1973
1974 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1978 where
1979 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1980 R: 'static,
1981 {
1982 if self.quitting {
1983 debug_panic!("Can't spawn on main thread after on_app_quit")
1984 };
1985
1986 let mut cx = self.to_async();
1987
1988 self.foreground_executor
1989 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
1990 }
1991
1992 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1995 self.push_effect(Effect::Defer {
1996 callback: Box::new(f),
1997 });
1998 }
1999
2000 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2002 &self.asset_source
2003 }
2004
2005 pub fn text_system(&self) -> &Arc<TextSystem> {
2007 &self.text_system
2008 }
2009
2010 pub fn has_global<G: Global>(&self) -> bool {
2012 self.globals_by_type.contains_key(&TypeId::of::<G>())
2013 }
2014
2015 #[track_caller]
2017 pub fn global<G: Global>(&self) -> &G {
2018 self.globals_by_type
2019 .get(&TypeId::of::<G>())
2020 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2021 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2022 }
2023
2024 pub fn try_global<G: Global>(&self) -> Option<&G> {
2026 self.globals_by_type
2027 .get(&TypeId::of::<G>())
2028 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2029 }
2030
2031 #[track_caller]
2033 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2034 let global_type = TypeId::of::<G>();
2035 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2036 self.globals_by_type
2037 .get_mut(&global_type)
2038 .and_then(|any_state| any_state.downcast_mut::<G>())
2039 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2040 }
2041
2042 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2045 let global_type = TypeId::of::<G>();
2046 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2047 self.globals_by_type
2048 .entry(global_type)
2049 .or_insert_with(|| Box::<G>::default())
2050 .downcast_mut::<G>()
2051 .unwrap()
2052 }
2053
2054 pub fn set_global<G: Global>(&mut self, global: G) {
2056 let global_type = TypeId::of::<G>();
2057 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2058 self.globals_by_type.insert(global_type, Box::new(global));
2059 }
2060
2061 #[cfg(any(test, feature = "test-support"))]
2063 pub fn clear_globals(&mut self) {
2064 self.globals_by_type.drain();
2065 }
2066
2067 pub fn remove_global<G: Global>(&mut self) -> G {
2069 let global_type = TypeId::of::<G>();
2070 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2071 *self
2072 .globals_by_type
2073 .remove(&global_type)
2074 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2075 .downcast()
2076 .unwrap()
2077 }
2078
2079 pub fn observe_global<G: Global>(
2081 &mut self,
2082 mut f: impl FnMut(&mut Self) + 'static,
2083 ) -> Subscription {
2084 let (subscription, activate) = self.global_observers.insert(
2085 TypeId::of::<G>(),
2086 Box::new(move |cx| {
2087 f(cx);
2088 true
2089 }),
2090 );
2091 self.defer(move |_| activate());
2092 subscription
2093 }
2094
2095 #[track_caller]
2097 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2098 GlobalLease::new(
2099 self.globals_by_type
2100 .remove(&TypeId::of::<G>())
2101 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2102 .unwrap(),
2103 )
2104 }
2105
2106 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2108 let global_type = TypeId::of::<G>();
2109
2110 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2111 self.globals_by_type.insert(global_type, lease.global);
2112 }
2113
2114 pub(crate) fn new_entity_observer(
2115 &self,
2116 key: TypeId,
2117 value: NewEntityListener,
2118 ) -> Subscription {
2119 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2120 activate();
2121 subscription
2122 }
2123
2124 pub fn observe_new<T: 'static>(
2127 &self,
2128 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2129 ) -> Subscription {
2130 self.new_entity_observer(
2131 TypeId::of::<T>(),
2132 Box::new(
2133 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2134 any_entity
2135 .downcast::<T>()
2136 .unwrap()
2137 .update(cx, |entity_state, cx| {
2138 on_new(entity_state, window.as_deref_mut(), cx)
2139 })
2140 },
2141 ),
2142 )
2143 }
2144
2145 pub fn observe_release<T>(
2148 &self,
2149 handle: &Entity<T>,
2150 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2151 ) -> Subscription
2152 where
2153 T: 'static,
2154 {
2155 let (subscription, activate) = self.release_listeners.insert(
2156 handle.entity_id(),
2157 Box::new(move |entity, cx| {
2158 let entity = entity.downcast_mut().expect("invalid entity type");
2159 on_release(entity, cx)
2160 }),
2161 );
2162 activate();
2163 subscription
2164 }
2165
2166 pub fn observe_release_in<T>(
2169 &self,
2170 handle: &Entity<T>,
2171 window: &Window,
2172 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2173 ) -> Subscription
2174 where
2175 T: 'static,
2176 {
2177 let window_handle = window.handle;
2178 self.observe_release(handle, move |entity, cx| {
2179 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2180 })
2181 }
2182
2183 pub fn observe_keystrokes(
2187 &mut self,
2188 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2189 ) -> Subscription {
2190 fn inner(
2191 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2192 handler: KeystrokeObserver,
2193 ) -> Subscription {
2194 let (subscription, activate) = keystroke_observers.insert((), handler);
2195 activate();
2196 subscription
2197 }
2198
2199 inner(
2200 &self.keystroke_observers,
2201 Box::new(move |event, window, cx| {
2202 f(event, window, cx);
2203 true
2204 }),
2205 )
2206 }
2207
2208 pub fn intercept_keystrokes(
2213 &mut self,
2214 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2215 ) -> Subscription {
2216 fn inner(
2217 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2218 handler: KeystrokeObserver,
2219 ) -> Subscription {
2220 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2221 activate();
2222 subscription
2223 }
2224
2225 inner(
2226 &self.keystroke_interceptors,
2227 Box::new(move |event, window, cx| {
2228 f(event, window, cx);
2229 true
2230 }),
2231 )
2232 }
2233
2234 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2236 self.keymap.borrow_mut().add_bindings(bindings);
2237 self.pending_effects.push_back(Effect::RefreshWindows);
2238 }
2239
2240 pub fn clear_key_bindings(&mut self) {
2242 self.keymap.borrow_mut().clear();
2243 self.pending_effects.push_back(Effect::RefreshWindows);
2244 }
2245
2246 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2248 self.keymap.clone()
2249 }
2250
2251 pub fn on_action<A: Action>(
2255 &mut self,
2256 listener: impl Fn(&A, &mut Self) + 'static,
2257 ) -> &mut Self {
2258 self.global_action_listeners
2259 .entry(TypeId::of::<A>())
2260 .or_default()
2261 .push(Rc::new(move |action, phase, cx| {
2262 if phase == DispatchPhase::Bubble {
2263 let action = action.downcast_ref().unwrap();
2264 listener(action, cx)
2265 }
2266 }));
2267 self
2268 }
2269
2270 pub fn stop_propagation(&mut self) {
2275 self.propagate_event = false;
2276 }
2277
2278 pub fn propagate(&mut self) {
2283 self.propagate_event = true;
2284 }
2285
2286 pub fn build_action(
2288 &self,
2289 name: &str,
2290 data: Option<serde_json::Value>,
2291 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2292 self.actions.build_action(name, data)
2293 }
2294
2295 pub fn all_action_names(&self) -> &[&'static str] {
2298 self.actions.all_action_names()
2299 }
2300
2301 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2305 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2306 }
2307
2308 pub fn action_schemas(
2310 &self,
2311 generator: &mut schemars::SchemaGenerator,
2312 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2313 self.actions.action_schemas(generator)
2314 }
2315
2316 pub fn action_schema_by_name(
2321 &self,
2322 name: &str,
2323 generator: &mut schemars::SchemaGenerator,
2324 ) -> Option<Option<schemars::Schema>> {
2325 self.actions.action_schema_by_name(name, generator)
2326 }
2327
2328 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2330 self.actions.deprecated_aliases()
2331 }
2332
2333 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2335 self.actions.deprecation_messages()
2336 }
2337
2338 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2340 self.actions.documentation()
2341 }
2342
2343 pub fn on_app_quit<Fut>(
2346 &self,
2347 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2348 ) -> Subscription
2349 where
2350 Fut: 'static + Future<Output = ()>,
2351 {
2352 let (subscription, activate) = self.quit_observers.insert(
2353 (),
2354 Box::new(move |cx| {
2355 let future = on_quit(cx);
2356 future.boxed_local()
2357 }),
2358 );
2359 activate();
2360 subscription
2361 }
2362
2363 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2367 let (subscription, activate) = self.restart_observers.insert(
2368 (),
2369 Box::new(move |cx| {
2370 on_restart(cx);
2371 true
2372 }),
2373 );
2374 activate();
2375 subscription
2376 }
2377
2378 pub fn on_window_closed(
2381 &self,
2382 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2383 ) -> Subscription {
2384 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2385 activate();
2386 subscription
2387 }
2388
2389 pub(crate) fn clear_pending_keystrokes(&mut self) {
2390 for window in self.windows() {
2391 window
2392 .update(self, |_, window, cx| {
2393 window.clear_pending_keystrokes(cx);
2394 })
2395 .ok();
2396 }
2397 }
2398
2399 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2402 let mut action_available = false;
2403 if let Some(window) = self.active_window()
2404 && let Ok(window_action_available) =
2405 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2406 {
2407 action_available = window_action_available;
2408 }
2409
2410 action_available
2411 || self
2412 .global_action_listeners
2413 .contains_key(&action.as_any().type_id())
2414 }
2415
2416 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2418 let menus: Vec<Menu> = menus.into_iter().collect();
2419 self.platform.set_menus(menus, &self.keymap.borrow());
2420 }
2421
2422 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2424 self.platform.get_menus()
2425 }
2426
2427 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2429 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2430 }
2431
2432 pub fn perform_dock_menu_action(&self, action: usize) {
2434 self.platform.perform_dock_menu_action(action);
2435 }
2436
2437 pub fn add_recent_document(&self, path: &Path) {
2442 self.platform.add_recent_document(path);
2443 }
2444
2445 pub fn update_jump_list(
2448 &self,
2449 menus: Vec<MenuItem>,
2450 entries: Vec<SmallVec<[PathBuf; 2]>>,
2451 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2452 self.platform.update_jump_list(menus, entries)
2453 }
2454
2455 pub fn dispatch_action(&mut self, action: &dyn Action) {
2458 if let Some(active_window) = self.active_window() {
2459 active_window
2460 .update(self, |_, window, cx| {
2461 window.dispatch_action(action.boxed_clone(), cx)
2462 })
2463 .log_err();
2464 } else {
2465 self.dispatch_global_action(action);
2466 }
2467 }
2468
2469 fn dispatch_global_action(&mut self, action: &dyn Action) {
2470 self.propagate_event = true;
2471
2472 if let Some(mut global_listeners) = self
2473 .global_action_listeners
2474 .remove(&action.as_any().type_id())
2475 {
2476 for listener in &global_listeners {
2477 listener(action.as_any(), DispatchPhase::Capture, self);
2478 if !self.propagate_event {
2479 break;
2480 }
2481 }
2482
2483 global_listeners.extend(
2484 self.global_action_listeners
2485 .remove(&action.as_any().type_id())
2486 .unwrap_or_default(),
2487 );
2488
2489 self.global_action_listeners
2490 .insert(action.as_any().type_id(), global_listeners);
2491 }
2492
2493 if self.propagate_event
2494 && let Some(mut global_listeners) = self
2495 .global_action_listeners
2496 .remove(&action.as_any().type_id())
2497 {
2498 for listener in global_listeners.iter().rev() {
2499 listener(action.as_any(), DispatchPhase::Bubble, self);
2500 if !self.propagate_event {
2501 break;
2502 }
2503 }
2504
2505 global_listeners.extend(
2506 self.global_action_listeners
2507 .remove(&action.as_any().type_id())
2508 .unwrap_or_default(),
2509 );
2510
2511 self.global_action_listeners
2512 .insert(action.as_any().type_id(), global_listeners);
2513 }
2514 }
2515
2516 pub fn has_active_drag(&self) -> bool {
2518 self.active_drag.is_some()
2519 }
2520
2521 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2523 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2524 }
2525
2526 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2528 if self.active_drag.is_some() {
2529 self.active_drag = None;
2530 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2531 drag.source_window == window.window_handle().window_id()
2532 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2533 }) {
2534 self.platform_owned_drag = None;
2535 }
2536 window.refresh();
2537 true
2538 } else {
2539 false
2540 }
2541 }
2542
2543 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2544 let Some(drag) = self.active_drag.take() else {
2545 return false;
2546 };
2547 self.platform_owned_drag = Some(PlatformOwnedDrag {
2548 source_window,
2549 state: PlatformOwnedDragState::Suspended(drag),
2550 });
2551 true
2552 }
2553
2554 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2555 let Some(platform_drag) = self
2556 .platform_owned_drag
2557 .as_mut()
2558 .filter(|drag| drag.source_window == source_window)
2559 else {
2560 return false;
2561 };
2562 let state = std::mem::replace(
2563 &mut platform_drag.state,
2564 PlatformOwnedDragState::RestoredInSourceWindow,
2565 );
2566 let PlatformOwnedDragState::Suspended(drag) = state else {
2567 return false;
2568 };
2569 self.active_drag = Some(drag);
2570 true
2571 }
2572
2573 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2574 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2575 drag.source_window == source_window
2576 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2577 }) else {
2578 return false;
2579 };
2580 let Some(drag) = self.active_drag.take() else {
2581 return false;
2582 };
2583 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2584 true
2585 }
2586
2587 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2588 if !self
2589 .platform_owned_drag
2590 .as_ref()
2591 .is_some_and(|drag| drag.source_window == source_window)
2592 {
2593 return false;
2594 }
2595 self.platform_owned_drag = None;
2596 self.active_drag = None;
2597 true
2598 }
2599
2600 pub fn set_active_drag_cursor_style(
2602 &mut self,
2603 cursor_style: CursorStyle,
2604 window: &mut Window,
2605 ) -> bool {
2606 if let Some(ref mut drag) = self.active_drag {
2607 drag.cursor_style = Some(cursor_style);
2608 window.refresh();
2609 true
2610 } else {
2611 false
2612 }
2613 }
2614
2615 pub fn set_prompt_builder(
2618 &mut self,
2619 renderer: impl Fn(
2620 PromptLevel,
2621 &str,
2622 Option<&str>,
2623 &[PromptButton],
2624 PromptHandle,
2625 &mut Window,
2626 &mut App,
2627 ) -> RenderablePromptHandle
2628 + 'static,
2629 ) {
2630 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2631 }
2632
2633 pub fn reset_prompt_builder(&mut self) {
2635 self.prompt_builder = Some(PromptBuilder::Default);
2636 }
2637
2638 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2640 let asset_id = (TypeId::of::<A>(), hash(source));
2641 self.loading_assets.remove(&asset_id);
2642 }
2643
2644 #[cfg(any(test, feature = "test-support"))]
2647 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
2648 let asset_id = (TypeId::of::<A>(), hash(source));
2649 self.loading_assets.contains_key(&asset_id)
2650 }
2651
2652 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2657 let asset_id = (TypeId::of::<A>(), hash(source));
2658 let mut is_first = false;
2659 let task = self
2660 .loading_assets
2661 .remove(&asset_id)
2662 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2663 .unwrap_or_else(|| {
2664 is_first = true;
2665 let future = A::load(source.clone(), self);
2666
2667 self.background_executor().spawn(future).shared()
2668 });
2669
2670 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2671
2672 (task, is_first)
2673 }
2674
2675 #[track_caller]
2678 pub fn focus_handle(&self) -> FocusHandle {
2679 FocusHandle::new(&self.focus_handles)
2680 }
2681
2682 pub fn notify(&mut self, entity_id: EntityId) {
2684 let window_invalidators = mem::take(
2685 self.window_invalidators_by_entity
2686 .entry(entity_id)
2687 .or_default(),
2688 );
2689
2690 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2695 .iter()
2696 .filter(|(window_id, _)| {
2697 self.tracked_entities
2698 .get(window_id)
2699 .is_some_and(|set| set.contains(&entity_id))
2700 })
2701 .map(|(_, invalidator)| invalidator.clone())
2702 .collect();
2703
2704 if live_invalidators.is_empty() {
2705 if self.pending_notifications.insert(entity_id) {
2706 self.pending_effects
2707 .push_back(Effect::Notify { emitter: entity_id });
2708 }
2709 } else {
2710 for invalidator in &live_invalidators {
2711 invalidator.invalidate_view(entity_id, self);
2712 }
2713 }
2714
2715 self.window_invalidators_by_entity
2716 .insert(entity_id, window_invalidators);
2717 }
2718
2719 #[cfg(any(test, feature = "test-support", debug_assertions))]
2721 pub fn get_name(&self) -> Option<&'static str> {
2722 self.name
2723 }
2724
2725 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2727 self.platform.can_select_mixed_files_and_dirs()
2728 }
2729
2730 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2735 for window in self.windows.values_mut().flatten() {
2737 _ = window.drop_image(image.clone());
2738 }
2739
2740 if let Some(window) = current_window {
2742 _ = window.drop_image(image);
2743 }
2744 }
2745
2746 #[cfg(any(feature = "inspector", debug_assertions))]
2748 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2749 self.inspector_renderer = Some(f);
2750 }
2751
2752 #[cfg(any(feature = "inspector", debug_assertions))]
2754 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2755 &mut self,
2756 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2757 ) {
2758 self.inspector_element_registry.register(f);
2759 }
2760
2761 pub fn init_colors(&mut self) {
2765 self.set_global(GlobalColors(Arc::new(Colors::default())));
2766 }
2767}
2768
2769impl AppContext for App {
2770 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2775 self.update(|cx| {
2776 let slot = cx.entities.reserve();
2777 let handle = slot.clone();
2778 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2779
2780 cx.push_effect(Effect::EntityCreated {
2781 entity: handle.into_any(),
2782 tid: TypeId::of::<T>(),
2783 window: cx.window_update_stack.last().cloned(),
2784 });
2785
2786 cx.entities.insert(slot, entity)
2787 })
2788 }
2789
2790 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
2791 Reservation(self.entities.reserve())
2792 }
2793
2794 fn insert_entity<T: 'static>(
2795 &mut self,
2796 reservation: Reservation<T>,
2797 build_entity: impl FnOnce(&mut Context<T>) -> T,
2798 ) -> Entity<T> {
2799 self.update(|cx| {
2800 let slot = reservation.0;
2801 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2802 cx.entities.insert(slot, entity)
2803 })
2804 }
2805
2806 fn update_entity<T: 'static, R>(
2809 &mut self,
2810 handle: &Entity<T>,
2811 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2812 ) -> R {
2813 self.update(|cx| {
2814 let mut entity = cx.entities.lease(handle);
2815 let result = update(
2816 &mut entity,
2817 &mut Context::new_context(cx, handle.downgrade()),
2818 );
2819 cx.entities.end_lease(entity);
2820 result
2821 })
2822 }
2823
2824 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2825 where
2826 T: 'static,
2827 {
2828 GpuiBorrow::new(handle.clone(), self)
2829 }
2830
2831 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
2832 where
2833 T: 'static,
2834 {
2835 let entity = self.entities.read(handle);
2836 read(entity, self)
2837 }
2838
2839 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2840 where
2841 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2842 {
2843 self.update_window_id(handle.id, update)
2844 }
2845
2846 fn with_window<R>(
2847 &mut self,
2848 entity_id: EntityId,
2849 f: impl FnOnce(&mut Window, &mut App) -> R,
2850 ) -> Option<R> {
2851 App::with_window(self, entity_id, f)
2852 }
2853
2854 fn read_window<T, R>(
2855 &self,
2856 window: &WindowHandle<T>,
2857 read: impl FnOnce(Entity<T>, &App) -> R,
2858 ) -> Result<R>
2859 where
2860 T: 'static,
2861 {
2862 let window = self
2863 .windows
2864 .get(window.id)
2865 .context("window not found")?
2866 .as_deref()
2867 .expect("attempted to read a window that is already on the stack");
2868
2869 let root_view = window.root.clone().unwrap();
2870 let view = root_view
2871 .downcast::<T>()
2872 .map_err(|_| anyhow!("root view's type has changed"))?;
2873
2874 Ok(read(view, self))
2875 }
2876
2877 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2878 where
2879 R: Send + 'static,
2880 {
2881 self.background_executor.spawn(future)
2882 }
2883
2884 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
2885 where
2886 G: Global,
2887 {
2888 let mut g = self.global::<G>();
2889 callback(g, self)
2890 }
2891}
2892
2893pub(crate) enum Effect {
2895 Notify {
2896 emitter: EntityId,
2897 },
2898 Emit {
2899 emitter: EntityId,
2900 event_type: TypeId,
2901 event: ArenaBox<dyn Any>,
2902 },
2903 RefreshWindows,
2904 NotifyGlobalObservers {
2905 global_type: TypeId,
2906 },
2907 Defer {
2908 callback: Box<dyn FnOnce(&mut App) + 'static>,
2909 },
2910 EntityCreated {
2911 entity: AnyEntity,
2912 tid: TypeId,
2913 window: Option<WindowId>,
2914 },
2915}
2916
2917impl std::fmt::Debug for Effect {
2918 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2919 match self {
2920 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2921 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2922 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2923 Effect::NotifyGlobalObservers { global_type } => {
2924 write!(f, "NotifyGlobalObservers({:?})", global_type)
2925 }
2926 Effect::Defer { .. } => write!(f, "Defer(..)"),
2927 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2928 }
2929 }
2930}
2931
2932pub(crate) struct GlobalLease<G: Global> {
2934 global: Box<dyn Any>,
2935 global_type: PhantomData<G>,
2936}
2937
2938impl<G: Global> GlobalLease<G> {
2939 fn new(global: Box<dyn Any>) -> Self {
2940 GlobalLease {
2941 global,
2942 global_type: PhantomData,
2943 }
2944 }
2945}
2946
2947impl<G: Global> Deref for GlobalLease<G> {
2948 type Target = G;
2949
2950 fn deref(&self) -> &Self::Target {
2951 self.global.downcast_ref().unwrap()
2952 }
2953}
2954
2955impl<G: Global> DerefMut for GlobalLease<G> {
2956 fn deref_mut(&mut self) -> &mut Self::Target {
2957 self.global.downcast_mut().unwrap()
2958 }
2959}
2960
2961pub struct AnyDrag {
2964 pub view: AnyView,
2966
2967 pub value: Arc<dyn Any>,
2969
2970 pub cursor_offset: Point<Pixels>,
2973
2974 pub cursor_style: Option<CursorStyle>,
2976
2977 pub external_payload_source: Option<ExternalDragPayloadSource>,
2980}
2981
2982pub type ExternalDragPayloadSource =
2985 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
2986
2987#[derive(Clone)]
2990pub struct AnyTooltip {
2991 pub view: AnyView,
2993
2994 pub mouse_position: Point<Pixels>,
2996
2997 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3001}
3002
3003#[derive(Debug)]
3005pub struct KeystrokeEvent {
3006 pub keystroke: Keystroke,
3008
3009 pub action: Option<Box<dyn Action>>,
3011
3012 pub context_stack: Vec<KeyContext>,
3014}
3015
3016struct NullHttpClient;
3017
3018impl HttpClient for NullHttpClient {
3019 fn send(
3020 &self,
3021 _req: http_client::Request<http_client::AsyncBody>,
3022 ) -> futures::future::BoxFuture<
3023 'static,
3024 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3025 > {
3026 async move {
3027 anyhow::bail!("No HttpClient available");
3028 }
3029 .boxed()
3030 }
3031
3032 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3033 None
3034 }
3035
3036 fn proxy(&self) -> Option<&Url> {
3037 None
3038 }
3039}
3040
3041pub struct GpuiBorrow<'a, T> {
3043 inner: Option<Lease<T>>,
3044 app: &'a mut App,
3045}
3046
3047impl<'a, T: 'static> GpuiBorrow<'a, T> {
3048 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3049 app.start_update();
3050 let lease = app.entities.lease(&inner);
3051 Self {
3052 inner: Some(lease),
3053 app,
3054 }
3055 }
3056}
3057
3058impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3059 fn borrow(&self) -> &T {
3060 self.inner.as_ref().unwrap().borrow()
3061 }
3062}
3063
3064impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3065 fn borrow_mut(&mut self) -> &mut T {
3066 self.inner.as_mut().unwrap().borrow_mut()
3067 }
3068}
3069
3070impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3071 type Target = T;
3072
3073 fn deref(&self) -> &Self::Target {
3074 self.inner.as_ref().unwrap()
3075 }
3076}
3077
3078impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3079 fn deref_mut(&mut self) -> &mut T {
3080 self.inner.as_mut().unwrap()
3081 }
3082}
3083
3084impl<'a, T> Drop for GpuiBorrow<'a, T> {
3085 fn drop(&mut self) {
3086 let lease = self.inner.take().unwrap();
3087 self.app.notify(lease.id);
3088 self.app.entities.end_lease(lease);
3089 self.app.finish_update();
3090 }
3091}
3092
3093#[cfg(test)]
3094mod test {
3095 use std::{
3096 cell::{Cell, RefCell},
3097 ffi::OsString,
3098 path::PathBuf,
3099 rc::Rc,
3100 };
3101
3102 #[cfg(unix)]
3103 use std::os::unix::ffi::OsStringExt;
3104
3105 use crate::{AppContext, Context, Empty, IntoElement, Render, TestAppContext, Window};
3106
3107 struct RenderCounter(Rc<Cell<usize>>);
3108
3109 impl Render for RenderCounter {
3110 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3111 self.0.set(self.0.get() + 1);
3112 Empty
3113 }
3114 }
3115
3116 #[gpui::test]
3117 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3118 let render_count = Rc::new(Cell::new(0));
3119
3120 let _window = cx.add_window({
3121 let render_count = render_count.clone();
3122 move |_, _| RenderCounter(render_count)
3123 });
3124
3125 cx.run_until_parked();
3126 let render_count_before_refresh = render_count.get();
3127
3128 cx.to_async().refresh();
3129
3130 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3131 }
3132
3133 #[test]
3134 fn test_gpui_borrow() {
3135 let cx = TestAppContext::single();
3136 let observation_count = Rc::new(RefCell::new(0));
3137
3138 let state = cx.update(|cx| {
3139 let state = cx.new(|_| false);
3140 cx.observe(&state, {
3141 let observation_count = observation_count.clone();
3142 move |_, _| {
3143 let mut count = observation_count.borrow_mut();
3144 *count += 1;
3145 }
3146 })
3147 .detach();
3148
3149 state
3150 });
3151
3152 cx.update(|cx| {
3153 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3155 });
3156
3157 cx.update(|cx| {
3158 state.write(cx, false);
3159 });
3160
3161 assert_eq!(*observation_count.borrow(), 2);
3162 }
3163
3164 #[gpui::test]
3165 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3166 #[cfg(unix)]
3167 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3168 #[cfg(not(unix))]
3169 let user_data_dir = OsString::from("C:\\zed data");
3170 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3171 let restart_path = PathBuf::from("updated-zed");
3172 let _application =
3173 super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3174 let restart = cx.expect_restart();
3175
3176 cx.update(|cx| {
3177 cx.set_restart_path(restart_path.clone());
3178 cx.restart();
3179 });
3180
3181 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3182 assert_eq!(path, Some(restart_path));
3183 assert_eq!(restart_arguments, arguments);
3184 }
3185}