1#[inline]
8#[allow(clippy::panic)] fn invariant<T>(value: Option<T>, message: &str) -> T {
10 match value {
11 Some(value) => value,
12 None => panic!("{message}"),
13 }
14}
15
16#[inline]
18#[allow(clippy::panic)] fn invariant_result<T, E>(result: Result<T, E>, message: &str) -> T {
20 match result {
21 Ok(value) => value,
22 Err(_) => panic!("{message}"),
23 }
24}
25use crate::scheduler::Instant;
26use std::{
27 any::{TypeId, type_name},
28 cell::{Cell, Ref, RefCell, RefMut},
29 marker::PhantomData,
30 mem,
31 ops::{Deref, DerefMut},
32 path::{Path, PathBuf},
33 rc::{Rc, Weak},
34 sync::{Arc, atomic::Ordering::SeqCst},
35 time::Duration,
36};
37
38use anyhow::{Context as _, Result, anyhow};
39use derive_more::{Deref, DerefMut};
40use futures::{
41 Future, FutureExt,
42 channel::oneshot,
43 future::{LocalBoxFuture, Shared},
44};
45use itertools::Itertools;
46use parking_lot::RwLock;
47use slotmap::SlotMap;
48
49use crate::collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
50use crate::debug_panic;
51use crate::http_client::{HttpClient, Url};
52use crate::rgpui_util::ResultExt;
53use crate::util::debounce::Debouncer;
54pub use async_context::*;
55#[cfg(feature = "bench")]
56pub use bench_context::{BenchAppContext, BenchReport, BenchWindowContext, bench_platform};
57pub use context::*;
58pub use entity_map::*;
59#[cfg(any(test, feature = "test-support"))]
60pub use headless_app_context::*;
61use smallvec::SmallVec;
62#[cfg(any(test, feature = "test-support"))]
63pub use test_app::*;
64#[cfg(any(test, feature = "test-support"))]
65pub use test_context::*;
66#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
67pub use visual_test_context::*;
68
69#[cfg(any(feature = "inspector", debug_assertions))]
70use crate::InspectorElementRegistry;
71use crate::{
72 Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
73 ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle,
74 DispatchPhase, DisplayId, EventEmitter, FocusHandle, FocusMap, FocusedWindowInfo,
75 ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu,
76 MenuItem, NetworkStatus, OsInfo, OwnedMenu, PathPromptOptions, PermissionStatus,
77 PermissionType, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
78 PlatformKeyboardMapper, Point, PowerSaveBlocker, PowerSaveBlockerKind, Priority, PromptBuilder,
79 PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle,
80 Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
81 SystemPowerEvent, Task, TextRenderingMode, TextSystem, ThermalState, Tray, TrayIconEvent,
82 TrayMenuItem, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
83 WindowInvalidator,
84 colors::{Colors, GlobalColors},
85 hash, init_app_menus,
86 root::Root,
87};
88
89mod async_context;
90#[cfg(feature = "bench")]
91#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
92mod bench_context;
94mod context;
95mod entity_map;
96#[cfg(any(test, feature = "test-support"))]
97#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
98mod headless_app_context;
100#[cfg(any(test, feature = "test-support"))]
101#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
102mod test_app;
104#[cfg(any(test, feature = "test-support"))]
105#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
106mod test_context;
108#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
109#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
110mod visual_test_context;
112
113pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
115
116#[doc(hidden)]
119pub struct AppCell {
120 app: RefCell<App>,
121 borrow_origin: Cell<Option<(&'static std::panic::Location<'static>, &'static str)>>,
127}
128
129pub(crate) struct AppBorrowError {
134 attempted: &'static std::panic::Location<'static>,
135 kind: &'static str,
136 origin: Option<(&'static std::panic::Location<'static>, &'static str)>,
137}
138
139impl std::fmt::Display for AppBorrowError {
140 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141 let Self {
142 attempted,
143 kind,
144 origin,
145 } = self;
146 write!(
147 formatter,
148 "RefCell already borrowed: attempted {kind} App borrow at {attempted}; "
149 )?;
150 match origin {
151 Some((origin, existing_kind)) => write!(
152 formatter,
153 "existing {existing_kind} borrow group began at {origin}"
154 ),
155 None => write!(formatter, "origin unavailable"),
156 }
157 }
158}
159
160impl std::fmt::Debug for AppBorrowError {
161 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 std::fmt::Display::fmt(self, formatter)
163 }
164}
165
166impl std::error::Error for AppBorrowError {}
167
168impl AppCell {
169 #[doc(hidden)]
170 #[track_caller]
171 pub fn borrow(&self) -> AppRef<'_> {
172 if option_env!("TRACK_THREAD_BORROWS").is_some() {
173 let thread_id = std::thread::current().id();
174 eprintln!("borrowed {thread_id:?}");
175 }
176 let starts_borrow_group = self.app.try_borrow_mut().is_ok();
179 let attempted = std::panic::Location::caller();
180 let borrow = match self.app.try_borrow() {
181 Ok(borrow) => borrow,
182 Err(_) => self.borrow_failed(AppBorrowError {
183 attempted,
184 kind: "shared",
185 origin: self.borrow_origin.get(),
186 }),
187 };
188 if starts_borrow_group {
189 self.borrow_origin
190 .set(Some((std::panic::Location::caller(), "shared")));
191 }
192 AppRef(borrow)
193 }
194
195 #[doc(hidden)]
196 #[track_caller]
197 pub fn borrow_mut(&self) -> AppRefMut<'_> {
198 match self.try_borrow_mut() {
199 Ok(borrow) => borrow,
200 Err(error) => self.borrow_failed(error),
201 }
202 }
203
204 #[doc(hidden)]
205 #[track_caller]
206 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>> {
207 if option_env!("TRACK_THREAD_BORROWS").is_some() {
208 let thread_id = std::thread::current().id();
209 eprintln!("borrowed {thread_id:?}");
210 }
211 let borrow = match self.app.try_borrow_mut() {
212 Ok(borrow) => borrow,
213 Err(_error) => {
214 return Err(AppBorrowError {
215 attempted: std::panic::Location::caller(),
216 kind: "mutable",
217 origin: self.borrow_origin.get(),
218 }
219 .into());
220 }
221 };
222 self.borrow_origin
223 .set(Some((std::panic::Location::caller(), "mutable")));
224 Ok(AppRefMut(borrow))
225 }
226
227 #[cold]
229 #[track_caller]
230 #[allow(clippy::panic)] fn borrow_failed(&self, error: impl std::fmt::Display) -> ! {
232 panic!("{error}")
233 }
234}
235
236#[doc(hidden)]
237#[derive(Deref, DerefMut)]
238pub struct AppRef<'a>(Ref<'a, App>);
239
240impl Drop for AppRef<'_> {
241 fn drop(&mut self) {
242 if option_env!("TRACK_THREAD_BORROWS").is_some() {
243 let thread_id = std::thread::current().id();
244 eprintln!("dropped borrow from {thread_id:?}");
245 }
246 }
247}
248
249#[doc(hidden)]
250#[derive(Deref, DerefMut)]
251pub struct AppRefMut<'a>(RefMut<'a, App>);
252
253impl Drop for AppRefMut<'_> {
254 fn drop(&mut self) {
255 if option_env!("TRACK_THREAD_BORROWS").is_some() {
256 let thread_id = std::thread::current().id();
257 eprintln!("dropped {thread_id:?}");
258 }
259 }
260}
261
262pub struct Application(Rc<AppCell>);
265
266pub struct ApplicationHandle {
271 app: Rc<AppCell>,
272}
273
274impl ApplicationHandle {
275 pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
278 let cx = &mut *self.app.borrow_mut();
279 f(cx)
280 }
281
282 pub fn to_async(&self) -> AsyncApp {
284 self.update(|cx| cx.to_async())
285 }
286}
287
288impl Application {
291 pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
293 Self(App::new_app(
294 platform,
295 Arc::new(()),
296 Arc::new(NullHttpClient),
297 ))
298 }
299
300 pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
307 let this = Self::with_platform(platform);
308 this.0.borrow_mut().accessibility_force_disabled = true;
309 this
310 }
311
312 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
314 let mut context_lock = self.0.borrow_mut();
315 let asset_source = Arc::new(asset_source);
316 context_lock.asset_source = asset_source.clone();
317 context_lock.svg_renderer = SvgRenderer::new(asset_source);
318 drop(context_lock);
319 self
320 }
321
322 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
324 let mut context_lock = self.0.borrow_mut();
325 context_lock.http_client = http_client;
326 drop(context_lock);
327 self
328 }
329
330 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
333 self.0.borrow_mut().quit_mode = mode;
334 self
335 }
336
337 pub fn run<F>(self, on_finish_launching: F)
339 where
340 F: 'static + FnOnce(&mut App),
341 {
342 let this = self.0.clone();
343 let platform = self.0.borrow().platform.clone();
344 platform.run(Box::new(move || {
345 let cx = &mut *this.borrow_mut();
346 on_finish_launching(cx);
347 }));
348 }
349
350 pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
359 where
360 F: 'static + FnOnce(&mut App),
361 {
362 let this = self.0.clone();
363 let platform = self.0.borrow().platform.clone();
364 platform.run(Box::new(move || {
365 let cx = &mut *this.borrow_mut();
366 on_finish_launching(cx);
367 }));
368 ApplicationHandle { app: self.0 }
369 }
370
371 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
373 where
374 F: 'static + FnMut(Vec<String>),
375 {
376 self.0.borrow().platform.on_open_urls(Box::new(callback));
377 self
378 }
379
380 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
383 where
384 F: 'static + FnMut(&mut App),
385 {
386 let this = Rc::downgrade(&self.0);
387 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
388 if let Some(app) = this.upgrade() {
389 callback(&mut app.borrow_mut());
390 }
391 }));
392 self
393 }
394
395 pub fn on_system_wake<F>(&self, mut callback: F) -> &Self
397 where
398 F: 'static + FnMut(&mut App),
399 {
400 let this = Rc::downgrade(&self.0);
401 self.0
402 .borrow_mut()
403 .platform
404 .on_system_wake(Box::new(move || {
405 if let Some(app) = this.upgrade() {
406 callback(&mut app.borrow_mut());
407 }
408 }));
409 self
410 }
411
412 pub fn background_executor(&self) -> BackgroundExecutor {
414 self.0.borrow().background_executor.clone()
415 }
416
417 pub fn foreground_executor(&self) -> ForegroundExecutor {
419 self.0.borrow().foreground_executor.clone()
420 }
421
422 pub fn text_system(&self) -> Arc<TextSystem> {
424 self.0.borrow().text_system.clone()
425 }
426
427 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
429 self.0.borrow().path_for_auxiliary_executable(name)
430 }
431}
432
433type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
434type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
435pub(crate) type KeystrokeObserver =
436 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
437type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
438type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
439type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
440type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
441
442#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
444pub enum QuitMode {
445 #[default]
447 Default,
448 LastWindowClosed,
450 Explicit,
452}
453
454#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
459pub enum CursorHideMode {
460 Never,
462 OnTyping,
464 #[default]
467 OnTypingAndAction,
468}
469
470#[doc(hidden)]
471#[derive(Clone, PartialEq, Eq)]
472pub struct SystemWindowTab {
473 pub id: WindowId,
474 pub title: SharedString,
475 pub handle: AnyWindowHandle,
476 pub last_active_at: Instant,
477}
478
479impl SystemWindowTab {
480 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
482 Self {
483 id: handle.id,
484 title,
485 handle,
486 last_active_at: Instant::now(),
487 }
488 }
489}
490
491#[derive(Default)]
493pub struct SystemWindowTabController {
494 visible: Option<bool>,
495 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
496}
497
498impl Global for SystemWindowTabController {}
499
500impl SystemWindowTabController {
501 pub fn new() -> Self {
503 Self {
504 visible: None,
505 tab_groups: FxHashMap::default(),
506 }
507 }
508
509 pub fn init(cx: &mut App) {
511 cx.set_global(SystemWindowTabController::new());
512 }
513
514 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
516 &self.tab_groups
517 }
518
519 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
521 let controller = cx.global::<SystemWindowTabController>();
522 let current_group = controller
523 .tab_groups
524 .iter()
525 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
526
527 let current_group = current_group?;
528 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
530 group_ids.sort();
531 let idx = group_ids.iter().position(|g| *g == current_group)?;
532 let next_idx = (idx + 1) % group_ids.len();
533
534 controller
535 .tab_groups
536 .get(group_ids[next_idx])
537 .and_then(|tabs| {
538 tabs.iter()
539 .max_by_key(|tab| tab.last_active_at)
540 .or_else(|| tabs.first())
541 .map(|tab| &tab.handle)
542 })
543 }
544
545 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
547 let controller = cx.global::<SystemWindowTabController>();
548 let current_group = controller
549 .tab_groups
550 .iter()
551 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
552
553 let current_group = current_group?;
554 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
556 group_ids.sort();
557 let idx = group_ids.iter().position(|g| *g == current_group)?;
558 let prev_idx = if idx == 0 {
559 group_ids.len() - 1
560 } else {
561 idx - 1
562 };
563
564 controller
565 .tab_groups
566 .get(group_ids[prev_idx])
567 .and_then(|tabs| {
568 tabs.iter()
569 .max_by_key(|tab| tab.last_active_at)
570 .or_else(|| tabs.first())
571 .map(|tab| &tab.handle)
572 })
573 }
574
575 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
577 self.tab_groups
578 .values()
579 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
580 }
581
582 pub fn init_visible(cx: &mut App, visible: bool) {
584 let mut controller = cx.global_mut::<SystemWindowTabController>();
585 if controller.visible.is_none() {
586 controller.visible = Some(visible);
587 }
588 }
589
590 pub fn is_visible(&self) -> bool {
592 self.visible.unwrap_or(false)
593 }
594
595 pub fn set_visible(cx: &mut App, visible: bool) {
597 let mut controller = cx.global_mut::<SystemWindowTabController>();
598 controller.visible = Some(visible);
599 }
600
601 pub fn update_last_active(cx: &mut App, id: WindowId) {
603 let mut controller = cx.global_mut::<SystemWindowTabController>();
604 for windows in controller.tab_groups.values_mut() {
605 for tab in windows.iter_mut() {
606 if tab.id == id {
607 tab.last_active_at = Instant::now();
608 }
609 }
610 }
611 }
612
613 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
615 let mut controller = cx.global_mut::<SystemWindowTabController>();
616 for (_, windows) in controller.tab_groups.iter_mut() {
617 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
618 if ix < windows.len() && current_pos != ix {
619 let window_tab = windows.remove(current_pos);
620 windows.insert(ix, window_tab);
621 }
622 break;
623 }
624 }
625 }
626
627 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
629 let controller = cx.global::<SystemWindowTabController>();
630 let tab = controller
631 .tab_groups
632 .values()
633 .flat_map(|windows| windows.iter())
634 .find(|tab| tab.id == id);
635
636 if tab.map_or(true, |t| t.title == title) {
637 return;
638 }
639
640 let mut controller = cx.global_mut::<SystemWindowTabController>();
641 for windows in controller.tab_groups.values_mut() {
642 for tab in windows.iter_mut() {
643 if tab.id == id {
644 tab.title = title;
645 return;
646 }
647 }
648 }
649 }
650
651 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
653 let mut controller = cx.global_mut::<SystemWindowTabController>();
654 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
655 return;
656 };
657
658 let mut expected_tab_ids: Vec<_> = tabs
659 .iter()
660 .filter(|tab| tab.id != id)
661 .map(|tab| tab.id)
662 .sorted()
663 .collect();
664
665 let mut tab_group_id = None;
666 for (group_id, group_tabs) in &controller.tab_groups {
667 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
668 if tab_ids == expected_tab_ids {
669 tab_group_id = Some(*group_id);
670 break;
671 }
672 }
673
674 if let Some(tab_group_id) = tab_group_id {
675 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
676 tabs.push(tab);
677 }
678 } else {
679 let new_group_id = controller.tab_groups.len();
680 controller.tab_groups.insert(new_group_id, tabs);
681 }
682 }
683
684 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
686 let mut controller = cx.global_mut::<SystemWindowTabController>();
687 let mut removed_tab = None;
688
689 controller.tab_groups.retain(|_, tabs| {
690 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
691 removed_tab = Some(tabs.remove(pos));
692 }
693 !tabs.is_empty()
694 });
695
696 removed_tab
697 }
698
699 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
701 let mut removed_tab = Self::remove_tab(cx, id);
702 let mut controller = cx.global_mut::<SystemWindowTabController>();
703
704 if let Some(tab) = removed_tab {
705 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
706 controller.tab_groups.insert(new_group_id, vec![tab]);
707 }
708 }
709
710 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
712 let mut controller = cx.global_mut::<SystemWindowTabController>();
713 let Some(initial_tabs) = controller.tabs(id) else {
714 return;
715 };
716
717 let initial_tabs_len = initial_tabs.len();
718 let mut all_tabs = initial_tabs.clone();
719
720 for (_, mut tabs) in controller.tab_groups.drain() {
721 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
722 all_tabs.extend(tabs);
723 }
724
725 controller.tab_groups.insert(0, all_tabs);
726 }
727
728 pub fn select_next_tab(cx: &mut App, id: WindowId) {
730 let mut controller = cx.global_mut::<SystemWindowTabController>();
731 let Some(tabs) = controller.tabs(id) else {
732 return;
733 };
734
735 let current_index = invariant(
736 tabs.iter().position(|tab| tab.id == id),
737 "tab id must exist in the tab list",
738 );
739 let next_index = (current_index + 1) % tabs.len();
740
741 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
742 window.activate_window();
743 });
744 }
745
746 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
748 let mut controller = cx.global_mut::<SystemWindowTabController>();
749 let Some(tabs) = controller.tabs(id) else {
750 return;
751 };
752
753 let current_index = invariant(
754 tabs.iter().position(|tab| tab.id == id),
755 "tab id must exist in the tab list",
756 );
757 let previous_index = if current_index == 0 {
758 tabs.len() - 1
759 } else {
760 current_index - 1
761 };
762
763 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
764 window.activate_window();
765 });
766 }
767}
768
769pub(crate) enum GpuiMode {
770 #[cfg(any(test, feature = "test-support"))]
771 Test {
772 skip_drawing: bool,
773 },
774 Production,
775}
776
777impl GpuiMode {
778 #[cfg(any(test, feature = "test-support"))]
779 pub fn test() -> Self {
780 GpuiMode::Test {
781 skip_drawing: false,
782 }
783 }
784
785 #[inline]
786 pub(crate) fn skip_drawing(&self) -> bool {
787 match self {
788 #[cfg(any(test, feature = "test-support"))]
789 GpuiMode::Test { skip_drawing } => *skip_drawing,
790 GpuiMode::Production => false,
791 }
792 }
793}
794
795pub struct App {
799 pub(crate) this: Weak<AppCell>,
800 pub(crate) platform: Rc<dyn Platform>,
801 text_system: Arc<TextSystem>,
802
803 pub(crate) actions: Rc<ActionRegistry>,
804 pub(crate) active_drag: Option<AnyDrag>,
805 pub(crate) background_executor: BackgroundExecutor,
806 pub(crate) foreground_executor: ForegroundExecutor,
807 pub(crate) entities: EntityMap,
808 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
809 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
810 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
811 pub(crate) focus_handles: Arc<FocusMap>,
812 pub(crate) keymap: Rc<RefCell<Keymap>>,
813 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
814 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
815 pub(crate) global_action_listeners:
816 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
817 pending_effects: VecDeque<Effect>,
818
819 pub(crate) observers: SubscriberSet<EntityId, Handler>,
820 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
821 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
822 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
823 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
824 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
825 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
826 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
827 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
828 pub(crate) restart_observers: SubscriberSet<(), Handler>,
829 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
830
831 pub(crate) element_arena: Rc<RefCell<Arena>>,
839 pub(crate) event_arena: Arena,
841
842 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
847 pub(crate) global_generations: TypeIdHashMap<crate::fast::dependencies::Generation>,
849 pub(crate) global_recorders: RefCell<Vec<crate::fast::dependencies::DependencyRecorder>>,
852 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
854 asset_source: Arc<dyn AssetSource>,
855 pub(crate) svg_renderer: SvgRenderer,
856 http_client: Arc<dyn HttpClient>,
857
858 pub(crate) pending_notifications: FxHashSet<EntityId>,
860 pub(crate) pending_global_notifications: TypeIdHashSet,
861 pub(crate) debouncers: FxHashMap<SharedString, Debouncer>,
863 pub(crate) recent_errors: std::collections::VecDeque<(u64, SharedString)>,
866 pub(crate) error_seq: u64,
868 pub(crate) crash_recorder_dir: Option<std::path::PathBuf>,
870 pub(crate) restart_path: Option<PathBuf>,
871 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
873 pub(crate) prompt_builder: Option<PromptBuilder>,
874 pub(crate) window_invalidators_by_entity:
875 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
876 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
877 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
878 #[cfg(any(feature = "inspector", debug_assertions))]
879 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
880 #[cfg(any(feature = "inspector", debug_assertions))]
881 pub(crate) inspector_element_registry: InspectorElementRegistry,
882 #[cfg(any(test, feature = "test-support", debug_assertions))]
883 pub(crate) name: Option<&'static str>,
884 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
885
886 pub(crate) window_update_stack: Vec<WindowId>,
887 pub(crate) mode: GpuiMode,
888 pub(crate) cursor_hide_mode: CursorHideMode,
889 pub(crate) reduce_motion: bool,
890 pub(crate) reduce_motion_override: bool,
893 pub(crate) synced_animation_epoch: Instant,
895 pub(crate) accessibility_force_disabled: bool,
898 flushing_effects: bool,
899 pending_updates: usize,
900 quit_mode: QuitMode,
901 keep_alive_without_windows: Cell<bool>,
906 quitting: bool,
907
908 #[cfg(any(test, feature = "leak-detection"))]
911 _ref_counts: Arc<RwLock<EntityRefCounts>>,
912}
913
914impl App {
915 #[allow(clippy::new_ret_no_self)]
916 pub(crate) fn new_app(
917 platform: Rc<dyn Platform>,
918 asset_source: Arc<dyn AssetSource>,
919 http_client: Arc<dyn HttpClient>,
920 ) -> Rc<AppCell> {
921 let background_executor = platform.background_executor();
922 let foreground_executor = platform.foreground_executor();
923 assert!(
924 background_executor.is_main_thread(),
925 "must construct App on main thread"
926 );
927
928 let text_system = Arc::new(TextSystem::new(platform.text_system()));
929 let entities = EntityMap::new();
930 let keyboard_layout = platform.keyboard_layout();
931 let keyboard_mapper = platform.keyboard_mapper();
932 let synced_animation_epoch = background_executor.now();
933
934 #[cfg(any(test, feature = "leak-detection"))]
935 let _ref_counts = entities.ref_counts_drop_handle();
936
937 let app = Rc::new_cyclic(|this| AppCell {
938 app: RefCell::new(App {
939 this: this.clone(),
940 platform: platform.clone(),
941 text_system,
942 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
943 mode: GpuiMode::Production,
944 actions: Rc::new(ActionRegistry::default()),
945 flushing_effects: false,
946 pending_updates: 0,
947 active_drag: None,
948 background_executor,
949 foreground_executor,
950 svg_renderer: SvgRenderer::new(asset_source.clone()),
951 loading_assets: Default::default(),
952 asset_source,
953 http_client,
954 globals_by_type: Default::default(),
955 global_generations: Default::default(),
956 global_recorders: RefCell::new(Vec::new()),
957 entities,
958 new_entity_observers: SubscriberSet::new(),
959 windows: SlotMap::with_key(),
960 window_update_stack: Vec::new(),
961 window_handles: FxHashMap::default(),
962 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
963 keymap: Rc::new(RefCell::new(Keymap::default())),
964 keyboard_layout,
965 keyboard_mapper,
966 global_action_listeners: Default::default(),
967 pending_effects: VecDeque::new(),
968 pending_notifications: FxHashSet::default(),
969 pending_global_notifications: Default::default(),
970 debouncers: FxHashMap::default(),
971 recent_errors: Default::default(),
972 error_seq: 0,
973 crash_recorder_dir: None,
974 observers: SubscriberSet::new(),
975 tracked_entities: FxHashMap::default(),
976 window_invalidators_by_entity: FxHashMap::default(),
977 current_window_by_entity: FxHashMap::default(),
978 event_listeners: SubscriberSet::new(),
979 release_listeners: SubscriberSet::new(),
980 keystroke_observers: SubscriberSet::new(),
981 keystroke_interceptors: SubscriberSet::new(),
982 keyboard_layout_observers: SubscriberSet::new(),
983 thermal_state_observers: SubscriberSet::new(),
984 global_observers: SubscriberSet::new(),
985 quit_observers: SubscriberSet::new(),
986 restart_observers: SubscriberSet::new(),
987 restart_path: None,
988 window_closed_observers: SubscriberSet::new(),
989 layout_id_buffer: Default::default(),
990 propagate_event: true,
991 prompt_builder: Some(PromptBuilder::Default),
992 #[cfg(any(feature = "inspector", debug_assertions))]
993 inspector_renderer: None,
994 #[cfg(any(feature = "inspector", debug_assertions))]
995 inspector_element_registry: InspectorElementRegistry::default(),
996 quit_mode: QuitMode::default(),
997 keep_alive_without_windows: Cell::new(false),
998 quitting: false,
999 cursor_hide_mode: CursorHideMode::default(),
1000 reduce_motion: false,
1001 reduce_motion_override: false,
1002 synced_animation_epoch,
1003 accessibility_force_disabled: false,
1004
1005 #[cfg(any(test, feature = "test-support", debug_assertions))]
1006 name: None,
1007 element_arena: Rc::new(RefCell::new(Arena::new(1024 * 1024))),
1008 event_arena: Arena::new(1024 * 1024),
1009
1010 #[cfg(any(test, feature = "leak-detection"))]
1011 _ref_counts,
1012 }),
1013 borrow_origin: Cell::new(None),
1014 });
1015
1016 init_app_menus(platform.as_ref(), &app.borrow());
1017 SystemWindowTabController::init(&mut app.borrow_mut());
1018
1019 platform.on_keyboard_layout_change(Box::new({
1020 let app = Rc::downgrade(&app);
1021 move || {
1022 if let Some(app) = app.upgrade() {
1023 let cx = &mut app.borrow_mut();
1024 cx.keyboard_layout = cx.platform.keyboard_layout();
1025 cx.keyboard_mapper = cx.platform.keyboard_mapper();
1026 cx.keyboard_layout_observers
1027 .clone()
1028 .retain(&(), move |callback| (callback)(cx));
1029 }
1030 }
1031 }));
1032
1033 platform.on_thermal_state_change(Box::new({
1034 let app = Rc::downgrade(&app);
1035 move || {
1036 if let Some(app) = app.upgrade() {
1037 let cx = &mut app.borrow_mut();
1038 cx.thermal_state_observers
1039 .clone()
1040 .retain(&(), move |callback| (callback)(cx));
1041 }
1042 }
1043 }));
1044
1045 platform.on_quit(Box::new({
1046 let cx = Rc::downgrade(&app);
1047 move || {
1048 if let Some(cx) = cx.upgrade() {
1049 cx.borrow_mut().shutdown();
1050 }
1051 }
1052 }));
1053
1054 app
1055 }
1056
1057 #[doc(hidden)]
1058 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1059 self.entities.ref_counts_drop_handle()
1060 }
1061
1062 #[cfg(any(test, feature = "leak-detection"))]
1068 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1069 self.entities.leak_detector_snapshot()
1070 }
1071
1072 #[cfg(any(test, feature = "leak-detection"))]
1083 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1084 self.entities.assert_no_new_leaks(snapshot)
1085 }
1086
1087 pub fn shutdown(&mut self) {
1090 let mut futures = Vec::new();
1091
1092 for observer in self.quit_observers.remove(&()) {
1093 futures.push(observer(self));
1094 }
1095
1096 self.windows.clear();
1097 self.window_handles.clear();
1098 self.flush_effects();
1099 self.quitting = true;
1100
1101 let futures = futures::future::join_all(futures);
1102 if self
1103 .foreground_executor
1104 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1105 .is_err()
1106 {
1107 log::error!("timed out waiting on app_will_quit");
1108 }
1109
1110 self.quitting = false;
1111 }
1112
1113 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1115 self.keyboard_layout.as_ref()
1116 }
1117
1118 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1120 &self.keyboard_mapper
1121 }
1122
1123 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1125 where
1126 F: 'static + FnMut(&mut App),
1127 {
1128 let (subscription, activate) = self.keyboard_layout_observers.insert(
1129 (),
1130 Box::new(move |cx| {
1131 callback(cx);
1132 true
1133 }),
1134 );
1135 activate();
1136 subscription
1137 }
1138
1139 pub fn quit(&self) {
1141 self.platform.quit();
1142 }
1143
1144 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1146 self.cursor_hide_mode
1147 }
1148
1149 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1151 self.cursor_hide_mode = mode;
1152 }
1153
1154 pub fn is_cursor_visible(&self) -> bool {
1159 self.platform.is_cursor_visible()
1160 }
1161
1162 pub fn reduce_motion(&self) -> bool {
1164 self.reduce_motion
1165 }
1166
1167 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1174 self.reduce_motion_override = true;
1175 if self.reduce_motion != reduce_motion {
1176 self.reduce_motion = reduce_motion;
1177 self.refresh_windows();
1178 }
1179 }
1180
1181 fn sync_reduce_motion_from_platform(&mut self) {
1186 if self.reduce_motion_override {
1187 return;
1188 }
1189 let reduce_motion = self.platform.reduce_motion_enabled();
1190 if self.reduce_motion != reduce_motion {
1191 self.reduce_motion = reduce_motion;
1192 self.refresh_windows();
1193 }
1194 }
1195
1196 pub fn refresh_windows(&mut self) {
1199 self.pending_effects.push_back(Effect::RefreshWindows);
1200 }
1201
1202 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1203 self.start_update();
1204 let result = update(self);
1205 self.finish_update();
1206 result
1207 }
1208
1209 pub(crate) fn start_update(&mut self) {
1210 self.pending_updates += 1;
1211 }
1212
1213 pub(crate) fn finish_update(&mut self) {
1214 if !self.flushing_effects && self.pending_updates == 1 {
1215 self.flushing_effects = true;
1216 self.flush_effects();
1217 self.flushing_effects = false;
1218 }
1219 self.pending_updates -= 1;
1220 }
1221
1222 pub fn observe<W>(
1224 &mut self,
1225 entity: &Entity<W>,
1226 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1227 ) -> Subscription
1228 where
1229 W: 'static,
1230 {
1231 self.observe_internal(entity, move |e, cx| {
1232 on_notify(e, cx);
1233 true
1234 })
1235 }
1236
1237 pub(crate) fn detect_accessed_entities<R>(
1238 &mut self,
1239 callback: impl FnOnce(&mut App) -> R,
1240 ) -> (R, FxHashSet<EntityId>) {
1241 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1242 let result = callback(self);
1243 let entities_accessed_in_callback = self
1244 .entities
1245 .accessed_entities
1246 .get_mut()
1247 .difference(&accessed_entities_start)
1248 .copied()
1249 .collect::<FxHashSet<EntityId>>();
1250 (result, entities_accessed_in_callback)
1251 }
1252
1253 pub(crate) fn record_entities_accessed(
1254 &mut self,
1255 window_handle: AnyWindowHandle,
1256 invalidator: WindowInvalidator,
1257 entities: &FxHashSet<EntityId>,
1258 ) {
1259 let mut tracked_entities =
1260 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1261 for entity in tracked_entities.iter() {
1262 self.window_invalidators_by_entity
1263 .entry(*entity)
1264 .and_modify(|windows| {
1265 windows.remove(&window_handle.id);
1266 });
1267 }
1268 for entity in entities.iter() {
1269 self.window_invalidators_by_entity
1270 .entry(*entity)
1271 .or_default()
1272 .insert(window_handle.id, invalidator.clone());
1273 self.current_window_by_entity
1274 .insert(*entity, window_handle.id);
1275 }
1276 tracked_entities.clear();
1277 tracked_entities.extend(entities.iter().copied());
1278 self.tracked_entities
1279 .insert(window_handle.id, tracked_entities);
1280 }
1281
1282 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1283 let (subscription, activate) = self.observers.insert(key, value);
1284 self.defer(move |_| activate());
1285 subscription
1286 }
1287
1288 pub(crate) fn observe_internal<W>(
1289 &mut self,
1290 entity: &Entity<W>,
1291 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1292 ) -> Subscription
1293 where
1294 W: 'static,
1295 {
1296 let entity_id = entity.entity_id();
1297 let handle = entity.downgrade();
1298 self.new_observer(
1299 entity_id,
1300 Box::new(move |cx| {
1301 if let Some(entity) = handle.upgrade() {
1302 on_notify(entity, cx)
1303 } else {
1304 false
1305 }
1306 }),
1307 )
1308 }
1309
1310 pub fn subscribe<T, Event>(
1313 &mut self,
1314 entity: &Entity<T>,
1315 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1316 ) -> Subscription
1317 where
1318 T: 'static + EventEmitter<Event>,
1319 Event: 'static,
1320 {
1321 self.subscribe_internal(entity, move |entity, event, cx| {
1322 on_event(entity, event, cx);
1323 true
1324 })
1325 }
1326
1327 pub(crate) fn new_subscription(
1328 &mut self,
1329 key: EntityId,
1330 value: (TypeId, Listener),
1331 ) -> Subscription {
1332 let (subscription, activate) = self.event_listeners.insert(key, value);
1333 self.defer(move |_| activate());
1334 subscription
1335 }
1336 pub(crate) fn subscribe_internal<T, Evt>(
1337 &mut self,
1338 entity: &Entity<T>,
1339 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1340 ) -> Subscription
1341 where
1342 T: 'static + EventEmitter<Evt>,
1343 Evt: 'static,
1344 {
1345 let entity_id = entity.entity_id();
1346 let handle = entity.downgrade();
1347 self.new_subscription(
1348 entity_id,
1349 (
1350 TypeId::of::<Evt>(),
1351 Box::new(move |event, cx| {
1352 let event: &Evt = invariant(event.downcast_ref(), "invalid event type");
1353 if let Some(entity) = handle.upgrade() {
1354 on_event(entity, event, cx)
1355 } else {
1356 false
1357 }
1358 }),
1359 ),
1360 )
1361 }
1362
1363 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1367 self.windows
1368 .keys()
1369 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1370 .collect()
1371 }
1372
1373 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1379 self.platform.window_stack()
1380 }
1381
1382 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1384 self.platform.active_window()
1385 }
1386
1387 pub fn open_window<V: 'static + Render>(
1390 &mut self,
1391 options: crate::WindowOptions,
1392 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1393 ) -> anyhow::Result<WindowHandle<V>> {
1394 self.update(|cx| {
1395 let id = cx.windows.insert(None);
1396 let handle = WindowHandle::new(id);
1397 match Window::new(handle.into(), options, cx) {
1398 Ok(mut window) => {
1399 if !cx.has_global::<crate::theme::Theme>() {
1401 cx.set_global(crate::theme::Theme::default());
1402 }
1403 cx.window_update_stack.push(id);
1404 let root_view: AnyView = build_root_view(&mut window, cx).into();
1405 cx.window_update_stack.pop();
1406 let root_view = if root_view.clone().downcast::<Root>().is_ok() {
1409 root_view
1410 } else {
1411 cx.new(|cx| Root::new(root_view, cx)).into()
1412 };
1413 window.root.replace(root_view);
1414 cx.sync_reduce_motion_from_platform();
1417 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1418
1419 let clear = window.draw(cx);
1424 clear.clear(cx);
1425
1426 cx.window_handles.insert(id, window.handle);
1427 invariant(cx.windows.get_mut(id), "window id must be registered")
1428 .replace(Box::new(window));
1429 Ok(handle)
1430 }
1431 Err(e) => {
1432 cx.windows.remove(id);
1433 Err(e)
1434 }
1435 }
1436 })
1437 }
1438
1439 pub fn activate(&self, ignoring_other_apps: bool) {
1441 self.platform.activate(ignoring_other_apps);
1442 }
1443
1444 pub fn hide(&self) {
1446 self.platform.hide();
1447 }
1448
1449 pub fn hide_other_apps(&self) {
1451 self.platform.hide_other_apps();
1452 }
1453
1454 pub fn unhide_other_apps(&self) {
1456 self.platform.unhide_other_apps();
1457 }
1458
1459 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1461 self.platform.displays()
1462 }
1463
1464 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1466 self.platform.primary_display()
1467 }
1468
1469 pub fn is_screen_capture_supported(&self) -> bool {
1471 self.platform.is_screen_capture_supported()
1472 }
1473
1474 pub fn screen_capture_sources(
1476 &self,
1477 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1478 self.platform.screen_capture_sources()
1479 }
1480
1481 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1483 self.displays()
1484 .iter()
1485 .find(|display| display.id() == id)
1486 .cloned()
1487 }
1488
1489 pub fn thermal_state(&self) -> ThermalState {
1491 self.platform.thermal_state()
1492 }
1493
1494 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1496 where
1497 F: 'static + FnMut(&mut App),
1498 {
1499 let (subscription, activate) = self.thermal_state_observers.insert(
1500 (),
1501 Box::new(move |cx| {
1502 callback(cx);
1503 true
1504 }),
1505 );
1506 activate();
1507 subscription
1508 }
1509
1510 pub fn window_appearance(&self) -> WindowAppearance {
1512 self.platform.window_appearance()
1513 }
1514
1515 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1517 self.platform.button_layout()
1518 }
1519
1520 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1522 self.platform.read_from_clipboard()
1523 }
1524
1525 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1527 self.text_rendering_mode.set(mode);
1528 }
1529
1530 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1532 self.text_rendering_mode.get()
1533 }
1534
1535 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1537 self.platform.write_to_clipboard(item)
1538 }
1539
1540 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1543 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1544 self.platform.read_from_primary()
1545 }
1546
1547 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1550 pub fn write_to_primary(&self, item: ClipboardItem) {
1551 self.platform.write_to_primary(item)
1552 }
1553
1554 #[cfg(target_os = "macos")]
1560 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1561 self.platform.read_from_find_pasteboard()
1562 }
1563
1564 #[cfg(target_os = "macos")]
1570 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1571 self.platform.write_to_find_pasteboard(item)
1572 }
1573
1574 pub fn write_credentials(
1576 &self,
1577 url: &str,
1578 username: &str,
1579 password: &[u8],
1580 ) -> Task<Result<()>> {
1581 self.platform.write_credentials(url, username, password)
1582 }
1583
1584 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1586 self.platform.read_credentials(url)
1587 }
1588
1589 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1591 self.platform.delete_credentials(url)
1592 }
1593
1594 pub fn open_url(&self, url: &str) {
1596 self.platform.open_url(url);
1597 }
1598
1599 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1604 self.platform.register_url_scheme(scheme)
1605 }
1606
1607 pub fn app_path(&self) -> Result<PathBuf> {
1611 self.platform.app_path()
1612 }
1613
1614 pub fn compositor_name(&self) -> &'static str {
1618 self.platform.compositor_name()
1619 }
1620
1621 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1623 self.platform.path_for_auxiliary_executable(name)
1624 }
1625
1626 pub fn prompt_for_paths(
1632 &self,
1633 options: PathPromptOptions,
1634 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1635 self.platform.prompt_for_paths(options)
1636 }
1637
1638 pub fn prompt_for_new_path(
1645 &self,
1646 directory: &Path,
1647 suggested_name: Option<&str>,
1648 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1649 self.platform.prompt_for_new_path(directory, suggested_name)
1650 }
1651
1652 pub fn debounce(
1659 &mut self,
1660 key: impl Into<SharedString>,
1661 duration: Duration,
1662 callback: impl FnOnce() + Send + 'static,
1663 ) {
1664 let executor = self.background_executor.clone();
1665 self.debouncers
1666 .entry(key.into())
1667 .or_default()
1668 .debounce(&executor, duration, callback);
1669 }
1670
1671 pub fn reveal_path(&self, path: &Path) {
1673 self.platform.reveal_path(path)
1674 }
1675
1676 pub fn open_with_system(&self, path: &Path) {
1678 self.platform.open_with_system(path)
1679 }
1680
1681 pub fn should_auto_hide_scrollbars(&self) -> bool {
1683 self.platform.should_auto_hide_scrollbars()
1684 }
1685
1686 pub fn restart(&mut self) {
1688 self.restart_observers
1689 .clone()
1690 .retain(&(), |observer| observer(self));
1691 self.platform.restart(self.restart_path.take())
1692 }
1693
1694 pub fn set_restart_path(&mut self, path: PathBuf) {
1696 self.restart_path = Some(path);
1697 }
1698
1699 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1701 self.http_client.clone()
1702 }
1703
1704 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1706 self.http_client = new_client;
1707 }
1708
1709 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1712 self.quit_mode = mode;
1713 }
1714
1715 pub fn svg_renderer(&self) -> SvgRenderer {
1717 self.svg_renderer.clone()
1718 }
1719
1720 pub(crate) fn push_effect(&mut self, effect: Effect) {
1721 match &effect {
1722 Effect::Notify { emitter } => {
1723 if !self.pending_notifications.insert(*emitter) {
1724 return;
1725 }
1726 }
1727 Effect::NotifyGlobalObservers { global_type } => {
1728 if !self.pending_global_notifications.insert(*global_type) {
1729 return;
1730 }
1731 }
1732 _ => {}
1733 };
1734
1735 self.pending_effects.push_back(effect);
1736 }
1737
1738 fn flush_effects(&mut self) {
1742 loop {
1743 self.release_dropped_entities();
1744 self.release_dropped_focus_handles();
1745 if let Some(effect) = self.pending_effects.pop_front() {
1746 match effect {
1747 Effect::Notify { emitter } => {
1748 self.apply_notify_effect(emitter);
1749 }
1750
1751 Effect::Emit {
1752 emitter,
1753 event_type,
1754 event,
1755 } => self.apply_emit_effect(emitter, event_type, &*event),
1756
1757 Effect::RefreshWindows => {
1758 self.apply_refresh_effect();
1759 }
1760
1761 Effect::NotifyGlobalObservers { global_type } => {
1762 self.apply_notify_global_observers_effect(global_type);
1763 }
1764
1765 Effect::Defer { callback } => {
1766 self.apply_defer_effect(callback);
1767 }
1768 Effect::EntityCreated {
1769 entity,
1770 tid,
1771 window,
1772 } => {
1773 self.apply_entity_created_effect(entity, tid, window);
1774 }
1775 }
1776 } else {
1777 #[cfg(any(test, feature = "test-support", feature = "bench"))]
1778 for window in self
1779 .windows
1780 .values()
1781 .filter_map(|window| {
1782 let window = window.as_deref()?;
1783 window.invalidator.is_dirty().then_some(window.handle)
1784 })
1785 .collect::<Vec<_>>()
1786 {
1787 if let Err(err) =
1788 self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1789 {
1790 log::debug!("[rgpui::app] 重绘窗口失败:{err}");
1792 }
1793 }
1794
1795 if self.pending_effects.is_empty() {
1796 self.event_arena.clear();
1797 break;
1798 }
1799 }
1800 }
1801 }
1802
1803 fn release_dropped_entities(&mut self) {
1806 loop {
1807 let dropped = self.entities.take_dropped();
1808 if dropped.is_empty() {
1809 break;
1810 }
1811
1812 for (entity_id, mut entity) in dropped {
1813 self.observers.remove(&entity_id);
1814 self.event_listeners.remove(&entity_id);
1815 self.window_invalidators_by_entity.remove(&entity_id);
1816 self.current_window_by_entity.remove(&entity_id);
1817 for release_callback in self.release_listeners.remove(&entity_id) {
1818 release_callback(entity.as_mut(), self);
1819 }
1820 }
1821 }
1822 }
1823
1824 fn release_dropped_focus_handles(&mut self) {
1826 self.focus_handles
1827 .clone()
1828 .write()
1829 .retain(|handle_id, focus| {
1830 if focus.ref_count.load(SeqCst) == 0 {
1831 for window_handle in self.windows() {
1832 if let Err(err) = window_handle.update(self, |_, window, _| {
1833 if window.focus == Some(handle_id) {
1834 window.blur();
1835 }
1836 }) {
1837 log::debug!("[rgpui::app] 取消焦点失败:{err}");
1839 }
1840 }
1841 false
1842 } else {
1843 true
1844 }
1845 });
1846 }
1847
1848 fn apply_notify_effect(&mut self, emitter: EntityId) {
1849 self.pending_notifications.remove(&emitter);
1850
1851 self.observers
1852 .clone()
1853 .retain(&emitter, |handler| handler(self));
1854 }
1855
1856 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1857 self.event_listeners
1858 .clone()
1859 .retain(&emitter, |(stored_type, handler)| {
1860 if *stored_type == event_type {
1861 handler(event, self)
1862 } else {
1863 true
1864 }
1865 });
1866 }
1867
1868 fn apply_refresh_effect(&mut self) {
1869 for window in self.windows.values_mut() {
1870 if let Some(window) = window.as_deref_mut() {
1871 window.refreshing = true;
1872 window.invalidator.set_dirty(true);
1873 }
1874 }
1875 }
1876
1877 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1878 self.pending_global_notifications.remove(&type_id);
1879 self.global_observers
1880 .clone()
1881 .retain(&type_id, |observer| observer(self));
1882 }
1883
1884 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1885 callback(self);
1886 }
1887
1888 #[allow(clippy::panic)] fn apply_entity_created_effect(
1890 &mut self,
1891 entity: AnyEntity,
1892 tid: TypeId,
1893 window: Option<WindowId>,
1894 ) {
1895 if let Some(id) = window {
1899 self.current_window_by_entity.insert(entity.entity_id(), id);
1900 }
1901
1902 self.new_entity_observers.clone().retain(&tid, |observer| {
1903 if let Some(id) = window {
1904 self.update_window_id(id, {
1905 let entity = entity.clone();
1906 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1907 })
1908 .unwrap_or_else(|err| {
1909 panic!("All windows should be off the stack when flushing effects: {err}")
1910 });
1911 } else {
1912 (observer)(entity.clone(), &mut None, self)
1913 }
1914 true
1915 });
1916 }
1917
1918 pub fn with_window<R>(
1922 &mut self,
1923 entity_id: EntityId,
1924 f: impl FnOnce(&mut Window, &mut App) -> R,
1925 ) -> Option<R> {
1926 let window_id = *self.current_window_by_entity.get(&entity_id)?;
1927 self.update_window_id(window_id, |_, window, cx| f(window, cx))
1928 .ok()
1929 }
1930
1931 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1932 self.current_window_by_entity
1933 .entry(entity_id)
1934 .or_insert(window);
1935 }
1936
1937 #[track_caller]
1938 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1939 where
1940 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1941 {
1942 self.update(|cx| {
1943 let mut window = cx.windows.get_mut(id)?.take()?;
1944
1945 let root_view = invariant(window.root.clone(), "window must have a root view");
1946
1947 cx.window_update_stack.push(window.handle.id);
1948 let result = update(root_view, &mut window, cx);
1949 fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1950 cx.window_update_stack.pop();
1951
1952 if window.removed {
1953 cx.window_handles.remove(&id);
1954 cx.windows.remove(id);
1955 if let Some(tracked) = cx.tracked_entities.remove(&id) {
1956 for entity_id in tracked {
1957 if let Some(windows) =
1958 cx.window_invalidators_by_entity.get_mut(&entity_id)
1959 {
1960 windows.remove(&id);
1961 }
1962 if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1963 cx.current_window_by_entity.remove(&entity_id);
1964 }
1965 }
1966 }
1967
1968 cx.window_closed_observers.clone().retain(&(), |callback| {
1969 callback(cx, id);
1970 true
1971 });
1972
1973 let quit_on_empty = !cx.keep_alive_without_windows.get()
1976 && match cx.quit_mode {
1977 QuitMode::Explicit => false,
1978 QuitMode::LastWindowClosed => true,
1979 QuitMode::Default => cfg!(not(target_os = "macos")),
1980 };
1981
1982 if quit_on_empty && cx.windows.is_empty() {
1983 cx.quit();
1984 }
1985 } else {
1986 cx.windows.get_mut(id)?.replace(window);
1987 }
1988 Some(())
1989 }
1990 trail(id, window, cx)?;
1991
1992 Some(result)
1993 })
1994 .context("window not found")
1995 }
1996
1997 pub fn to_async(&self) -> AsyncApp {
2000 AsyncApp {
2001 app: self.this.clone(),
2002 background_executor: self.background_executor.clone(),
2003 foreground_executor: self.foreground_executor.clone(),
2004 }
2005 }
2006
2007 pub fn background_executor(&self) -> &BackgroundExecutor {
2009 &self.background_executor
2010 }
2011
2012 #[allow(clippy::panic)] pub fn foreground_executor(&self) -> &ForegroundExecutor {
2015 if self.quitting {
2016 panic!("Can't spawn on main thread after on_app_quit")
2017 };
2018 &self.foreground_executor
2019 }
2020
2021 #[allow(clippy::panic)] #[track_caller]
2025 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2026 where
2027 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2028 R: 'static,
2029 {
2030 if self.quitting {
2031 debug_panic!("Can't spawn on main thread after on_app_quit")
2032 };
2033
2034 let mut cx = self.to_async();
2035
2036 self.foreground_executor
2037 .spawn(async move { f(&mut cx).await }.boxed_local())
2038 }
2039
2040 #[allow(clippy::panic)] pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2044 where
2045 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2046 R: 'static,
2047 {
2048 if self.quitting {
2049 debug_panic!("Can't spawn on main thread after on_app_quit")
2050 };
2051
2052 let mut cx = self.to_async();
2053
2054 self.foreground_executor
2055 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2056 }
2057
2058 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2061 self.push_effect(Effect::Defer {
2062 callback: Box::new(f),
2063 });
2064 }
2065
2066 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2068 &self.asset_source
2069 }
2070
2071 pub fn text_system(&self) -> &Arc<TextSystem> {
2073 &self.text_system
2074 }
2075
2076 pub fn has_global<G: Global>(&self) -> bool {
2078 let present = self.globals_by_type.contains_key(&TypeId::of::<G>());
2079 if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2081 recorder.record_global_presence(TypeId::of::<G>(), present);
2082 }
2083 present
2084 }
2085
2086 #[allow(clippy::panic)] #[track_caller]
2089 pub fn global<G: Global>(&self) -> &G {
2090 if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2092 recorder.record_global(TypeId::of::<G>(), self.global_generation_or_initial::<G>());
2093 }
2094 self.globals_by_type
2095 .get(&TypeId::of::<G>())
2096 .map(|any_state| invariant(any_state.downcast_ref::<G>(), "global type must match"))
2097 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2098 }
2099
2100 pub fn try_global<G: Global>(&self) -> Option<&G> {
2102 let global = self
2103 .globals_by_type
2104 .get(&TypeId::of::<G>())
2105 .map(|any_state| invariant(any_state.downcast_ref::<G>(), "global type must match"));
2106 if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2108 if global.is_some() {
2109 recorder.record_global(TypeId::of::<G>(), self.global_generation_or_initial::<G>());
2110 } else {
2111 recorder.record_global_presence(TypeId::of::<G>(), false);
2112 }
2113 }
2114 global
2115 }
2116
2117 #[allow(clippy::panic)] #[track_caller]
2120 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2121 let global_type = TypeId::of::<G>();
2122 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2123 self.bump_global_generation(global_type);
2124 self.globals_by_type
2125 .get_mut(&global_type)
2126 .and_then(|any_state| any_state.downcast_mut::<G>())
2127 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2128 }
2129
2130 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2132 let global_type = TypeId::of::<G>();
2133 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2134 self.bump_global_generation(global_type);
2135 invariant(
2136 self.globals_by_type
2137 .entry(global_type)
2138 .or_insert_with(|| Box::<G>::default())
2139 .downcast_mut::<G>(),
2140 "global type must match",
2141 )
2142 }
2143
2144 pub fn set_global<G: Global>(&mut self, global: G) {
2146 let global_type = TypeId::of::<G>();
2147 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2148 self.bump_global_generation(global_type);
2149 self.globals_by_type.insert(global_type, Box::new(global));
2150 }
2151
2152 #[cfg(any(test, feature = "test-support"))]
2154 pub fn clear_globals(&mut self) {
2155 self.globals_by_type.drain();
2156 self.global_generations.clear();
2158 }
2159
2160 #[allow(clippy::panic)] pub fn remove_global<G: Global>(&mut self) -> G {
2163 let global_type = TypeId::of::<G>();
2164 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2165 self.bump_global_generation(global_type);
2166 *invariant_result(
2167 self.globals_by_type
2168 .remove(&global_type)
2169 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2170 .downcast(),
2171 "global type must match",
2172 )
2173 }
2174
2175 pub fn observe_global<G: Global>(
2177 &mut self,
2178 mut f: impl FnMut(&mut Self) + 'static,
2179 ) -> Subscription {
2180 let (subscription, activate) = self.global_observers.insert(
2181 TypeId::of::<G>(),
2182 Box::new(move |cx| {
2183 f(cx);
2184 true
2185 }),
2186 );
2187 self.defer(move |_| activate());
2188 subscription
2189 }
2190
2191 #[track_caller]
2193 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2194 GlobalLease::new(invariant_result(
2195 self.globals_by_type
2196 .remove(&TypeId::of::<G>())
2197 .with_context(|| format!("no global registered of type {}", type_name::<G>())),
2198 "global type must match",
2199 ))
2200 }
2201
2202 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2204 let global_type = TypeId::of::<G>();
2205
2206 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2207 self.bump_global_generation(global_type);
2208 self.globals_by_type.insert(global_type, lease.global);
2209 }
2210
2211 fn bump_global_generation(&mut self, global_type: TypeId) {
2213 let bumped = self
2214 .global_generations
2215 .get(&global_type)
2216 .copied()
2217 .unwrap_or_else(crate::fast::dependencies::Generation::initial)
2218 .bumped();
2219 self.global_generations.insert(global_type, bumped);
2220 }
2221
2222 fn global_generation_or_initial<G: Global>(&self) -> crate::fast::dependencies::Generation {
2224 self.global_generation::<G>()
2225 .unwrap_or_else(crate::fast::dependencies::Generation::initial)
2226 }
2227
2228 pub(crate) fn global_generation<G: Global>(
2230 &self,
2231 ) -> Option<crate::fast::dependencies::Generation> {
2232 self.global_generations.get(&TypeId::of::<G>()).copied()
2233 }
2234
2235 pub(crate) fn global_generation_by_type(
2237 &self,
2238 global_type: TypeId,
2239 ) -> Option<crate::fast::dependencies::Generation> {
2240 self.global_generations.get(&global_type).copied()
2241 }
2242
2243 pub(crate) fn entity_generation(
2245 &self,
2246 id: EntityId,
2247 ) -> Option<crate::fast::dependencies::Generation> {
2248 self.entities.entity_generation(id)
2249 }
2250
2251 pub(crate) fn begin_dependency_recording(&self) {
2253 self.entities.begin_dependency_recording();
2254 self.global_recorders
2255 .borrow_mut()
2256 .push(crate::fast::dependencies::DependencyRecorder::new());
2257 }
2258
2259 pub(crate) fn end_dependency_recording(&self) -> crate::fast::dependencies::DependencySet {
2264 let mut set = self.entities.end_dependency_recording();
2265 if let Some(recorder) = self.global_recorders.borrow_mut().pop() {
2266 set.merge(recorder.finish());
2267 }
2268 if let Some(parent) = self.global_recorders.borrow_mut().last_mut() {
2269 parent.absorb_shared(&set);
2270 }
2271 self.entities.absorb_entities_into_parent(&set);
2272 set
2273 }
2274
2275 pub(crate) fn note_state_read(&self, version: &crate::fast::dependencies::StateVersion) {
2277 if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2278 recorder.record_state(version);
2279 }
2280 }
2281
2282 pub(crate) fn new_entity_observer(
2283 &self,
2284 key: TypeId,
2285 value: NewEntityListener,
2286 ) -> Subscription {
2287 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2288 activate();
2289 subscription
2290 }
2291
2292 pub fn observe_new<T: 'static>(
2295 &self,
2296 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2297 ) -> Subscription {
2298 self.new_entity_observer(
2299 TypeId::of::<T>(),
2300 Box::new(
2301 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2302 invariant_result(any_entity.downcast::<T>(), "entity type must match")
2303 .update(cx, |entity_state, cx| {
2304 on_new(entity_state, window.as_deref_mut(), cx)
2305 })
2306 },
2307 ),
2308 )
2309 }
2310
2311 pub fn observe_release<T>(
2313 &self,
2314 handle: &Entity<T>,
2315 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2316 ) -> Subscription
2317 where
2318 T: 'static,
2319 {
2320 let (subscription, activate) = self.release_listeners.insert(
2321 handle.entity_id(),
2322 Box::new(move |entity, cx| {
2323 let entity = invariant(entity.downcast_mut(), "invalid entity type");
2324 on_release(entity, cx)
2325 }),
2326 );
2327 activate();
2328 subscription
2329 }
2330
2331 pub fn observe_release_in<T>(
2333 &self,
2334 handle: &Entity<T>,
2335 window: &Window,
2336 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2337 ) -> Subscription
2338 where
2339 T: 'static,
2340 {
2341 let window_handle = window.handle;
2342 self.observe_release(handle, move |entity, cx| {
2343 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2344 })
2345 }
2346
2347 pub fn observe_keystrokes(
2351 &mut self,
2352 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2353 ) -> Subscription {
2354 fn inner(
2355 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2356 handler: KeystrokeObserver,
2357 ) -> Subscription {
2358 let (subscription, activate) = keystroke_observers.insert((), handler);
2359 activate();
2360 subscription
2361 }
2362
2363 inner(
2364 &self.keystroke_observers,
2365 Box::new(move |event, window, cx| {
2366 f(event, window, cx);
2367 true
2368 }),
2369 )
2370 }
2371
2372 pub fn intercept_keystrokes(
2377 &mut self,
2378 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2379 ) -> Subscription {
2380 fn inner(
2381 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2382 handler: KeystrokeObserver,
2383 ) -> Subscription {
2384 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2385 activate();
2386 subscription
2387 }
2388
2389 inner(
2390 &self.keystroke_interceptors,
2391 Box::new(move |event, window, cx| {
2392 f(event, window, cx);
2393 true
2394 }),
2395 )
2396 }
2397
2398 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2400 self.keymap.borrow_mut().add_bindings(bindings);
2401 self.pending_effects.push_back(Effect::RefreshWindows);
2402 }
2403
2404 pub fn clear_key_bindings(&mut self) {
2406 self.keymap.borrow_mut().clear();
2407 self.pending_effects.push_back(Effect::RefreshWindows);
2408 }
2409
2410 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2412 self.keymap.clone()
2413 }
2414
2415 pub fn on_action<A: Action>(
2419 &mut self,
2420 listener: impl Fn(&A, &mut Self) + 'static,
2421 ) -> &mut Self {
2422 self.global_action_listeners
2423 .entry(TypeId::of::<A>())
2424 .or_default()
2425 .push(Rc::new(move |action, phase, cx| {
2426 if phase == DispatchPhase::Bubble {
2427 let action = invariant(action.downcast_ref(), "action type must match");
2428 listener(action, cx)
2429 }
2430 }));
2431 self
2432 }
2433
2434 pub fn on_global_action<A: Action>(
2446 &mut self,
2447 action: A,
2448 keystroke: Option<&str>,
2449 handler: impl Fn(&mut Window, &mut App) + 'static,
2450 ) -> &mut Self {
2451 if let Some(keystroke) = keystroke {
2452 self.bind_keys([KeyBinding::new(keystroke, action, None)]);
2453 }
2454 let handler = Arc::new(handler);
2455 self.on_action(move |_: &A, cx: &mut App| {
2456 if let Some(window) = cx.active_window() {
2457 let handler = handler.clone();
2458 cx.spawn(async move |cx| {
2459 _ = window.update(cx, |_, window, cx| handler(window, cx));
2460 })
2461 .detach();
2462 }
2463 })
2464 }
2465
2466 pub fn stop_propagation(&mut self) {
2470 self.propagate_event = false;
2471 }
2472
2473 pub fn propagate(&mut self) {
2478 self.propagate_event = true;
2479 }
2480
2481 pub fn build_action(
2483 &self,
2484 name: &str,
2485 data: Option<serde_json::Value>,
2486 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2487 self.actions.build_action(name, data)
2488 }
2489
2490 pub fn all_action_names(&self) -> &[&'static str] {
2493 self.actions.all_action_names()
2494 }
2495
2496 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2499 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2500 }
2501
2502 pub fn action_schemas(
2504 &self,
2505 generator: &mut schemars::SchemaGenerator,
2506 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2507 self.actions.action_schemas(generator)
2508 }
2509
2510 pub fn action_schema_by_name(
2515 &self,
2516 name: &str,
2517 generator: &mut schemars::SchemaGenerator,
2518 ) -> Option<Option<schemars::Schema>> {
2519 self.actions.action_schema_by_name(name, generator)
2520 }
2521
2522 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2524 self.actions.deprecated_aliases()
2525 }
2526
2527 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2529 self.actions.deprecation_messages()
2530 }
2531
2532 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2534 self.actions.documentation()
2535 }
2536
2537 pub fn on_app_quit<Fut>(
2540 &self,
2541 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2542 ) -> Subscription
2543 where
2544 Fut: 'static + Future<Output = ()>,
2545 {
2546 let (subscription, activate) = self.quit_observers.insert(
2547 (),
2548 Box::new(move |cx| {
2549 let future = on_quit(cx);
2550 future.boxed_local()
2551 }),
2552 );
2553 activate();
2554 subscription
2555 }
2556
2557 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2561 let (subscription, activate) = self.restart_observers.insert(
2562 (),
2563 Box::new(move |cx| {
2564 on_restart(cx);
2565 true
2566 }),
2567 );
2568 activate();
2569 subscription
2570 }
2571
2572 pub fn on_window_closed(
2575 &self,
2576 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2577 ) -> Subscription {
2578 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2579 activate();
2580 subscription
2581 }
2582
2583 pub(crate) fn clear_pending_keystrokes(&mut self) {
2584 for window in self.windows() {
2585 window
2586 .update(self, |_, window, cx| {
2587 if window.pending_input_keystrokes().is_some() {
2588 window.clear_pending_keystrokes();
2589 window.pending_input_changed(cx);
2590 }
2591 })
2592 .ok();
2593 }
2594 }
2595
2596 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2599 let mut action_available = false;
2600 if let Some(window) = self.active_window()
2601 && let Ok(window_action_available) =
2602 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2603 {
2604 action_available = window_action_available;
2605 }
2606
2607 action_available
2608 || self
2609 .global_action_listeners
2610 .contains_key(&action.as_any().type_id())
2611 }
2612
2613 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2620 let menus: Vec<Menu> = menus.into_iter().collect();
2621 self.platform.set_menus(menus, &self.keymap.borrow());
2622 }
2623
2624 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2626 self.platform.get_menus()
2627 }
2628
2629 pub fn on_app_menu_action(&self, mut callback: impl FnMut(&dyn Action, &mut App) + 'static) {
2636 let this = self.this.clone();
2637 self.platform.on_app_menu_action(Box::new(move |action| {
2638 if let Some(app) = this.upgrade() {
2639 callback(action, &mut app.borrow_mut());
2640 }
2641 }));
2642 }
2643
2644 pub fn on_will_open_app_menu(&self, mut callback: impl FnMut(&mut App) + 'static) {
2648 let this = self.this.clone();
2649 self.platform.on_will_open_app_menu(Box::new(move || {
2650 if let Some(app) = this.upgrade() {
2651 callback(&mut app.borrow_mut());
2652 }
2653 }));
2654 }
2655
2656 pub fn on_validate_app_menu_command(
2660 &self,
2661 mut callback: impl FnMut(&dyn Action, &mut App) -> bool + 'static,
2662 ) {
2663 let this = self.this.clone();
2664 self.platform
2665 .on_validate_app_menu_command(Box::new(move |action| match this.upgrade() {
2666 Some(app) => callback(action, &mut app.borrow_mut()),
2667 None => true,
2668 }));
2669 }
2670
2671 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2673 self.platform.set_dock_menu(menus, &self.keymap.borrow())
2674 }
2675
2676 pub fn perform_dock_menu_action(&self, action: usize) {
2678 self.platform.perform_dock_menu_action(action);
2679 }
2680
2681 pub fn add_recent_document(&self, path: &Path) {
2686 self.platform.add_recent_document(path);
2687 }
2688
2689 pub fn update_jump_list(
2692 &self,
2693 menus: Vec<MenuItem>,
2694 entries: Vec<SmallVec<[PathBuf; 2]>>,
2695 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2696 self.platform.update_jump_list(menus, entries)
2697 }
2698
2699 pub fn set_tray(&self, tray: Tray, menus: Option<Vec<MenuItem>>) {
2701 self.platform.set_tray(tray, menus, &self.keymap.borrow())
2702 }
2703
2704 pub fn set_tray_icon(&self, icon: Option<&[u8]>) {
2706 self.platform.set_tray_icon(icon);
2707 }
2708
2709 pub fn set_tray_menu(&self, menu: Vec<TrayMenuItem>) {
2711 self.platform.set_tray_menu(menu);
2712 }
2713
2714 pub fn set_tray_tooltip(&self, tooltip: &str) {
2716 self.platform.set_tray_tooltip(tooltip);
2717 }
2718
2719 pub fn set_tray_panel_mode(&self, enabled: bool) {
2722 self.platform.set_tray_panel_mode(enabled);
2723 }
2724
2725 pub fn show_notification(&self, title: &str, body: &str) -> Result<()> {
2727 self.platform.show_notification(title, body)
2728 }
2729
2730 pub fn push_notification(&self, title: &str, message: &str) -> Result<()> {
2734 self.show_notification(title, message)
2735 }
2736
2737 pub fn tray_icon_bounds(&self) -> Option<Bounds<Pixels>> {
2739 self.platform.get_tray_icon_bounds()
2740 }
2741
2742 pub fn on_tray_icon_event(&self, mut callback: impl FnMut(TrayIconEvent, &mut App) + 'static) {
2744 let this = self.this.clone();
2745 self.platform.on_tray_icon_event(Box::new(move |event| {
2746 if let Some(app) = this.upgrade() {
2747 callback(event, &mut app.borrow_mut());
2748 }
2749 }));
2750 }
2751
2752 pub fn on_tray_menu_action(&self, mut callback: impl FnMut(SharedString, &mut App) + 'static) {
2754 let this = self.this.clone();
2755 self.platform.on_tray_menu_action(Box::new(move |id| {
2756 if let Some(app) = this.upgrade() {
2757 callback(id, &mut app.borrow_mut());
2758 }
2759 }));
2760 }
2761
2762 pub fn set_keep_alive_without_windows(&self, keep_alive: bool) {
2767 self.keep_alive_without_windows.set(keep_alive);
2768 }
2769
2770 pub fn check_permission(&self, kind: PermissionType) -> PermissionStatus {
2775 self.platform.check_permission(kind)
2776 }
2777
2778 pub fn request_permission(&self, kind: PermissionType) {
2780 self.platform.request_permission(kind);
2781 }
2782
2783 pub fn os_info(&self) -> OsInfo {
2785 self.platform.os_info()
2786 }
2787
2788 pub fn system_idle_time(&self) -> Option<Duration> {
2790 self.platform.system_idle_time()
2791 }
2792
2793 pub fn network_status(&self) -> NetworkStatus {
2795 self.platform.network_status()
2796 }
2797
2798 pub fn on_system_power_event(
2804 &self,
2805 mut callback: impl FnMut(SystemPowerEvent, &mut App) + 'static,
2806 ) {
2807 let this = self.this.clone();
2808 self.platform.on_system_power_event(Box::new(move |event| {
2809 if let Some(app) = this.upgrade() {
2810 callback(event, &mut app.borrow_mut());
2811 }
2812 }));
2813 }
2814
2815 pub fn start_power_save_blocker(
2820 &self,
2821 kind: PowerSaveBlockerKind,
2822 ) -> Option<Box<dyn PowerSaveBlocker>> {
2823 self.platform.start_power_save_blocker(kind)
2824 }
2825
2826 pub fn set_auto_launch(&self, app_id: &str, enabled: bool) -> Result<()> {
2828 self.platform.set_auto_launch(app_id, enabled)
2829 }
2830
2831 pub fn is_auto_launch_enabled(&self, app_id: &str) -> bool {
2833 self.platform.is_auto_launch_enabled(app_id)
2834 }
2835
2836 pub fn focused_window_info(&self) -> Option<FocusedWindowInfo> {
2838 self.platform.focused_window_info()
2839 }
2840
2841 pub fn minimize_to_tray(&mut self) {
2845 let windows: Vec<AnyWindowHandle> = self.windows();
2846 for window in windows {
2847 self.update_window(window, |_view, window, _cx| {
2848 window.hide_window();
2849 })
2850 .ok();
2851 }
2852 }
2853
2854 pub fn show_all_windows(&mut self) {
2856 let windows: Vec<AnyWindowHandle> = self.windows();
2857 for window in windows {
2858 self.update_window(window, |_view, window, _cx| {
2859 window.activate_window();
2860 })
2861 .ok();
2862 }
2863 }
2864
2865 pub fn hide_all_windows(&mut self) {
2867 let windows: Vec<AnyWindowHandle> = self.windows();
2868 for window in windows {
2869 self.update_window(window, |_view, window, _cx| {
2870 window.hide_window();
2871 })
2872 .ok();
2873 }
2874 }
2875
2876 pub fn minimize_all_windows(&mut self) {
2878 let windows: Vec<AnyWindowHandle> = self.windows();
2879 for window in windows {
2880 self.update_window(window, |_view, window, _cx| {
2881 window.minimize_window();
2882 })
2883 .ok();
2884 }
2885 }
2886
2887 pub fn register_global_hotkey(&self, id: u32, keystroke: &Keystroke) -> Result<()> {
2896 self.platform.register_global_hotkey(id, keystroke)
2897 }
2898
2899 pub fn unregister_global_hotkey(&self, id: u32) {
2904 self.platform.unregister_global_hotkey(id);
2905 }
2906
2907 pub fn on_global_hotkey(&self, mut callback: impl FnMut(u32, &mut App) + 'static) {
2909 let this = self.this.clone();
2910 self.platform.on_global_hotkey(Box::new(move |id| {
2911 if let Some(app) = this.upgrade() {
2912 callback(id, &mut app.borrow_mut());
2913 }
2914 }));
2915 }
2916
2917 pub fn dispatch_action(&mut self, action: &dyn Action) {
2920 let window = self.active_window().or_else(|| self.first_window_handle());
2923
2924 if let Some(window) = window {
2925 let dispatched = window
2926 .update(self, |_, window, cx| window.dispatch_action_now(action, cx))
2927 .is_ok();
2928
2929 if dispatched {
2930 return;
2931 }
2932
2933 let action = action.boxed_clone();
2937 self.defer(move |cx| {
2938 let window = cx.active_window().or_else(|| cx.first_window_handle());
2939 if let Some(window) = window {
2940 window
2941 .update(cx, |_, window, cx| {
2942 window.dispatch_action_now(action.as_ref(), cx)
2943 })
2944 .log_err();
2945 } else {
2946 cx.dispatch_global_action(action.as_ref());
2947 }
2948 });
2949 } else {
2950 self.dispatch_global_action(action);
2951 }
2952 }
2953
2954 fn first_window_handle(&self) -> Option<AnyWindowHandle> {
2956 self.windows
2957 .values()
2958 .flatten()
2959 .next()
2960 .map(|window| window.handle)
2961 }
2962
2963 fn dispatch_global_action(&mut self, action: &dyn Action) {
2964 self.propagate_event = true;
2965
2966 if let Some(mut global_listeners) = self
2967 .global_action_listeners
2968 .remove(&action.as_any().type_id())
2969 {
2970 for listener in &global_listeners {
2971 listener(action.as_any(), DispatchPhase::Capture, self);
2972 if !self.propagate_event {
2973 break;
2974 }
2975 }
2976
2977 global_listeners.extend(
2978 self.global_action_listeners
2979 .remove(&action.as_any().type_id())
2980 .unwrap_or_default(),
2981 );
2982
2983 self.global_action_listeners
2984 .insert(action.as_any().type_id(), global_listeners);
2985 }
2986
2987 if self.propagate_event
2988 && let Some(mut global_listeners) = self
2989 .global_action_listeners
2990 .remove(&action.as_any().type_id())
2991 {
2992 for listener in global_listeners.iter().rev() {
2993 listener(action.as_any(), DispatchPhase::Bubble, self);
2994 if !self.propagate_event {
2995 break;
2996 }
2997 }
2998
2999 global_listeners.extend(
3000 self.global_action_listeners
3001 .remove(&action.as_any().type_id())
3002 .unwrap_or_default(),
3003 );
3004
3005 self.global_action_listeners
3006 .insert(action.as_any().type_id(), global_listeners);
3007 }
3008 }
3009
3010 pub fn has_active_drag(&self) -> bool {
3012 self.active_drag.is_some()
3013 }
3014
3015 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3017 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3018 }
3019
3020 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3022 if self.active_drag.is_some() {
3023 self.active_drag = None;
3024 window.refresh();
3025 true
3026 } else {
3027 false
3028 }
3029 }
3030
3031 pub fn take_active_drag_value(&mut self) -> Option<Arc<dyn std::any::Any>> {
3033 self.active_drag.take().map(|drag| drag.value)
3034 }
3035
3036 pub fn set_active_drag_cursor_style(
3038 &mut self,
3039 cursor_style: CursorStyle,
3040 window: &mut Window,
3041 ) -> bool {
3042 if let Some(ref mut drag) = self.active_drag {
3043 drag.cursor_style = Some(cursor_style);
3044 window.refresh();
3045 true
3046 } else {
3047 false
3048 }
3049 }
3050
3051 pub fn set_prompt_builder(
3053 &mut self,
3054 renderer: impl Fn(
3055 PromptLevel,
3056 &str,
3057 Option<&str>,
3058 &[PromptButton],
3059 PromptHandle,
3060 &mut Window,
3061 &mut App,
3062 ) -> RenderablePromptHandle
3063 + 'static,
3064 ) {
3065 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3066 }
3067
3068 pub fn reset_prompt_builder(&mut self) {
3070 self.prompt_builder = Some(PromptBuilder::Default);
3071 }
3072
3073 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3075 let asset_id = (TypeId::of::<A>(), hash(source));
3076 self.loading_assets.remove(&asset_id);
3077 }
3078
3079 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
3084 let asset_id = (TypeId::of::<A>(), hash(source));
3085 let mut is_first = false;
3086 let task = self
3087 .loading_assets
3088 .remove(&asset_id)
3089 .map(|boxed_task| {
3090 *invariant_result(
3091 boxed_task.downcast::<Shared<Task<A::Output>>>(),
3092 "asset task type must match",
3093 )
3094 })
3095 .unwrap_or_else(|| {
3096 is_first = true;
3097 let future = A::load(source.clone(), self);
3098
3099 self.background_executor().spawn(future).shared()
3100 });
3101
3102 self.loading_assets.insert(asset_id, Box::new(task.clone()));
3103
3104 (task, is_first)
3105 }
3106
3107 #[track_caller]
3110 pub fn focus_handle(&self) -> FocusHandle {
3111 FocusHandle::new(&self.focus_handles)
3112 }
3113
3114 pub fn notify(&mut self, entity_id: EntityId) {
3116 let window_invalidators = mem::take(
3117 self.window_invalidators_by_entity
3118 .entry(entity_id)
3119 .or_default(),
3120 );
3121
3122 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3127 .iter()
3128 .filter(|(window_id, _)| {
3129 self.tracked_entities
3130 .get(window_id)
3131 .is_some_and(|set| set.contains(&entity_id))
3132 })
3133 .map(|(_, invalidator)| invalidator.clone())
3134 .collect();
3135
3136 if live_invalidators.is_empty() {
3137 if self.pending_notifications.insert(entity_id) {
3138 self.pending_effects
3139 .push_back(Effect::Notify { emitter: entity_id });
3140 }
3141 } else {
3142 for invalidator in &live_invalidators {
3143 invalidator.invalidate_view(entity_id, self);
3144 }
3145 }
3146
3147 self.window_invalidators_by_entity
3148 .insert(entity_id, window_invalidators);
3149 }
3150
3151 #[cfg(any(test, feature = "test-support", debug_assertions))]
3153 pub fn get_name(&self) -> Option<&'static str> {
3154 self.name
3155 }
3156
3157 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3159 self.platform.can_select_mixed_files_and_dirs()
3160 }
3161
3162 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3167 for window in self.windows.values_mut().flatten() {
3169 _ = window.drop_image(image.clone());
3170 }
3171
3172 if let Some(window) = current_window {
3174 _ = window.drop_image(image);
3175 }
3176 }
3177
3178 #[cfg(any(feature = "inspector", debug_assertions))]
3180 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3181 self.inspector_renderer = Some(f);
3182 }
3183
3184 #[cfg(any(feature = "inspector", debug_assertions))]
3186 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
3187 &mut self,
3188 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3189 ) {
3190 self.inspector_element_registry.register(f);
3191 }
3192
3193 #[cfg(any(feature = "inspector", debug_assertions))]
3201 pub fn enable_default_inspector(&mut self) {
3202 self.set_inspector_renderer(Box::new(crate::inspector_panel::default_inspector_panel));
3203 self.register_inspector_element(crate::inspector_panel::render_div_inspector_state);
3204 }
3205
3206 pub fn report_error(&mut self, message: impl Into<SharedString>) {
3211 const CAP: usize = 50;
3212 if self.recent_errors.len() >= CAP {
3213 self.recent_errors.pop_front();
3214 }
3215 let seq = self.error_seq;
3216 self.error_seq += 1;
3217 self.recent_errors.push_back((seq, message.into()));
3218 }
3219
3220 pub fn recent_errors(&self) -> Vec<(u64, SharedString)> {
3222 self.recent_errors.iter().cloned().collect()
3223 }
3224
3225 pub fn enable_crash_recorder(&mut self, dir: impl Into<std::path::PathBuf>) {
3231 self.crash_recorder_dir = Some(dir.into());
3232 }
3233
3234 #[cfg(any(feature = "inspector", debug_assertions))]
3239 pub fn set_inspector_panel_slots(
3240 &mut self,
3241 slots: crate::inspector_panel::InspectorPanelSlots,
3242 ) {
3243 self.set_global(slots);
3244 }
3245
3246 pub fn init_colors(&mut self) {
3250 self.set_global(GlobalColors(Arc::new(Colors::default())));
3251 }
3252}
3253
3254impl AppContext for App {
3255 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3260 self.update(|cx| {
3261 let slot = cx.entities.reserve();
3262 let handle = slot.clone();
3263 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3264
3265 cx.push_effect(Effect::EntityCreated {
3266 entity: handle.into_any(),
3267 tid: TypeId::of::<T>(),
3268 window: cx.window_update_stack.last().cloned(),
3269 });
3270
3271 cx.entities.insert(slot, entity)
3272 })
3273 }
3274
3275 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3276 Reservation(self.entities.reserve())
3277 }
3278
3279 fn insert_entity<T: 'static>(
3280 &mut self,
3281 reservation: Reservation<T>,
3282 build_entity: impl FnOnce(&mut Context<T>) -> T,
3283 ) -> Entity<T> {
3284 self.update(|cx| {
3285 let slot = reservation.0;
3286 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3287 cx.entities.insert(slot, entity)
3288 })
3289 }
3290
3291 fn update_entity<T: 'static, R>(
3293 &mut self,
3294 handle: &Entity<T>,
3295 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3296 ) -> R {
3297 self.update(|cx| {
3298 let mut entity = cx.entities.lease(handle);
3299 let result = update(
3300 &mut entity,
3301 &mut Context::new_context(cx, handle.downgrade()),
3302 );
3303 cx.entities.end_lease(entity);
3304 result
3305 })
3306 }
3307
3308 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3309 where
3310 T: 'static,
3311 {
3312 GpuiBorrow::new(handle.clone(), self)
3313 }
3314
3315 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3316 where
3317 T: 'static,
3318 {
3319 let entity = self.entities.read(handle);
3320 read(entity, self)
3321 }
3322
3323 #[track_caller]
3324 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3325 where
3326 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3327 {
3328 self.update_window_id(handle.id, update)
3329 }
3330
3331 fn with_window<R>(
3332 &mut self,
3333 entity_id: EntityId,
3334 f: impl FnOnce(&mut Window, &mut App) -> R,
3335 ) -> Option<R> {
3336 App::with_window(self, entity_id, f)
3337 }
3338
3339 fn read_window<T, R>(
3340 &self,
3341 window: &WindowHandle<T>,
3342 read: impl FnOnce(Entity<T>, &App) -> R,
3343 ) -> Result<R>
3344 where
3345 T: 'static,
3346 {
3347 let window = self
3348 .windows
3349 .get(window.id)
3350 .context("window not found")?
3351 .as_deref();
3352 let window = invariant(
3353 window,
3354 "attempted to read a window that is already on the stack",
3355 );
3356
3357 let root_view = invariant(window.root.clone(), "window must have a root view");
3358 let view = Root::root_view_downcast::<T>(root_view, self)
3359 .map_err(|_| anyhow!("root view's type has changed"))?;
3360
3361 Ok(read(view, self))
3362 }
3363
3364 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3365 where
3366 R: Send + 'static,
3367 {
3368 self.background_executor.spawn(future)
3369 }
3370
3371 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3372 where
3373 G: Global,
3374 {
3375 let mut g = self.global::<G>();
3376 callback(g, self)
3377 }
3378}
3379
3380pub(crate) enum Effect {
3382 Notify {
3383 emitter: EntityId,
3384 },
3385 Emit {
3386 emitter: EntityId,
3387 event_type: TypeId,
3388 event: ArenaBox<dyn Any>,
3389 },
3390 RefreshWindows,
3391 NotifyGlobalObservers {
3392 global_type: TypeId,
3393 },
3394 Defer {
3395 callback: Box<dyn FnOnce(&mut App) + 'static>,
3396 },
3397 EntityCreated {
3398 entity: AnyEntity,
3399 tid: TypeId,
3400 window: Option<WindowId>,
3401 },
3402}
3403
3404impl std::fmt::Debug for Effect {
3405 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3406 match self {
3407 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3408 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3409 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3410 Effect::NotifyGlobalObservers { global_type } => {
3411 write!(f, "NotifyGlobalObservers({:?})", global_type)
3412 }
3413 Effect::Defer { .. } => write!(f, "Defer(..)"),
3414 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3415 }
3416 }
3417}
3418
3419pub(crate) struct GlobalLease<G: Global> {
3421 global: Box<dyn Any>,
3422 global_type: PhantomData<G>,
3423}
3424
3425impl<G: Global> GlobalLease<G> {
3426 fn new(global: Box<dyn Any>) -> Self {
3427 GlobalLease {
3428 global,
3429 global_type: PhantomData,
3430 }
3431 }
3432}
3433
3434impl<G: Global> Deref for GlobalLease<G> {
3435 type Target = G;
3436
3437 fn deref(&self) -> &Self::Target {
3438 invariant(self.global.downcast_ref(), "global type must match")
3439 }
3440}
3441
3442impl<G: Global> DerefMut for GlobalLease<G> {
3443 fn deref_mut(&mut self) -> &mut Self::Target {
3444 invariant(self.global.downcast_mut(), "global type must match")
3445 }
3446}
3447
3448pub struct AnyDrag {
3451 pub view: AnyView,
3453
3454 pub value: Arc<dyn Any>,
3456
3457 pub cursor_offset: Point<Pixels>,
3459
3460 pub cursor_style: Option<CursorStyle>,
3462}
3463
3464#[derive(Clone)]
3467pub struct AnyTooltip {
3468 pub view: AnyView,
3470
3471 pub mouse_position: Point<Pixels>,
3473
3474 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3478}
3479
3480#[derive(Debug)]
3482pub struct KeystrokeEvent {
3483 pub keystroke: Keystroke,
3485
3486 pub action: Option<Box<dyn Action>>,
3488
3489 pub context_stack: Vec<KeyContext>,
3491}
3492
3493struct NullHttpClient;
3494
3495impl HttpClient for NullHttpClient {
3496 fn send(
3497 &self,
3498 _req: crate::http_client::Request<crate::http_client::AsyncBody>,
3499 ) -> futures::future::BoxFuture<
3500 'static,
3501 anyhow::Result<crate::http_client::Response<crate::http_client::AsyncBody>>,
3502 > {
3503 async move {
3504 anyhow::bail!("No HttpClient available");
3505 }
3506 .boxed()
3507 }
3508
3509 fn user_agent(&self) -> Option<&crate::http_client::http::HeaderValue> {
3510 None
3511 }
3512
3513 fn proxy(&self) -> Option<&Url> {
3514 None
3515 }
3516}
3517
3518pub struct GpuiBorrow<'a, T> {
3520 inner: Option<Lease<T>>,
3521 app: &'a mut App,
3522}
3523
3524impl<'a, T: 'static> GpuiBorrow<'a, T> {
3525 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3526 app.start_update();
3527 let lease = app.entities.lease(&inner);
3528 Self {
3529 inner: Some(lease),
3530 app,
3531 }
3532 }
3533}
3534
3535impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3536 fn borrow(&self) -> &T {
3537 let lease: &Lease<T> = invariant(self.inner.as_ref(), "borrow must be alive");
3539 lease
3540 }
3541}
3542
3543impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3544 fn borrow_mut(&mut self) -> &mut T {
3545 let lease: &mut Lease<T> = invariant(self.inner.as_mut(), "borrow must be alive");
3547 lease
3548 }
3549}
3550
3551impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3552 type Target = T;
3553
3554 fn deref(&self) -> &Self::Target {
3555 let lease: &Lease<T> = invariant(self.inner.as_ref(), "borrow must be alive");
3557 lease
3558 }
3559}
3560
3561impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3562 fn deref_mut(&mut self) -> &mut T {
3563 let lease: &mut Lease<T> = invariant(self.inner.as_mut(), "borrow must be alive");
3565 lease
3566 }
3567}
3568
3569impl<'a, T> Drop for GpuiBorrow<'a, T> {
3570 fn drop(&mut self) {
3571 let lease = invariant(self.inner.take(), "borrow must be alive");
3572 self.app.notify(lease.id);
3573 self.app.entities.end_lease(lease);
3574 self.app.finish_update();
3575 }
3576}
3577
3578#[cfg(test)]
3579mod test {
3580 use std::{cell::RefCell, rc::Rc};
3581
3582 use crate::{AppContext, TestAppContext};
3583
3584 #[test]
3585 fn test_gpui_borrow() {
3586 let cx = TestAppContext::single();
3587 let observation_count = Rc::new(RefCell::new(0));
3588
3589 let state = cx.update(|cx| {
3590 let state = cx.new(|_| false);
3591 cx.observe(&state, {
3592 let observation_count = observation_count.clone();
3593 move |_, _| {
3594 let mut count = observation_count.borrow_mut();
3595 *count += 1;
3596 }
3597 })
3598 .detach();
3599
3600 state
3601 });
3602
3603 cx.update(|cx| {
3604 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3606 });
3607
3608 cx.update(|cx| {
3609 state.write(cx, false);
3610 });
3611
3612 assert_eq!(*observation_count.borrow(), 2);
3613 }
3614}