1use scheduler::Instant;
2use std::{
3 any::{TypeId, type_name},
4 cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
5 ffi::OsString,
6 marker::PhantomData,
7 mem,
8 ops::{Deref, DerefMut},
9 path::{Path, PathBuf},
10 rc::{Rc, Weak},
11 sync::{Arc, atomic::Ordering::SeqCst},
12 time::Duration,
13};
14
15use anyhow::{Context as _, Result, anyhow};
16use derive_more::{Deref, DerefMut};
17use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
18use itertools::Itertools;
19use parking_lot::RwLock;
20use slotmap::SlotMap;
21
22pub use async_context::*;
23#[cfg(feature = "bench-support")]
24pub use bench_context::{
25 BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
26 MetricReport, bench_platform,
27};
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::asset_cache::CachedLoad;
46use crate::{
47 Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
48 AnyWindowHandle, AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds,
49 ClipboardItem, ClipboardReadError, CursorStyle, DefaultTextSystem, DispatchPhase,
50 DisplayChanges, DisplayEvent, DisplayId, DmaBufCapabilities, EventEmitter, ExternalDragPayload,
51 FocusHandle, FocusMap, ForegroundExecutor, FramePipeline, Global, GpuAdapterInfo, KeyBinding,
52 KeyContext, Keymap, Keystroke, LayoutEngine, LayoutId, Menu, MenuCommandId, MenuItem,
53 MissingGlyph, OwnedMenu, OwnedMenuItem, PathPromptOptions, Pixels, Platform, PlatformDisplay,
54 PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
55 PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
56 ScreenCaptureSource, SharedString, StandardImmediatePipeline, SubscriberSet, Subscription,
57 SvgRenderer, SystemNotification, SystemNotificationResponse, SystemWindowTab, Task,
58 TextRenderingMode, TextSystem, ThermalState, Window, WindowAppearance, WindowButtonLayout,
59 WindowHandle, WindowHost, WindowId, WindowInvalidator, WindowingRequest,
60 colors::{Colors, GlobalColors},
61 hash, init_app_menus, resolve_dock_menu, resolve_menus,
62};
63
64mod async_context;
65#[cfg(feature = "bench-support")]
66mod bench_context;
67mod context;
68mod entity_map;
69#[cfg(any(test, feature = "test-support"))]
70mod headless_app_context;
71#[cfg(any(test, feature = "test-support"))]
72mod test_app;
73#[cfg(any(test, feature = "test-support"))]
74mod test_context;
75#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
76mod visual_test_context;
77
78pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
81
82pub(crate) type WindowCell = Rc<RefCell<WindowHost>>;
85
86#[derive(Default)]
97pub(crate) struct WindowRegistry {
98 hosts: SlotMap<WindowId, Option<WindowCell>>,
99}
100
101impl WindowRegistry {
102 pub(crate) fn reserve(&mut self) -> WindowId {
104 self.hosts.insert(None)
105 }
106
107 pub(crate) fn register(&mut self, id: WindowId, host: WindowHost) {
109 if let Some(slot) = self.hosts.get_mut(id) {
110 *slot = Some(Rc::new(RefCell::new(host)));
111 }
112 }
113
114 pub(crate) fn cell(&self, id: WindowId) -> Option<WindowCell> {
116 self.hosts.get(id).and_then(|slot| slot.clone())
117 }
118
119 pub(crate) fn remove(&mut self, id: WindowId) {
120 self.hosts.remove(id);
121 }
122
123 pub(crate) fn clear(&mut self) {
125 self.hosts.clear();
126 }
127
128 pub(crate) fn ids(&self) -> impl Iterator<Item = WindowId> + '_ {
130 self.hosts.keys()
131 }
132
133 pub(crate) fn is_empty(&self) -> bool {
134 self.hosts.is_empty()
135 }
136
137 pub(crate) fn cells(&self) -> impl Iterator<Item = &WindowCell> {
139 self.hosts.values().filter_map(|slot| slot.as_ref())
140 }
141}
142
143#[doc(hidden)]
146pub struct AppCell {
147 app: RefCell<App>,
148}
149
150impl AppCell {
151 #[doc(hidden)]
152 #[track_caller]
153 pub fn borrow(&self) -> AppRef<'_> {
154 if option_env!("TRACK_THREAD_BORROWS").is_some() {
155 let thread_id = std::thread::current().id();
156 eprintln!("borrowed {thread_id:?}");
157 }
158 AppRef(self.app.borrow())
159 }
160
161 #[doc(hidden)]
162 #[track_caller]
163 pub fn borrow_mut(&self) -> AppRefMut<'_> {
164 if option_env!("TRACK_THREAD_BORROWS").is_some() {
165 let thread_id = std::thread::current().id();
166 eprintln!("borrowed {thread_id:?}");
167 }
168 AppRefMut(self.app.borrow_mut())
169 }
170
171 #[doc(hidden)]
172 #[track_caller]
173 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
174 if option_env!("TRACK_THREAD_BORROWS").is_some() {
175 let thread_id = std::thread::current().id();
176 eprintln!("borrowed {thread_id:?}");
177 }
178 Ok(AppRefMut(self.app.try_borrow_mut()?))
179 }
180}
181
182#[doc(hidden)]
183#[derive(Deref, DerefMut)]
184pub struct AppRef<'a>(Ref<'a, App>);
185
186impl Drop for AppRef<'_> {
187 fn drop(&mut self) {
188 if option_env!("TRACK_THREAD_BORROWS").is_some() {
189 let thread_id = std::thread::current().id();
190 eprintln!("dropped borrow from {thread_id:?}");
191 }
192 }
193}
194
195#[doc(hidden)]
196#[derive(Deref, DerefMut)]
197pub struct AppRefMut<'a>(RefMut<'a, App>);
198
199impl Drop for AppRefMut<'_> {
200 fn drop(&mut self) {
201 if option_env!("TRACK_THREAD_BORROWS").is_some() {
202 let thread_id = std::thread::current().id();
203 eprintln!("dropped {thread_id:?}");
204 }
205 }
206}
207
208type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
209type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
210
211#[derive(Clone, Copy, PartialEq)]
213struct DisplayState {
214 bounds: Bounds<Pixels>,
215 refresh_interval: Option<Duration>,
216}
217
218impl DisplayState {
219 fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
220 let mut changes = DisplayChanges::empty();
221 changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
222 changes.set(
223 DisplayChanges::REFRESH_INTERVAL,
224 self.refresh_interval != previous.refresh_interval,
225 );
226 changes
227 }
228}
229
230fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
231 platform
232 .displays()
233 .into_iter()
234 .map(|display| {
235 let state = DisplayState {
236 bounds: display.bounds(),
237 refresh_interval: display.refresh_interval(),
238 };
239 (display.id(), state)
240 })
241 .collect()
242}
243
244fn display_events(
246 previous: &HashMap<DisplayId, DisplayState>,
247 current: &HashMap<DisplayId, DisplayState>,
248) -> Vec<DisplayEvent> {
249 let removed = previous
250 .keys()
251 .filter(|id| !current.contains_key(id))
252 .map(|id| DisplayEvent::Removed(*id));
253 let added_or_changed = current.iter().filter_map(|(id, state)| {
254 let Some(previous_state) = previous.get(id) else {
255 return Some(DisplayEvent::Added(*id));
256 };
257 let changes = state.changes_from(previous_state);
258 (!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
259 });
260 removed.chain(added_or_changed).collect()
261}
262type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
263type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
264pub(crate) type KeystrokeObserver =
265 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
266type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
267type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
268type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
269type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
270
271struct MissingGlyphCallbackEntry {
272 registration: Rc<()>,
273 callback: Option<MissingGlyphCallback>,
274}
275
276#[derive(Default)]
277struct MissingGlyphCallbackSlot {
278 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
279}
280
281impl MissingGlyphCallbackSlot {
282 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
283 let registration = Rc::new(());
284 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
285 registration: registration.clone(),
286 callback: Some(callback),
287 });
288 registration
289 }
290
291 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
292 let Some((registration, mut callback)) =
293 self.entry.borrow_mut().as_mut().and_then(|entry| {
294 entry
295 .callback
296 .take()
297 .map(|callback| (entry.registration.clone(), callback))
298 })
299 else {
300 return;
301 };
302 callback(missing_glyphs, cx);
303
304 let mut entry = self.entry.borrow_mut();
305 let is_current = entry
306 .as_ref()
307 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
308 if is_current {
309 let Some(entry) = entry.as_mut() else {
310 return;
311 };
312 entry.callback = Some(callback);
313 }
314 }
315
316 fn remove(&self, registration: &Rc<()>) -> bool {
317 let mut entry = self.entry.borrow_mut();
318 let is_current = entry
319 .as_ref()
320 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
321 if is_current {
322 entry.take();
323 }
324 is_current
325 }
326}
327
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
330pub enum QuitMode {
331 #[default]
333 Default,
334 LastWindowClosed,
336 Explicit,
338}
339
340#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
345pub enum CursorHideMode {
346 Never,
348 OnTyping,
350 #[default]
353 OnTypingAndAction,
354}
355
356#[derive(Default)]
358pub struct SystemWindowTabController {
359 visible: Option<bool>,
360 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
361}
362
363impl Global for SystemWindowTabController {}
364
365impl SystemWindowTabController {
366 pub fn new() -> Self {
368 Self {
369 visible: None,
370 tab_groups: FxHashMap::default(),
371 }
372 }
373
374 pub fn init(cx: &mut App) {
376 cx.set_global(SystemWindowTabController::new());
377 }
378
379 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
381 &self.tab_groups
382 }
383
384 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<AnyWindowHandle> {
386 let controller = cx.global::<SystemWindowTabController>();
387 let current_group = controller
388 .tab_groups
389 .iter()
390 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
391
392 let current_group = current_group?;
393 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
395 let idx = group_ids.iter().position(|g| *g == current_group)?;
396 let next_idx = (idx + 1) % group_ids.len();
397
398 let tab_handle = controller
399 .tab_groups
400 .get(group_ids[next_idx])
401 .and_then(|tabs| {
402 tabs.iter()
403 .max_by_key(|tab| tab.last_active_at)
404 .or_else(|| tabs.first())
405 .map(|tab| tab.handle)
406 })?;
407 cx.window_handle(tab_handle)
408 }
409
410 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<AnyWindowHandle> {
412 let controller = cx.global::<SystemWindowTabController>();
413 let current_group = controller
414 .tab_groups
415 .iter()
416 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
417
418 let current_group = current_group?;
419 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
421 let idx = group_ids.iter().position(|g| *g == current_group)?;
422 let prev_idx = if idx == 0 {
423 group_ids.len() - 1
424 } else {
425 idx - 1
426 };
427
428 let tab_handle = controller
429 .tab_groups
430 .get(group_ids[prev_idx])
431 .and_then(|tabs| {
432 tabs.iter()
433 .max_by_key(|tab| tab.last_active_at)
434 .or_else(|| tabs.first())
435 .map(|tab| tab.handle)
436 })?;
437 cx.window_handle(tab_handle)
438 }
439
440 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
442 self.tab_groups
443 .values()
444 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
445 }
446
447 pub fn init_visible(cx: &mut App, visible: bool) {
449 let mut controller = cx.global_mut::<SystemWindowTabController>();
450 if controller.visible.is_none() {
451 controller.visible = Some(visible);
452 }
453 }
454
455 pub fn is_visible(&self) -> bool {
457 self.visible.unwrap_or(false)
458 }
459
460 pub fn set_visible(cx: &mut App, visible: bool) {
462 let mut controller = cx.global_mut::<SystemWindowTabController>();
463 controller.visible = Some(visible);
464 }
465
466 pub fn update_last_active(cx: &mut App, id: WindowId) {
468 let mut controller = cx.global_mut::<SystemWindowTabController>();
469 for windows in controller.tab_groups.values_mut() {
470 for tab in windows.iter_mut() {
471 if tab.id == id {
472 tab.last_active_at = Instant::now();
473 }
474 }
475 }
476 }
477
478 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
480 let mut controller = cx.global_mut::<SystemWindowTabController>();
481 for (_, windows) in controller.tab_groups.iter_mut() {
482 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
483 if ix < windows.len() && current_pos != ix {
484 let window_tab = windows.remove(current_pos);
485 windows.insert(ix, window_tab);
486 }
487 break;
488 }
489 }
490 }
491
492 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
494 let controller = cx.global::<SystemWindowTabController>();
495 let tab = controller
496 .tab_groups
497 .values()
498 .flat_map(|windows| windows.iter())
499 .find(|tab| tab.id == id);
500
501 if tab.map_or(true, |t| t.title == title) {
502 return;
503 }
504
505 let mut controller = cx.global_mut::<SystemWindowTabController>();
506 for windows in controller.tab_groups.values_mut() {
507 for tab in windows.iter_mut() {
508 if tab.id == id {
509 tab.title = title;
510 return;
511 }
512 }
513 }
514 }
515
516 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
518 let mut controller = cx.global_mut::<SystemWindowTabController>();
519 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
520 return;
521 };
522
523 let mut expected_tab_ids: Vec<_> = tabs
524 .iter()
525 .filter(|tab| tab.id != id)
526 .map(|tab| tab.id)
527 .sorted()
528 .collect();
529
530 let mut tab_group_id = None;
531 for (group_id, group_tabs) in &controller.tab_groups {
532 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
533 if tab_ids == expected_tab_ids {
534 tab_group_id = Some(*group_id);
535 break;
536 }
537 }
538
539 if let Some(tab_group_id) = tab_group_id {
540 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
541 tabs.push(tab);
542 }
543 } else {
544 let new_group_id = controller.tab_groups.len();
545 controller.tab_groups.insert(new_group_id, tabs);
546 }
547 }
548
549 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
551 let mut controller = cx.global_mut::<SystemWindowTabController>();
552 let mut removed_tab = None;
553
554 controller.tab_groups.retain(|_, tabs| {
555 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
556 removed_tab = Some(tabs.remove(pos));
557 }
558 !tabs.is_empty()
559 });
560
561 removed_tab
562 }
563
564 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
566 let mut removed_tab = Self::remove_tab(cx, id);
567 let mut controller = cx.global_mut::<SystemWindowTabController>();
568
569 if let Some(tab) = removed_tab {
570 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
571 controller.tab_groups.insert(new_group_id, vec![tab]);
572 }
573 }
574
575 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
577 let mut controller = cx.global_mut::<SystemWindowTabController>();
578 let Some(initial_tabs) = controller.tabs(id) else {
579 return;
580 };
581
582 let initial_tabs_len = initial_tabs.len();
583 let mut all_tabs = initial_tabs.clone();
584
585 for (_, mut tabs) in controller.tab_groups.drain() {
586 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
587 all_tabs.extend(tabs);
588 }
589
590 controller.tab_groups.insert(0, all_tabs);
591 }
592
593 pub fn select_next_tab(cx: &mut App, id: WindowId) {
595 let next_handle = {
596 let controller = cx.global::<SystemWindowTabController>();
597 let Some(tabs) = controller.tabs(id) else {
598 return;
599 };
600
601 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
602 let next_index = (current_index + 1) % tabs.len();
603 tabs[next_index].handle
604 };
605
606 if let Some(handle) = cx.window_handle(next_handle) {
607 let _ = handle.update(cx, |_, window, _| {
608 window.activate_window();
609 });
610 }
611 }
612
613 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
615 let previous_handle = {
616 let controller = cx.global::<SystemWindowTabController>();
617 let Some(tabs) = controller.tabs(id) else {
618 return;
619 };
620
621 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
622 let previous_index = if current_index == 0 {
623 tabs.len() - 1
624 } else {
625 current_index - 1
626 };
627 tabs[previous_index].handle
628 };
629
630 if let Some(handle) = cx.window_handle(previous_handle) {
631 let _ = handle.update(cx, |_, window, _| {
632 window.activate_window();
633 });
634 }
635 }
636}
637
638pub(crate) enum GpuiMode {
639 #[cfg(any(test, feature = "test-support"))]
640 Test {
641 skip_drawing: bool,
642 },
643 Production,
644}
645
646impl GpuiMode {
647 #[cfg(any(test, feature = "test-support"))]
648 pub fn test() -> Self {
649 GpuiMode::Test {
650 skip_drawing: false,
651 }
652 }
653
654 #[inline]
655 pub(crate) fn skip_drawing(&self) -> bool {
656 match self {
657 #[cfg(any(test, feature = "test-support"))]
658 GpuiMode::Test { skip_drawing } => *skip_drawing,
659 GpuiMode::Production => false,
660 }
661 }
662}
663
664struct PlatformOwnedDrag {
665 source_window: WindowId,
666 state: PlatformOwnedDragState,
667}
668
669enum PlatformOwnedDragState {
670 Suspended(AnyDrag),
671 RestoredInSourceWindow,
674}
675
676pub struct App {
680 pub(crate) this: Weak<AppCell>,
681 pub(crate) platform: Rc<dyn Platform>,
682 text_system: Arc<dyn TextSystem>,
683 layout_engine_factory: Rc<dyn Fn() -> Box<dyn LayoutEngine>>,
687 frame_pipeline_factory: Rc<dyn Fn(WindowId) -> Box<dyn FramePipeline>>,
691
692 pub(crate) actions: Rc<ActionRegistry>,
693 pub(crate) active_drag: Option<AnyDrag>,
694 platform_owned_drag: Option<PlatformOwnedDrag>,
695 pub(crate) background_executor: BackgroundExecutor,
696 pub(crate) foreground_executor: ForegroundExecutor,
697 #[cfg(feature = "profiler")]
698 foreground_journal: crate::profiler::journal::ForegroundJournal,
699 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
700 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
701 pub(crate) entities: EntityMap,
702 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
703 pub(crate) windows: WindowRegistry,
704 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
705 pub(crate) focus_handles: Arc<FocusMap>,
706 pub(crate) keymap: Rc<RefCell<Keymap>>,
707 pub(crate) menu_actions: Rc<RefCell<Vec<Box<dyn Action>>>>,
708 owned_menus: Rc<RefCell<Option<Vec<OwnedMenu>>>>,
709 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
710 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
711 pub(crate) global_action_listeners:
712 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
713 pending_effects: VecDeque<Effect>,
714
715 pub(crate) observers: SubscriberSet<EntityId, Handler>,
716 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
717 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
718 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
719 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
720 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
721 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
722 pub(crate) display_observers: SubscriberSet<(), DisplayHandler>,
723 displays: HashMap<DisplayId, DisplayState>,
726 pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
727 pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
728 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
729 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
730 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
731 pub(crate) restart_observers: SubscriberSet<(), Handler>,
732 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
733
734 pub(crate) element_arena: RefCell<Arena>,
737 pub(crate) event_arena: Arena,
739
740 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
745
746 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
748 asset_source: Arc<dyn AssetSource>,
749 pub(crate) svg_renderer: SvgRenderer,
750 http_client: Arc<dyn HttpClient>,
751
752 pub(crate) pending_notifications: FxHashSet<EntityId>,
754 pub(crate) pending_global_notifications: TypeIdHashSet,
755 pub(crate) restart_path: Option<PathBuf>,
756 pub(crate) restart_arguments: Vec<OsString>,
757 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
759 pub(crate) prompt_builder: Option<PromptBuilder>,
760 pub(crate) window_invalidators_by_entity:
761 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
762 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
763 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
764 #[cfg(any(feature = "inspector", debug_assertions))]
765 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
766 #[cfg(any(feature = "inspector", debug_assertions))]
767 pub(crate) inspector_element_registry: InspectorElementRegistry,
768 #[cfg(any(test, feature = "test-support", debug_assertions))]
769 pub(crate) name: Option<&'static str>,
770 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
771
772 pub(crate) window_update_stack: Vec<WindowId>,
773 pub(crate) mode: GpuiMode,
774 pub(crate) cursor_hide_mode: CursorHideMode,
775 pub(crate) reduce_motion: bool,
776 pub(crate) synced_animation_epoch: Instant,
778 pub(crate) accessibility_force_disabled: bool,
781 pending_updates: usize,
782 quit_mode: QuitMode,
783 quitting: bool,
784
785 #[cfg(any(test, gpui_leak_detection))]
788 _ref_counts: Arc<RwLock<EntityRefCounts>>,
789}
790
791impl App {
792 pub(crate) fn new_layout_engine(&self) -> Box<dyn LayoutEngine> {
794 (self.layout_engine_factory)()
795 }
796
797 pub(crate) fn new_frame_pipeline(&self, window_id: WindowId) -> Box<dyn FramePipeline> {
799 (self.frame_pipeline_factory)(window_id)
800 }
801
802 #[allow(clippy::new_ret_no_self)]
803 pub(crate) fn new_app(
804 platform: Rc<dyn Platform>,
805 asset_source: Arc<dyn AssetSource>,
806 http_client: Arc<dyn HttpClient>,
807 ) -> Rc<AppCell> {
808 let background_executor = platform.background_executor();
809 let foreground_executor = platform.foreground_executor();
810 assert!(
811 background_executor.is_main_thread(),
812 "must construct App on main thread"
813 );
814 crate::profiler::install_profiler_hooks();
815 #[cfg(feature = "profiler")]
816 let foreground_journal = crate::profiler::journal::install_foreground_journal();
817 let synced_animation_epoch = background_executor.now();
818
819 let text_system = Arc::new(DefaultTextSystem::new(platform.text_system()));
820 let entities = EntityMap::new();
821 let keyboard_layout = platform.keyboard_layout();
822 let keyboard_mapper = platform.keyboard_mapper();
823
824 #[cfg(any(test, gpui_leak_detection))]
825 let _ref_counts = entities.ref_counts_drop_handle();
826
827 let app = Rc::new_cyclic(|this| AppCell {
828 app: RefCell::new(App {
829 this: this.clone(),
830 platform: platform.clone(),
831 text_system,
832 layout_engine_factory: Rc::new(gpui_engine_default::default_layout_engine),
833 frame_pipeline_factory: Rc::new(|_| Box::new(StandardImmediatePipeline)),
834 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
835 mode: GpuiMode::Production,
836 actions: Rc::new(ActionRegistry::default()),
837 pending_updates: 0,
838 active_drag: None,
839 platform_owned_drag: None,
840 background_executor,
841 foreground_executor,
842 #[cfg(feature = "profiler")]
843 foreground_journal,
844 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
845 hang_monitor: None,
846 svg_renderer: SvgRenderer::new(asset_source.clone()),
847 loading_assets: Default::default(),
848 asset_source,
849 http_client,
850 globals_by_type: Default::default(),
851 entities,
852 new_entity_observers: SubscriberSet::new(),
853 windows: WindowRegistry::default(),
854 window_update_stack: Vec::new(),
855 window_handles: FxHashMap::default(),
856 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
857 keymap: Rc::new(RefCell::new(Keymap::default())),
858 menu_actions: Rc::new(RefCell::new(Vec::new())),
859 owned_menus: Rc::new(RefCell::new(None)),
860 keyboard_layout,
861 keyboard_mapper,
862 global_action_listeners: Default::default(),
863 pending_effects: VecDeque::new(),
864 pending_notifications: FxHashSet::default(),
865 pending_global_notifications: Default::default(),
866 observers: SubscriberSet::new(),
867 tracked_entities: FxHashMap::default(),
868 window_invalidators_by_entity: FxHashMap::default(),
869 current_window_by_entity: FxHashMap::default(),
870 event_listeners: SubscriberSet::new(),
871 release_listeners: SubscriberSet::new(),
872 keystroke_observers: SubscriberSet::new(),
873 keystroke_interceptors: SubscriberSet::new(),
874 keyboard_layout_observers: SubscriberSet::new(),
875 missing_glyph_callback: Rc::default(),
876 thermal_state_observers: SubscriberSet::new(),
877 display_observers: SubscriberSet::new(),
878 displays: read_displays(platform.as_ref()),
879 system_sleep_observers: SubscriberSet::new(),
880 system_wake_observers: SubscriberSet::new(),
881 global_observers: SubscriberSet::new(),
882 quit_observers: SubscriberSet::new(),
883 restart_observers: SubscriberSet::new(),
884 restart_path: None,
885 restart_arguments: Vec::new(),
886 window_closed_observers: SubscriberSet::new(),
887 layout_id_buffer: Default::default(),
888 propagate_event: true,
889 prompt_builder: Some(PromptBuilder::Default),
890 #[cfg(any(feature = "inspector", debug_assertions))]
891 inspector_renderer: None,
892 #[cfg(any(feature = "inspector", debug_assertions))]
893 inspector_element_registry: InspectorElementRegistry::default(),
894 quit_mode: QuitMode::default(),
895 quitting: false,
896 cursor_hide_mode: CursorHideMode::default(),
897 reduce_motion: false,
898 synced_animation_epoch,
899 accessibility_force_disabled: false,
900
901 #[cfg(any(test, feature = "test-support", debug_assertions))]
902 name: None,
903 element_arena: RefCell::new(Arena::new(1024 * 1024)),
904 event_arena: Arena::new(1024 * 1024),
905
906 #[cfg(any(test, gpui_leak_detection))]
907 _ref_counts,
908 }),
909 });
910
911 init_app_menus(platform.as_ref(), &app.borrow());
912 SystemWindowTabController::init(&mut app.borrow_mut());
913 #[cfg(feature = "profiler")]
914 crate::profiler::journal::observe_power(&app.borrow());
915
916 platform.on_keyboard_layout_change(Box::new({
917 let app = Rc::downgrade(&app);
918 move || {
919 if let Some(app) = app.upgrade() {
920 let cx = &mut app.borrow_mut();
921 cx.keyboard_layout = cx.platform.keyboard_layout();
922 cx.keyboard_mapper = cx.platform.keyboard_mapper();
923 cx.keyboard_layout_observers
924 .clone()
925 .retain(&(), move |callback| (callback)(cx));
926 }
927 }
928 }));
929
930 platform.on_thermal_state_change(Box::new({
931 let app = Rc::downgrade(&app);
932 move || {
933 if let Some(app) = app.upgrade() {
934 let cx = &mut app.borrow_mut();
935 cx.thermal_state_observers
936 .clone()
937 .retain(&(), move |callback| (callback)(cx));
938 }
939 }
940 }));
941
942 platform.on_displays_changed(Box::new({
943 let app = Rc::downgrade(&app);
944 move || {
945 if let Some(app) = app.upgrade() {
946 app.borrow_mut().displays_changed();
947 }
948 }
949 }));
950
951 platform.on_system_sleep(Box::new({
952 let app = Rc::downgrade(&app);
953 move || {
954 if let Some(app) = app.upgrade() {
955 let cx = &mut app.borrow_mut();
956 cx.system_sleep_observers
957 .clone()
958 .retain(&(), move |callback| (callback)(cx));
959 }
960 }
961 }));
962
963 platform.on_system_wake(Box::new({
964 let app = Rc::downgrade(&app);
965 move || {
966 if let Some(app) = app.upgrade() {
967 let cx = &mut app.borrow_mut();
968 cx.system_wake_observers
969 .clone()
970 .retain(&(), move |callback| (callback)(cx));
971 }
972 }
973 }));
974
975 platform.on_quit(Box::new({
976 let cx = Rc::downgrade(&app);
977 move || {
978 let Some(cx) = cx.upgrade() else {
979 return true;
980 };
981 match cx.try_borrow_mut() {
982 Ok(mut cx) => {
983 cx.shutdown();
984 true
985 }
986 Err(_) => {
987 false
990 }
991 }
992 }
993 }));
994
995 app
996 }
997
998 #[doc(hidden)]
999 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1000 self.entities.ref_counts_drop_handle()
1001 }
1002
1003 #[cfg(any(test, gpui_leak_detection))]
1009 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1010 self.entities.leak_detector_snapshot()
1011 }
1012
1013 #[cfg(any(test, gpui_leak_detection))]
1025 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1026 self.entities.assert_no_new_leaks(snapshot)
1027 }
1028
1029 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1031 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1032 LeakDetectorSnapshot::default()
1033 }
1034
1035 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1038 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1039
1040 pub fn shutdown(&mut self) {
1046 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1049 let hang_monitor_flush = self
1050 .hang_monitor
1051 .as_ref()
1052 .and_then(|hang_monitor| hang_monitor.request_flush());
1053
1054 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1055
1056 for observer in self.quit_observers.remove(&()) {
1057 futures.push(observer(self));
1058 }
1059
1060 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1061 if let Some(flushed) = hang_monitor_flush {
1062 futures.push(
1063 async move {
1064 if flushed.await.is_err() {
1065 log::warn!("hang monitor exited before flushing");
1066 }
1067 }
1068 .boxed_local(),
1069 );
1070 }
1071
1072 self.windows.clear();
1073 self.window_handles.clear();
1074 self.flush_effects();
1075 self.quitting = true;
1076
1077 let futures = futures::future::join_all(futures);
1078 #[cfg(not(target_family = "wasm"))]
1079 if self
1080 .foreground_executor
1081 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1082 .is_err()
1083 {
1084 log::error!("timed out waiting on app_will_quit");
1085 }
1086 #[cfg(target_family = "wasm")]
1087 self.foreground_executor.spawn(futures).detach();
1088
1089 self.quitting = false;
1090 }
1091
1092 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1094 self.keyboard_layout.as_ref()
1095 }
1096
1097 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1099 &self.keyboard_mapper
1100 }
1101
1102 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1104 where
1105 F: 'static + FnMut(&mut App),
1106 {
1107 let (subscription, activate) = self.keyboard_layout_observers.insert(
1108 (),
1109 Box::new(move |cx| {
1110 callback(cx);
1111 true
1112 }),
1113 );
1114 activate();
1115 subscription
1116 }
1117
1118 pub fn quit(&self) {
1120 self.platform.quit();
1121 }
1122
1123 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1137 if !self.windows.is_empty() {
1138 return Task::ready(Err(anyhow::anyhow!(
1139 "cannot switch windowing modes while windows are open"
1140 )));
1141 }
1142 self.platform.request_windowing(request)
1143 }
1144
1145 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1155 self.platform.graphical_environment()
1156 }
1157
1158 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1161 self.cursor_hide_mode
1162 }
1163
1164 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1167 self.cursor_hide_mode = mode;
1168 }
1169
1170 pub fn is_cursor_visible(&self) -> bool {
1176 self.platform.is_cursor_visible()
1177 }
1178
1179 pub fn reduce_motion(&self) -> bool {
1182 self.reduce_motion
1183 }
1184
1185 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1188 if self.reduce_motion != reduce_motion {
1189 self.reduce_motion = reduce_motion;
1190 self.refresh_windows();
1191 }
1192 }
1193
1194 pub fn refresh_windows(&mut self) {
1197 self.pending_effects.push_back(Effect::RefreshWindows);
1198 }
1199
1200 #[inline(always)]
1201 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1202 self.start_update();
1203 let result = update(self);
1204 self.finish_update();
1205 result
1206 }
1207
1208 pub(crate) fn start_update(&mut self) {
1209 self.pending_updates += 1;
1210 }
1211
1212 #[inline(never)]
1213 pub(crate) fn finish_update(&mut self) {
1214 if self.pending_updates == 1 {
1215 self.flush_effects();
1216 }
1217 self.pending_updates -= 1;
1218 }
1219
1220 pub fn observe<W>(
1222 &mut self,
1223 entity: &Entity<W>,
1224 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1225 ) -> Subscription
1226 where
1227 W: 'static,
1228 {
1229 self.observe_internal(entity, move |e, cx| {
1230 on_notify(e, cx);
1231 true
1232 })
1233 }
1234
1235 pub(crate) fn detect_accessed_entities<R>(
1236 &mut self,
1237 callback: impl FnOnce(&mut App) -> R,
1238 ) -> (R, FxHashSet<EntityId>) {
1239 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1240 let result = callback(self);
1241 let entities_accessed_in_callback = self
1242 .entities
1243 .accessed_entities
1244 .get_mut()
1245 .difference(&accessed_entities_start)
1246 .copied()
1247 .collect::<FxHashSet<EntityId>>();
1248 (result, entities_accessed_in_callback)
1249 }
1250
1251 pub(crate) fn record_entities_accessed(
1252 &mut self,
1253 window_handle: AnyWindowHandle,
1254 invalidator: WindowInvalidator,
1255 entities: &FxHashSet<EntityId>,
1256 ) {
1257 let mut tracked_entities =
1258 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1259 for entity in tracked_entities.iter() {
1260 self.window_invalidators_by_entity
1261 .entry(*entity)
1262 .and_modify(|windows| {
1263 windows.remove(&window_handle.id);
1264 });
1265 }
1266 for entity in entities.iter() {
1267 self.window_invalidators_by_entity
1268 .entry(*entity)
1269 .or_default()
1270 .insert(window_handle.id, invalidator.clone());
1271 self.current_window_by_entity
1272 .insert(*entity, window_handle.id);
1273 }
1274 tracked_entities.clear();
1275 tracked_entities.extend(entities.iter().copied());
1276 self.tracked_entities
1277 .insert(window_handle.id, tracked_entities);
1278 }
1279
1280 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1281 let (subscription, activate) = self.observers.insert(key, value);
1282 self.defer(move |_| activate());
1283 subscription
1284 }
1285
1286 pub(crate) fn observe_internal<W>(
1287 &mut self,
1288 entity: &Entity<W>,
1289 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1290 ) -> Subscription
1291 where
1292 W: 'static,
1293 {
1294 let entity_id = entity.entity_id();
1295 let handle = entity.downgrade();
1296 self.new_observer(
1297 entity_id,
1298 Box::new(move |cx| {
1299 if let Some(entity) = handle.upgrade() {
1300 on_notify(entity, cx)
1301 } else {
1302 false
1303 }
1304 }),
1305 )
1306 }
1307
1308 pub fn subscribe<T, Event>(
1311 &mut self,
1312 entity: &Entity<T>,
1313 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1314 ) -> Subscription
1315 where
1316 T: 'static + EventEmitter<Event>,
1317 Event: 'static,
1318 {
1319 self.subscribe_internal(entity, move |entity, event, cx| {
1320 on_event(entity, event, cx);
1321 true
1322 })
1323 }
1324
1325 pub(crate) fn new_subscription(
1326 &mut self,
1327 key: EntityId,
1328 value: (TypeId, Listener),
1329 ) -> Subscription {
1330 let (subscription, activate) = self.event_listeners.insert(key, value);
1331 self.defer(move |_| activate());
1332 subscription
1333 }
1334 pub(crate) fn subscribe_internal<T, Evt>(
1335 &mut self,
1336 entity: &Entity<T>,
1337 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1338 ) -> Subscription
1339 where
1340 T: 'static + EventEmitter<Evt>,
1341 Evt: 'static,
1342 {
1343 let entity_id = entity.entity_id();
1344 let handle = entity.downgrade();
1345 self.new_subscription(
1346 entity_id,
1347 (
1348 TypeId::of::<Evt>(),
1349 Box::new(move |event, cx| {
1350 let event: &Evt = event.downcast_ref().expect("invalid event type");
1351 if let Some(entity) = handle.upgrade() {
1352 on_event(entity, event, cx)
1353 } else {
1354 false
1355 }
1356 }),
1357 ),
1358 )
1359 }
1360
1361 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1365 self.windows
1366 .ids()
1367 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1368 .collect()
1369 }
1370
1371 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1377 self.platform.window_stack().map(|window_ids| {
1378 window_ids
1379 .into_iter()
1380 .filter_map(|window_id| self.window_handle(window_id))
1381 .collect()
1382 })
1383 }
1384
1385 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1387 self.platform
1388 .active_window()
1389 .and_then(|window_id| self.window_handle(window_id))
1390 }
1391
1392 pub fn window_handle(&self, window_id: WindowId) -> Option<AnyWindowHandle> {
1394 self.window_handles.get(&window_id).copied()
1395 }
1396
1397 pub fn open_window<V: 'static + Render>(
1401 &mut self,
1402 options: crate::WindowOptions,
1403 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1404 ) -> anyhow::Result<WindowHandle<V>> {
1405 self.update(|cx| {
1406 let id = cx.windows.reserve();
1407 let handle = WindowHandle::new(id);
1408 match WindowHost::new(handle.into(), options, cx) {
1409 Ok(mut host) => {
1410 cx.window_update_stack.push(id);
1411 let root_view = host.with_window(|window| build_root_view(window, cx));
1412 cx.window_update_stack.pop();
1413 host.core.root.replace(root_view.into());
1414 host.with_window(|window| {
1415 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1416
1417 let clear = window.draw(cx);
1422 clear.clear(cx);
1423 });
1424
1425 cx.window_handles.insert(id, host.core.handle);
1426 cx.windows.register(id, host);
1427 Ok(handle)
1428 }
1429 Err(e) => {
1430 cx.windows.remove(id);
1431 Err(e)
1432 }
1433 }
1434 })
1435 }
1436
1437 pub fn activate(&self, ignoring_other_apps: bool) {
1439 self.platform.activate(ignoring_other_apps);
1440 }
1441
1442 pub fn hide(&self) {
1444 self.platform.hide();
1445 }
1446
1447 pub fn hide_other_apps(&self) {
1449 self.platform.hide_other_apps();
1450 }
1451
1452 pub fn unhide_other_apps(&self) {
1454 self.platform.unhide_other_apps();
1455 }
1456
1457 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1459 self.platform.displays()
1460 }
1461
1462 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1464 self.platform.primary_display()
1465 }
1466
1467 pub fn is_screen_capture_supported(&self) -> bool {
1469 self.platform.is_screen_capture_supported()
1470 }
1471
1472 pub fn screen_capture_sources(
1474 &self,
1475 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1476 self.platform.screen_capture_sources()
1477 }
1478
1479 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1481 self.displays()
1482 .iter()
1483 .find(|display| display.id() == id)
1484 .cloned()
1485 }
1486
1487 pub fn thermal_state(&self) -> ThermalState {
1489 self.platform.thermal_state()
1490 }
1491
1492 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1494 self.platform.prevent_idle_sleep(reason)
1495 }
1496
1497 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1499 where
1500 F: 'static + FnMut(&mut App),
1501 {
1502 let (subscription, activate) = self.thermal_state_observers.insert(
1503 (),
1504 Box::new(move |cx| {
1505 callback(cx);
1506 true
1507 }),
1508 );
1509 activate();
1510 subscription
1511 }
1512
1513 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1518 where
1519 F: 'static + FnMut(&mut App),
1520 {
1521 let (subscription, activate) = self.system_sleep_observers.insert(
1522 (),
1523 Box::new(move |cx| {
1524 callback(cx);
1525 true
1526 }),
1527 );
1528 activate();
1529 subscription
1530 }
1531
1532 pub(crate) fn displays_changed(&mut self) {
1533 let current = read_displays(self.platform.as_ref());
1534 let events = display_events(&self.displays, ¤t);
1535 self.displays = current;
1536 for event in &events {
1537 let DisplayEvent::Changed { id, .. } = *event else {
1538 continue;
1539 };
1540 for handle in self.windows() {
1541 self.update_window(handle, |_, window, cx| {
1542 if window.core.display_id == Some(id) {
1543 window.notify_display_observers(cx);
1544 }
1545 })
1546 .log_err();
1547 }
1548 }
1549 for event in events {
1550 self.display_observers
1551 .clone()
1552 .retain(&(), |callback| (callback)(event, self));
1553 }
1554 }
1555
1556 pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1557 self.displays.contains_key(&id)
1558 }
1559
1560 pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1563 self.displays.get(&id)?.refresh_interval
1564 }
1565
1566 pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1569 where
1570 F: 'static + FnMut(DisplayEvent, &mut App),
1571 {
1572 let (subscription, activate) = self.display_observers.insert(
1573 (),
1574 Box::new(move |event, cx| {
1575 callback(event, cx);
1576 true
1577 }),
1578 );
1579 activate();
1580 subscription
1581 }
1582
1583 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1585 where
1586 F: 'static + FnMut(&mut App),
1587 {
1588 let (subscription, activate) = self.system_wake_observers.insert(
1589 (),
1590 Box::new(move |cx| {
1591 callback(cx);
1592 true
1593 }),
1594 );
1595 activate();
1596 subscription
1597 }
1598
1599 pub fn window_appearance(&self) -> WindowAppearance {
1601 self.platform.window_appearance()
1602 }
1603
1604 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1615 self.platform.set_window_appearance(appearance);
1616 }
1617
1618 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1620 self.platform.button_layout()
1621 }
1622
1623 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1625 self.platform.read_from_clipboard()
1626 }
1627
1628 pub fn read_from_clipboard_async(
1636 &self,
1637 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1638 self.platform.read_from_clipboard_async()
1639 }
1640
1641 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1643 self.text_rendering_mode.set(mode);
1644 }
1645
1646 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1648 self.text_rendering_mode.get()
1649 }
1650
1651 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1653 self.platform.write_to_clipboard(item)
1654 }
1655
1656 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1659 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1660 self.platform.read_from_primary()
1661 }
1662
1663 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1666 pub fn write_to_primary(&self, item: ClipboardItem) {
1667 self.platform.write_to_primary(item)
1668 }
1669
1670 #[cfg(target_os = "macos")]
1676 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1677 self.platform.read_from_find_pasteboard()
1678 }
1679
1680 #[cfg(target_os = "macos")]
1686 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1687 self.platform.write_to_find_pasteboard(item)
1688 }
1689
1690 pub fn write_credentials(
1692 &self,
1693 url: &str,
1694 username: &str,
1695 password: &[u8],
1696 ) -> Task<Result<()>> {
1697 self.platform.write_credentials(url, username, password)
1698 }
1699
1700 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1702 self.platform.read_credentials(url)
1703 }
1704
1705 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1707 self.platform.delete_credentials(url)
1708 }
1709
1710 pub fn open_url(&self, url: &str) {
1712 self.platform.open_url(url);
1713 }
1714
1715 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1722 self.platform.register_url_scheme(scheme)
1723 }
1724
1725 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1732 self.platform.set_app_identity(identifier, name);
1733 }
1734
1735 pub fn show_system_notification(&self, notification: SystemNotification) {
1742 self.platform.show_system_notification(notification);
1743 }
1744
1745 pub fn dismiss_system_notification(&self, tag: &str) {
1750 self.platform.dismiss_system_notification(tag);
1751 }
1752
1753 pub fn on_system_notification_response<F>(&self, mut callback: F)
1757 where
1758 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1759 {
1760 let this = self.this.clone();
1761 self.platform
1762 .on_system_notification_response(Box::new(move |response| {
1763 if let Some(app) = this.upgrade() {
1764 callback(response, &mut app.borrow_mut());
1765 }
1766 }));
1767 }
1768
1769 pub fn app_path(&self) -> Result<PathBuf> {
1773 self.platform.app_path()
1774 }
1775
1776 pub fn compositor_name(&self) -> &'static str {
1780 self.platform.compositor_name()
1781 }
1782
1783 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1785 self.platform.path_for_auxiliary_executable(name)
1786 }
1787
1788 pub fn prompt_for_paths(
1794 &self,
1795 options: PathPromptOptions,
1796 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1797 self.platform.prompt_for_paths(options)
1798 }
1799
1800 pub fn prompt_for_new_path(
1807 &self,
1808 directory: &Path,
1809 suggested_name: Option<&str>,
1810 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1811 self.platform.prompt_for_new_path(directory, suggested_name)
1812 }
1813
1814 pub fn reveal_path(&self, path: &Path) {
1816 self.platform.reveal_path(path)
1817 }
1818
1819 pub fn open_with_system(&self, path: &Path) {
1821 self.platform.open_with_system(path)
1822 }
1823
1824 pub fn should_auto_hide_scrollbars(&self) -> bool {
1826 self.platform.should_auto_hide_scrollbars()
1827 }
1828
1829 pub fn restart(&mut self) {
1831 self.restart_observers
1832 .clone()
1833 .retain(&(), |observer| observer(self));
1834 self.platform.restart(
1835 self.restart_path.take(),
1836 std::mem::take(&mut self.restart_arguments),
1837 )
1838 }
1839
1840 pub fn set_restart_path(&mut self, path: PathBuf) {
1842 self.restart_path = Some(path);
1843 }
1844
1845 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1847 self.http_client.clone()
1848 }
1849
1850 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1852 self.http_client = new_client;
1853 }
1854
1855 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1858 self.quit_mode = mode;
1859 }
1860
1861 pub fn set_initial_windowing(&mut self, request: WindowingRequest) {
1865 self.platform.set_initial_windowing(request);
1866 }
1867
1868 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
1877 self.platform.set_activation_policy(policy);
1878 }
1879
1880 pub fn svg_renderer(&self) -> SvgRenderer {
1882 self.svg_renderer.clone()
1883 }
1884
1885 pub(crate) fn push_effect(&mut self, effect: Effect) {
1886 match &effect {
1887 Effect::Notify { emitter } => {
1888 if !self.pending_notifications.insert(*emitter) {
1889 return;
1890 }
1891 }
1892 Effect::NotifyGlobalObservers { global_type } => {
1893 if !self.pending_global_notifications.insert(*global_type) {
1894 return;
1895 }
1896 }
1897 _ => {}
1898 };
1899
1900 self.pending_effects.push_back(effect);
1901 }
1902
1903 fn flush_effects(&mut self) {
1907 loop {
1908 self.release_dropped_entities();
1909 self.release_dropped_focus_handles();
1910 if let Some(effect) = self.pending_effects.pop_front() {
1911 match effect {
1912 Effect::Notify { emitter } => {
1913 self.apply_notify_effect(emitter);
1914 }
1915
1916 Effect::Emit {
1917 emitter,
1918 event_type,
1919 event,
1920 } => self.apply_emit_effect(emitter, event_type, &*event),
1921
1922 Effect::RefreshWindows => {
1923 self.apply_refresh_effect();
1924 }
1925
1926 Effect::NotifyGlobalObservers { global_type } => {
1927 self.apply_notify_global_observers_effect(global_type);
1928 }
1929
1930 Effect::Defer { callback } => {
1931 self.apply_defer_effect(callback);
1932 }
1933 Effect::EntityCreated {
1934 entity,
1935 tid,
1936 window,
1937 } => {
1938 self.apply_entity_created_effect(entity, tid, window);
1939 }
1940 }
1941 } else {
1942 #[cfg(any(test, feature = "test-support"))]
1943 if matches!(self.mode, GpuiMode::Test { .. }) {
1944 for handle in self
1945 .windows
1946 .cells()
1947 .filter_map(|cell| {
1948 let host = cell.borrow();
1949 host.core.should_render_frame().then_some(host.core.handle)
1950 })
1951 .collect::<Vec<_>>()
1952 {
1953 self.update_window(handle, |_, window, cx| window.draw(cx).clear(cx))
1954 .unwrap();
1955 }
1956 }
1957
1958 if self.pending_effects.is_empty() {
1959 for cell in self.windows.cells() {
1960 let host = cell.borrow();
1961 if host.core.invalidator.is_dirty()
1962 || host.core.needs_present.get()
1963 || !host.core.next_frame_callbacks.borrow().is_empty()
1964 {
1965 host.core.platform_window.schedule_frame();
1970 }
1971 }
1972
1973 self.event_arena.clear();
1974 break;
1975 }
1976 }
1977 }
1978 }
1979
1980 fn release_dropped_entities(&mut self) {
1984 loop {
1985 let dropped = self.entities.take_dropped();
1986 if dropped.is_empty() {
1987 break;
1988 }
1989
1990 for (entity_id, mut entity) in dropped {
1991 self.observers.remove(&entity_id);
1992 self.event_listeners.remove(&entity_id);
1993 self.window_invalidators_by_entity.remove(&entity_id);
1994 self.current_window_by_entity.remove(&entity_id);
1995 for release_callback in self.release_listeners.remove(&entity_id) {
1996 release_callback(entity.as_mut(), self);
1997 }
1998 }
1999 }
2000 }
2001
2002 fn release_dropped_focus_handles(&mut self) {
2004 self.focus_handles
2005 .clone()
2006 .write()
2007 .retain(|handle_id, focus| {
2008 if focus.ref_count.load(SeqCst) == 0 {
2009 for window_handle in self.windows() {
2010 window_handle
2011 .update(self, |_, window, cx| {
2012 if window.core.focus == Some(handle_id) {
2013 window.blur(cx);
2014 }
2015 })
2016 .unwrap();
2017 }
2018 false
2019 } else {
2020 true
2021 }
2022 });
2023 }
2024
2025 fn apply_notify_effect(&mut self, emitter: EntityId) {
2026 self.pending_notifications.remove(&emitter);
2027
2028 self.observers
2029 .clone()
2030 .retain(&emitter, |handler| handler(self));
2031 }
2032
2033 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2034 self.event_listeners
2035 .clone()
2036 .retain(&emitter, |(stored_type, handler)| {
2037 if *stored_type == event_type {
2038 handler(event, self)
2039 } else {
2040 true
2041 }
2042 });
2043 }
2044
2045 fn apply_refresh_effect(&mut self) {
2046 for cell in self.windows.cells() {
2047 let mut host = cell.borrow_mut();
2048 host.core.refreshing = true;
2049 host.core.invalidator.set_dirty(true);
2050 }
2051 }
2052
2053 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2054 self.pending_global_notifications.remove(&type_id);
2055 self.global_observers
2056 .clone()
2057 .retain(&type_id, |observer| observer(self));
2058 }
2059
2060 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2061 callback(self);
2062 }
2063
2064 fn apply_entity_created_effect(
2065 &mut self,
2066 entity: AnyEntity,
2067 tid: TypeId,
2068 window: Option<WindowId>,
2069 ) {
2070 if let Some(id) = window {
2074 self.current_window_by_entity.insert(entity.entity_id(), id);
2075 }
2076
2077 self.new_entity_observers.clone().retain(&tid, |observer| {
2078 if let Some(id) = window {
2079 self.update_window_id(id, {
2080 let entity = entity.clone();
2081 |_, window, cx| (observer)(entity, &mut Some(window), cx)
2082 })
2083 .expect("All windows should be off the stack when flushing effects");
2084 } else {
2085 (observer)(entity.clone(), &mut None, self)
2086 }
2087 true
2088 });
2089 }
2090
2091 #[inline(always)]
2097 pub fn with_window<R>(
2098 &mut self,
2099 entity_id: EntityId,
2100 f: impl FnOnce(&mut Window, &mut App) -> R,
2101 ) -> Option<R> {
2102 let window_id = *self.current_window_by_entity.get(&entity_id)?;
2103 self.update_window_id(window_id, |_, window, cx| f(window, cx))
2104 .ok()
2105 }
2106
2107 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2108 self.current_window_by_entity
2109 .entry(entity_id)
2110 .or_insert(window);
2111 }
2112
2113 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2114 where
2115 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2116 {
2117 self.update(|cx| {
2118 let cell = cx
2119 .windows
2120 .cell(id)
2121 .ok_or_else(|| anyhow!("window {id:?} is not open"))?;
2122 let mut host = cell
2123 .try_borrow_mut()
2124 .map_err(|_| anyhow!("window {id:?} is already being updated"))?;
2125
2126 let root_view = host.core.root.clone().unwrap();
2127
2128 cx.window_update_stack.push(host.core.handle.id);
2129 let result = host.with_window(|window| update(root_view, window, cx));
2130 let removed = host.core.removed;
2131 drop(host);
2132 cx.window_update_stack.pop();
2133
2134 if removed {
2135 cx.end_platform_drag(id);
2136 cx.window_handles.remove(&id);
2137 cx.windows.remove(id);
2138 if let Some(tracked) = cx.tracked_entities.remove(&id) {
2139 for entity_id in tracked {
2140 if let Some(windows) = cx.window_invalidators_by_entity.get_mut(&entity_id)
2141 {
2142 windows.remove(&id);
2143 }
2144 if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
2145 cx.current_window_by_entity.remove(&entity_id);
2146 }
2147 }
2148 }
2149
2150 cx.window_closed_observers.clone().retain(&(), |callback| {
2151 callback(cx, id);
2152 true
2153 });
2154
2155 let quit_on_empty = match cx.quit_mode {
2156 QuitMode::Explicit => false,
2157 QuitMode::LastWindowClosed => true,
2158 QuitMode::Default => cfg!(not(target_os = "macos")),
2159 };
2160
2161 if quit_on_empty && cx.windows.is_empty() {
2162 cx.quit();
2163 }
2164 }
2165
2166 Ok(result)
2167 })
2168 }
2169
2170 pub fn to_async(&self) -> AsyncApp {
2173 AsyncApp {
2174 app: self.this.clone(),
2175 background_executor: self.background_executor.clone(),
2176 foreground_executor: self.foreground_executor.clone(),
2177 }
2178 }
2179
2180 pub fn background_executor(&self) -> &BackgroundExecutor {
2182 &self.background_executor
2183 }
2184
2185 pub fn is_test(&self) -> bool {
2188 self.background_executor.is_test()
2189 }
2190
2191 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2193 if self.quitting {
2194 panic!("Can't spawn on main thread after on_app_quit")
2195 };
2196 &self.foreground_executor
2197 }
2198
2199 #[cfg(feature = "profiler")]
2202 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2203 self.foreground_journal.clone()
2204 }
2205
2206 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2223 pub fn start_hang_monitor(
2224 &mut self,
2225 config: crate::profiler::hang::HangMonitorConfig,
2226 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2227 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2228 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2229
2230 if self.hang_monitor.is_some() {
2231 debug_assert!(false, "the hang monitor was started twice");
2232 return Err(HangMonitorError::AlreadyStarted);
2233 }
2234 let detector = HangDetector::new(
2235 self.foreground_journal(),
2236 config.threshold,
2237 config.frame_budget,
2238 );
2239 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2240 .map_err(HangMonitorError::Spawn)?;
2241 self.hang_monitor = Some(monitor);
2242 Ok(())
2243 }
2244
2245 #[track_caller]
2248 #[inline(always)]
2249 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2250 where
2251 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2252 R: 'static,
2253 {
2254 let mut cx = self.prepare_spawn();
2255
2256 self.foreground_executor
2257 .spawn(async move { f(&mut cx).await }.boxed_local())
2258 }
2259
2260 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2264 where
2265 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2266 R: 'static,
2267 {
2268 if self.quitting {
2269 debug_panic!("Can't spawn on main thread after on_app_quit")
2270 };
2271
2272 let mut cx = self.to_async();
2273
2274 self.foreground_executor
2275 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2276 }
2277
2278 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2281 self.push_effect(Effect::Defer {
2282 callback: Box::new(f),
2283 });
2284 }
2285
2286 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2288 &self.asset_source
2289 }
2290
2291 pub fn text_system(&self) -> &Arc<dyn TextSystem> {
2293 &self.text_system
2294 }
2295
2296 pub fn enumerate_gpus(&self) -> Vec<GpuAdapterInfo> {
2303 self.platform.enumerate_gpus()
2304 }
2305
2306 pub fn active_gpu(&self) -> Option<GpuAdapterInfo> {
2311 self.platform.active_gpu()
2312 }
2313
2314 pub fn dmabuf_capabilities(&self) -> Option<DmaBufCapabilities> {
2323 self.platform.dmabuf_capabilities()
2324 }
2325
2326 pub fn on_missing_glyphs(
2337 &self,
2338 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2339 ) -> Subscription {
2340 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2341
2342 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2343 let callback = self.missing_glyph_callback.clone();
2344 self.spawn(async move |cx| {
2345 while let Some(missing_glyphs) = receiver.recv().await {
2346 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2347 }
2348 })
2349 .detach();
2350 }
2351 self.text_system.enable_missing_glyph_reporting();
2352
2353 let callback = self.missing_glyph_callback.clone();
2354 let text_system = self.text_system.clone();
2355 Subscription::new(move || {
2356 if callback.remove(®istration) {
2357 text_system.disable_missing_glyph_reporting();
2358 }
2359 })
2360 }
2361
2362 pub fn has_global<G: Global>(&self) -> bool {
2364 self.globals_by_type.contains_key(&TypeId::of::<G>())
2365 }
2366
2367 #[track_caller]
2369 pub fn global<G: Global>(&self) -> &G {
2370 self.globals_by_type
2371 .get(&TypeId::of::<G>())
2372 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2373 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2374 }
2375
2376 pub fn try_global<G: Global>(&self) -> Option<&G> {
2378 self.globals_by_type
2379 .get(&TypeId::of::<G>())
2380 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2381 }
2382
2383 #[track_caller]
2385 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2386 let global_type = TypeId::of::<G>();
2387 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2388 self.globals_by_type
2389 .get_mut(&global_type)
2390 .and_then(|any_state| any_state.downcast_mut::<G>())
2391 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2392 }
2393
2394 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2397 let global_type = TypeId::of::<G>();
2398 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2399 self.globals_by_type
2400 .entry(global_type)
2401 .or_insert_with(|| Box::<G>::default())
2402 .downcast_mut::<G>()
2403 .unwrap()
2404 }
2405
2406 pub fn set_global<G: Global>(&mut self, global: G) {
2408 let global_type = TypeId::of::<G>();
2409 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2410 self.globals_by_type.insert(global_type, Box::new(global));
2411 }
2412
2413 #[cfg(any(test, feature = "test-support"))]
2415 pub fn clear_globals(&mut self) {
2416 self.globals_by_type.drain();
2417 }
2418
2419 pub fn remove_global<G: Global>(&mut self) -> G {
2421 let global_type = TypeId::of::<G>();
2422 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2423 *self
2424 .globals_by_type
2425 .remove(&global_type)
2426 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2427 .downcast()
2428 .unwrap()
2429 }
2430
2431 pub fn observe_global<G: Global>(
2433 &mut self,
2434 mut f: impl FnMut(&mut Self) + 'static,
2435 ) -> Subscription {
2436 let (subscription, activate) = self.global_observers.insert(
2437 TypeId::of::<G>(),
2438 Box::new(move |cx| {
2439 f(cx);
2440 true
2441 }),
2442 );
2443 self.defer(move |_| activate());
2444 subscription
2445 }
2446
2447 #[track_caller]
2449 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2450 GlobalLease::new(
2451 self.globals_by_type
2452 .remove(&TypeId::of::<G>())
2453 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2454 .unwrap(),
2455 )
2456 }
2457
2458 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2460 let global_type = TypeId::of::<G>();
2461
2462 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2463 self.globals_by_type.insert(global_type, lease.global);
2464 }
2465
2466 pub(crate) fn new_entity_observer(
2467 &self,
2468 key: TypeId,
2469 value: NewEntityListener,
2470 ) -> Subscription {
2471 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2472 activate();
2473 subscription
2474 }
2475
2476 pub fn observe_new<T: 'static>(
2479 &self,
2480 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2481 ) -> Subscription {
2482 self.new_entity_observer(
2483 TypeId::of::<T>(),
2484 Box::new(
2485 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2486 any_entity
2487 .downcast::<T>()
2488 .unwrap()
2489 .update(cx, |entity_state, cx| {
2490 on_new(entity_state, window.as_deref_mut(), cx)
2491 })
2492 },
2493 ),
2494 )
2495 }
2496
2497 pub fn observe_release<T>(
2500 &self,
2501 handle: &Entity<T>,
2502 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2503 ) -> Subscription
2504 where
2505 T: 'static,
2506 {
2507 let (subscription, activate) = self.release_listeners.insert(
2508 handle.entity_id(),
2509 Box::new(move |entity, cx| {
2510 let entity = entity.downcast_mut().expect("invalid entity type");
2511 on_release(entity, cx)
2512 }),
2513 );
2514 activate();
2515 subscription
2516 }
2517
2518 pub fn observe_release_in<T>(
2521 &self,
2522 handle: &Entity<T>,
2523 window: &Window,
2524 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2525 ) -> Subscription
2526 where
2527 T: 'static,
2528 {
2529 let window_handle = window.core.handle;
2530 self.observe_release(handle, move |entity, cx| {
2531 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2532 })
2533 }
2534
2535 pub fn observe_keystrokes(
2540 &mut self,
2541 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2542 ) -> Subscription {
2543 fn inner(
2544 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2545 handler: KeystrokeObserver,
2546 ) -> Subscription {
2547 let (subscription, activate) = keystroke_observers.insert((), handler);
2548 activate();
2549 subscription
2550 }
2551
2552 inner(
2553 &self.keystroke_observers,
2554 Box::new(move |event, window, cx| {
2555 f(event, window, cx);
2556 true
2557 }),
2558 )
2559 }
2560
2561 pub fn intercept_keystrokes(
2566 &mut self,
2567 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2568 ) -> Subscription {
2569 fn inner(
2570 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2571 handler: KeystrokeObserver,
2572 ) -> Subscription {
2573 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2574 activate();
2575 subscription
2576 }
2577
2578 inner(
2579 &self.keystroke_interceptors,
2580 Box::new(move |event, window, cx| {
2581 f(event, window, cx);
2582 true
2583 }),
2584 )
2585 }
2586
2587 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2589 self.keymap.borrow_mut().add_bindings(bindings);
2590 self.pending_effects.push_back(Effect::RefreshWindows);
2591 }
2592
2593 pub fn clear_key_bindings(&mut self) {
2595 self.keymap.borrow_mut().clear();
2596 self.pending_effects.push_back(Effect::RefreshWindows);
2597 }
2598
2599 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2601 self.keymap.clone()
2602 }
2603
2604 pub fn on_action<A: Action>(
2608 &mut self,
2609 listener: impl Fn(&A, &mut Self) + 'static,
2610 ) -> &mut Self {
2611 self.global_action_listeners
2612 .entry(TypeId::of::<A>())
2613 .or_default()
2614 .push(Rc::new(move |action, phase, cx| {
2615 if phase == DispatchPhase::Bubble {
2616 let action = action.downcast_ref().unwrap();
2617 listener(action, cx)
2618 }
2619 }));
2620 self
2621 }
2622
2623 pub fn stop_propagation(&mut self) {
2628 self.propagate_event = false;
2629 }
2630
2631 pub fn propagate(&mut self) {
2636 self.propagate_event = true;
2637 }
2638
2639 pub fn build_action(
2641 &self,
2642 name: &str,
2643 data: Option<serde_json::Value>,
2644 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2645 self.actions.build_action(name, data)
2646 }
2647
2648 pub fn all_action_names(&self) -> &[&'static str] {
2651 self.actions.all_action_names()
2652 }
2653
2654 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2658 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2659 }
2660
2661 pub fn action_schemas(
2663 &self,
2664 generator: &mut schemars::SchemaGenerator,
2665 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2666 self.actions.action_schemas(generator)
2667 }
2668
2669 pub fn action_schema_by_name(
2674 &self,
2675 name: &str,
2676 generator: &mut schemars::SchemaGenerator,
2677 ) -> Option<Option<schemars::Schema>> {
2678 self.actions.action_schema_by_name(name, generator)
2679 }
2680
2681 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2683 self.actions.deprecated_aliases()
2684 }
2685
2686 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2688 self.actions.deprecation_messages()
2689 }
2690
2691 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2693 self.actions.documentation()
2694 }
2695
2696 pub fn on_app_quit<Fut>(
2699 &self,
2700 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2701 ) -> Subscription
2702 where
2703 Fut: 'static + Future<Output = ()>,
2704 {
2705 let (subscription, activate) = self.quit_observers.insert(
2706 (),
2707 Box::new(move |cx| {
2708 let future = on_quit(cx);
2709 future.boxed_local()
2710 }),
2711 );
2712 activate();
2713 subscription
2714 }
2715
2716 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2720 let (subscription, activate) = self.restart_observers.insert(
2721 (),
2722 Box::new(move |cx| {
2723 on_restart(cx);
2724 true
2725 }),
2726 );
2727 activate();
2728 subscription
2729 }
2730
2731 pub fn on_window_closed(
2734 &self,
2735 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2736 ) -> Subscription {
2737 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2738 activate();
2739 subscription
2740 }
2741
2742 pub(crate) fn clear_pending_keystrokes(&mut self) {
2743 for window in self.windows() {
2744 window
2745 .update(self, |_, window, cx| {
2746 window.clear_pending_keystrokes(cx);
2747 })
2748 .ok();
2749 }
2750 }
2751
2752 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2755 let mut action_available = false;
2756 if let Some(window) = self.active_window()
2757 && let Ok(window_action_available) =
2758 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2759 {
2760 action_available = window_action_available;
2761 }
2762
2763 action_available
2764 || self
2765 .global_action_listeners
2766 .contains_key(&action.as_any().type_id())
2767 }
2768
2769 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2771 let owned: Vec<OwnedMenu> = menus.into_iter().map(Menu::owned).collect();
2772 let resolved = {
2773 let keymap = self.keymap.borrow();
2774 let mut actions = self.menu_actions.borrow_mut();
2775 resolve_menus(&owned, &keymap, &mut actions)
2776 };
2777 *self.owned_menus.borrow_mut() = Some(owned);
2778 self.platform.set_menus(resolved);
2779 }
2780
2781 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2783 self.owned_menus.borrow().clone()
2784 }
2785
2786 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2788 let owned: Vec<OwnedMenuItem> = menus.into_iter().map(MenuItem::owned).collect();
2789 let resolved = {
2790 let keymap = self.keymap.borrow();
2791 let mut actions = self.menu_actions.borrow_mut();
2792 resolve_dock_menu(&owned, &keymap, &mut actions)
2793 };
2794 self.platform.set_dock_menu(resolved)
2795 }
2796
2797 pub(crate) fn is_menu_command_available(&mut self, command_id: MenuCommandId) -> bool {
2799 let action = self
2800 .menu_actions
2801 .borrow()
2802 .get(command_id)
2803 .map(|action| action.boxed_clone());
2804 action.is_some_and(|action| self.is_action_available(action.as_ref()))
2805 }
2806
2807 pub(crate) fn dispatch_menu_command(&mut self, command_id: MenuCommandId) {
2809 let action = self
2810 .menu_actions
2811 .borrow()
2812 .get(command_id)
2813 .map(|action| action.boxed_clone());
2814 if let Some(action) = action {
2815 self.dispatch_action(action.as_ref());
2816 }
2817 }
2818
2819 pub fn perform_dock_menu_action(&self, action: usize) {
2821 self.platform.perform_dock_menu_action(action);
2822 }
2823
2824 pub fn add_recent_document(&self, path: &Path) {
2829 self.platform.add_recent_document(path);
2830 }
2831
2832 pub fn update_jump_list(
2835 &self,
2836 menus: Vec<MenuItem>,
2837 entries: Vec<SmallVec<[PathBuf; 2]>>,
2838 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2839 let owned: Vec<OwnedMenuItem> = menus.into_iter().map(MenuItem::owned).collect();
2840 let resolved = {
2841 let keymap = self.keymap.borrow();
2842 let mut actions = self.menu_actions.borrow_mut();
2843 resolve_dock_menu(&owned, &keymap, &mut actions)
2844 };
2845 self.platform.update_jump_list(resolved, entries)
2846 }
2847
2848 pub fn dispatch_action(&mut self, action: &dyn Action) {
2851 if let Some(active_window) = self.active_window() {
2852 active_window
2853 .update(self, |_, window, cx| {
2854 window.dispatch_action(action.boxed_clone(), cx)
2855 })
2856 .log_err();
2857 } else {
2858 self.dispatch_global_action(action);
2859 }
2860 }
2861
2862 fn dispatch_global_action(&mut self, action: &dyn Action) {
2863 self.propagate_event = true;
2864
2865 if let Some(mut global_listeners) = self
2866 .global_action_listeners
2867 .remove(&action.as_any().type_id())
2868 {
2869 for listener in &global_listeners {
2870 listener(action.as_any(), DispatchPhase::Capture, self);
2871 if !self.propagate_event {
2872 break;
2873 }
2874 }
2875
2876 global_listeners.extend(
2877 self.global_action_listeners
2878 .remove(&action.as_any().type_id())
2879 .unwrap_or_default(),
2880 );
2881
2882 self.global_action_listeners
2883 .insert(action.as_any().type_id(), global_listeners);
2884 }
2885
2886 if self.propagate_event
2887 && let Some(mut global_listeners) = self
2888 .global_action_listeners
2889 .remove(&action.as_any().type_id())
2890 {
2891 for listener in global_listeners.iter().rev() {
2892 listener(action.as_any(), DispatchPhase::Bubble, self);
2893 if !self.propagate_event {
2894 break;
2895 }
2896 }
2897
2898 global_listeners.extend(
2899 self.global_action_listeners
2900 .remove(&action.as_any().type_id())
2901 .unwrap_or_default(),
2902 );
2903
2904 self.global_action_listeners
2905 .insert(action.as_any().type_id(), global_listeners);
2906 }
2907 }
2908
2909 pub fn has_active_drag(&self) -> bool {
2911 self.active_drag.is_some()
2912 }
2913
2914 pub fn active_drag_value<T: 'static>(&self) -> Option<&T> {
2919 self.active_drag
2920 .as_ref()
2921 .and_then(|drag| drag.value.downcast_ref::<T>())
2922 }
2923
2924 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2926 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2927 }
2928
2929 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2931 if self.active_drag.is_some() {
2932 self.active_drag = None;
2933 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2934 drag.source_window == window.window_handle().window_id()
2935 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2936 }) {
2937 self.platform_owned_drag = None;
2938 }
2939 window.refresh();
2940 true
2941 } else {
2942 false
2943 }
2944 }
2945
2946 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2947 let Some(drag) = self.active_drag.take() else {
2948 return false;
2949 };
2950 self.platform_owned_drag = Some(PlatformOwnedDrag {
2951 source_window,
2952 state: PlatformOwnedDragState::Suspended(drag),
2953 });
2954 true
2955 }
2956
2957 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2958 let Some(platform_drag) = self
2959 .platform_owned_drag
2960 .as_mut()
2961 .filter(|drag| drag.source_window == source_window)
2962 else {
2963 return false;
2964 };
2965 let state = std::mem::replace(
2966 &mut platform_drag.state,
2967 PlatformOwnedDragState::RestoredInSourceWindow,
2968 );
2969 let PlatformOwnedDragState::Suspended(drag) = state else {
2970 return false;
2971 };
2972 self.active_drag = Some(drag);
2973 true
2974 }
2975
2976 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2977 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2978 drag.source_window == source_window
2979 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2980 }) else {
2981 return false;
2982 };
2983 let Some(drag) = self.active_drag.take() else {
2984 return false;
2985 };
2986 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2987 true
2988 }
2989
2990 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2991 if !self
2992 .platform_owned_drag
2993 .as_ref()
2994 .is_some_and(|drag| drag.source_window == source_window)
2995 {
2996 return false;
2997 }
2998 self.platform_owned_drag = None;
2999 self.active_drag = None;
3000 true
3001 }
3002
3003 pub fn set_active_drag_cursor_style(
3005 &mut self,
3006 cursor_style: CursorStyle,
3007 window: &mut Window,
3008 ) -> bool {
3009 if let Some(ref mut drag) = self.active_drag {
3010 drag.cursor_style = Some(cursor_style);
3011 window.refresh();
3012 true
3013 } else {
3014 false
3015 }
3016 }
3017
3018 pub fn set_prompt_builder(
3021 &mut self,
3022 renderer: impl Fn(
3023 PromptLevel,
3024 &str,
3025 Option<&str>,
3026 &[PromptButton],
3027 PromptHandle,
3028 &mut Window,
3029 &mut App,
3030 ) -> RenderablePromptHandle
3031 + 'static,
3032 ) {
3033 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3034 }
3035
3036 pub fn reset_prompt_builder(&mut self) {
3038 self.prompt_builder = Some(PromptBuilder::Default);
3039 }
3040
3041 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3043 let asset_id = (TypeId::of::<A>(), hash(source));
3044 self.loading_assets.remove(&asset_id);
3045 }
3046
3047 #[cfg(any(test, feature = "test-support"))]
3050 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3051 let asset_id = (TypeId::of::<A>(), hash(source));
3052 self.loading_assets.contains_key(&asset_id)
3053 }
3054
3055 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3060 self.asset_entry::<A>(source).get()
3061 }
3062
3063 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3064 let asset_id = (TypeId::of::<A>(), hash(source));
3065 if !self.loading_assets.contains_key(&asset_id) {
3066 let future = A::load(source.clone(), self);
3067 let entry = CachedLoad::new(future, self);
3068 self.loading_assets.insert(asset_id, Box::new(entry));
3069 }
3070 self.loading_assets
3071 .get(&asset_id)
3072 .and_then(|entry| entry.downcast_ref())
3073 .expect("asset cache entries are keyed by their asset type")
3074 }
3075
3076 #[track_caller]
3079 pub fn focus_handle(&self) -> FocusHandle {
3080 FocusHandle::new(&self.focus_handles)
3081 }
3082
3083 pub fn notify(&mut self, entity_id: EntityId) {
3085 let window_invalidators = mem::take(
3086 self.window_invalidators_by_entity
3087 .entry(entity_id)
3088 .or_default(),
3089 );
3090
3091 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3096 .iter()
3097 .filter(|(window_id, _)| {
3098 self.tracked_entities
3099 .get(window_id)
3100 .is_some_and(|set| set.contains(&entity_id))
3101 })
3102 .map(|(_, invalidator)| invalidator.clone())
3103 .collect();
3104
3105 if live_invalidators.is_empty() {
3106 if self.pending_notifications.insert(entity_id) {
3107 self.pending_effects
3108 .push_back(Effect::Notify { emitter: entity_id });
3109 }
3110 } else {
3111 for invalidator in &live_invalidators {
3112 invalidator.invalidate_view(entity_id, self);
3113 }
3114 }
3115
3116 self.window_invalidators_by_entity
3117 .insert(entity_id, window_invalidators);
3118 }
3119
3120 #[cfg(any(test, feature = "test-support", debug_assertions))]
3122 pub fn get_name(&self) -> Option<&'static str> {
3123 self.name
3124 }
3125
3126 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3128 self.platform.can_select_mixed_files_and_dirs()
3129 }
3130
3131 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3136 for cell in self.windows.cells() {
3138 let mut host = cell.borrow_mut();
3139 _ = host.with_window(|window| window.drop_image(image.clone()));
3140 }
3141
3142 if let Some(window) = current_window {
3144 _ = window.drop_image(image);
3145 }
3146 }
3147
3148 #[cfg(any(feature = "inspector", debug_assertions))]
3150 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3151 self.inspector_renderer = Some(f);
3152 }
3153
3154 #[cfg(any(feature = "inspector", debug_assertions))]
3156 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3157 &mut self,
3158 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3159 ) where
3160 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3161 {
3162 self.inspector_element_registry.register(factory);
3163 }
3164
3165 pub fn init_colors(&mut self) {
3169 self.set_global(GlobalColors(Arc::new(Colors::default())));
3170 }
3171
3172 #[inline(never)]
3173 fn update_entity_erased(
3174 &mut self,
3175 handle: &AnyEntity,
3176 entity_type: &str,
3177 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3178 ) {
3179 self.update(|cx| {
3180 let mut lease = cx.entities.lease_erased(handle, entity_type);
3181 update(lease.entity.as_deref_mut().unwrap(), cx);
3182 cx.entities.end_lease_erased(handle.entity_id, lease);
3183 });
3184 }
3185
3186 #[inline(never)]
3187 #[track_caller]
3188 fn prepare_spawn(&self) -> AsyncApp {
3189 if self.quitting {
3190 debug_panic!("Can't spawn on main thread after on_app_quit")
3191 };
3192 self.to_async()
3193 }
3194}
3195
3196impl App {
3202 #[doc(hidden)]
3205 pub fn new_app_for_platform(platform: Rc<dyn Platform>) -> Rc<AppCell> {
3206 Self::new_app(platform, Arc::new(()), Arc::new(NullHttpClient))
3207 }
3208
3209 #[doc(hidden)]
3211 pub fn platform(&self) -> Rc<dyn Platform> {
3212 self.platform.clone()
3213 }
3214
3215 #[doc(hidden)]
3217 pub fn set_asset_source(&mut self, asset_source: Arc<dyn AssetSource>) {
3218 self.asset_source = asset_source.clone();
3219 self.svg_renderer = SvgRenderer::new(asset_source);
3220 }
3221
3222 #[doc(hidden)]
3224 pub fn set_layout_engine_factory(&mut self, factory: Rc<dyn Fn() -> Box<dyn LayoutEngine>>) {
3225 self.layout_engine_factory = factory;
3226 }
3227
3228 #[doc(hidden)]
3230 pub fn set_frame_pipeline_factory(
3231 &mut self,
3232 factory: Rc<dyn Fn(WindowId) -> Box<dyn FramePipeline>>,
3233 ) {
3234 self.frame_pipeline_factory = factory;
3235 }
3236
3237 #[doc(hidden)]
3239 pub fn set_text_system(&mut self, text_system: Arc<dyn TextSystem>) {
3240 self.text_system = text_system;
3241 }
3242
3243 #[doc(hidden)]
3245 pub fn set_restart_arguments(&mut self, arguments: Vec<OsString>) {
3246 self.restart_arguments = arguments;
3247 }
3248
3249 #[doc(hidden)]
3251 pub fn set_accessibility_force_disabled(&mut self, disabled: bool) {
3252 self.accessibility_force_disabled = disabled;
3253 }
3254}
3255
3256impl AppContext for App {
3257 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3262 self.update(|cx| {
3263 let slot = cx.entities.reserve();
3264 let handle = slot.clone();
3265 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3266
3267 cx.push_effect(Effect::EntityCreated {
3268 entity: handle.into_any(),
3269 tid: TypeId::of::<T>(),
3270 window: cx.window_update_stack.last().cloned(),
3271 });
3272
3273 cx.entities.insert(slot, entity)
3274 })
3275 }
3276
3277 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3278 Reservation(self.entities.reserve())
3279 }
3280
3281 fn insert_entity<T: 'static>(
3282 &mut self,
3283 reservation: Reservation<T>,
3284 build_entity: impl FnOnce(&mut Context<T>) -> T,
3285 ) -> Entity<T> {
3286 self.update(|cx| {
3287 let slot = reservation.0;
3288 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3289 cx.entities.insert(slot, entity)
3290 })
3291 }
3292
3293 #[inline(always)]
3296 fn update_entity<T: 'static, R>(
3297 &mut self,
3298 handle: &Entity<T>,
3299 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3300 ) -> R {
3301 let mut update = Some(update);
3302 let mut result = None;
3303 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3304 let value = update.take().unwrap()(
3305 entity.downcast_mut::<T>().unwrap(),
3306 &mut Context::new_context(cx, handle.downgrade()),
3307 );
3308 result = Some(value);
3309 });
3310 result.unwrap()
3311 }
3312
3313 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3314 where
3315 T: 'static,
3316 {
3317 GpuiBorrow::new(handle.clone(), self)
3318 }
3319
3320 #[inline(always)]
3321 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3322 where
3323 T: 'static,
3324 {
3325 let entity = self.entities.read(handle);
3326 read(entity, self)
3327 }
3328
3329 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3330 where
3331 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3332 {
3333 self.update_window_id(handle.id, update)
3334 }
3335
3336 fn with_window<R>(
3337 &mut self,
3338 entity_id: EntityId,
3339 f: impl FnOnce(&mut Window, &mut App) -> R,
3340 ) -> Option<R> {
3341 App::with_window(self, entity_id, f)
3342 }
3343
3344 fn read_window<T, R>(
3345 &self,
3346 window: &WindowHandle<T>,
3347 read: impl FnOnce(Entity<T>, &App) -> R,
3348 ) -> Result<R>
3349 where
3350 T: 'static,
3351 {
3352 let cell = self.windows.cell(window.id).context("window not found")?;
3353 let host = cell
3354 .try_borrow()
3355 .expect("attempted to read a window that is already on the stack");
3356
3357 let root_view = host.core.root.clone().unwrap();
3358 let view = root_view
3359 .downcast::<T>()
3360 .map_err(|_| anyhow!("root view's type has changed"))?;
3361
3362 Ok(read(view, self))
3363 }
3364
3365 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3366 where
3367 R: Send + 'static,
3368 {
3369 self.background_executor.spawn(future)
3370 }
3371
3372 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3373 where
3374 G: Global,
3375 {
3376 let mut g = self.global::<G>();
3377 callback(g, self)
3378 }
3379}
3380
3381pub(crate) enum Effect {
3383 Notify {
3384 emitter: EntityId,
3385 },
3386 Emit {
3387 emitter: EntityId,
3388 event_type: TypeId,
3389 event: ArenaBox<dyn Any>,
3390 },
3391 RefreshWindows,
3392 NotifyGlobalObservers {
3393 global_type: TypeId,
3394 },
3395 Defer {
3396 callback: Box<dyn FnOnce(&mut App) + 'static>,
3397 },
3398 EntityCreated {
3399 entity: AnyEntity,
3400 tid: TypeId,
3401 window: Option<WindowId>,
3402 },
3403}
3404
3405impl std::fmt::Debug for Effect {
3406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3407 match self {
3408 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3409 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3410 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3411 Effect::NotifyGlobalObservers { global_type } => {
3412 write!(f, "NotifyGlobalObservers({:?})", global_type)
3413 }
3414 Effect::Defer { .. } => write!(f, "Defer(..)"),
3415 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3416 }
3417 }
3418}
3419
3420pub(crate) struct GlobalLease<G: Global> {
3422 global: Box<dyn Any>,
3423 global_type: PhantomData<G>,
3424}
3425
3426impl<G: Global> GlobalLease<G> {
3427 fn new(global: Box<dyn Any>) -> Self {
3428 GlobalLease {
3429 global,
3430 global_type: PhantomData,
3431 }
3432 }
3433}
3434
3435impl<G: Global> Deref for GlobalLease<G> {
3436 type Target = G;
3437
3438 fn deref(&self) -> &Self::Target {
3439 self.global.downcast_ref().unwrap()
3440 }
3441}
3442
3443impl<G: Global> DerefMut for GlobalLease<G> {
3444 fn deref_mut(&mut self) -> &mut Self::Target {
3445 self.global.downcast_mut().unwrap()
3446 }
3447}
3448
3449pub struct AnyDrag {
3452 pub view: AnyView,
3454
3455 pub value: Arc<dyn Any>,
3457
3458 pub cursor_offset: Point<Pixels>,
3461
3462 pub cursor_style: Option<CursorStyle>,
3464
3465 pub external_payload_source: Option<ExternalDragPayloadSource>,
3468}
3469
3470pub type ExternalDragPayloadSource =
3473 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3474
3475#[derive(Clone)]
3478pub struct AnyTooltip {
3479 pub view: AnyView,
3481
3482 pub mouse_position: Point<Pixels>,
3484
3485 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3489}
3490
3491#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3493pub enum InputPreference {
3494 CharacterInput,
3496 KeyBindings,
3498}
3499
3500#[derive(Debug)]
3502pub struct KeystrokeEvent {
3503 pub keystroke: Keystroke,
3505
3506 pub input_preference: InputPreference,
3514
3515 pub action: Option<Box<dyn Action>>,
3517
3518 pub context_stack: Vec<KeyContext>,
3520}
3521
3522struct NullHttpClient;
3523
3524impl HttpClient for NullHttpClient {
3525 fn send(
3526 &self,
3527 _req: http_client::Request<http_client::AsyncBody>,
3528 ) -> futures::future::BoxFuture<
3529 'static,
3530 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3531 > {
3532 async move {
3533 anyhow::bail!("No HttpClient available");
3534 }
3535 .boxed()
3536 }
3537
3538 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3539 None
3540 }
3541
3542 fn proxy(&self) -> Option<&Url> {
3543 None
3544 }
3545}
3546
3547pub struct GpuiBorrow<'a, T> {
3549 inner: Option<Lease<T>>,
3550 app: &'a mut App,
3551}
3552
3553impl<'a, T: 'static> GpuiBorrow<'a, T> {
3554 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3555 app.start_update();
3556 let lease = app.entities.lease(&inner);
3557 Self {
3558 inner: Some(lease),
3559 app,
3560 }
3561 }
3562}
3563
3564impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3565 fn borrow(&self) -> &T {
3566 self.inner.as_ref().unwrap().borrow()
3567 }
3568}
3569
3570impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3571 fn borrow_mut(&mut self) -> &mut T {
3572 self.inner.as_mut().unwrap().borrow_mut()
3573 }
3574}
3575
3576impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3577 type Target = T;
3578
3579 fn deref(&self) -> &Self::Target {
3580 self.inner.as_ref().unwrap()
3581 }
3582}
3583
3584impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3585 fn deref_mut(&mut self) -> &mut T {
3586 self.inner.as_mut().unwrap()
3587 }
3588}
3589
3590impl<'a, T> Drop for GpuiBorrow<'a, T> {
3591 fn drop(&mut self) {
3592 let lease = self.inner.take().unwrap();
3593 self.app.notify(lease.id);
3594 self.app.entities.end_lease(lease);
3595 self.app.finish_update();
3596 }
3597}
3598
3599#[cfg(test)]
3600mod test {
3601 use std::{
3602 cell::{Cell, RefCell},
3603 ffi::OsString,
3604 path::PathBuf,
3605 rc::Rc,
3606 };
3607
3608 #[cfg(unix)]
3609 use std::os::unix::ffi::OsStringExt;
3610
3611 use crate::{
3612 AppContext, Context, DefaultTextSystemExt, Empty, FallbackFontClass, IntoElement,
3613 MissingGlyph, Render, TestAppContext, Window,
3614 };
3615
3616 struct RenderCounter(Rc<Cell<usize>>);
3617
3618 impl Render for RenderCounter {
3619 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3620 self.0.set(self.0.get() + 1);
3621 Empty
3622 }
3623 }
3624
3625 #[gpui::test]
3626 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3627 let render_count = Rc::new(Cell::new(0));
3628
3629 let _window = cx.add_window({
3630 let render_count = render_count.clone();
3631 move |_, _| RenderCounter(render_count)
3632 });
3633
3634 cx.run_until_parked();
3635 let render_count_before_refresh = render_count.get();
3636
3637 cx.to_async().refresh();
3638
3639 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3640 }
3641
3642 #[gpui::test]
3643 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3644 let observed = Rc::new(RefCell::new(Vec::new()));
3645 let subscription = cx.update(|cx| {
3646 let observed = observed.clone();
3647 cx.on_missing_glyphs(move |missing_glyphs, _| {
3648 observed.borrow_mut().extend_from_slice(missing_glyphs);
3649 })
3650 });
3651 cx.update(|cx| {
3652 cx.text_system()
3653 .as_default_text_system()
3654 .expect("the test harness installs a DefaultTextSystem")
3655 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3656 });
3657 cx.run_until_parked();
3658 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3659
3660 let second_observed = Rc::new(RefCell::new(Vec::new()));
3661 let second_subscription = cx.update(|cx| {
3662 let second_observed = second_observed.clone();
3663 cx.on_missing_glyphs(move |missing_glyphs, _| {
3664 second_observed
3665 .borrow_mut()
3666 .extend_from_slice(missing_glyphs);
3667 })
3668 });
3669 cx.update(|cx| {
3670 cx.text_system()
3671 .as_default_text_system()
3672 .expect("the test harness installs a DefaultTextSystem")
3673 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3674 });
3675 cx.run_until_parked();
3676 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3677 assert_eq!(
3678 second_observed.borrow().as_slice(),
3679 &[missing_glyph("replacement")]
3680 );
3681
3682 drop(subscription);
3683 cx.update(|cx| {
3684 cx.text_system()
3685 .as_default_text_system()
3686 .expect("the test harness installs a DefaultTextSystem")
3687 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3688 });
3689 cx.run_until_parked();
3690 assert_eq!(
3691 second_observed.borrow().as_slice(),
3692 &[
3693 missing_glyph("replacement"),
3694 missing_glyph("after old drop")
3695 ]
3696 );
3697
3698 drop(second_subscription);
3699 cx.update(|cx| {
3700 cx.text_system()
3701 .as_default_text_system()
3702 .expect("the test harness installs a DefaultTextSystem")
3703 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3704 });
3705 cx.run_until_parked();
3706 assert_eq!(second_observed.borrow().len(), 2);
3707 }
3708
3709 #[test]
3710 fn test_gpui_borrow() {
3711 let cx = TestAppContext::single();
3712 let observation_count = Rc::new(RefCell::new(0));
3713
3714 let state = cx.update(|cx| {
3715 let state = cx.new(|_| false);
3716 cx.observe(&state, {
3717 let observation_count = observation_count.clone();
3718 move |_, _| {
3719 let mut count = observation_count.borrow_mut();
3720 *count += 1;
3721 }
3722 })
3723 .detach();
3724
3725 state
3726 });
3727
3728 cx.update(|cx| {
3729 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3731 });
3732
3733 cx.update(|cx| {
3734 state.write(cx, false);
3735 });
3736
3737 assert_eq!(*observation_count.borrow(), 2);
3738 }
3739
3740 #[gpui::test]
3741 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3742 #[cfg(unix)]
3743 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3744 #[cfg(not(unix))]
3745 let user_data_dir = OsString::from("C:\\zed data");
3746 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3747 let restart_path = PathBuf::from("updated-zed");
3748 cx.update(|cx| cx.set_restart_arguments(arguments.clone()));
3749 let restart = cx.expect_restart();
3750
3751 cx.update(|cx| {
3752 cx.set_restart_path(restart_path.clone());
3753 cx.restart();
3754 });
3755
3756 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3757 assert_eq!(path, Some(restart_path));
3758 assert_eq!(restart_arguments, arguments);
3759 }
3760
3761 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3762 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3763 }
3764}