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
25pub use async_context::*;
26#[cfg(feature = "bench")]
27pub use bench_context::{BenchAppContext, BenchReport, BenchWindowContext, bench_platform};
28use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
29pub use context::*;
30pub use entity_map::*;
31use gpui_util::{ResultExt, debug_panic};
32#[cfg(any(test, feature = "test-support"))]
33pub use headless_app_context::*;
34use http_client::{HttpClient, Url};
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;
45use crate::{
46 Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
47 ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle,
48 DispatchPhase, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap,
49 ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu,
50 MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
51 PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
52 PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
53 ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
54 SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
55 ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
56 WindowInvalidator,
57 colors::{Colors, GlobalColors},
58 hash, init_app_menus,
59};
60
61mod async_context;
62#[cfg(feature = "bench")]
63mod bench_context;
64mod context;
65mod entity_map;
66#[cfg(any(test, feature = "test-support"))]
67mod headless_app_context;
68#[cfg(any(test, feature = "test-support"))]
69mod test_app;
70#[cfg(any(test, feature = "test-support"))]
71mod test_context;
72#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
73mod visual_test_context;
74
75pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
77
78#[doc(hidden)]
81pub struct AppCell {
82 app: RefCell<App>,
83}
84
85impl AppCell {
86 #[doc(hidden)]
87 #[track_caller]
88 pub fn borrow(&self) -> AppRef<'_> {
89 if option_env!("TRACK_THREAD_BORROWS").is_some() {
90 let thread_id = std::thread::current().id();
91 eprintln!("borrowed {thread_id:?}");
92 }
93 AppRef(self.app.borrow())
94 }
95
96 #[doc(hidden)]
97 #[track_caller]
98 pub fn borrow_mut(&self) -> AppRefMut<'_> {
99 if option_env!("TRACK_THREAD_BORROWS").is_some() {
100 let thread_id = std::thread::current().id();
101 eprintln!("borrowed {thread_id:?}");
102 }
103 AppRefMut(self.app.borrow_mut())
104 }
105
106 #[doc(hidden)]
107 #[track_caller]
108 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
109 if option_env!("TRACK_THREAD_BORROWS").is_some() {
110 let thread_id = std::thread::current().id();
111 eprintln!("borrowed {thread_id:?}");
112 }
113 Ok(AppRefMut(self.app.try_borrow_mut()?))
114 }
115}
116
117#[doc(hidden)]
118#[derive(Deref, DerefMut)]
119pub struct AppRef<'a>(Ref<'a, App>);
120
121impl Drop for AppRef<'_> {
122 fn drop(&mut self) {
123 if option_env!("TRACK_THREAD_BORROWS").is_some() {
124 let thread_id = std::thread::current().id();
125 eprintln!("dropped borrow from {thread_id:?}");
126 }
127 }
128}
129
130#[doc(hidden)]
131#[derive(Deref, DerefMut)]
132pub struct AppRefMut<'a>(RefMut<'a, App>);
133
134impl Drop for AppRefMut<'_> {
135 fn drop(&mut self) {
136 if option_env!("TRACK_THREAD_BORROWS").is_some() {
137 let thread_id = std::thread::current().id();
138 eprintln!("dropped {thread_id:?}");
139 }
140 }
141}
142
143pub struct Application(Rc<AppCell>);
146
147pub struct ApplicationHandle {
153 app: Rc<AppCell>,
154}
155
156impl ApplicationHandle {
157 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
161 let cx = &mut *self.app.borrow_mut();
162 f(cx)
163 }
164
165 pub fn to_async(&self) -> AsyncApp {
168 self.update(|cx| cx.to_async())
169 }
170}
171
172impl Application {
175 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
177 Self(App::new_app(
178 platform,
179 Arc::new(()),
180 Arc::new(NullHttpClient),
181 ))
182 }
183
184 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
194 let this = Self::with_platform(platform);
195 this.0.borrow_mut().accessibility_force_disabled = true;
196 this
197 }
198
199 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
201 let mut context_lock = self.0.borrow_mut();
202 let asset_source = Arc::new(asset_source);
203 context_lock.asset_source = asset_source.clone();
204 context_lock.svg_renderer = SvgRenderer::new(asset_source);
205 drop(context_lock);
206 self
207 }
208
209 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
211 let mut context_lock = self.0.borrow_mut();
212 context_lock.http_client = http_client;
213 drop(context_lock);
214 self
215 }
216
217 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
220 self.0.borrow_mut().quit_mode = mode;
221 self
222 }
223
224 pub fn run<F>(self, on_finish_launching: F)
227 where
228 F: 'static + FnOnce(&mut App),
229 {
230 let this = self.0.clone();
231 let platform = self.0.borrow().platform.clone();
232 platform.run(Box::new(move || {
233 let cx = &mut *this.borrow_mut();
234 on_finish_launching(cx);
235 }));
236 }
237
238 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
248 where
249 F: 'static + FnOnce(&mut App),
250 {
251 let this = self.0.clone();
252 let platform = self.0.borrow().platform.clone();
253 platform.run(Box::new(move || {
254 let cx = &mut *this.borrow_mut();
255 on_finish_launching(cx);
256 }));
257 ApplicationHandle { app: self.0 }
258 }
259
260 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
263 where
264 F: 'static + FnMut(Vec<String>),
265 {
266 self.0.borrow().platform.on_open_urls(Box::new(callback));
267 self
268 }
269
270 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
273 where
274 F: 'static + FnMut(&mut App),
275 {
276 let this = Rc::downgrade(&self.0);
277 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
278 if let Some(app) = this.upgrade() {
279 callback(&mut app.borrow_mut());
280 }
281 }));
282 self
283 }
284
285 pub fn on_system_wake<F>(&self, mut callback: F) -> &Self
287 where
288 F: 'static + FnMut(&mut App),
289 {
290 let this = Rc::downgrade(&self.0);
291 self.0
292 .borrow_mut()
293 .platform
294 .on_system_wake(Box::new(move || {
295 if let Some(app) = this.upgrade() {
296 callback(&mut app.borrow_mut());
297 }
298 }));
299 self
300 }
301
302 pub fn background_executor(&self) -> BackgroundExecutor {
304 self.0.borrow().background_executor.clone()
305 }
306
307 pub fn foreground_executor(&self) -> ForegroundExecutor {
309 self.0.borrow().foreground_executor.clone()
310 }
311
312 pub fn text_system(&self) -> Arc<TextSystem> {
314 self.0.borrow().text_system.clone()
315 }
316
317 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
319 self.0.borrow().path_for_auxiliary_executable(name)
320 }
321}
322
323type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
324type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
325pub(crate) type KeystrokeObserver =
326 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
327type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
328type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
329type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
330type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
334pub enum QuitMode {
335 #[default]
337 Default,
338 LastWindowClosed,
340 Explicit,
342}
343
344#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
349pub enum CursorHideMode {
350 Never,
352 OnTyping,
354 #[default]
357 OnTypingAndAction,
358}
359
360#[doc(hidden)]
361#[derive(Clone, PartialEq, Eq)]
362pub struct SystemWindowTab {
363 pub id: WindowId,
364 pub title: SharedString,
365 pub handle: AnyWindowHandle,
366 pub last_active_at: Instant,
367}
368
369impl SystemWindowTab {
370 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
372 Self {
373 id: handle.id,
374 title,
375 handle,
376 last_active_at: Instant::now(),
377 }
378 }
379}
380
381#[derive(Default)]
383pub struct SystemWindowTabController {
384 visible: Option<bool>,
385 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
386}
387
388impl Global for SystemWindowTabController {}
389
390impl SystemWindowTabController {
391 pub fn new() -> Self {
393 Self {
394 visible: None,
395 tab_groups: FxHashMap::default(),
396 }
397 }
398
399 pub fn init(cx: &mut App) {
401 cx.set_global(SystemWindowTabController::new());
402 }
403
404 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
406 &self.tab_groups
407 }
408
409 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
411 let controller = cx.global::<SystemWindowTabController>();
412 let current_group = controller
413 .tab_groups
414 .iter()
415 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
416
417 let current_group = current_group?;
418 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
420 let idx = group_ids.iter().position(|g| *g == current_group)?;
421 let next_idx = (idx + 1) % group_ids.len();
422
423 controller
424 .tab_groups
425 .get(group_ids[next_idx])
426 .and_then(|tabs| {
427 tabs.iter()
428 .max_by_key(|tab| tab.last_active_at)
429 .or_else(|| tabs.first())
430 .map(|tab| &tab.handle)
431 })
432 }
433
434 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
436 let controller = cx.global::<SystemWindowTabController>();
437 let current_group = controller
438 .tab_groups
439 .iter()
440 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
441
442 let current_group = current_group?;
443 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
445 let idx = group_ids.iter().position(|g| *g == current_group)?;
446 let prev_idx = if idx == 0 {
447 group_ids.len() - 1
448 } else {
449 idx - 1
450 };
451
452 controller
453 .tab_groups
454 .get(group_ids[prev_idx])
455 .and_then(|tabs| {
456 tabs.iter()
457 .max_by_key(|tab| tab.last_active_at)
458 .or_else(|| tabs.first())
459 .map(|tab| &tab.handle)
460 })
461 }
462
463 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
465 self.tab_groups
466 .values()
467 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
468 }
469
470 pub fn init_visible(cx: &mut App, visible: bool) {
472 let mut controller = cx.global_mut::<SystemWindowTabController>();
473 if controller.visible.is_none() {
474 controller.visible = Some(visible);
475 }
476 }
477
478 pub fn is_visible(&self) -> bool {
480 self.visible.unwrap_or(false)
481 }
482
483 pub fn set_visible(cx: &mut App, visible: bool) {
485 let mut controller = cx.global_mut::<SystemWindowTabController>();
486 controller.visible = Some(visible);
487 }
488
489 pub fn update_last_active(cx: &mut App, id: WindowId) {
491 let mut controller = cx.global_mut::<SystemWindowTabController>();
492 for windows in controller.tab_groups.values_mut() {
493 for tab in windows.iter_mut() {
494 if tab.id == id {
495 tab.last_active_at = Instant::now();
496 }
497 }
498 }
499 }
500
501 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
503 let mut controller = cx.global_mut::<SystemWindowTabController>();
504 for (_, windows) in controller.tab_groups.iter_mut() {
505 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
506 if ix < windows.len() && current_pos != ix {
507 let window_tab = windows.remove(current_pos);
508 windows.insert(ix, window_tab);
509 }
510 break;
511 }
512 }
513 }
514
515 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
517 let controller = cx.global::<SystemWindowTabController>();
518 let tab = controller
519 .tab_groups
520 .values()
521 .flat_map(|windows| windows.iter())
522 .find(|tab| tab.id == id);
523
524 if tab.map_or(true, |t| t.title == title) {
525 return;
526 }
527
528 let mut controller = cx.global_mut::<SystemWindowTabController>();
529 for windows in controller.tab_groups.values_mut() {
530 for tab in windows.iter_mut() {
531 if tab.id == id {
532 tab.title = title;
533 return;
534 }
535 }
536 }
537 }
538
539 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
541 let mut controller = cx.global_mut::<SystemWindowTabController>();
542 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
543 return;
544 };
545
546 let mut expected_tab_ids: Vec<_> = tabs
547 .iter()
548 .filter(|tab| tab.id != id)
549 .map(|tab| tab.id)
550 .sorted()
551 .collect();
552
553 let mut tab_group_id = None;
554 for (group_id, group_tabs) in &controller.tab_groups {
555 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
556 if tab_ids == expected_tab_ids {
557 tab_group_id = Some(*group_id);
558 break;
559 }
560 }
561
562 if let Some(tab_group_id) = tab_group_id {
563 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
564 tabs.push(tab);
565 }
566 } else {
567 let new_group_id = controller.tab_groups.len();
568 controller.tab_groups.insert(new_group_id, tabs);
569 }
570 }
571
572 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
574 let mut controller = cx.global_mut::<SystemWindowTabController>();
575 let mut removed_tab = None;
576
577 controller.tab_groups.retain(|_, tabs| {
578 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
579 removed_tab = Some(tabs.remove(pos));
580 }
581 !tabs.is_empty()
582 });
583
584 removed_tab
585 }
586
587 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
589 let mut removed_tab = Self::remove_tab(cx, id);
590 let mut controller = cx.global_mut::<SystemWindowTabController>();
591
592 if let Some(tab) = removed_tab {
593 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
594 controller.tab_groups.insert(new_group_id, vec![tab]);
595 }
596 }
597
598 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
600 let mut controller = cx.global_mut::<SystemWindowTabController>();
601 let Some(initial_tabs) = controller.tabs(id) else {
602 return;
603 };
604
605 let initial_tabs_len = initial_tabs.len();
606 let mut all_tabs = initial_tabs.clone();
607
608 for (_, mut tabs) in controller.tab_groups.drain() {
609 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
610 all_tabs.extend(tabs);
611 }
612
613 controller.tab_groups.insert(0, all_tabs);
614 }
615
616 pub fn select_next_tab(cx: &mut App, id: WindowId) {
618 let mut controller = cx.global_mut::<SystemWindowTabController>();
619 let Some(tabs) = controller.tabs(id) else {
620 return;
621 };
622
623 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
624 let next_index = (current_index + 1) % tabs.len();
625
626 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
627 window.activate_window();
628 });
629 }
630
631 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
633 let mut controller = cx.global_mut::<SystemWindowTabController>();
634 let Some(tabs) = controller.tabs(id) else {
635 return;
636 };
637
638 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
639 let previous_index = if current_index == 0 {
640 tabs.len() - 1
641 } else {
642 current_index - 1
643 };
644
645 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
646 window.activate_window();
647 });
648 }
649}
650
651pub(crate) enum GpuiMode {
652 #[cfg(any(test, feature = "test-support"))]
653 Test {
654 skip_drawing: bool,
655 },
656 Production,
657}
658
659impl GpuiMode {
660 #[cfg(any(test, feature = "test-support"))]
661 pub fn test() -> Self {
662 GpuiMode::Test {
663 skip_drawing: false,
664 }
665 }
666
667 #[inline]
668 pub(crate) fn skip_drawing(&self) -> bool {
669 match self {
670 #[cfg(any(test, feature = "test-support"))]
671 GpuiMode::Test { skip_drawing } => *skip_drawing,
672 GpuiMode::Production => false,
673 }
674 }
675}
676
677struct PlatformOwnedDrag {
678 source_window: WindowId,
679 state: PlatformOwnedDragState,
680}
681
682enum PlatformOwnedDragState {
683 Suspended(AnyDrag),
684 RestoredInSourceWindow,
687}
688
689pub struct App {
693 pub(crate) this: Weak<AppCell>,
694 pub(crate) platform: Rc<dyn Platform>,
695 text_system: Arc<TextSystem>,
696
697 pub(crate) actions: Rc<ActionRegistry>,
698 pub(crate) active_drag: Option<AnyDrag>,
699 platform_owned_drag: Option<PlatformOwnedDrag>,
700 pub(crate) background_executor: BackgroundExecutor,
701 pub(crate) foreground_executor: ForegroundExecutor,
702 pub(crate) entities: EntityMap,
703 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
704 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
705 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
706 pub(crate) focus_handles: Arc<FocusMap>,
707 pub(crate) keymap: Rc<RefCell<Keymap>>,
708 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
709 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
710 pub(crate) global_action_listeners:
711 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
712 pending_effects: VecDeque<Effect>,
713
714 pub(crate) observers: SubscriberSet<EntityId, Handler>,
715 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
716 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
717 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
718 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
719 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
720 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
721 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
722 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
723 pub(crate) restart_observers: SubscriberSet<(), Handler>,
724 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
725
726 pub(crate) element_arena: RefCell<Arena>,
729 pub(crate) event_arena: Arena,
731
732 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
737
738 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
740 asset_source: Arc<dyn AssetSource>,
741 pub(crate) svg_renderer: SvgRenderer,
742 http_client: Arc<dyn HttpClient>,
743
744 pub(crate) pending_notifications: FxHashSet<EntityId>,
746 pub(crate) pending_global_notifications: TypeIdHashSet,
747 pub(crate) restart_path: Option<PathBuf>,
748 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
750 pub(crate) prompt_builder: Option<PromptBuilder>,
751 pub(crate) window_invalidators_by_entity:
752 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
753 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
754 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
755 #[cfg(any(feature = "inspector", debug_assertions))]
756 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
757 #[cfg(any(feature = "inspector", debug_assertions))]
758 pub(crate) inspector_element_registry: InspectorElementRegistry,
759 #[cfg(any(test, feature = "test-support", debug_assertions))]
760 pub(crate) name: Option<&'static str>,
761 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
762
763 pub(crate) window_update_stack: Vec<WindowId>,
764 pub(crate) mode: GpuiMode,
765 pub(crate) cursor_hide_mode: CursorHideMode,
766 pub(crate) reduce_motion: bool,
767 pub(crate) accessibility_force_disabled: bool,
770 flushing_effects: bool,
771 pending_updates: usize,
772 quit_mode: QuitMode,
773 quitting: bool,
774
775 #[cfg(any(test, feature = "leak-detection"))]
778 _ref_counts: Arc<RwLock<EntityRefCounts>>,
779}
780
781impl App {
782 #[allow(clippy::new_ret_no_self)]
783 pub(crate) fn new_app(
784 platform: Rc<dyn Platform>,
785 asset_source: Arc<dyn AssetSource>,
786 http_client: Arc<dyn HttpClient>,
787 ) -> Rc<AppCell> {
788 let background_executor = platform.background_executor();
789 let foreground_executor = platform.foreground_executor();
790 assert!(
791 background_executor.is_main_thread(),
792 "must construct App on main thread"
793 );
794
795 let text_system = Arc::new(TextSystem::new(platform.text_system()));
796 let entities = EntityMap::new();
797 let keyboard_layout = platform.keyboard_layout();
798 let keyboard_mapper = platform.keyboard_mapper();
799
800 #[cfg(any(test, feature = "leak-detection"))]
801 let _ref_counts = entities.ref_counts_drop_handle();
802
803 let app = Rc::new_cyclic(|this| AppCell {
804 app: RefCell::new(App {
805 this: this.clone(),
806 platform: platform.clone(),
807 text_system,
808 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
809 mode: GpuiMode::Production,
810 actions: Rc::new(ActionRegistry::default()),
811 flushing_effects: false,
812 pending_updates: 0,
813 active_drag: None,
814 platform_owned_drag: None,
815 background_executor,
816 foreground_executor,
817 svg_renderer: SvgRenderer::new(asset_source.clone()),
818 loading_assets: Default::default(),
819 asset_source,
820 http_client,
821 globals_by_type: Default::default(),
822 entities,
823 new_entity_observers: SubscriberSet::new(),
824 windows: SlotMap::with_key(),
825 window_update_stack: Vec::new(),
826 window_handles: FxHashMap::default(),
827 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
828 keymap: Rc::new(RefCell::new(Keymap::default())),
829 keyboard_layout,
830 keyboard_mapper,
831 global_action_listeners: Default::default(),
832 pending_effects: VecDeque::new(),
833 pending_notifications: FxHashSet::default(),
834 pending_global_notifications: Default::default(),
835 observers: SubscriberSet::new(),
836 tracked_entities: FxHashMap::default(),
837 window_invalidators_by_entity: FxHashMap::default(),
838 current_window_by_entity: FxHashMap::default(),
839 event_listeners: SubscriberSet::new(),
840 release_listeners: SubscriberSet::new(),
841 keystroke_observers: SubscriberSet::new(),
842 keystroke_interceptors: SubscriberSet::new(),
843 keyboard_layout_observers: SubscriberSet::new(),
844 thermal_state_observers: SubscriberSet::new(),
845 global_observers: SubscriberSet::new(),
846 quit_observers: SubscriberSet::new(),
847 restart_observers: SubscriberSet::new(),
848 restart_path: None,
849 window_closed_observers: SubscriberSet::new(),
850 layout_id_buffer: Default::default(),
851 propagate_event: true,
852 prompt_builder: Some(PromptBuilder::Default),
853 #[cfg(any(feature = "inspector", debug_assertions))]
854 inspector_renderer: None,
855 #[cfg(any(feature = "inspector", debug_assertions))]
856 inspector_element_registry: InspectorElementRegistry::default(),
857 quit_mode: QuitMode::default(),
858 quitting: false,
859 cursor_hide_mode: CursorHideMode::default(),
860 reduce_motion: false,
861 accessibility_force_disabled: false,
862
863 #[cfg(any(test, feature = "test-support", debug_assertions))]
864 name: None,
865 element_arena: RefCell::new(Arena::new(1024 * 1024)),
866 event_arena: Arena::new(1024 * 1024),
867
868 #[cfg(any(test, feature = "leak-detection"))]
869 _ref_counts,
870 }),
871 });
872
873 init_app_menus(platform.as_ref(), &app.borrow());
874 SystemWindowTabController::init(&mut app.borrow_mut());
875
876 platform.on_keyboard_layout_change(Box::new({
877 let app = Rc::downgrade(&app);
878 move || {
879 if let Some(app) = app.upgrade() {
880 let cx = &mut app.borrow_mut();
881 cx.keyboard_layout = cx.platform.keyboard_layout();
882 cx.keyboard_mapper = cx.platform.keyboard_mapper();
883 cx.keyboard_layout_observers
884 .clone()
885 .retain(&(), move |callback| (callback)(cx));
886 }
887 }
888 }));
889
890 platform.on_thermal_state_change(Box::new({
891 let app = Rc::downgrade(&app);
892 move || {
893 if let Some(app) = app.upgrade() {
894 let cx = &mut app.borrow_mut();
895 cx.thermal_state_observers
896 .clone()
897 .retain(&(), move |callback| (callback)(cx));
898 }
899 }
900 }));
901
902 platform.on_quit(Box::new({
903 let cx = Rc::downgrade(&app);
904 move || {
905 if let Some(cx) = cx.upgrade() {
906 cx.borrow_mut().shutdown();
907 }
908 }
909 }));
910
911 app
912 }
913
914 #[doc(hidden)]
915 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
916 self.entities.ref_counts_drop_handle()
917 }
918
919 #[cfg(any(test, feature = "leak-detection"))]
925 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
926 self.entities.leak_detector_snapshot()
927 }
928
929 #[cfg(any(test, feature = "leak-detection"))]
941 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
942 self.entities.assert_no_new_leaks(snapshot)
943 }
944
945 pub fn shutdown(&mut self) {
948 let mut futures = Vec::new();
949
950 for observer in self.quit_observers.remove(&()) {
951 futures.push(observer(self));
952 }
953
954 self.windows.clear();
955 self.window_handles.clear();
956 self.flush_effects();
957 self.quitting = true;
958
959 let futures = futures::future::join_all(futures);
960 if self
961 .foreground_executor
962 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
963 .is_err()
964 {
965 log::error!("timed out waiting on app_will_quit");
966 }
967
968 self.quitting = false;
969 }
970
971 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
973 self.keyboard_layout.as_ref()
974 }
975
976 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
978 &self.keyboard_mapper
979 }
980
981 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
983 where
984 F: 'static + FnMut(&mut App),
985 {
986 let (subscription, activate) = self.keyboard_layout_observers.insert(
987 (),
988 Box::new(move |cx| {
989 callback(cx);
990 true
991 }),
992 );
993 activate();
994 subscription
995 }
996
997 pub fn quit(&self) {
999 self.platform.quit();
1000 }
1001
1002 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1005 self.cursor_hide_mode
1006 }
1007
1008 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1011 self.cursor_hide_mode = mode;
1012 }
1013
1014 pub fn is_cursor_visible(&self) -> bool {
1020 self.platform.is_cursor_visible()
1021 }
1022
1023 pub fn reduce_motion(&self) -> bool {
1026 self.reduce_motion
1027 }
1028
1029 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1032 if self.reduce_motion != reduce_motion {
1033 self.reduce_motion = reduce_motion;
1034 self.refresh_windows();
1035 }
1036 }
1037
1038 pub fn refresh_windows(&mut self) {
1041 self.pending_effects.push_back(Effect::RefreshWindows);
1042 }
1043
1044 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1045 self.start_update();
1046 let result = update(self);
1047 self.finish_update();
1048 result
1049 }
1050
1051 pub(crate) fn start_update(&mut self) {
1052 self.pending_updates += 1;
1053 }
1054
1055 pub(crate) fn finish_update(&mut self) {
1056 if !self.flushing_effects && self.pending_updates == 1 {
1057 self.flushing_effects = true;
1058 self.flush_effects();
1059 self.flushing_effects = false;
1060 }
1061 self.pending_updates -= 1;
1062 }
1063
1064 pub fn observe<W>(
1066 &mut self,
1067 entity: &Entity<W>,
1068 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1069 ) -> Subscription
1070 where
1071 W: 'static,
1072 {
1073 self.observe_internal(entity, move |e, cx| {
1074 on_notify(e, cx);
1075 true
1076 })
1077 }
1078
1079 pub(crate) fn detect_accessed_entities<R>(
1080 &mut self,
1081 callback: impl FnOnce(&mut App) -> R,
1082 ) -> (R, FxHashSet<EntityId>) {
1083 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1084 let result = callback(self);
1085 let entities_accessed_in_callback = self
1086 .entities
1087 .accessed_entities
1088 .get_mut()
1089 .difference(&accessed_entities_start)
1090 .copied()
1091 .collect::<FxHashSet<EntityId>>();
1092 (result, entities_accessed_in_callback)
1093 }
1094
1095 pub(crate) fn record_entities_accessed(
1096 &mut self,
1097 window_handle: AnyWindowHandle,
1098 invalidator: WindowInvalidator,
1099 entities: &FxHashSet<EntityId>,
1100 ) {
1101 let mut tracked_entities =
1102 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1103 for entity in tracked_entities.iter() {
1104 self.window_invalidators_by_entity
1105 .entry(*entity)
1106 .and_modify(|windows| {
1107 windows.remove(&window_handle.id);
1108 });
1109 }
1110 for entity in entities.iter() {
1111 self.window_invalidators_by_entity
1112 .entry(*entity)
1113 .or_default()
1114 .insert(window_handle.id, invalidator.clone());
1115 self.current_window_by_entity
1116 .insert(*entity, window_handle.id);
1117 }
1118 tracked_entities.clear();
1119 tracked_entities.extend(entities.iter().copied());
1120 self.tracked_entities
1121 .insert(window_handle.id, tracked_entities);
1122 }
1123
1124 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1125 let (subscription, activate) = self.observers.insert(key, value);
1126 self.defer(move |_| activate());
1127 subscription
1128 }
1129
1130 pub(crate) fn observe_internal<W>(
1131 &mut self,
1132 entity: &Entity<W>,
1133 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1134 ) -> Subscription
1135 where
1136 W: 'static,
1137 {
1138 let entity_id = entity.entity_id();
1139 let handle = entity.downgrade();
1140 self.new_observer(
1141 entity_id,
1142 Box::new(move |cx| {
1143 if let Some(entity) = handle.upgrade() {
1144 on_notify(entity, cx)
1145 } else {
1146 false
1147 }
1148 }),
1149 )
1150 }
1151
1152 pub fn subscribe<T, Event>(
1155 &mut self,
1156 entity: &Entity<T>,
1157 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1158 ) -> Subscription
1159 where
1160 T: 'static + EventEmitter<Event>,
1161 Event: 'static,
1162 {
1163 self.subscribe_internal(entity, move |entity, event, cx| {
1164 on_event(entity, event, cx);
1165 true
1166 })
1167 }
1168
1169 pub(crate) fn new_subscription(
1170 &mut self,
1171 key: EntityId,
1172 value: (TypeId, Listener),
1173 ) -> Subscription {
1174 let (subscription, activate) = self.event_listeners.insert(key, value);
1175 self.defer(move |_| activate());
1176 subscription
1177 }
1178 pub(crate) fn subscribe_internal<T, Evt>(
1179 &mut self,
1180 entity: &Entity<T>,
1181 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1182 ) -> Subscription
1183 where
1184 T: 'static + EventEmitter<Evt>,
1185 Evt: 'static,
1186 {
1187 let entity_id = entity.entity_id();
1188 let handle = entity.downgrade();
1189 self.new_subscription(
1190 entity_id,
1191 (
1192 TypeId::of::<Evt>(),
1193 Box::new(move |event, cx| {
1194 let event: &Evt = event.downcast_ref().expect("invalid event type");
1195 if let Some(entity) = handle.upgrade() {
1196 on_event(entity, event, cx)
1197 } else {
1198 false
1199 }
1200 }),
1201 ),
1202 )
1203 }
1204
1205 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1209 self.windows
1210 .keys()
1211 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1212 .collect()
1213 }
1214
1215 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1221 self.platform.window_stack()
1222 }
1223
1224 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1226 self.platform.active_window()
1227 }
1228
1229 pub fn open_window<V: 'static + Render>(
1233 &mut self,
1234 options: crate::WindowOptions,
1235 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1236 ) -> anyhow::Result<WindowHandle<V>> {
1237 self.update(|cx| {
1238 let id = cx.windows.insert(None);
1239 let handle = WindowHandle::new(id);
1240 match Window::new(handle.into(), options, cx) {
1241 Ok(mut window) => {
1242 cx.window_update_stack.push(id);
1243 let root_view = build_root_view(&mut window, cx);
1244 cx.window_update_stack.pop();
1245 window.root.replace(root_view.into());
1246 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1247
1248 let clear = window.draw(cx);
1253 clear.clear(cx);
1254
1255 cx.window_handles.insert(id, window.handle);
1256 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1257 Ok(handle)
1258 }
1259 Err(e) => {
1260 cx.windows.remove(id);
1261 Err(e)
1262 }
1263 }
1264 })
1265 }
1266
1267 pub fn activate(&self, ignoring_other_apps: bool) {
1269 self.platform.activate(ignoring_other_apps);
1270 }
1271
1272 pub fn hide(&self) {
1274 self.platform.hide();
1275 }
1276
1277 pub fn hide_other_apps(&self) {
1279 self.platform.hide_other_apps();
1280 }
1281
1282 pub fn unhide_other_apps(&self) {
1284 self.platform.unhide_other_apps();
1285 }
1286
1287 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1289 self.platform.displays()
1290 }
1291
1292 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1294 self.platform.primary_display()
1295 }
1296
1297 pub fn is_screen_capture_supported(&self) -> bool {
1299 self.platform.is_screen_capture_supported()
1300 }
1301
1302 pub fn screen_capture_sources(
1304 &self,
1305 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1306 self.platform.screen_capture_sources()
1307 }
1308
1309 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1311 self.displays()
1312 .iter()
1313 .find(|display| display.id() == id)
1314 .cloned()
1315 }
1316
1317 pub fn thermal_state(&self) -> ThermalState {
1319 self.platform.thermal_state()
1320 }
1321
1322 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1324 where
1325 F: 'static + FnMut(&mut App),
1326 {
1327 let (subscription, activate) = self.thermal_state_observers.insert(
1328 (),
1329 Box::new(move |cx| {
1330 callback(cx);
1331 true
1332 }),
1333 );
1334 activate();
1335 subscription
1336 }
1337
1338 pub fn window_appearance(&self) -> WindowAppearance {
1340 self.platform.window_appearance()
1341 }
1342
1343 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1354 self.platform.set_window_appearance(appearance);
1355 }
1356
1357 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1359 self.platform.button_layout()
1360 }
1361
1362 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1364 self.platform.read_from_clipboard()
1365 }
1366
1367 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1369 self.text_rendering_mode.set(mode);
1370 }
1371
1372 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1374 self.text_rendering_mode.get()
1375 }
1376
1377 pub fn supports_file_clipboard(&self, operation: crate::FileClipboardOperation) -> bool {
1379 self.platform.supports_file_clipboard(operation)
1380 }
1381
1382 pub fn write_files_to_clipboard(
1389 &self,
1390 paths: crate::ExternalPaths,
1391 operation: crate::FileClipboardOperation,
1392 ) -> std::result::Result<(), crate::FileClipboardError> {
1393 if !self.supports_file_clipboard(operation) {
1394 return Err(crate::FileClipboardError::Unsupported);
1395 }
1396 paths.validate_for_clipboard()?;
1397 self.platform.write_files_to_clipboard(paths, operation)
1398 }
1399
1400 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1402 self.platform.write_to_clipboard(item)
1403 }
1404
1405 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1408 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1409 self.platform.read_from_primary()
1410 }
1411
1412 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1415 pub fn write_to_primary(&self, item: ClipboardItem) {
1416 self.platform.write_to_primary(item)
1417 }
1418
1419 #[cfg(target_os = "macos")]
1425 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1426 self.platform.read_from_find_pasteboard()
1427 }
1428
1429 #[cfg(target_os = "macos")]
1435 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1436 self.platform.write_to_find_pasteboard(item)
1437 }
1438
1439 pub fn write_credentials(
1441 &self,
1442 url: &str,
1443 username: &str,
1444 password: &[u8],
1445 ) -> Task<Result<()>> {
1446 self.platform.write_credentials(url, username, password)
1447 }
1448
1449 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1451 self.platform.read_credentials(url)
1452 }
1453
1454 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1456 self.platform.delete_credentials(url)
1457 }
1458
1459 pub fn open_url(&self, url: &str) {
1461 self.platform.open_url(url);
1462 }
1463
1464 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1471 self.platform.register_url_scheme(scheme)
1472 }
1473
1474 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1481 self.platform.set_app_identity(identifier, name);
1482 }
1483
1484 pub fn show_system_notification(&self, notification: SystemNotification) {
1491 self.platform.show_system_notification(notification);
1492 }
1493
1494 pub fn dismiss_system_notification(&self, tag: &str) {
1499 self.platform.dismiss_system_notification(tag);
1500 }
1501
1502 pub fn on_system_notification_response<F>(&self, mut callback: F)
1506 where
1507 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1508 {
1509 let this = self.this.clone();
1510 self.platform
1511 .on_system_notification_response(Box::new(move |response| {
1512 if let Some(app) = this.upgrade() {
1513 callback(response, &mut app.borrow_mut());
1514 }
1515 }));
1516 }
1517
1518 pub fn app_path(&self) -> Result<PathBuf> {
1522 self.platform.app_path()
1523 }
1524
1525 pub fn compositor_name(&self) -> &'static str {
1529 self.platform.compositor_name()
1530 }
1531
1532 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1534 self.platform.path_for_auxiliary_executable(name)
1535 }
1536
1537 pub fn prompt_for_paths(
1543 &self,
1544 options: PathPromptOptions,
1545 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1546 self.platform.prompt_for_paths(options)
1547 }
1548
1549 pub fn prompt_for_new_path(
1556 &self,
1557 directory: &Path,
1558 suggested_name: Option<&str>,
1559 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1560 self.platform.prompt_for_new_path(directory, suggested_name)
1561 }
1562
1563 pub fn reveal_path(&self, path: &Path) {
1565 self.platform.reveal_path(path)
1566 }
1567
1568 pub fn open_with_system(&self, path: &Path) {
1570 self.platform.open_with_system(path)
1571 }
1572
1573 pub fn should_auto_hide_scrollbars(&self) -> bool {
1575 self.platform.should_auto_hide_scrollbars()
1576 }
1577
1578 pub fn restart(&mut self) {
1580 self.restart_observers
1581 .clone()
1582 .retain(&(), |observer| observer(self));
1583 self.platform.restart(self.restart_path.take())
1584 }
1585
1586 pub fn set_restart_path(&mut self, path: PathBuf) {
1588 self.restart_path = Some(path);
1589 }
1590
1591 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1593 self.http_client.clone()
1594 }
1595
1596 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1598 self.http_client = new_client;
1599 }
1600
1601 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1604 self.quit_mode = mode;
1605 }
1606
1607 pub fn svg_renderer(&self) -> SvgRenderer {
1609 self.svg_renderer.clone()
1610 }
1611
1612 pub(crate) fn push_effect(&mut self, effect: Effect) {
1613 match &effect {
1614 Effect::Notify { emitter } => {
1615 if !self.pending_notifications.insert(*emitter) {
1616 return;
1617 }
1618 }
1619 Effect::NotifyGlobalObservers { global_type } => {
1620 if !self.pending_global_notifications.insert(*global_type) {
1621 return;
1622 }
1623 }
1624 _ => {}
1625 };
1626
1627 self.pending_effects.push_back(effect);
1628 }
1629
1630 fn flush_effects(&mut self) {
1634 loop {
1635 self.release_dropped_entities();
1636 self.release_dropped_focus_handles();
1637 if let Some(effect) = self.pending_effects.pop_front() {
1638 match effect {
1639 Effect::Notify { emitter } => {
1640 self.apply_notify_effect(emitter);
1641 }
1642
1643 Effect::Emit {
1644 emitter,
1645 event_type,
1646 event,
1647 } => self.apply_emit_effect(emitter, event_type, &*event),
1648
1649 Effect::RefreshWindows => {
1650 self.apply_refresh_effect();
1651 }
1652
1653 Effect::NotifyGlobalObservers { global_type } => {
1654 self.apply_notify_global_observers_effect(global_type);
1655 }
1656
1657 Effect::Defer { callback } => {
1658 self.apply_defer_effect(callback);
1659 }
1660 Effect::EntityCreated {
1661 entity,
1662 tid,
1663 window,
1664 } => {
1665 self.apply_entity_created_effect(entity, tid, window);
1666 }
1667 }
1668 } else {
1669 #[cfg(any(test, feature = "test-support", feature = "bench"))]
1670 for window in self
1671 .windows
1672 .values()
1673 .filter_map(|window| {
1674 let window = window.as_deref()?;
1675 window.invalidator.is_dirty().then_some(window.handle)
1676 })
1677 .collect::<Vec<_>>()
1678 {
1679 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1680 .unwrap();
1681 }
1682
1683 if self.pending_effects.is_empty() {
1684 self.event_arena.clear();
1685 break;
1686 }
1687 }
1688 }
1689 }
1690
1691 fn release_dropped_entities(&mut self) {
1695 loop {
1696 let dropped = self.entities.take_dropped();
1697 if dropped.is_empty() {
1698 break;
1699 }
1700
1701 for (entity_id, mut entity) in dropped {
1702 self.observers.remove(&entity_id);
1703 self.event_listeners.remove(&entity_id);
1704 self.window_invalidators_by_entity.remove(&entity_id);
1705 self.current_window_by_entity.remove(&entity_id);
1706 for release_callback in self.release_listeners.remove(&entity_id) {
1707 release_callback(entity.as_mut(), self);
1708 }
1709 }
1710 }
1711 }
1712
1713 fn release_dropped_focus_handles(&mut self) {
1715 self.focus_handles
1716 .clone()
1717 .write()
1718 .retain(|handle_id, focus| {
1719 if focus.ref_count.load(SeqCst) == 0 {
1720 for window_handle in self.windows() {
1721 window_handle
1722 .update(self, |_, window, _| {
1723 if window.focus == Some(handle_id) {
1724 window.blur();
1725 }
1726 })
1727 .unwrap();
1728 }
1729 false
1730 } else {
1731 true
1732 }
1733 });
1734 }
1735
1736 fn apply_notify_effect(&mut self, emitter: EntityId) {
1737 self.pending_notifications.remove(&emitter);
1738
1739 self.observers
1740 .clone()
1741 .retain(&emitter, |handler| handler(self));
1742 }
1743
1744 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1745 self.event_listeners
1746 .clone()
1747 .retain(&emitter, |(stored_type, handler)| {
1748 if *stored_type == event_type {
1749 handler(event, self)
1750 } else {
1751 true
1752 }
1753 });
1754 }
1755
1756 fn apply_refresh_effect(&mut self) {
1757 for window in self.windows.values_mut() {
1758 if let Some(window) = window.as_deref_mut() {
1759 window.refreshing = true;
1760 window.invalidator.set_dirty(true);
1761 }
1762 }
1763 }
1764
1765 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1766 self.pending_global_notifications.remove(&type_id);
1767 self.global_observers
1768 .clone()
1769 .retain(&type_id, |observer| observer(self));
1770 }
1771
1772 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1773 callback(self);
1774 }
1775
1776 fn apply_entity_created_effect(
1777 &mut self,
1778 entity: AnyEntity,
1779 tid: TypeId,
1780 window: Option<WindowId>,
1781 ) {
1782 if let Some(id) = window {
1786 self.current_window_by_entity.insert(entity.entity_id(), id);
1787 }
1788
1789 self.new_entity_observers.clone().retain(&tid, |observer| {
1790 if let Some(id) = window {
1791 self.update_window_id(id, {
1792 let entity = entity.clone();
1793 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1794 })
1795 .expect("All windows should be off the stack when flushing effects");
1796 } else {
1797 (observer)(entity.clone(), &mut None, self)
1798 }
1799 true
1800 });
1801 }
1802
1803 pub fn with_window<R>(
1809 &mut self,
1810 entity_id: EntityId,
1811 f: impl FnOnce(&mut Window, &mut App) -> R,
1812 ) -> Option<R> {
1813 let window_id = *self.current_window_by_entity.get(&entity_id)?;
1814 self.update_window_id(window_id, |_, window, cx| f(window, cx))
1815 .ok()
1816 }
1817
1818 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1819 self.current_window_by_entity
1820 .entry(entity_id)
1821 .or_insert(window);
1822 }
1823
1824 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1825 where
1826 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1827 {
1828 self.update(|cx| {
1829 let mut window = cx.windows.get_mut(id)?.take()?;
1830
1831 let root_view = window.root.clone().unwrap();
1832
1833 cx.window_update_stack.push(window.handle.id);
1834 let result = update(root_view, &mut window, cx);
1835 fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1836 cx.window_update_stack.pop();
1837
1838 if window.removed {
1839 cx.end_platform_drag(id);
1840 cx.window_handles.remove(&id);
1841 cx.windows.remove(id);
1842 if let Some(tracked) = cx.tracked_entities.remove(&id) {
1843 for entity_id in tracked {
1844 if let Some(windows) =
1845 cx.window_invalidators_by_entity.get_mut(&entity_id)
1846 {
1847 windows.remove(&id);
1848 }
1849 if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1850 cx.current_window_by_entity.remove(&entity_id);
1851 }
1852 }
1853 }
1854
1855 cx.window_closed_observers.clone().retain(&(), |callback| {
1856 callback(cx, id);
1857 true
1858 });
1859
1860 let quit_on_empty = match cx.quit_mode {
1861 QuitMode::Explicit => false,
1862 QuitMode::LastWindowClosed => true,
1863 QuitMode::Default => cfg!(not(target_os = "macos")),
1864 };
1865
1866 if quit_on_empty && cx.windows.is_empty() {
1867 cx.quit();
1868 }
1869 } else {
1870 cx.windows.get_mut(id)?.replace(window);
1871 }
1872 Some(())
1873 }
1874 trail(id, window, cx)?;
1875
1876 Some(result)
1877 })
1878 .context("window not found")
1879 }
1880
1881 pub fn to_async(&self) -> AsyncApp {
1884 AsyncApp {
1885 app: self.this.clone(),
1886 background_executor: self.background_executor.clone(),
1887 foreground_executor: self.foreground_executor.clone(),
1888 }
1889 }
1890
1891 pub fn background_executor(&self) -> &BackgroundExecutor {
1893 &self.background_executor
1894 }
1895
1896 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1898 if self.quitting {
1899 panic!("Can't spawn on main thread after on_app_quit")
1900 };
1901 &self.foreground_executor
1902 }
1903
1904 #[track_caller]
1907 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1908 where
1909 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1910 R: 'static,
1911 {
1912 if self.quitting {
1913 debug_panic!("Can't spawn on main thread after on_app_quit")
1914 };
1915
1916 let mut cx = self.to_async();
1917
1918 self.foreground_executor
1919 .spawn(async move { f(&mut cx).await }.boxed_local())
1920 }
1921
1922 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1926 where
1927 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1928 R: 'static,
1929 {
1930 if self.quitting {
1931 debug_panic!("Can't spawn on main thread after on_app_quit")
1932 };
1933
1934 let mut cx = self.to_async();
1935
1936 self.foreground_executor
1937 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
1938 }
1939
1940 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1943 self.push_effect(Effect::Defer {
1944 callback: Box::new(f),
1945 });
1946 }
1947
1948 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1950 &self.asset_source
1951 }
1952
1953 pub fn text_system(&self) -> &Arc<TextSystem> {
1955 &self.text_system
1956 }
1957
1958 pub fn has_global<G: Global>(&self) -> bool {
1960 self.globals_by_type.contains_key(&TypeId::of::<G>())
1961 }
1962
1963 #[track_caller]
1965 pub fn global<G: Global>(&self) -> &G {
1966 self.globals_by_type
1967 .get(&TypeId::of::<G>())
1968 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1969 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1970 }
1971
1972 pub fn try_global<G: Global>(&self) -> Option<&G> {
1974 self.globals_by_type
1975 .get(&TypeId::of::<G>())
1976 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1977 }
1978
1979 #[track_caller]
1981 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1982 let global_type = TypeId::of::<G>();
1983 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1984 self.globals_by_type
1985 .get_mut(&global_type)
1986 .and_then(|any_state| any_state.downcast_mut::<G>())
1987 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1988 }
1989
1990 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1993 let global_type = TypeId::of::<G>();
1994 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1995 self.globals_by_type
1996 .entry(global_type)
1997 .or_insert_with(|| Box::<G>::default())
1998 .downcast_mut::<G>()
1999 .unwrap()
2000 }
2001
2002 pub fn set_global<G: Global>(&mut self, global: G) {
2004 let global_type = TypeId::of::<G>();
2005 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2006 self.globals_by_type.insert(global_type, Box::new(global));
2007 }
2008
2009 #[cfg(any(test, feature = "test-support"))]
2011 pub fn clear_globals(&mut self) {
2012 self.globals_by_type.drain();
2013 }
2014
2015 pub fn remove_global<G: Global>(&mut self) -> G {
2017 let global_type = TypeId::of::<G>();
2018 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2019 *self
2020 .globals_by_type
2021 .remove(&global_type)
2022 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2023 .downcast()
2024 .unwrap()
2025 }
2026
2027 pub fn observe_global<G: Global>(
2029 &mut self,
2030 mut f: impl FnMut(&mut Self) + 'static,
2031 ) -> Subscription {
2032 let (subscription, activate) = self.global_observers.insert(
2033 TypeId::of::<G>(),
2034 Box::new(move |cx| {
2035 f(cx);
2036 true
2037 }),
2038 );
2039 self.defer(move |_| activate());
2040 subscription
2041 }
2042
2043 #[track_caller]
2045 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2046 GlobalLease::new(
2047 self.globals_by_type
2048 .remove(&TypeId::of::<G>())
2049 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2050 .unwrap(),
2051 )
2052 }
2053
2054 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2056 let global_type = TypeId::of::<G>();
2057
2058 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2059 self.globals_by_type.insert(global_type, lease.global);
2060 }
2061
2062 pub(crate) fn new_entity_observer(
2063 &self,
2064 key: TypeId,
2065 value: NewEntityListener,
2066 ) -> Subscription {
2067 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2068 activate();
2069 subscription
2070 }
2071
2072 pub fn observe_new<T: 'static>(
2075 &self,
2076 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2077 ) -> Subscription {
2078 self.new_entity_observer(
2079 TypeId::of::<T>(),
2080 Box::new(
2081 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2082 any_entity
2083 .downcast::<T>()
2084 .unwrap()
2085 .update(cx, |entity_state, cx| {
2086 on_new(entity_state, window.as_deref_mut(), cx)
2087 })
2088 },
2089 ),
2090 )
2091 }
2092
2093 pub fn observe_release<T>(
2096 &self,
2097 handle: &Entity<T>,
2098 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2099 ) -> Subscription
2100 where
2101 T: 'static,
2102 {
2103 let (subscription, activate) = self.release_listeners.insert(
2104 handle.entity_id(),
2105 Box::new(move |entity, cx| {
2106 let entity = entity.downcast_mut().expect("invalid entity type");
2107 on_release(entity, cx)
2108 }),
2109 );
2110 activate();
2111 subscription
2112 }
2113
2114 pub fn observe_release_in<T>(
2117 &self,
2118 handle: &Entity<T>,
2119 window: &Window,
2120 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2121 ) -> Subscription
2122 where
2123 T: 'static,
2124 {
2125 let window_handle = window.handle;
2126 self.observe_release(handle, move |entity, cx| {
2127 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2128 })
2129 }
2130
2131 pub fn observe_keystrokes(
2135 &mut self,
2136 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2137 ) -> Subscription {
2138 fn inner(
2139 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2140 handler: KeystrokeObserver,
2141 ) -> Subscription {
2142 let (subscription, activate) = keystroke_observers.insert((), handler);
2143 activate();
2144 subscription
2145 }
2146
2147 inner(
2148 &self.keystroke_observers,
2149 Box::new(move |event, window, cx| {
2150 f(event, window, cx);
2151 true
2152 }),
2153 )
2154 }
2155
2156 pub fn intercept_keystrokes(
2161 &mut self,
2162 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2163 ) -> Subscription {
2164 fn inner(
2165 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2166 handler: KeystrokeObserver,
2167 ) -> Subscription {
2168 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2169 activate();
2170 subscription
2171 }
2172
2173 inner(
2174 &self.keystroke_interceptors,
2175 Box::new(move |event, window, cx| {
2176 f(event, window, cx);
2177 true
2178 }),
2179 )
2180 }
2181
2182 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2184 self.keymap.borrow_mut().add_bindings(bindings);
2185 self.pending_effects.push_back(Effect::RefreshWindows);
2186 }
2187
2188 pub fn clear_key_bindings(&mut self) {
2190 self.keymap.borrow_mut().clear();
2191 self.pending_effects.push_back(Effect::RefreshWindows);
2192 }
2193
2194 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2196 self.keymap.clone()
2197 }
2198
2199 pub fn on_action<A: Action>(
2203 &mut self,
2204 listener: impl Fn(&A, &mut Self) + 'static,
2205 ) -> &mut Self {
2206 self.global_action_listeners
2207 .entry(TypeId::of::<A>())
2208 .or_default()
2209 .push(Rc::new(move |action, phase, cx| {
2210 if phase == DispatchPhase::Bubble {
2211 let action = action.downcast_ref().unwrap();
2212 listener(action, cx)
2213 }
2214 }));
2215 self
2216 }
2217
2218 pub fn stop_propagation(&mut self) {
2223 self.propagate_event = false;
2224 }
2225
2226 pub fn propagate(&mut self) {
2231 self.propagate_event = true;
2232 }
2233
2234 pub fn build_action(
2236 &self,
2237 name: &str,
2238 data: Option<serde_json::Value>,
2239 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2240 self.actions.build_action(name, data)
2241 }
2242
2243 pub fn all_action_names(&self) -> &[&'static str] {
2246 self.actions.all_action_names()
2247 }
2248
2249 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2253 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2254 }
2255
2256 pub fn action_schemas(
2258 &self,
2259 generator: &mut schemars::SchemaGenerator,
2260 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2261 self.actions.action_schemas(generator)
2262 }
2263
2264 pub fn action_schema_by_name(
2269 &self,
2270 name: &str,
2271 generator: &mut schemars::SchemaGenerator,
2272 ) -> Option<Option<schemars::Schema>> {
2273 self.actions.action_schema_by_name(name, generator)
2274 }
2275
2276 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2278 self.actions.deprecated_aliases()
2279 }
2280
2281 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2283 self.actions.deprecation_messages()
2284 }
2285
2286 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2288 self.actions.documentation()
2289 }
2290
2291 pub fn on_app_quit<Fut>(
2294 &self,
2295 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2296 ) -> Subscription
2297 where
2298 Fut: 'static + Future<Output = ()>,
2299 {
2300 let (subscription, activate) = self.quit_observers.insert(
2301 (),
2302 Box::new(move |cx| {
2303 let future = on_quit(cx);
2304 future.boxed_local()
2305 }),
2306 );
2307 activate();
2308 subscription
2309 }
2310
2311 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2315 let (subscription, activate) = self.restart_observers.insert(
2316 (),
2317 Box::new(move |cx| {
2318 on_restart(cx);
2319 true
2320 }),
2321 );
2322 activate();
2323 subscription
2324 }
2325
2326 pub fn on_window_closed(
2329 &self,
2330 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2331 ) -> Subscription {
2332 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2333 activate();
2334 subscription
2335 }
2336
2337 pub(crate) fn clear_pending_keystrokes(&mut self) {
2338 for window in self.windows() {
2339 window
2340 .update(self, |_, window, cx| {
2341 if window.pending_input_keystrokes().is_some() {
2342 window.clear_pending_keystrokes();
2343 window.pending_input_changed(cx);
2344 }
2345 })
2346 .ok();
2347 }
2348 }
2349
2350 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2353 let mut action_available = false;
2354 if let Some(window) = self.active_window()
2355 && let Ok(window_action_available) =
2356 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2357 {
2358 action_available = window_action_available;
2359 }
2360
2361 action_available
2362 || self
2363 .global_action_listeners
2364 .contains_key(&action.as_any().type_id())
2365 }
2366
2367 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2369 let menus: Vec<Menu> = menus.into_iter().collect();
2370 self.platform.set_menus(menus, &self.keymap.borrow());
2371 }
2372
2373 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2375 self.platform.get_menus()
2376 }
2377
2378 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2380 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2381 }
2382
2383 pub fn perform_dock_menu_action(&self, action: usize) {
2385 self.platform.perform_dock_menu_action(action);
2386 }
2387
2388 pub fn add_recent_document(&self, path: &Path) {
2393 self.platform.add_recent_document(path);
2394 }
2395
2396 pub fn update_jump_list(
2399 &self,
2400 menus: Vec<MenuItem>,
2401 entries: Vec<SmallVec<[PathBuf; 2]>>,
2402 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2403 self.platform.update_jump_list(menus, entries)
2404 }
2405
2406 pub fn dispatch_action(&mut self, action: &dyn Action) {
2409 if let Some(active_window) = self.active_window() {
2410 active_window
2411 .update(self, |_, window, cx| {
2412 window.dispatch_action(action.boxed_clone(), cx)
2413 })
2414 .log_err();
2415 } else {
2416 self.dispatch_global_action(action);
2417 }
2418 }
2419
2420 fn dispatch_global_action(&mut self, action: &dyn Action) {
2421 self.propagate_event = true;
2422
2423 if let Some(mut global_listeners) = self
2424 .global_action_listeners
2425 .remove(&action.as_any().type_id())
2426 {
2427 for listener in &global_listeners {
2428 listener(action.as_any(), DispatchPhase::Capture, self);
2429 if !self.propagate_event {
2430 break;
2431 }
2432 }
2433
2434 global_listeners.extend(
2435 self.global_action_listeners
2436 .remove(&action.as_any().type_id())
2437 .unwrap_or_default(),
2438 );
2439
2440 self.global_action_listeners
2441 .insert(action.as_any().type_id(), global_listeners);
2442 }
2443
2444 if self.propagate_event
2445 && let Some(mut global_listeners) = self
2446 .global_action_listeners
2447 .remove(&action.as_any().type_id())
2448 {
2449 for listener in global_listeners.iter().rev() {
2450 listener(action.as_any(), DispatchPhase::Bubble, self);
2451 if !self.propagate_event {
2452 break;
2453 }
2454 }
2455
2456 global_listeners.extend(
2457 self.global_action_listeners
2458 .remove(&action.as_any().type_id())
2459 .unwrap_or_default(),
2460 );
2461
2462 self.global_action_listeners
2463 .insert(action.as_any().type_id(), global_listeners);
2464 }
2465 }
2466
2467 pub fn has_active_drag(&self) -> bool {
2469 self.active_drag.is_some()
2470 }
2471
2472 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2474 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2475 }
2476
2477 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2479 if self.active_drag.is_some() {
2480 self.active_drag = None;
2481 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2482 drag.source_window == window.window_handle().window_id()
2483 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2484 }) {
2485 self.platform_owned_drag = None;
2486 }
2487 window.refresh();
2488 true
2489 } else {
2490 false
2491 }
2492 }
2493
2494 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2495 let Some(drag) = self.active_drag.take() else {
2496 return false;
2497 };
2498 self.platform_owned_drag = Some(PlatformOwnedDrag {
2499 source_window,
2500 state: PlatformOwnedDragState::Suspended(drag),
2501 });
2502 true
2503 }
2504
2505 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2506 let Some(platform_drag) = self
2507 .platform_owned_drag
2508 .as_mut()
2509 .filter(|drag| drag.source_window == source_window)
2510 else {
2511 return false;
2512 };
2513 let state = std::mem::replace(
2514 &mut platform_drag.state,
2515 PlatformOwnedDragState::RestoredInSourceWindow,
2516 );
2517 let PlatformOwnedDragState::Suspended(drag) = state else {
2518 return false;
2519 };
2520 self.active_drag = Some(drag);
2521 true
2522 }
2523
2524 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2525 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2526 drag.source_window == source_window
2527 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2528 }) else {
2529 return false;
2530 };
2531 let Some(drag) = self.active_drag.take() else {
2532 return false;
2533 };
2534 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2535 true
2536 }
2537
2538 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2539 if !self
2540 .platform_owned_drag
2541 .as_ref()
2542 .is_some_and(|drag| drag.source_window == source_window)
2543 {
2544 return false;
2545 }
2546 self.platform_owned_drag = None;
2547 self.active_drag = None;
2548 true
2549 }
2550
2551 pub fn set_active_drag_cursor_style(
2553 &mut self,
2554 cursor_style: CursorStyle,
2555 window: &mut Window,
2556 ) -> bool {
2557 if let Some(ref mut drag) = self.active_drag {
2558 drag.cursor_style = Some(cursor_style);
2559 window.refresh();
2560 true
2561 } else {
2562 false
2563 }
2564 }
2565
2566 pub fn set_prompt_builder(
2569 &mut self,
2570 renderer: impl Fn(
2571 PromptLevel,
2572 &str,
2573 Option<&str>,
2574 &[PromptButton],
2575 PromptHandle,
2576 &mut Window,
2577 &mut App,
2578 ) -> RenderablePromptHandle
2579 + 'static,
2580 ) {
2581 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2582 }
2583
2584 pub fn reset_prompt_builder(&mut self) {
2586 self.prompt_builder = Some(PromptBuilder::Default);
2587 }
2588
2589 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2591 let asset_id = (TypeId::of::<A>(), hash(source));
2592 self.loading_assets.remove(&asset_id);
2593 }
2594
2595 #[cfg(any(test, feature = "test-support"))]
2598 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
2599 let asset_id = (TypeId::of::<A>(), hash(source));
2600 self.loading_assets.contains_key(&asset_id)
2601 }
2602
2603 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2608 let asset_id = (TypeId::of::<A>(), hash(source));
2609 let mut is_first = false;
2610 let task = self
2611 .loading_assets
2612 .remove(&asset_id)
2613 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2614 .unwrap_or_else(|| {
2615 is_first = true;
2616 let future = A::load(source.clone(), self);
2617
2618 self.background_executor().spawn(future).shared()
2619 });
2620
2621 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2622
2623 (task, is_first)
2624 }
2625
2626 #[track_caller]
2629 pub fn focus_handle(&self) -> FocusHandle {
2630 FocusHandle::new(&self.focus_handles)
2631 }
2632
2633 pub fn notify(&mut self, entity_id: EntityId) {
2635 let window_invalidators = mem::take(
2636 self.window_invalidators_by_entity
2637 .entry(entity_id)
2638 .or_default(),
2639 );
2640
2641 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2646 .iter()
2647 .filter(|(window_id, _)| {
2648 self.tracked_entities
2649 .get(window_id)
2650 .is_some_and(|set| set.contains(&entity_id))
2651 })
2652 .map(|(_, invalidator)| invalidator.clone())
2653 .collect();
2654
2655 if live_invalidators.is_empty() {
2656 if self.pending_notifications.insert(entity_id) {
2657 self.pending_effects
2658 .push_back(Effect::Notify { emitter: entity_id });
2659 }
2660 } else {
2661 for invalidator in &live_invalidators {
2662 invalidator.invalidate_view(entity_id, self);
2663 }
2664 }
2665
2666 self.window_invalidators_by_entity
2667 .insert(entity_id, window_invalidators);
2668 }
2669
2670 #[cfg(any(test, feature = "test-support", debug_assertions))]
2672 pub fn get_name(&self) -> Option<&'static str> {
2673 self.name
2674 }
2675
2676 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2678 self.platform.can_select_mixed_files_and_dirs()
2679 }
2680
2681 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2686 for window in self.windows.values_mut().flatten() {
2688 _ = window.drop_image(image.clone());
2689 }
2690
2691 if let Some(window) = current_window {
2693 _ = window.drop_image(image);
2694 }
2695 }
2696
2697 #[cfg(any(feature = "inspector", debug_assertions))]
2699 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2700 self.inspector_renderer = Some(f);
2701 }
2702
2703 #[cfg(any(feature = "inspector", debug_assertions))]
2705 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2706 &mut self,
2707 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2708 ) {
2709 self.inspector_element_registry.register(f);
2710 }
2711
2712 pub fn init_colors(&mut self) {
2716 self.set_global(GlobalColors(Arc::new(Colors::default())));
2717 }
2718}
2719
2720impl AppContext for App {
2721 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2726 self.update(|cx| {
2727 let slot = cx.entities.reserve();
2728 let handle = slot.clone();
2729 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2730
2731 cx.push_effect(Effect::EntityCreated {
2732 entity: handle.into_any(),
2733 tid: TypeId::of::<T>(),
2734 window: cx.window_update_stack.last().cloned(),
2735 });
2736
2737 cx.entities.insert(slot, entity)
2738 })
2739 }
2740
2741 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
2742 Reservation(self.entities.reserve())
2743 }
2744
2745 fn insert_entity<T: 'static>(
2746 &mut self,
2747 reservation: Reservation<T>,
2748 build_entity: impl FnOnce(&mut Context<T>) -> T,
2749 ) -> Entity<T> {
2750 self.update(|cx| {
2751 let slot = reservation.0;
2752 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2753 cx.entities.insert(slot, entity)
2754 })
2755 }
2756
2757 fn update_entity<T: 'static, R>(
2760 &mut self,
2761 handle: &Entity<T>,
2762 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2763 ) -> R {
2764 self.update(|cx| {
2765 let mut entity = cx.entities.lease(handle);
2766 let result = update(
2767 &mut entity,
2768 &mut Context::new_context(cx, handle.downgrade()),
2769 );
2770 cx.entities.end_lease(entity);
2771 result
2772 })
2773 }
2774
2775 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2776 where
2777 T: 'static,
2778 {
2779 GpuiBorrow::new(handle.clone(), self)
2780 }
2781
2782 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
2783 where
2784 T: 'static,
2785 {
2786 let entity = self.entities.read(handle);
2787 read(entity, self)
2788 }
2789
2790 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2791 where
2792 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2793 {
2794 self.update_window_id(handle.id, update)
2795 }
2796
2797 fn with_window<R>(
2798 &mut self,
2799 entity_id: EntityId,
2800 f: impl FnOnce(&mut Window, &mut App) -> R,
2801 ) -> Option<R> {
2802 App::with_window(self, entity_id, f)
2803 }
2804
2805 fn read_window<T, R>(
2806 &self,
2807 window: &WindowHandle<T>,
2808 read: impl FnOnce(Entity<T>, &App) -> R,
2809 ) -> Result<R>
2810 where
2811 T: 'static,
2812 {
2813 let window = self
2814 .windows
2815 .get(window.id)
2816 .context("window not found")?
2817 .as_deref()
2818 .expect("attempted to read a window that is already on the stack");
2819
2820 let root_view = window.root.clone().unwrap();
2821 let view = root_view
2822 .downcast::<T>()
2823 .map_err(|_| anyhow!("root view's type has changed"))?;
2824
2825 Ok(read(view, self))
2826 }
2827
2828 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2829 where
2830 R: Send + 'static,
2831 {
2832 self.background_executor.spawn(future)
2833 }
2834
2835 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
2836 where
2837 G: Global,
2838 {
2839 let mut g = self.global::<G>();
2840 callback(g, self)
2841 }
2842}
2843
2844pub(crate) enum Effect {
2846 Notify {
2847 emitter: EntityId,
2848 },
2849 Emit {
2850 emitter: EntityId,
2851 event_type: TypeId,
2852 event: ArenaBox<dyn Any>,
2853 },
2854 RefreshWindows,
2855 NotifyGlobalObservers {
2856 global_type: TypeId,
2857 },
2858 Defer {
2859 callback: Box<dyn FnOnce(&mut App) + 'static>,
2860 },
2861 EntityCreated {
2862 entity: AnyEntity,
2863 tid: TypeId,
2864 window: Option<WindowId>,
2865 },
2866}
2867
2868impl std::fmt::Debug for Effect {
2869 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2870 match self {
2871 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2872 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2873 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2874 Effect::NotifyGlobalObservers { global_type } => {
2875 write!(f, "NotifyGlobalObservers({:?})", global_type)
2876 }
2877 Effect::Defer { .. } => write!(f, "Defer(..)"),
2878 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2879 }
2880 }
2881}
2882
2883pub(crate) struct GlobalLease<G: Global> {
2885 global: Box<dyn Any>,
2886 global_type: PhantomData<G>,
2887}
2888
2889impl<G: Global> GlobalLease<G> {
2890 fn new(global: Box<dyn Any>) -> Self {
2891 GlobalLease {
2892 global,
2893 global_type: PhantomData,
2894 }
2895 }
2896}
2897
2898impl<G: Global> Deref for GlobalLease<G> {
2899 type Target = G;
2900
2901 fn deref(&self) -> &Self::Target {
2902 self.global.downcast_ref().unwrap()
2903 }
2904}
2905
2906impl<G: Global> DerefMut for GlobalLease<G> {
2907 fn deref_mut(&mut self) -> &mut Self::Target {
2908 self.global.downcast_mut().unwrap()
2909 }
2910}
2911
2912pub struct AnyDrag {
2915 pub view: AnyView,
2917
2918 pub value: Arc<dyn Any>,
2920
2921 pub cursor_offset: Point<Pixels>,
2924
2925 pub cursor_style: Option<CursorStyle>,
2927
2928 pub external_payload_source: Option<ExternalDragPayloadSource>,
2931}
2932
2933pub type ExternalDragPayloadSource =
2936 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
2937
2938#[derive(Clone)]
2941pub struct AnyTooltip {
2942 pub view: AnyView,
2944
2945 pub mouse_position: Point<Pixels>,
2947
2948 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2952}
2953
2954#[derive(Debug)]
2956pub struct KeystrokeEvent {
2957 pub keystroke: Keystroke,
2959
2960 pub action: Option<Box<dyn Action>>,
2962
2963 pub context_stack: Vec<KeyContext>,
2965}
2966
2967struct NullHttpClient;
2968
2969impl HttpClient for NullHttpClient {
2970 fn send(
2971 &self,
2972 _req: http_client::Request<http_client::AsyncBody>,
2973 ) -> futures::future::BoxFuture<
2974 'static,
2975 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2976 > {
2977 async move {
2978 anyhow::bail!("No HttpClient available");
2979 }
2980 .boxed()
2981 }
2982
2983 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2984 None
2985 }
2986
2987 fn proxy(&self) -> Option<&Url> {
2988 None
2989 }
2990}
2991
2992pub struct GpuiBorrow<'a, T> {
2994 inner: Option<Lease<T>>,
2995 app: &'a mut App,
2996}
2997
2998impl<'a, T: 'static> GpuiBorrow<'a, T> {
2999 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3000 app.start_update();
3001 let lease = app.entities.lease(&inner);
3002 Self {
3003 inner: Some(lease),
3004 app,
3005 }
3006 }
3007}
3008
3009impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3010 fn borrow(&self) -> &T {
3011 self.inner.as_ref().unwrap().borrow()
3012 }
3013}
3014
3015impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3016 fn borrow_mut(&mut self) -> &mut T {
3017 self.inner.as_mut().unwrap().borrow_mut()
3018 }
3019}
3020
3021impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3022 type Target = T;
3023
3024 fn deref(&self) -> &Self::Target {
3025 self.inner.as_ref().unwrap()
3026 }
3027}
3028
3029impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3030 fn deref_mut(&mut self) -> &mut T {
3031 self.inner.as_mut().unwrap()
3032 }
3033}
3034
3035impl<'a, T> Drop for GpuiBorrow<'a, T> {
3036 fn drop(&mut self) {
3037 let lease = self.inner.take().unwrap();
3038 self.app.notify(lease.id);
3039 self.app.entities.end_lease(lease);
3040 self.app.finish_update();
3041 }
3042}
3043
3044#[cfg(test)]
3045mod test {
3046 use std::{cell::RefCell, rc::Rc};
3047
3048 use crate::{AppContext, TestAppContext};
3049
3050 #[test]
3051 fn test_gpui_borrow() {
3052 let cx = TestAppContext::single();
3053 let observation_count = Rc::new(RefCell::new(0));
3054
3055 let state = cx.update(|cx| {
3056 let state = cx.new(|_| false);
3057 cx.observe(&state, {
3058 let observation_count = observation_count.clone();
3059 move |_, _| {
3060 let mut count = observation_count.borrow_mut();
3061 *count += 1;
3062 }
3063 })
3064 .detach();
3065
3066 state
3067 });
3068
3069 cx.update(|cx| {
3070 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3072 });
3073
3074 cx.update(|cx| {
3075 state.write(cx, false);
3076 });
3077
3078 assert_eq!(*observation_count.borrow(), 2);
3079 }
3080}