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: Rc<RefCell<Arena>>,
734 pub(crate) event_arena: Arena,
736
737 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
742
743 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
745 asset_source: Arc<dyn AssetSource>,
746 pub(crate) svg_renderer: SvgRenderer,
747 http_client: Arc<dyn HttpClient>,
748
749 pub(crate) pending_notifications: FxHashSet<EntityId>,
751 pub(crate) pending_global_notifications: TypeIdHashSet,
752 pub(crate) restart_path: Option<PathBuf>,
753 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
755 pub(crate) prompt_builder: Option<PromptBuilder>,
756 pub(crate) window_invalidators_by_entity:
757 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
758 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
759 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
760 #[cfg(any(feature = "inspector", debug_assertions))]
761 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
762 #[cfg(any(feature = "inspector", debug_assertions))]
763 pub(crate) inspector_element_registry: InspectorElementRegistry,
764 #[cfg(any(test, feature = "test-support", debug_assertions))]
765 pub(crate) name: Option<&'static str>,
766 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
767
768 pub(crate) window_update_stack: Vec<WindowId>,
769 pub(crate) mode: GpuiMode,
770 pub(crate) cursor_hide_mode: CursorHideMode,
771 pub(crate) reduce_motion: bool,
772 pub(crate) accessibility_force_disabled: bool,
775 flushing_effects: bool,
776 pending_updates: usize,
777 quit_mode: QuitMode,
778 quitting: bool,
779
780 #[cfg(any(test, feature = "leak-detection"))]
783 _ref_counts: Arc<RwLock<EntityRefCounts>>,
784}
785
786impl App {
787 #[allow(clippy::new_ret_no_self)]
788 pub(crate) fn new_app(
789 platform: Rc<dyn Platform>,
790 asset_source: Arc<dyn AssetSource>,
791 http_client: Arc<dyn HttpClient>,
792 ) -> Rc<AppCell> {
793 let background_executor = platform.background_executor();
794 let foreground_executor = platform.foreground_executor();
795 assert!(
796 background_executor.is_main_thread(),
797 "must construct App on main thread"
798 );
799
800 let text_system = Arc::new(TextSystem::new(platform.text_system()));
801 let entities = EntityMap::new();
802 let keyboard_layout = platform.keyboard_layout();
803 let keyboard_mapper = platform.keyboard_mapper();
804
805 #[cfg(any(test, feature = "leak-detection"))]
806 let _ref_counts = entities.ref_counts_drop_handle();
807
808 let app = Rc::new_cyclic(|this| AppCell {
809 app: RefCell::new(App {
810 this: this.clone(),
811 platform: platform.clone(),
812 text_system,
813 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
814 mode: GpuiMode::Production,
815 actions: Rc::new(ActionRegistry::default()),
816 flushing_effects: false,
817 pending_updates: 0,
818 active_drag: None,
819 platform_owned_drag: None,
820 background_executor,
821 foreground_executor,
822 svg_renderer: SvgRenderer::new(asset_source.clone()),
823 loading_assets: Default::default(),
824 asset_source,
825 http_client,
826 globals_by_type: Default::default(),
827 entities,
828 new_entity_observers: SubscriberSet::new(),
829 windows: SlotMap::with_key(),
830 window_update_stack: Vec::new(),
831 window_handles: FxHashMap::default(),
832 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
833 keymap: Rc::new(RefCell::new(Keymap::default())),
834 keyboard_layout,
835 keyboard_mapper,
836 global_action_listeners: Default::default(),
837 pending_effects: VecDeque::new(),
838 pending_notifications: FxHashSet::default(),
839 pending_global_notifications: Default::default(),
840 observers: SubscriberSet::new(),
841 tracked_entities: FxHashMap::default(),
842 window_invalidators_by_entity: FxHashMap::default(),
843 current_window_by_entity: FxHashMap::default(),
844 event_listeners: SubscriberSet::new(),
845 release_listeners: SubscriberSet::new(),
846 keystroke_observers: SubscriberSet::new(),
847 keystroke_interceptors: SubscriberSet::new(),
848 keyboard_layout_observers: SubscriberSet::new(),
849 thermal_state_observers: SubscriberSet::new(),
850 global_observers: SubscriberSet::new(),
851 quit_observers: SubscriberSet::new(),
852 restart_observers: SubscriberSet::new(),
853 restart_path: None,
854 window_closed_observers: SubscriberSet::new(),
855 layout_id_buffer: Default::default(),
856 propagate_event: true,
857 prompt_builder: Some(PromptBuilder::Default),
858 #[cfg(any(feature = "inspector", debug_assertions))]
859 inspector_renderer: None,
860 #[cfg(any(feature = "inspector", debug_assertions))]
861 inspector_element_registry: InspectorElementRegistry::default(),
862 quit_mode: QuitMode::default(),
863 quitting: false,
864 cursor_hide_mode: CursorHideMode::default(),
865 reduce_motion: false,
866 accessibility_force_disabled: false,
867
868 #[cfg(any(test, feature = "test-support", debug_assertions))]
869 name: None,
870 element_arena: Rc::new(RefCell::new(Arena::new(1024 * 1024))),
871 event_arena: Arena::new(1024 * 1024),
872
873 #[cfg(any(test, feature = "leak-detection"))]
874 _ref_counts,
875 }),
876 });
877
878 init_app_menus(platform.as_ref(), &app.borrow());
879 SystemWindowTabController::init(&mut app.borrow_mut());
880
881 platform.on_keyboard_layout_change(Box::new({
882 let app = Rc::downgrade(&app);
883 move || {
884 if let Some(app) = app.upgrade() {
885 let cx = &mut app.borrow_mut();
886 cx.keyboard_layout = cx.platform.keyboard_layout();
887 cx.keyboard_mapper = cx.platform.keyboard_mapper();
888 cx.keyboard_layout_observers
889 .clone()
890 .retain(&(), move |callback| (callback)(cx));
891 }
892 }
893 }));
894
895 platform.on_thermal_state_change(Box::new({
896 let app = Rc::downgrade(&app);
897 move || {
898 if let Some(app) = app.upgrade() {
899 let cx = &mut app.borrow_mut();
900 cx.thermal_state_observers
901 .clone()
902 .retain(&(), move |callback| (callback)(cx));
903 }
904 }
905 }));
906
907 platform.on_quit(Box::new({
908 let cx = Rc::downgrade(&app);
909 move || {
910 if let Some(cx) = cx.upgrade() {
911 cx.borrow_mut().shutdown();
912 }
913 }
914 }));
915
916 app
917 }
918
919 #[doc(hidden)]
920 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
921 self.entities.ref_counts_drop_handle()
922 }
923
924 #[cfg(any(test, feature = "leak-detection"))]
930 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
931 self.entities.leak_detector_snapshot()
932 }
933
934 #[cfg(any(test, feature = "leak-detection"))]
946 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
947 self.entities.assert_no_new_leaks(snapshot)
948 }
949
950 pub fn shutdown(&mut self) {
953 let mut futures = Vec::new();
954
955 for observer in self.quit_observers.remove(&()) {
956 futures.push(observer(self));
957 }
958
959 self.windows.clear();
960 self.window_handles.clear();
961 self.flush_effects();
962 self.quitting = true;
963
964 let futures = futures::future::join_all(futures);
965 if self
966 .foreground_executor
967 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
968 .is_err()
969 {
970 log::error!("timed out waiting on app_will_quit");
971 }
972
973 self.quitting = false;
974 }
975
976 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
978 self.keyboard_layout.as_ref()
979 }
980
981 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
983 &self.keyboard_mapper
984 }
985
986 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
988 where
989 F: 'static + FnMut(&mut App),
990 {
991 let (subscription, activate) = self.keyboard_layout_observers.insert(
992 (),
993 Box::new(move |cx| {
994 callback(cx);
995 true
996 }),
997 );
998 activate();
999 subscription
1000 }
1001
1002 pub fn quit(&self) {
1004 self.platform.quit();
1005 }
1006
1007 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1010 self.cursor_hide_mode
1011 }
1012
1013 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1016 self.cursor_hide_mode = mode;
1017 }
1018
1019 pub fn is_cursor_visible(&self) -> bool {
1025 self.platform.is_cursor_visible()
1026 }
1027
1028 pub fn reduce_motion(&self) -> bool {
1031 self.reduce_motion
1032 }
1033
1034 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1037 if self.reduce_motion != reduce_motion {
1038 self.reduce_motion = reduce_motion;
1039 self.refresh_windows();
1040 }
1041 }
1042
1043 pub fn refresh_windows(&mut self) {
1046 self.pending_effects.push_back(Effect::RefreshWindows);
1047 }
1048
1049 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1050 self.start_update();
1051 let result = update(self);
1052 self.finish_update();
1053 result
1054 }
1055
1056 pub(crate) fn start_update(&mut self) {
1057 self.pending_updates += 1;
1058 }
1059
1060 pub(crate) fn finish_update(&mut self) {
1061 if !self.flushing_effects && self.pending_updates == 1 {
1062 self.flushing_effects = true;
1063 self.flush_effects();
1064 self.flushing_effects = false;
1065 }
1066 self.pending_updates -= 1;
1067 }
1068
1069 pub fn observe<W>(
1071 &mut self,
1072 entity: &Entity<W>,
1073 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1074 ) -> Subscription
1075 where
1076 W: 'static,
1077 {
1078 self.observe_internal(entity, move |e, cx| {
1079 on_notify(e, cx);
1080 true
1081 })
1082 }
1083
1084 pub(crate) fn detect_accessed_entities<R>(
1085 &mut self,
1086 callback: impl FnOnce(&mut App) -> R,
1087 ) -> (R, FxHashSet<EntityId>) {
1088 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1089 let result = callback(self);
1090 let entities_accessed_in_callback = self
1091 .entities
1092 .accessed_entities
1093 .get_mut()
1094 .difference(&accessed_entities_start)
1095 .copied()
1096 .collect::<FxHashSet<EntityId>>();
1097 (result, entities_accessed_in_callback)
1098 }
1099
1100 pub(crate) fn record_entities_accessed(
1101 &mut self,
1102 window_handle: AnyWindowHandle,
1103 invalidator: WindowInvalidator,
1104 entities: &FxHashSet<EntityId>,
1105 ) {
1106 let mut tracked_entities =
1107 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1108 for entity in tracked_entities.iter() {
1109 self.window_invalidators_by_entity
1110 .entry(*entity)
1111 .and_modify(|windows| {
1112 windows.remove(&window_handle.id);
1113 });
1114 }
1115 for entity in entities.iter() {
1116 self.window_invalidators_by_entity
1117 .entry(*entity)
1118 .or_default()
1119 .insert(window_handle.id, invalidator.clone());
1120 self.current_window_by_entity
1121 .insert(*entity, window_handle.id);
1122 }
1123 tracked_entities.clear();
1124 tracked_entities.extend(entities.iter().copied());
1125 self.tracked_entities
1126 .insert(window_handle.id, tracked_entities);
1127 }
1128
1129 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1130 let (subscription, activate) = self.observers.insert(key, value);
1131 self.defer(move |_| activate());
1132 subscription
1133 }
1134
1135 pub(crate) fn observe_internal<W>(
1136 &mut self,
1137 entity: &Entity<W>,
1138 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1139 ) -> Subscription
1140 where
1141 W: 'static,
1142 {
1143 let entity_id = entity.entity_id();
1144 let handle = entity.downgrade();
1145 self.new_observer(
1146 entity_id,
1147 Box::new(move |cx| {
1148 if let Some(entity) = handle.upgrade() {
1149 on_notify(entity, cx)
1150 } else {
1151 false
1152 }
1153 }),
1154 )
1155 }
1156
1157 pub fn subscribe<T, Event>(
1160 &mut self,
1161 entity: &Entity<T>,
1162 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1163 ) -> Subscription
1164 where
1165 T: 'static + EventEmitter<Event>,
1166 Event: 'static,
1167 {
1168 self.subscribe_internal(entity, move |entity, event, cx| {
1169 on_event(entity, event, cx);
1170 true
1171 })
1172 }
1173
1174 pub(crate) fn new_subscription(
1175 &mut self,
1176 key: EntityId,
1177 value: (TypeId, Listener),
1178 ) -> Subscription {
1179 let (subscription, activate) = self.event_listeners.insert(key, value);
1180 self.defer(move |_| activate());
1181 subscription
1182 }
1183 pub(crate) fn subscribe_internal<T, Evt>(
1184 &mut self,
1185 entity: &Entity<T>,
1186 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1187 ) -> Subscription
1188 where
1189 T: 'static + EventEmitter<Evt>,
1190 Evt: 'static,
1191 {
1192 let entity_id = entity.entity_id();
1193 let handle = entity.downgrade();
1194 self.new_subscription(
1195 entity_id,
1196 (
1197 TypeId::of::<Evt>(),
1198 Box::new(move |event, cx| {
1199 let event: &Evt = event.downcast_ref().expect("invalid event type");
1200 if let Some(entity) = handle.upgrade() {
1201 on_event(entity, event, cx)
1202 } else {
1203 false
1204 }
1205 }),
1206 ),
1207 )
1208 }
1209
1210 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1214 self.windows
1215 .keys()
1216 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1217 .collect()
1218 }
1219
1220 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1226 self.platform.window_stack()
1227 }
1228
1229 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1231 self.platform.active_window()
1232 }
1233
1234 pub fn open_window<V: 'static + Render>(
1238 &mut self,
1239 options: crate::WindowOptions,
1240 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1241 ) -> anyhow::Result<WindowHandle<V>> {
1242 self.update(|cx| {
1243 let id = cx.windows.insert(None);
1244 let handle = WindowHandle::new(id);
1245 match Window::new(handle.into(), options, cx) {
1246 Ok(mut window) => {
1247 cx.window_update_stack.push(id);
1248 let root_view = build_root_view(&mut window, cx);
1249 cx.window_update_stack.pop();
1250 window.root.replace(root_view.into());
1251 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1252
1253 let clear = window.draw(cx);
1258 clear.clear(cx);
1259
1260 cx.window_handles.insert(id, window.handle);
1261 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1262 Ok(handle)
1263 }
1264 Err(e) => {
1265 cx.windows.remove(id);
1266 Err(e)
1267 }
1268 }
1269 })
1270 }
1271
1272 pub fn activate(&self, ignoring_other_apps: bool) {
1274 self.platform.activate(ignoring_other_apps);
1275 }
1276
1277 pub fn hide(&self) {
1279 self.platform.hide();
1280 }
1281
1282 pub fn hide_other_apps(&self) {
1284 self.platform.hide_other_apps();
1285 }
1286
1287 pub fn unhide_other_apps(&self) {
1289 self.platform.unhide_other_apps();
1290 }
1291
1292 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1294 self.platform.displays()
1295 }
1296
1297 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1299 self.platform.primary_display()
1300 }
1301
1302 pub fn is_screen_capture_supported(&self) -> bool {
1304 self.platform.is_screen_capture_supported()
1305 }
1306
1307 pub fn screen_capture_sources(
1309 &self,
1310 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1311 self.platform.screen_capture_sources()
1312 }
1313
1314 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1316 self.displays()
1317 .iter()
1318 .find(|display| display.id() == id)
1319 .cloned()
1320 }
1321
1322 pub fn thermal_state(&self) -> ThermalState {
1324 self.platform.thermal_state()
1325 }
1326
1327 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1329 where
1330 F: 'static + FnMut(&mut App),
1331 {
1332 let (subscription, activate) = self.thermal_state_observers.insert(
1333 (),
1334 Box::new(move |cx| {
1335 callback(cx);
1336 true
1337 }),
1338 );
1339 activate();
1340 subscription
1341 }
1342
1343 pub fn window_appearance(&self) -> WindowAppearance {
1345 self.platform.window_appearance()
1346 }
1347
1348 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1359 self.platform.set_window_appearance(appearance);
1360 }
1361
1362 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1364 self.platform.button_layout()
1365 }
1366
1367 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1369 self.platform.read_from_clipboard()
1370 }
1371
1372 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1374 self.text_rendering_mode.set(mode);
1375 }
1376
1377 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1379 self.text_rendering_mode.get()
1380 }
1381
1382 pub fn supports_file_clipboard(&self, operation: crate::FileClipboardOperation) -> bool {
1384 self.platform.supports_file_clipboard(operation)
1385 }
1386
1387 pub fn write_files_to_clipboard(
1394 &self,
1395 paths: crate::ExternalPaths,
1396 operation: crate::FileClipboardOperation,
1397 ) -> std::result::Result<(), crate::FileClipboardError> {
1398 if !self.supports_file_clipboard(operation) {
1399 return Err(crate::FileClipboardError::Unsupported);
1400 }
1401 paths.validate_for_clipboard()?;
1402 self.platform.write_files_to_clipboard(paths, operation)
1403 }
1404
1405 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1407 self.platform.write_to_clipboard(item)
1408 }
1409
1410 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1413 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1414 self.platform.read_from_primary()
1415 }
1416
1417 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1420 pub fn write_to_primary(&self, item: ClipboardItem) {
1421 self.platform.write_to_primary(item)
1422 }
1423
1424 #[cfg(target_os = "macos")]
1430 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1431 self.platform.read_from_find_pasteboard()
1432 }
1433
1434 #[cfg(target_os = "macos")]
1440 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1441 self.platform.write_to_find_pasteboard(item)
1442 }
1443
1444 pub fn write_credentials(
1446 &self,
1447 url: &str,
1448 username: &str,
1449 password: &[u8],
1450 ) -> Task<Result<()>> {
1451 self.platform.write_credentials(url, username, password)
1452 }
1453
1454 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1456 self.platform.read_credentials(url)
1457 }
1458
1459 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1461 self.platform.delete_credentials(url)
1462 }
1463
1464 pub fn open_url(&self, url: &str) {
1466 self.platform.open_url(url);
1467 }
1468
1469 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1476 self.platform.register_url_scheme(scheme)
1477 }
1478
1479 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1486 self.platform.set_app_identity(identifier, name);
1487 }
1488
1489 pub fn show_system_notification(&self, notification: SystemNotification) {
1496 self.platform.show_system_notification(notification);
1497 }
1498
1499 pub fn dismiss_system_notification(&self, tag: &str) {
1504 self.platform.dismiss_system_notification(tag);
1505 }
1506
1507 pub fn on_system_notification_response<F>(&self, mut callback: F)
1511 where
1512 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1513 {
1514 let this = self.this.clone();
1515 self.platform
1516 .on_system_notification_response(Box::new(move |response| {
1517 if let Some(app) = this.upgrade() {
1518 callback(response, &mut app.borrow_mut());
1519 }
1520 }));
1521 }
1522
1523 pub fn app_path(&self) -> Result<PathBuf> {
1527 self.platform.app_path()
1528 }
1529
1530 pub fn compositor_name(&self) -> &'static str {
1534 self.platform.compositor_name()
1535 }
1536
1537 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1539 self.platform.path_for_auxiliary_executable(name)
1540 }
1541
1542 pub fn prompt_for_paths(
1548 &self,
1549 options: PathPromptOptions,
1550 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1551 self.platform.prompt_for_paths(options)
1552 }
1553
1554 pub fn prompt_for_new_path(
1561 &self,
1562 directory: &Path,
1563 suggested_name: Option<&str>,
1564 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1565 self.platform.prompt_for_new_path(directory, suggested_name)
1566 }
1567
1568 pub fn reveal_path(&self, path: &Path) {
1570 self.platform.reveal_path(path)
1571 }
1572
1573 pub fn open_with_system(&self, path: &Path) {
1575 self.platform.open_with_system(path)
1576 }
1577
1578 pub fn should_auto_hide_scrollbars(&self) -> bool {
1580 self.platform.should_auto_hide_scrollbars()
1581 }
1582
1583 pub fn restart(&mut self) {
1585 self.restart_observers
1586 .clone()
1587 .retain(&(), |observer| observer(self));
1588 self.platform.restart(self.restart_path.take())
1589 }
1590
1591 pub fn set_restart_path(&mut self, path: PathBuf) {
1593 self.restart_path = Some(path);
1594 }
1595
1596 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1598 self.http_client.clone()
1599 }
1600
1601 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1603 self.http_client = new_client;
1604 }
1605
1606 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1609 self.quit_mode = mode;
1610 }
1611
1612 pub fn svg_renderer(&self) -> SvgRenderer {
1614 self.svg_renderer.clone()
1615 }
1616
1617 pub(crate) fn push_effect(&mut self, effect: Effect) {
1618 match &effect {
1619 Effect::Notify { emitter } => {
1620 if !self.pending_notifications.insert(*emitter) {
1621 return;
1622 }
1623 }
1624 Effect::NotifyGlobalObservers { global_type } => {
1625 if !self.pending_global_notifications.insert(*global_type) {
1626 return;
1627 }
1628 }
1629 _ => {}
1630 };
1631
1632 self.pending_effects.push_back(effect);
1633 }
1634
1635 fn flush_effects(&mut self) {
1639 loop {
1640 self.release_dropped_entities();
1641 self.release_dropped_focus_handles();
1642 if let Some(effect) = self.pending_effects.pop_front() {
1643 match effect {
1644 Effect::Notify { emitter } => {
1645 self.apply_notify_effect(emitter);
1646 }
1647
1648 Effect::Emit {
1649 emitter,
1650 event_type,
1651 event,
1652 } => self.apply_emit_effect(emitter, event_type, &*event),
1653
1654 Effect::RefreshWindows => {
1655 self.apply_refresh_effect();
1656 }
1657
1658 Effect::NotifyGlobalObservers { global_type } => {
1659 self.apply_notify_global_observers_effect(global_type);
1660 }
1661
1662 Effect::Defer { callback } => {
1663 self.apply_defer_effect(callback);
1664 }
1665 Effect::EntityCreated {
1666 entity,
1667 tid,
1668 window,
1669 } => {
1670 self.apply_entity_created_effect(entity, tid, window);
1671 }
1672 }
1673 } else {
1674 #[cfg(any(test, feature = "test-support", feature = "bench"))]
1675 for window in self
1676 .windows
1677 .values()
1678 .filter_map(|window| {
1679 let window = window.as_deref()?;
1680 window.invalidator.is_dirty().then_some(window.handle)
1681 })
1682 .collect::<Vec<_>>()
1683 {
1684 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1685 .unwrap();
1686 }
1687
1688 if self.pending_effects.is_empty() {
1689 self.event_arena.clear();
1690 break;
1691 }
1692 }
1693 }
1694 }
1695
1696 fn release_dropped_entities(&mut self) {
1700 loop {
1701 let dropped = self.entities.take_dropped();
1702 if dropped.is_empty() {
1703 break;
1704 }
1705
1706 for (entity_id, mut entity) in dropped {
1707 self.observers.remove(&entity_id);
1708 self.event_listeners.remove(&entity_id);
1709 self.window_invalidators_by_entity.remove(&entity_id);
1710 self.current_window_by_entity.remove(&entity_id);
1711 for release_callback in self.release_listeners.remove(&entity_id) {
1712 release_callback(entity.as_mut(), self);
1713 }
1714 }
1715 }
1716 }
1717
1718 fn release_dropped_focus_handles(&mut self) {
1720 self.focus_handles
1721 .clone()
1722 .write()
1723 .retain(|handle_id, focus| {
1724 if focus.ref_count.load(SeqCst) == 0 {
1725 for window_handle in self.windows() {
1726 window_handle
1727 .update(self, |_, window, _| {
1728 if window.focus == Some(handle_id) {
1729 window.blur();
1730 }
1731 })
1732 .unwrap();
1733 }
1734 false
1735 } else {
1736 true
1737 }
1738 });
1739 }
1740
1741 fn apply_notify_effect(&mut self, emitter: EntityId) {
1742 self.pending_notifications.remove(&emitter);
1743
1744 self.observers
1745 .clone()
1746 .retain(&emitter, |handler| handler(self));
1747 }
1748
1749 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1750 self.event_listeners
1751 .clone()
1752 .retain(&emitter, |(stored_type, handler)| {
1753 if *stored_type == event_type {
1754 handler(event, self)
1755 } else {
1756 true
1757 }
1758 });
1759 }
1760
1761 fn apply_refresh_effect(&mut self) {
1762 for window in self.windows.values_mut() {
1763 if let Some(window) = window.as_deref_mut() {
1764 window.refreshing = true;
1765 window.invalidator.set_dirty(true);
1766 }
1767 }
1768 }
1769
1770 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1771 self.pending_global_notifications.remove(&type_id);
1772 self.global_observers
1773 .clone()
1774 .retain(&type_id, |observer| observer(self));
1775 }
1776
1777 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1778 callback(self);
1779 }
1780
1781 fn apply_entity_created_effect(
1782 &mut self,
1783 entity: AnyEntity,
1784 tid: TypeId,
1785 window: Option<WindowId>,
1786 ) {
1787 if let Some(id) = window {
1791 self.current_window_by_entity.insert(entity.entity_id(), id);
1792 }
1793
1794 self.new_entity_observers.clone().retain(&tid, |observer| {
1795 if let Some(id) = window {
1796 self.update_window_id(id, {
1797 let entity = entity.clone();
1798 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1799 })
1800 .expect("All windows should be off the stack when flushing effects");
1801 } else {
1802 (observer)(entity.clone(), &mut None, self)
1803 }
1804 true
1805 });
1806 }
1807
1808 pub fn with_window<R>(
1814 &mut self,
1815 entity_id: EntityId,
1816 f: impl FnOnce(&mut Window, &mut App) -> R,
1817 ) -> Option<R> {
1818 let window_id = *self.current_window_by_entity.get(&entity_id)?;
1819 self.update_window_id(window_id, |_, window, cx| f(window, cx))
1820 .ok()
1821 }
1822
1823 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1824 self.current_window_by_entity
1825 .entry(entity_id)
1826 .or_insert(window);
1827 }
1828
1829 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1830 where
1831 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1832 {
1833 self.update(|cx| {
1834 let mut window = cx.windows.get_mut(id)?.take()?;
1835
1836 let root_view = window.root.clone().unwrap();
1837
1838 cx.window_update_stack.push(window.handle.id);
1839 let result = update(root_view, &mut window, cx);
1840 fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1841 cx.window_update_stack.pop();
1842
1843 if window.removed {
1844 cx.end_platform_drag(id);
1845 cx.window_handles.remove(&id);
1846 cx.windows.remove(id);
1847 if let Some(tracked) = cx.tracked_entities.remove(&id) {
1848 for entity_id in tracked {
1849 if let Some(windows) =
1850 cx.window_invalidators_by_entity.get_mut(&entity_id)
1851 {
1852 windows.remove(&id);
1853 }
1854 if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1855 cx.current_window_by_entity.remove(&entity_id);
1856 }
1857 }
1858 }
1859
1860 cx.window_closed_observers.clone().retain(&(), |callback| {
1861 callback(cx, id);
1862 true
1863 });
1864
1865 let quit_on_empty = match cx.quit_mode {
1866 QuitMode::Explicit => false,
1867 QuitMode::LastWindowClosed => true,
1868 QuitMode::Default => cfg!(not(target_os = "macos")),
1869 };
1870
1871 if quit_on_empty && cx.windows.is_empty() {
1872 cx.quit();
1873 }
1874 } else {
1875 cx.windows.get_mut(id)?.replace(window);
1876 }
1877 Some(())
1878 }
1879 trail(id, window, cx)?;
1880
1881 Some(result)
1882 })
1883 .context("window not found")
1884 }
1885
1886 pub fn to_async(&self) -> AsyncApp {
1889 AsyncApp {
1890 app: self.this.clone(),
1891 background_executor: self.background_executor.clone(),
1892 foreground_executor: self.foreground_executor.clone(),
1893 }
1894 }
1895
1896 pub fn background_executor(&self) -> &BackgroundExecutor {
1898 &self.background_executor
1899 }
1900
1901 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1903 if self.quitting {
1904 panic!("Can't spawn on main thread after on_app_quit")
1905 };
1906 &self.foreground_executor
1907 }
1908
1909 #[track_caller]
1912 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1913 where
1914 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1915 R: 'static,
1916 {
1917 if self.quitting {
1918 debug_panic!("Can't spawn on main thread after on_app_quit")
1919 };
1920
1921 let mut cx = self.to_async();
1922
1923 self.foreground_executor
1924 .spawn(async move { f(&mut cx).await }.boxed_local())
1925 }
1926
1927 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1931 where
1932 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1933 R: 'static,
1934 {
1935 if self.quitting {
1936 debug_panic!("Can't spawn on main thread after on_app_quit")
1937 };
1938
1939 let mut cx = self.to_async();
1940
1941 self.foreground_executor
1942 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
1943 }
1944
1945 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1948 self.push_effect(Effect::Defer {
1949 callback: Box::new(f),
1950 });
1951 }
1952
1953 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1955 &self.asset_source
1956 }
1957
1958 pub fn text_system(&self) -> &Arc<TextSystem> {
1960 &self.text_system
1961 }
1962
1963 pub fn has_global<G: Global>(&self) -> bool {
1965 self.globals_by_type.contains_key(&TypeId::of::<G>())
1966 }
1967
1968 #[track_caller]
1970 pub fn global<G: Global>(&self) -> &G {
1971 self.globals_by_type
1972 .get(&TypeId::of::<G>())
1973 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1974 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1975 }
1976
1977 pub fn try_global<G: Global>(&self) -> Option<&G> {
1979 self.globals_by_type
1980 .get(&TypeId::of::<G>())
1981 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1982 }
1983
1984 #[track_caller]
1986 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1987 let global_type = TypeId::of::<G>();
1988 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1989 self.globals_by_type
1990 .get_mut(&global_type)
1991 .and_then(|any_state| any_state.downcast_mut::<G>())
1992 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1993 }
1994
1995 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1998 let global_type = TypeId::of::<G>();
1999 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2000 self.globals_by_type
2001 .entry(global_type)
2002 .or_insert_with(|| Box::<G>::default())
2003 .downcast_mut::<G>()
2004 .unwrap()
2005 }
2006
2007 pub fn set_global<G: Global>(&mut self, global: G) {
2009 let global_type = TypeId::of::<G>();
2010 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2011 self.globals_by_type.insert(global_type, Box::new(global));
2012 }
2013
2014 #[cfg(any(test, feature = "test-support"))]
2016 pub fn clear_globals(&mut self) {
2017 self.globals_by_type.drain();
2018 }
2019
2020 pub fn remove_global<G: Global>(&mut self) -> G {
2022 let global_type = TypeId::of::<G>();
2023 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2024 *self
2025 .globals_by_type
2026 .remove(&global_type)
2027 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2028 .downcast()
2029 .unwrap()
2030 }
2031
2032 pub fn observe_global<G: Global>(
2034 &mut self,
2035 mut f: impl FnMut(&mut Self) + 'static,
2036 ) -> Subscription {
2037 let (subscription, activate) = self.global_observers.insert(
2038 TypeId::of::<G>(),
2039 Box::new(move |cx| {
2040 f(cx);
2041 true
2042 }),
2043 );
2044 self.defer(move |_| activate());
2045 subscription
2046 }
2047
2048 #[track_caller]
2050 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2051 GlobalLease::new(
2052 self.globals_by_type
2053 .remove(&TypeId::of::<G>())
2054 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2055 .unwrap(),
2056 )
2057 }
2058
2059 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2061 let global_type = TypeId::of::<G>();
2062
2063 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2064 self.globals_by_type.insert(global_type, lease.global);
2065 }
2066
2067 pub(crate) fn new_entity_observer(
2068 &self,
2069 key: TypeId,
2070 value: NewEntityListener,
2071 ) -> Subscription {
2072 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2073 activate();
2074 subscription
2075 }
2076
2077 pub fn observe_new<T: 'static>(
2080 &self,
2081 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2082 ) -> Subscription {
2083 self.new_entity_observer(
2084 TypeId::of::<T>(),
2085 Box::new(
2086 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2087 any_entity
2088 .downcast::<T>()
2089 .unwrap()
2090 .update(cx, |entity_state, cx| {
2091 on_new(entity_state, window.as_deref_mut(), cx)
2092 })
2093 },
2094 ),
2095 )
2096 }
2097
2098 pub fn observe_release<T>(
2101 &self,
2102 handle: &Entity<T>,
2103 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2104 ) -> Subscription
2105 where
2106 T: 'static,
2107 {
2108 let (subscription, activate) = self.release_listeners.insert(
2109 handle.entity_id(),
2110 Box::new(move |entity, cx| {
2111 let entity = entity.downcast_mut().expect("invalid entity type");
2112 on_release(entity, cx)
2113 }),
2114 );
2115 activate();
2116 subscription
2117 }
2118
2119 pub fn observe_release_in<T>(
2122 &self,
2123 handle: &Entity<T>,
2124 window: &Window,
2125 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2126 ) -> Subscription
2127 where
2128 T: 'static,
2129 {
2130 let window_handle = window.handle;
2131 self.observe_release(handle, move |entity, cx| {
2132 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2133 })
2134 }
2135
2136 pub fn observe_keystrokes(
2140 &mut self,
2141 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2142 ) -> Subscription {
2143 fn inner(
2144 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2145 handler: KeystrokeObserver,
2146 ) -> Subscription {
2147 let (subscription, activate) = keystroke_observers.insert((), handler);
2148 activate();
2149 subscription
2150 }
2151
2152 inner(
2153 &self.keystroke_observers,
2154 Box::new(move |event, window, cx| {
2155 f(event, window, cx);
2156 true
2157 }),
2158 )
2159 }
2160
2161 pub fn intercept_keystrokes(
2166 &mut self,
2167 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2168 ) -> Subscription {
2169 fn inner(
2170 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2171 handler: KeystrokeObserver,
2172 ) -> Subscription {
2173 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2174 activate();
2175 subscription
2176 }
2177
2178 inner(
2179 &self.keystroke_interceptors,
2180 Box::new(move |event, window, cx| {
2181 f(event, window, cx);
2182 true
2183 }),
2184 )
2185 }
2186
2187 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2189 self.keymap.borrow_mut().add_bindings(bindings);
2190 self.pending_effects.push_back(Effect::RefreshWindows);
2191 }
2192
2193 pub fn clear_key_bindings(&mut self) {
2195 self.keymap.borrow_mut().clear();
2196 self.pending_effects.push_back(Effect::RefreshWindows);
2197 }
2198
2199 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2201 self.keymap.clone()
2202 }
2203
2204 pub fn on_action<A: Action>(
2208 &mut self,
2209 listener: impl Fn(&A, &mut Self) + 'static,
2210 ) -> &mut Self {
2211 self.global_action_listeners
2212 .entry(TypeId::of::<A>())
2213 .or_default()
2214 .push(Rc::new(move |action, phase, cx| {
2215 if phase == DispatchPhase::Bubble {
2216 let action = action.downcast_ref().unwrap();
2217 listener(action, cx)
2218 }
2219 }));
2220 self
2221 }
2222
2223 pub fn stop_propagation(&mut self) {
2228 self.propagate_event = false;
2229 }
2230
2231 pub fn propagate(&mut self) {
2236 self.propagate_event = true;
2237 }
2238
2239 pub fn build_action(
2241 &self,
2242 name: &str,
2243 data: Option<serde_json::Value>,
2244 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2245 self.actions.build_action(name, data)
2246 }
2247
2248 pub fn all_action_names(&self) -> &[&'static str] {
2251 self.actions.all_action_names()
2252 }
2253
2254 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2258 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2259 }
2260
2261 pub fn action_schemas(
2263 &self,
2264 generator: &mut schemars::SchemaGenerator,
2265 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2266 self.actions.action_schemas(generator)
2267 }
2268
2269 pub fn action_schema_by_name(
2274 &self,
2275 name: &str,
2276 generator: &mut schemars::SchemaGenerator,
2277 ) -> Option<Option<schemars::Schema>> {
2278 self.actions.action_schema_by_name(name, generator)
2279 }
2280
2281 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2283 self.actions.deprecated_aliases()
2284 }
2285
2286 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2288 self.actions.deprecation_messages()
2289 }
2290
2291 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2293 self.actions.documentation()
2294 }
2295
2296 pub fn on_app_quit<Fut>(
2299 &self,
2300 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2301 ) -> Subscription
2302 where
2303 Fut: 'static + Future<Output = ()>,
2304 {
2305 let (subscription, activate) = self.quit_observers.insert(
2306 (),
2307 Box::new(move |cx| {
2308 let future = on_quit(cx);
2309 future.boxed_local()
2310 }),
2311 );
2312 activate();
2313 subscription
2314 }
2315
2316 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2320 let (subscription, activate) = self.restart_observers.insert(
2321 (),
2322 Box::new(move |cx| {
2323 on_restart(cx);
2324 true
2325 }),
2326 );
2327 activate();
2328 subscription
2329 }
2330
2331 pub fn on_window_closed(
2334 &self,
2335 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2336 ) -> Subscription {
2337 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2338 activate();
2339 subscription
2340 }
2341
2342 pub(crate) fn clear_pending_keystrokes(&mut self) {
2343 for window in self.windows() {
2344 window
2345 .update(self, |_, window, cx| {
2346 if window.pending_input_keystrokes().is_some() {
2347 window.clear_pending_keystrokes();
2348 window.pending_input_changed(cx);
2349 }
2350 })
2351 .ok();
2352 }
2353 }
2354
2355 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2358 let mut action_available = false;
2359 if let Some(window) = self.active_window()
2360 && let Ok(window_action_available) =
2361 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2362 {
2363 action_available = window_action_available;
2364 }
2365
2366 action_available
2367 || self
2368 .global_action_listeners
2369 .contains_key(&action.as_any().type_id())
2370 }
2371
2372 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2374 let menus: Vec<Menu> = menus.into_iter().collect();
2375 self.platform.set_menus(menus, &self.keymap.borrow());
2376 }
2377
2378 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2380 self.platform.get_menus()
2381 }
2382
2383 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2385 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2386 }
2387
2388 pub fn perform_dock_menu_action(&self, action: usize) {
2390 self.platform.perform_dock_menu_action(action);
2391 }
2392
2393 pub fn add_recent_document(&self, path: &Path) {
2398 self.platform.add_recent_document(path);
2399 }
2400
2401 pub fn update_jump_list(
2404 &self,
2405 menus: Vec<MenuItem>,
2406 entries: Vec<SmallVec<[PathBuf; 2]>>,
2407 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2408 self.platform.update_jump_list(menus, entries)
2409 }
2410
2411 pub fn dispatch_action(&mut self, action: &dyn Action) {
2414 if let Some(active_window) = self.active_window() {
2415 active_window
2416 .update(self, |_, window, cx| {
2417 window.dispatch_action(action.boxed_clone(), cx)
2418 })
2419 .log_err();
2420 } else {
2421 self.dispatch_global_action(action);
2422 }
2423 }
2424
2425 fn dispatch_global_action(&mut self, action: &dyn Action) {
2426 self.propagate_event = true;
2427
2428 if let Some(mut global_listeners) = self
2429 .global_action_listeners
2430 .remove(&action.as_any().type_id())
2431 {
2432 for listener in &global_listeners {
2433 listener(action.as_any(), DispatchPhase::Capture, self);
2434 if !self.propagate_event {
2435 break;
2436 }
2437 }
2438
2439 global_listeners.extend(
2440 self.global_action_listeners
2441 .remove(&action.as_any().type_id())
2442 .unwrap_or_default(),
2443 );
2444
2445 self.global_action_listeners
2446 .insert(action.as_any().type_id(), global_listeners);
2447 }
2448
2449 if self.propagate_event
2450 && let Some(mut global_listeners) = self
2451 .global_action_listeners
2452 .remove(&action.as_any().type_id())
2453 {
2454 for listener in global_listeners.iter().rev() {
2455 listener(action.as_any(), DispatchPhase::Bubble, self);
2456 if !self.propagate_event {
2457 break;
2458 }
2459 }
2460
2461 global_listeners.extend(
2462 self.global_action_listeners
2463 .remove(&action.as_any().type_id())
2464 .unwrap_or_default(),
2465 );
2466
2467 self.global_action_listeners
2468 .insert(action.as_any().type_id(), global_listeners);
2469 }
2470 }
2471
2472 pub fn has_active_drag(&self) -> bool {
2474 self.active_drag.is_some()
2475 }
2476
2477 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2479 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2480 }
2481
2482 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2484 if self.active_drag.is_some() {
2485 self.active_drag = None;
2486 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2487 drag.source_window == window.window_handle().window_id()
2488 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2489 }) {
2490 self.platform_owned_drag = None;
2491 }
2492 window.refresh();
2493 true
2494 } else {
2495 false
2496 }
2497 }
2498
2499 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2500 let Some(drag) = self.active_drag.take() else {
2501 return false;
2502 };
2503 self.platform_owned_drag = Some(PlatformOwnedDrag {
2504 source_window,
2505 state: PlatformOwnedDragState::Suspended(drag),
2506 });
2507 true
2508 }
2509
2510 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2511 let Some(platform_drag) = self
2512 .platform_owned_drag
2513 .as_mut()
2514 .filter(|drag| drag.source_window == source_window)
2515 else {
2516 return false;
2517 };
2518 let state = std::mem::replace(
2519 &mut platform_drag.state,
2520 PlatformOwnedDragState::RestoredInSourceWindow,
2521 );
2522 let PlatformOwnedDragState::Suspended(drag) = state else {
2523 return false;
2524 };
2525 self.active_drag = Some(drag);
2526 true
2527 }
2528
2529 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2530 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2531 drag.source_window == source_window
2532 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2533 }) else {
2534 return false;
2535 };
2536 let Some(drag) = self.active_drag.take() else {
2537 return false;
2538 };
2539 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2540 true
2541 }
2542
2543 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2544 if !self
2545 .platform_owned_drag
2546 .as_ref()
2547 .is_some_and(|drag| drag.source_window == source_window)
2548 {
2549 return false;
2550 }
2551 self.platform_owned_drag = None;
2552 self.active_drag = None;
2553 true
2554 }
2555
2556 pub fn set_active_drag_cursor_style(
2558 &mut self,
2559 cursor_style: CursorStyle,
2560 window: &mut Window,
2561 ) -> bool {
2562 if let Some(ref mut drag) = self.active_drag {
2563 drag.cursor_style = Some(cursor_style);
2564 window.refresh();
2565 true
2566 } else {
2567 false
2568 }
2569 }
2570
2571 pub fn set_prompt_builder(
2574 &mut self,
2575 renderer: impl Fn(
2576 PromptLevel,
2577 &str,
2578 Option<&str>,
2579 &[PromptButton],
2580 PromptHandle,
2581 &mut Window,
2582 &mut App,
2583 ) -> RenderablePromptHandle
2584 + 'static,
2585 ) {
2586 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2587 }
2588
2589 pub fn reset_prompt_builder(&mut self) {
2591 self.prompt_builder = Some(PromptBuilder::Default);
2592 }
2593
2594 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2596 let asset_id = (TypeId::of::<A>(), hash(source));
2597 self.loading_assets.remove(&asset_id);
2598 }
2599
2600 #[cfg(any(test, feature = "test-support"))]
2603 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
2604 let asset_id = (TypeId::of::<A>(), hash(source));
2605 self.loading_assets.contains_key(&asset_id)
2606 }
2607
2608 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2613 let asset_id = (TypeId::of::<A>(), hash(source));
2614 let mut is_first = false;
2615 let task = self
2616 .loading_assets
2617 .remove(&asset_id)
2618 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2619 .unwrap_or_else(|| {
2620 is_first = true;
2621 let future = A::load(source.clone(), self);
2622
2623 self.background_executor().spawn(future).shared()
2624 });
2625
2626 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2627
2628 (task, is_first)
2629 }
2630
2631 #[track_caller]
2634 pub fn focus_handle(&self) -> FocusHandle {
2635 FocusHandle::new(&self.focus_handles)
2636 }
2637
2638 pub fn notify(&mut self, entity_id: EntityId) {
2640 let window_invalidators = mem::take(
2641 self.window_invalidators_by_entity
2642 .entry(entity_id)
2643 .or_default(),
2644 );
2645
2646 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2651 .iter()
2652 .filter(|(window_id, _)| {
2653 self.tracked_entities
2654 .get(window_id)
2655 .is_some_and(|set| set.contains(&entity_id))
2656 })
2657 .map(|(_, invalidator)| invalidator.clone())
2658 .collect();
2659
2660 if live_invalidators.is_empty() {
2661 if self.pending_notifications.insert(entity_id) {
2662 self.pending_effects
2663 .push_back(Effect::Notify { emitter: entity_id });
2664 }
2665 } else {
2666 for invalidator in &live_invalidators {
2667 invalidator.invalidate_view(entity_id, self);
2668 }
2669 }
2670
2671 self.window_invalidators_by_entity
2672 .insert(entity_id, window_invalidators);
2673 }
2674
2675 #[cfg(any(test, feature = "test-support", debug_assertions))]
2677 pub fn get_name(&self) -> Option<&'static str> {
2678 self.name
2679 }
2680
2681 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2683 self.platform.can_select_mixed_files_and_dirs()
2684 }
2685
2686 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2691 for window in self.windows.values_mut().flatten() {
2693 _ = window.drop_image(image.clone());
2694 }
2695
2696 if let Some(window) = current_window {
2698 _ = window.drop_image(image);
2699 }
2700 }
2701
2702 #[cfg(any(feature = "inspector", debug_assertions))]
2704 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2705 self.inspector_renderer = Some(f);
2706 }
2707
2708 #[cfg(any(feature = "inspector", debug_assertions))]
2710 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2711 &mut self,
2712 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2713 ) {
2714 self.inspector_element_registry.register(f);
2715 }
2716
2717 pub fn init_colors(&mut self) {
2721 self.set_global(GlobalColors(Arc::new(Colors::default())));
2722 }
2723}
2724
2725impl AppContext for App {
2726 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2731 self.update(|cx| {
2732 let slot = cx.entities.reserve();
2733 let handle = slot.clone();
2734 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2735
2736 cx.push_effect(Effect::EntityCreated {
2737 entity: handle.into_any(),
2738 tid: TypeId::of::<T>(),
2739 window: cx.window_update_stack.last().cloned(),
2740 });
2741
2742 cx.entities.insert(slot, entity)
2743 })
2744 }
2745
2746 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
2747 Reservation(self.entities.reserve())
2748 }
2749
2750 fn insert_entity<T: 'static>(
2751 &mut self,
2752 reservation: Reservation<T>,
2753 build_entity: impl FnOnce(&mut Context<T>) -> T,
2754 ) -> Entity<T> {
2755 self.update(|cx| {
2756 let slot = reservation.0;
2757 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2758 cx.entities.insert(slot, entity)
2759 })
2760 }
2761
2762 fn update_entity<T: 'static, R>(
2765 &mut self,
2766 handle: &Entity<T>,
2767 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2768 ) -> R {
2769 self.update(|cx| {
2770 let mut entity = cx.entities.lease(handle);
2771 let result = update(
2772 &mut entity,
2773 &mut Context::new_context(cx, handle.downgrade()),
2774 );
2775 cx.entities.end_lease(entity);
2776 result
2777 })
2778 }
2779
2780 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2781 where
2782 T: 'static,
2783 {
2784 GpuiBorrow::new(handle.clone(), self)
2785 }
2786
2787 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
2788 where
2789 T: 'static,
2790 {
2791 let entity = self.entities.read(handle);
2792 read(entity, self)
2793 }
2794
2795 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2796 where
2797 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2798 {
2799 self.update_window_id(handle.id, update)
2800 }
2801
2802 fn with_window<R>(
2803 &mut self,
2804 entity_id: EntityId,
2805 f: impl FnOnce(&mut Window, &mut App) -> R,
2806 ) -> Option<R> {
2807 App::with_window(self, entity_id, f)
2808 }
2809
2810 fn read_window<T, R>(
2811 &self,
2812 window: &WindowHandle<T>,
2813 read: impl FnOnce(Entity<T>, &App) -> R,
2814 ) -> Result<R>
2815 where
2816 T: 'static,
2817 {
2818 let window = self
2819 .windows
2820 .get(window.id)
2821 .context("window not found")?
2822 .as_deref()
2823 .expect("attempted to read a window that is already on the stack");
2824
2825 let root_view = window.root.clone().unwrap();
2826 let view = root_view
2827 .downcast::<T>()
2828 .map_err(|_| anyhow!("root view's type has changed"))?;
2829
2830 Ok(read(view, self))
2831 }
2832
2833 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2834 where
2835 R: Send + 'static,
2836 {
2837 self.background_executor.spawn(future)
2838 }
2839
2840 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
2841 where
2842 G: Global,
2843 {
2844 let mut g = self.global::<G>();
2845 callback(g, self)
2846 }
2847}
2848
2849pub(crate) enum Effect {
2851 Notify {
2852 emitter: EntityId,
2853 },
2854 Emit {
2855 emitter: EntityId,
2856 event_type: TypeId,
2857 event: ArenaBox<dyn Any>,
2858 },
2859 RefreshWindows,
2860 NotifyGlobalObservers {
2861 global_type: TypeId,
2862 },
2863 Defer {
2864 callback: Box<dyn FnOnce(&mut App) + 'static>,
2865 },
2866 EntityCreated {
2867 entity: AnyEntity,
2868 tid: TypeId,
2869 window: Option<WindowId>,
2870 },
2871}
2872
2873impl std::fmt::Debug for Effect {
2874 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2875 match self {
2876 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2877 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2878 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2879 Effect::NotifyGlobalObservers { global_type } => {
2880 write!(f, "NotifyGlobalObservers({:?})", global_type)
2881 }
2882 Effect::Defer { .. } => write!(f, "Defer(..)"),
2883 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2884 }
2885 }
2886}
2887
2888pub(crate) struct GlobalLease<G: Global> {
2890 global: Box<dyn Any>,
2891 global_type: PhantomData<G>,
2892}
2893
2894impl<G: Global> GlobalLease<G> {
2895 fn new(global: Box<dyn Any>) -> Self {
2896 GlobalLease {
2897 global,
2898 global_type: PhantomData,
2899 }
2900 }
2901}
2902
2903impl<G: Global> Deref for GlobalLease<G> {
2904 type Target = G;
2905
2906 fn deref(&self) -> &Self::Target {
2907 self.global.downcast_ref().unwrap()
2908 }
2909}
2910
2911impl<G: Global> DerefMut for GlobalLease<G> {
2912 fn deref_mut(&mut self) -> &mut Self::Target {
2913 self.global.downcast_mut().unwrap()
2914 }
2915}
2916
2917pub struct AnyDrag {
2920 pub view: AnyView,
2922
2923 pub value: Arc<dyn Any>,
2925
2926 pub cursor_offset: Point<Pixels>,
2929
2930 pub cursor_style: Option<CursorStyle>,
2932
2933 pub external_payload_source: Option<ExternalDragPayloadSource>,
2936}
2937
2938pub type ExternalDragPayloadSource =
2941 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
2942
2943#[derive(Clone)]
2946pub struct AnyTooltip {
2947 pub view: AnyView,
2949
2950 pub mouse_position: Point<Pixels>,
2952
2953 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2957}
2958
2959#[derive(Debug)]
2961pub struct KeystrokeEvent {
2962 pub keystroke: Keystroke,
2964
2965 pub action: Option<Box<dyn Action>>,
2967
2968 pub context_stack: Vec<KeyContext>,
2970}
2971
2972struct NullHttpClient;
2973
2974impl HttpClient for NullHttpClient {
2975 fn send(
2976 &self,
2977 _req: http_client::Request<http_client::AsyncBody>,
2978 ) -> futures::future::BoxFuture<
2979 'static,
2980 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2981 > {
2982 async move {
2983 anyhow::bail!("No HttpClient available");
2984 }
2985 .boxed()
2986 }
2987
2988 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2989 None
2990 }
2991
2992 fn proxy(&self) -> Option<&Url> {
2993 None
2994 }
2995}
2996
2997pub struct GpuiBorrow<'a, T> {
2999 inner: Option<Lease<T>>,
3000 app: &'a mut App,
3001}
3002
3003impl<'a, T: 'static> GpuiBorrow<'a, T> {
3004 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3005 app.start_update();
3006 let lease = app.entities.lease(&inner);
3007 Self {
3008 inner: Some(lease),
3009 app,
3010 }
3011 }
3012}
3013
3014impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3015 fn borrow(&self) -> &T {
3016 self.inner.as_ref().unwrap().borrow()
3017 }
3018}
3019
3020impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3021 fn borrow_mut(&mut self) -> &mut T {
3022 self.inner.as_mut().unwrap().borrow_mut()
3023 }
3024}
3025
3026impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3027 type Target = T;
3028
3029 fn deref(&self) -> &Self::Target {
3030 self.inner.as_ref().unwrap()
3031 }
3032}
3033
3034impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3035 fn deref_mut(&mut self) -> &mut T {
3036 self.inner.as_mut().unwrap()
3037 }
3038}
3039
3040impl<'a, T> Drop for GpuiBorrow<'a, T> {
3041 fn drop(&mut self) {
3042 let lease = self.inner.take().unwrap();
3043 self.app.notify(lease.id);
3044 self.app.entities.end_lease(lease);
3045 self.app.finish_update();
3046 }
3047}
3048
3049#[cfg(test)]
3050mod test {
3051 use std::{cell::RefCell, rc::Rc};
3052
3053 use crate::{AppContext, TestAppContext};
3054
3055 #[test]
3056 fn test_gpui_borrow() {
3057 let cx = TestAppContext::single();
3058 let observation_count = Rc::new(RefCell::new(0));
3059
3060 let state = cx.update(|cx| {
3061 let state = cx.new(|_| false);
3062 cx.observe(&state, {
3063 let observation_count = observation_count.clone();
3064 move |_, _| {
3065 let mut count = observation_count.borrow_mut();
3066 *count += 1;
3067 }
3068 })
3069 .detach();
3070
3071 state
3072 });
3073
3074 cx.update(|cx| {
3075 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3077 });
3078
3079 cx.update(|cx| {
3080 state.write(cx, false);
3081 });
3082
3083 assert_eq!(*observation_count.borrow(), 2);
3084 }
3085}