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, DisplayId,
50 DmaBufCapabilities, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap,
51 ForegroundExecutor, FramePipeline, Global, GpuAdapterInfo, KeyBinding, KeyContext, Keymap,
52 Keystroke, LayoutEngine, LayoutId, Menu, MenuCommandId, MenuItem, MissingGlyph, OwnedMenu,
53 OwnedMenuItem, PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
54 PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton, PromptHandle,
55 PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource,
56 SharedString, StandardImmediatePipeline, SubscriberSet, Subscription, SvgRenderer,
57 SystemNotification, SystemNotificationResponse, SystemWindowTab, Task, TextRenderingMode,
58 TextSystem, ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle,
59 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 Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
210type MissingGlyphCallback = Box<dyn FnMut(&[MissingGlyph], &mut App) + 'static>;
211pub(crate) type KeystrokeObserver =
212 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
213type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
214type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
215type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
216type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
217
218struct MissingGlyphCallbackEntry {
219 registration: Rc<()>,
220 callback: Option<MissingGlyphCallback>,
221}
222
223#[derive(Default)]
224struct MissingGlyphCallbackSlot {
225 entry: RefCell<Option<MissingGlyphCallbackEntry>>,
226}
227
228impl MissingGlyphCallbackSlot {
229 fn replace(&self, callback: MissingGlyphCallback) -> Rc<()> {
230 let registration = Rc::new(());
231 self.entry.borrow_mut().replace(MissingGlyphCallbackEntry {
232 registration: registration.clone(),
233 callback: Some(callback),
234 });
235 registration
236 }
237
238 fn invoke(&self, missing_glyphs: &[MissingGlyph], cx: &mut App) {
239 let Some((registration, mut callback)) =
240 self.entry.borrow_mut().as_mut().and_then(|entry| {
241 entry
242 .callback
243 .take()
244 .map(|callback| (entry.registration.clone(), callback))
245 })
246 else {
247 return;
248 };
249 callback(missing_glyphs, cx);
250
251 let mut entry = self.entry.borrow_mut();
252 let is_current = entry
253 .as_ref()
254 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, ®istration));
255 if is_current {
256 let Some(entry) = entry.as_mut() else {
257 return;
258 };
259 entry.callback = Some(callback);
260 }
261 }
262
263 fn remove(&self, registration: &Rc<()>) -> bool {
264 let mut entry = self.entry.borrow_mut();
265 let is_current = entry
266 .as_ref()
267 .is_some_and(|entry| Rc::ptr_eq(&entry.registration, registration));
268 if is_current {
269 entry.take();
270 }
271 is_current
272 }
273}
274
275#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
277pub enum QuitMode {
278 #[default]
280 Default,
281 LastWindowClosed,
283 Explicit,
285}
286
287#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
292pub enum CursorHideMode {
293 Never,
295 OnTyping,
297 #[default]
300 OnTypingAndAction,
301}
302
303#[derive(Default)]
305pub struct SystemWindowTabController {
306 visible: Option<bool>,
307 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
308}
309
310impl Global for SystemWindowTabController {}
311
312impl SystemWindowTabController {
313 pub fn new() -> Self {
315 Self {
316 visible: None,
317 tab_groups: FxHashMap::default(),
318 }
319 }
320
321 pub fn init(cx: &mut App) {
323 cx.set_global(SystemWindowTabController::new());
324 }
325
326 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
328 &self.tab_groups
329 }
330
331 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<AnyWindowHandle> {
333 let controller = cx.global::<SystemWindowTabController>();
334 let current_group = controller
335 .tab_groups
336 .iter()
337 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
338
339 let current_group = current_group?;
340 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
342 let idx = group_ids.iter().position(|g| *g == current_group)?;
343 let next_idx = (idx + 1) % group_ids.len();
344
345 let tab_handle = controller
346 .tab_groups
347 .get(group_ids[next_idx])
348 .and_then(|tabs| {
349 tabs.iter()
350 .max_by_key(|tab| tab.last_active_at)
351 .or_else(|| tabs.first())
352 .map(|tab| tab.handle)
353 })?;
354 cx.window_handle(tab_handle)
355 }
356
357 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<AnyWindowHandle> {
359 let controller = cx.global::<SystemWindowTabController>();
360 let current_group = controller
361 .tab_groups
362 .iter()
363 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
364
365 let current_group = current_group?;
366 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
368 let idx = group_ids.iter().position(|g| *g == current_group)?;
369 let prev_idx = if idx == 0 {
370 group_ids.len() - 1
371 } else {
372 idx - 1
373 };
374
375 let tab_handle = controller
376 .tab_groups
377 .get(group_ids[prev_idx])
378 .and_then(|tabs| {
379 tabs.iter()
380 .max_by_key(|tab| tab.last_active_at)
381 .or_else(|| tabs.first())
382 .map(|tab| tab.handle)
383 })?;
384 cx.window_handle(tab_handle)
385 }
386
387 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
389 self.tab_groups
390 .values()
391 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
392 }
393
394 pub fn init_visible(cx: &mut App, visible: bool) {
396 let mut controller = cx.global_mut::<SystemWindowTabController>();
397 if controller.visible.is_none() {
398 controller.visible = Some(visible);
399 }
400 }
401
402 pub fn is_visible(&self) -> bool {
404 self.visible.unwrap_or(false)
405 }
406
407 pub fn set_visible(cx: &mut App, visible: bool) {
409 let mut controller = cx.global_mut::<SystemWindowTabController>();
410 controller.visible = Some(visible);
411 }
412
413 pub fn update_last_active(cx: &mut App, id: WindowId) {
415 let mut controller = cx.global_mut::<SystemWindowTabController>();
416 for windows in controller.tab_groups.values_mut() {
417 for tab in windows.iter_mut() {
418 if tab.id == id {
419 tab.last_active_at = Instant::now();
420 }
421 }
422 }
423 }
424
425 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
427 let mut controller = cx.global_mut::<SystemWindowTabController>();
428 for (_, windows) in controller.tab_groups.iter_mut() {
429 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
430 if ix < windows.len() && current_pos != ix {
431 let window_tab = windows.remove(current_pos);
432 windows.insert(ix, window_tab);
433 }
434 break;
435 }
436 }
437 }
438
439 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
441 let controller = cx.global::<SystemWindowTabController>();
442 let tab = controller
443 .tab_groups
444 .values()
445 .flat_map(|windows| windows.iter())
446 .find(|tab| tab.id == id);
447
448 if tab.map_or(true, |t| t.title == title) {
449 return;
450 }
451
452 let mut controller = cx.global_mut::<SystemWindowTabController>();
453 for windows in controller.tab_groups.values_mut() {
454 for tab in windows.iter_mut() {
455 if tab.id == id {
456 tab.title = title;
457 return;
458 }
459 }
460 }
461 }
462
463 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
465 let mut controller = cx.global_mut::<SystemWindowTabController>();
466 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
467 return;
468 };
469
470 let mut expected_tab_ids: Vec<_> = tabs
471 .iter()
472 .filter(|tab| tab.id != id)
473 .map(|tab| tab.id)
474 .sorted()
475 .collect();
476
477 let mut tab_group_id = None;
478 for (group_id, group_tabs) in &controller.tab_groups {
479 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
480 if tab_ids == expected_tab_ids {
481 tab_group_id = Some(*group_id);
482 break;
483 }
484 }
485
486 if let Some(tab_group_id) = tab_group_id {
487 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
488 tabs.push(tab);
489 }
490 } else {
491 let new_group_id = controller.tab_groups.len();
492 controller.tab_groups.insert(new_group_id, tabs);
493 }
494 }
495
496 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
498 let mut controller = cx.global_mut::<SystemWindowTabController>();
499 let mut removed_tab = None;
500
501 controller.tab_groups.retain(|_, tabs| {
502 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
503 removed_tab = Some(tabs.remove(pos));
504 }
505 !tabs.is_empty()
506 });
507
508 removed_tab
509 }
510
511 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
513 let mut removed_tab = Self::remove_tab(cx, id);
514 let mut controller = cx.global_mut::<SystemWindowTabController>();
515
516 if let Some(tab) = removed_tab {
517 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
518 controller.tab_groups.insert(new_group_id, vec![tab]);
519 }
520 }
521
522 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
524 let mut controller = cx.global_mut::<SystemWindowTabController>();
525 let Some(initial_tabs) = controller.tabs(id) else {
526 return;
527 };
528
529 let initial_tabs_len = initial_tabs.len();
530 let mut all_tabs = initial_tabs.clone();
531
532 for (_, mut tabs) in controller.tab_groups.drain() {
533 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
534 all_tabs.extend(tabs);
535 }
536
537 controller.tab_groups.insert(0, all_tabs);
538 }
539
540 pub fn select_next_tab(cx: &mut App, id: WindowId) {
542 let next_handle = {
543 let controller = cx.global::<SystemWindowTabController>();
544 let Some(tabs) = controller.tabs(id) else {
545 return;
546 };
547
548 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
549 let next_index = (current_index + 1) % tabs.len();
550 tabs[next_index].handle
551 };
552
553 if let Some(handle) = cx.window_handle(next_handle) {
554 let _ = handle.update(cx, |_, window, _| {
555 window.activate_window();
556 });
557 }
558 }
559
560 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
562 let previous_handle = {
563 let controller = cx.global::<SystemWindowTabController>();
564 let Some(tabs) = controller.tabs(id) else {
565 return;
566 };
567
568 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
569 let previous_index = if current_index == 0 {
570 tabs.len() - 1
571 } else {
572 current_index - 1
573 };
574 tabs[previous_index].handle
575 };
576
577 if let Some(handle) = cx.window_handle(previous_handle) {
578 let _ = handle.update(cx, |_, window, _| {
579 window.activate_window();
580 });
581 }
582 }
583}
584
585pub(crate) enum GpuiMode {
586 #[cfg(any(test, feature = "test-support"))]
587 Test {
588 skip_drawing: bool,
589 },
590 Production,
591}
592
593impl GpuiMode {
594 #[cfg(any(test, feature = "test-support"))]
595 pub fn test() -> Self {
596 GpuiMode::Test {
597 skip_drawing: false,
598 }
599 }
600
601 #[inline]
602 pub(crate) fn skip_drawing(&self) -> bool {
603 match self {
604 #[cfg(any(test, feature = "test-support"))]
605 GpuiMode::Test { skip_drawing } => *skip_drawing,
606 GpuiMode::Production => false,
607 }
608 }
609}
610
611struct PlatformOwnedDrag {
612 source_window: WindowId,
613 state: PlatformOwnedDragState,
614}
615
616enum PlatformOwnedDragState {
617 Suspended(AnyDrag),
618 RestoredInSourceWindow,
621}
622
623pub struct App {
627 pub(crate) this: Weak<AppCell>,
628 pub(crate) platform: Rc<dyn Platform>,
629 text_system: Arc<dyn TextSystem>,
630 layout_engine_factory: Rc<dyn Fn() -> Box<dyn LayoutEngine>>,
634 frame_pipeline_factory: Rc<dyn Fn(WindowId) -> Box<dyn FramePipeline>>,
638
639 pub(crate) actions: Rc<ActionRegistry>,
640 pub(crate) active_drag: Option<AnyDrag>,
641 platform_owned_drag: Option<PlatformOwnedDrag>,
642 pub(crate) background_executor: BackgroundExecutor,
643 pub(crate) foreground_executor: ForegroundExecutor,
644 #[cfg(feature = "profiler")]
645 foreground_journal: crate::profiler::journal::ForegroundJournal,
646 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
647 hang_monitor: Option<crate::profiler::hang::HangMonitor>,
648 pub(crate) entities: EntityMap,
649 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
650 pub(crate) windows: WindowRegistry,
651 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
652 pub(crate) focus_handles: Arc<FocusMap>,
653 pub(crate) keymap: Rc<RefCell<Keymap>>,
654 pub(crate) menu_actions: Rc<RefCell<Vec<Box<dyn Action>>>>,
655 owned_menus: Rc<RefCell<Option<Vec<OwnedMenu>>>>,
656 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
657 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
658 pub(crate) global_action_listeners:
659 TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
660 pending_effects: VecDeque<Effect>,
661
662 pub(crate) observers: SubscriberSet<EntityId, Handler>,
663 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
664 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
665 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
666 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
667 missing_glyph_callback: Rc<MissingGlyphCallbackSlot>,
668 pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
669 pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
670 pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
671 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
672 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
673 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
674 pub(crate) restart_observers: SubscriberSet<(), Handler>,
675 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
676
677 pub(crate) element_arena: RefCell<Arena>,
680 pub(crate) event_arena: Arena,
682
683 pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
688
689 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
691 asset_source: Arc<dyn AssetSource>,
692 pub(crate) svg_renderer: SvgRenderer,
693 http_client: Arc<dyn HttpClient>,
694
695 pub(crate) pending_notifications: FxHashSet<EntityId>,
697 pub(crate) pending_global_notifications: TypeIdHashSet,
698 pub(crate) restart_path: Option<PathBuf>,
699 pub(crate) restart_arguments: Vec<OsString>,
700 pub(crate) layout_id_buffer: Vec<LayoutId>, pub(crate) propagate_event: bool,
702 pub(crate) prompt_builder: Option<PromptBuilder>,
703 pub(crate) window_invalidators_by_entity:
704 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
705 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
706 pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
707 #[cfg(any(feature = "inspector", debug_assertions))]
708 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
709 #[cfg(any(feature = "inspector", debug_assertions))]
710 pub(crate) inspector_element_registry: InspectorElementRegistry,
711 #[cfg(any(test, feature = "test-support", debug_assertions))]
712 pub(crate) name: Option<&'static str>,
713 pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
714
715 pub(crate) window_update_stack: Vec<WindowId>,
716 pub(crate) mode: GpuiMode,
717 pub(crate) cursor_hide_mode: CursorHideMode,
718 pub(crate) reduce_motion: bool,
719 pub(crate) synced_animation_epoch: Instant,
721 pub(crate) accessibility_force_disabled: bool,
724 pending_updates: usize,
725 quit_mode: QuitMode,
726 quitting: bool,
727
728 #[cfg(any(test, gpui_leak_detection))]
731 _ref_counts: Arc<RwLock<EntityRefCounts>>,
732}
733
734impl App {
735 pub(crate) fn new_layout_engine(&self) -> Box<dyn LayoutEngine> {
737 (self.layout_engine_factory)()
738 }
739
740 pub(crate) fn new_frame_pipeline(&self, window_id: WindowId) -> Box<dyn FramePipeline> {
742 (self.frame_pipeline_factory)(window_id)
743 }
744
745 #[allow(clippy::new_ret_no_self)]
746 pub(crate) fn new_app(
747 platform: Rc<dyn Platform>,
748 asset_source: Arc<dyn AssetSource>,
749 http_client: Arc<dyn HttpClient>,
750 ) -> Rc<AppCell> {
751 let background_executor = platform.background_executor();
752 let foreground_executor = platform.foreground_executor();
753 assert!(
754 background_executor.is_main_thread(),
755 "must construct App on main thread"
756 );
757 crate::profiler::install_profiler_hooks();
758 #[cfg(feature = "profiler")]
759 let foreground_journal = crate::profiler::journal::install_foreground_journal();
760 let synced_animation_epoch = background_executor.now();
761
762 let text_system = Arc::new(DefaultTextSystem::new(platform.text_system()));
763 let entities = EntityMap::new();
764 let keyboard_layout = platform.keyboard_layout();
765 let keyboard_mapper = platform.keyboard_mapper();
766
767 #[cfg(any(test, gpui_leak_detection))]
768 let _ref_counts = entities.ref_counts_drop_handle();
769
770 let app = Rc::new_cyclic(|this| AppCell {
771 app: RefCell::new(App {
772 this: this.clone(),
773 platform: platform.clone(),
774 text_system,
775 layout_engine_factory: Rc::new(gpui_engine_default::default_layout_engine),
776 frame_pipeline_factory: Rc::new(|_| Box::new(StandardImmediatePipeline)),
777 text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
778 mode: GpuiMode::Production,
779 actions: Rc::new(ActionRegistry::default()),
780 pending_updates: 0,
781 active_drag: None,
782 platform_owned_drag: None,
783 background_executor,
784 foreground_executor,
785 #[cfg(feature = "profiler")]
786 foreground_journal,
787 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
788 hang_monitor: None,
789 svg_renderer: SvgRenderer::new(asset_source.clone()),
790 loading_assets: Default::default(),
791 asset_source,
792 http_client,
793 globals_by_type: Default::default(),
794 entities,
795 new_entity_observers: SubscriberSet::new(),
796 windows: WindowRegistry::default(),
797 window_update_stack: Vec::new(),
798 window_handles: FxHashMap::default(),
799 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
800 keymap: Rc::new(RefCell::new(Keymap::default())),
801 menu_actions: Rc::new(RefCell::new(Vec::new())),
802 owned_menus: Rc::new(RefCell::new(None)),
803 keyboard_layout,
804 keyboard_mapper,
805 global_action_listeners: Default::default(),
806 pending_effects: VecDeque::new(),
807 pending_notifications: FxHashSet::default(),
808 pending_global_notifications: Default::default(),
809 observers: SubscriberSet::new(),
810 tracked_entities: FxHashMap::default(),
811 window_invalidators_by_entity: FxHashMap::default(),
812 current_window_by_entity: FxHashMap::default(),
813 event_listeners: SubscriberSet::new(),
814 release_listeners: SubscriberSet::new(),
815 keystroke_observers: SubscriberSet::new(),
816 keystroke_interceptors: SubscriberSet::new(),
817 keyboard_layout_observers: SubscriberSet::new(),
818 missing_glyph_callback: Rc::default(),
819 thermal_state_observers: SubscriberSet::new(),
820 system_sleep_observers: SubscriberSet::new(),
821 system_wake_observers: SubscriberSet::new(),
822 global_observers: SubscriberSet::new(),
823 quit_observers: SubscriberSet::new(),
824 restart_observers: SubscriberSet::new(),
825 restart_path: None,
826 restart_arguments: Vec::new(),
827 window_closed_observers: SubscriberSet::new(),
828 layout_id_buffer: Default::default(),
829 propagate_event: true,
830 prompt_builder: Some(PromptBuilder::Default),
831 #[cfg(any(feature = "inspector", debug_assertions))]
832 inspector_renderer: None,
833 #[cfg(any(feature = "inspector", debug_assertions))]
834 inspector_element_registry: InspectorElementRegistry::default(),
835 quit_mode: QuitMode::default(),
836 quitting: false,
837 cursor_hide_mode: CursorHideMode::default(),
838 reduce_motion: false,
839 synced_animation_epoch,
840 accessibility_force_disabled: false,
841
842 #[cfg(any(test, feature = "test-support", debug_assertions))]
843 name: None,
844 element_arena: RefCell::new(Arena::new(1024 * 1024)),
845 event_arena: Arena::new(1024 * 1024),
846
847 #[cfg(any(test, gpui_leak_detection))]
848 _ref_counts,
849 }),
850 });
851
852 init_app_menus(platform.as_ref(), &app.borrow());
853 SystemWindowTabController::init(&mut app.borrow_mut());
854 #[cfg(feature = "profiler")]
855 crate::profiler::journal::observe_power(&app.borrow());
856
857 platform.on_keyboard_layout_change(Box::new({
858 let app = Rc::downgrade(&app);
859 move || {
860 if let Some(app) = app.upgrade() {
861 let cx = &mut app.borrow_mut();
862 cx.keyboard_layout = cx.platform.keyboard_layout();
863 cx.keyboard_mapper = cx.platform.keyboard_mapper();
864 cx.keyboard_layout_observers
865 .clone()
866 .retain(&(), move |callback| (callback)(cx));
867 }
868 }
869 }));
870
871 platform.on_thermal_state_change(Box::new({
872 let app = Rc::downgrade(&app);
873 move || {
874 if let Some(app) = app.upgrade() {
875 let cx = &mut app.borrow_mut();
876 cx.thermal_state_observers
877 .clone()
878 .retain(&(), move |callback| (callback)(cx));
879 }
880 }
881 }));
882
883 platform.on_system_sleep(Box::new({
884 let app = Rc::downgrade(&app);
885 move || {
886 if let Some(app) = app.upgrade() {
887 let cx = &mut app.borrow_mut();
888 cx.system_sleep_observers
889 .clone()
890 .retain(&(), move |callback| (callback)(cx));
891 }
892 }
893 }));
894
895 platform.on_system_wake(Box::new({
896 let app = Rc::downgrade(&app);
897 move || {
898 if let Some(app) = app.upgrade() {
899 let cx = &mut app.borrow_mut();
900 cx.system_wake_observers
901 .clone()
902 .retain(&(), move |callback| (callback)(cx));
903 }
904 }
905 }));
906
907 platform.on_quit(Box::new({
908 let cx = Rc::downgrade(&app);
909 move || {
910 let Some(cx) = cx.upgrade() else {
911 return true;
912 };
913 match cx.try_borrow_mut() {
914 Ok(mut cx) => {
915 cx.shutdown();
916 true
917 }
918 Err(_) => {
919 false
922 }
923 }
924 }
925 }));
926
927 app
928 }
929
930 #[doc(hidden)]
931 pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
932 self.entities.ref_counts_drop_handle()
933 }
934
935 #[cfg(any(test, gpui_leak_detection))]
941 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
942 self.entities.leak_detector_snapshot()
943 }
944
945 #[cfg(any(test, gpui_leak_detection))]
957 pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
958 self.entities.assert_no_new_leaks(snapshot)
959 }
960
961 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
963 pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
964 LeakDetectorSnapshot::default()
965 }
966
967 #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
970 pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
971
972 pub fn shutdown(&mut self) {
978 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
981 let hang_monitor_flush = self
982 .hang_monitor
983 .as_ref()
984 .and_then(|hang_monitor| hang_monitor.request_flush());
985
986 let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
987
988 for observer in self.quit_observers.remove(&()) {
989 futures.push(observer(self));
990 }
991
992 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
993 if let Some(flushed) = hang_monitor_flush {
994 futures.push(
995 async move {
996 if flushed.await.is_err() {
997 log::warn!("hang monitor exited before flushing");
998 }
999 }
1000 .boxed_local(),
1001 );
1002 }
1003
1004 self.windows.clear();
1005 self.window_handles.clear();
1006 self.flush_effects();
1007 self.quitting = true;
1008
1009 let futures = futures::future::join_all(futures);
1010 #[cfg(not(target_family = "wasm"))]
1011 if self
1012 .foreground_executor
1013 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1014 .is_err()
1015 {
1016 log::error!("timed out waiting on app_will_quit");
1017 }
1018 #[cfg(target_family = "wasm")]
1019 self.foreground_executor.spawn(futures).detach();
1020
1021 self.quitting = false;
1022 }
1023
1024 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1026 self.keyboard_layout.as_ref()
1027 }
1028
1029 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1031 &self.keyboard_mapper
1032 }
1033
1034 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1036 where
1037 F: 'static + FnMut(&mut App),
1038 {
1039 let (subscription, activate) = self.keyboard_layout_observers.insert(
1040 (),
1041 Box::new(move |cx| {
1042 callback(cx);
1043 true
1044 }),
1045 );
1046 activate();
1047 subscription
1048 }
1049
1050 pub fn quit(&self) {
1052 self.platform.quit();
1053 }
1054
1055 pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1069 if !self.windows.is_empty() {
1070 return Task::ready(Err(anyhow::anyhow!(
1071 "cannot switch windowing modes while windows are open"
1072 )));
1073 }
1074 self.platform.request_windowing(request)
1075 }
1076
1077 pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1087 self.platform.graphical_environment()
1088 }
1089
1090 pub fn cursor_hide_mode(&self) -> CursorHideMode {
1093 self.cursor_hide_mode
1094 }
1095
1096 pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1099 self.cursor_hide_mode = mode;
1100 }
1101
1102 pub fn is_cursor_visible(&self) -> bool {
1108 self.platform.is_cursor_visible()
1109 }
1110
1111 pub fn reduce_motion(&self) -> bool {
1114 self.reduce_motion
1115 }
1116
1117 pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1120 if self.reduce_motion != reduce_motion {
1121 self.reduce_motion = reduce_motion;
1122 self.refresh_windows();
1123 }
1124 }
1125
1126 pub fn refresh_windows(&mut self) {
1129 self.pending_effects.push_back(Effect::RefreshWindows);
1130 }
1131
1132 #[inline(always)]
1133 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1134 self.start_update();
1135 let result = update(self);
1136 self.finish_update();
1137 result
1138 }
1139
1140 pub(crate) fn start_update(&mut self) {
1141 self.pending_updates += 1;
1142 }
1143
1144 #[inline(never)]
1145 pub(crate) fn finish_update(&mut self) {
1146 if self.pending_updates == 1 {
1147 self.flush_effects();
1148 }
1149 self.pending_updates -= 1;
1150 }
1151
1152 pub fn observe<W>(
1154 &mut self,
1155 entity: &Entity<W>,
1156 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1157 ) -> Subscription
1158 where
1159 W: 'static,
1160 {
1161 self.observe_internal(entity, move |e, cx| {
1162 on_notify(e, cx);
1163 true
1164 })
1165 }
1166
1167 pub(crate) fn detect_accessed_entities<R>(
1168 &mut self,
1169 callback: impl FnOnce(&mut App) -> R,
1170 ) -> (R, FxHashSet<EntityId>) {
1171 let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1172 let result = callback(self);
1173 let entities_accessed_in_callback = self
1174 .entities
1175 .accessed_entities
1176 .get_mut()
1177 .difference(&accessed_entities_start)
1178 .copied()
1179 .collect::<FxHashSet<EntityId>>();
1180 (result, entities_accessed_in_callback)
1181 }
1182
1183 pub(crate) fn record_entities_accessed(
1184 &mut self,
1185 window_handle: AnyWindowHandle,
1186 invalidator: WindowInvalidator,
1187 entities: &FxHashSet<EntityId>,
1188 ) {
1189 let mut tracked_entities =
1190 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1191 for entity in tracked_entities.iter() {
1192 self.window_invalidators_by_entity
1193 .entry(*entity)
1194 .and_modify(|windows| {
1195 windows.remove(&window_handle.id);
1196 });
1197 }
1198 for entity in entities.iter() {
1199 self.window_invalidators_by_entity
1200 .entry(*entity)
1201 .or_default()
1202 .insert(window_handle.id, invalidator.clone());
1203 self.current_window_by_entity
1204 .insert(*entity, window_handle.id);
1205 }
1206 tracked_entities.clear();
1207 tracked_entities.extend(entities.iter().copied());
1208 self.tracked_entities
1209 .insert(window_handle.id, tracked_entities);
1210 }
1211
1212 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1213 let (subscription, activate) = self.observers.insert(key, value);
1214 self.defer(move |_| activate());
1215 subscription
1216 }
1217
1218 pub(crate) fn observe_internal<W>(
1219 &mut self,
1220 entity: &Entity<W>,
1221 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1222 ) -> Subscription
1223 where
1224 W: 'static,
1225 {
1226 let entity_id = entity.entity_id();
1227 let handle = entity.downgrade();
1228 self.new_observer(
1229 entity_id,
1230 Box::new(move |cx| {
1231 if let Some(entity) = handle.upgrade() {
1232 on_notify(entity, cx)
1233 } else {
1234 false
1235 }
1236 }),
1237 )
1238 }
1239
1240 pub fn subscribe<T, Event>(
1243 &mut self,
1244 entity: &Entity<T>,
1245 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1246 ) -> Subscription
1247 where
1248 T: 'static + EventEmitter<Event>,
1249 Event: 'static,
1250 {
1251 self.subscribe_internal(entity, move |entity, event, cx| {
1252 on_event(entity, event, cx);
1253 true
1254 })
1255 }
1256
1257 pub(crate) fn new_subscription(
1258 &mut self,
1259 key: EntityId,
1260 value: (TypeId, Listener),
1261 ) -> Subscription {
1262 let (subscription, activate) = self.event_listeners.insert(key, value);
1263 self.defer(move |_| activate());
1264 subscription
1265 }
1266 pub(crate) fn subscribe_internal<T, Evt>(
1267 &mut self,
1268 entity: &Entity<T>,
1269 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1270 ) -> Subscription
1271 where
1272 T: 'static + EventEmitter<Evt>,
1273 Evt: 'static,
1274 {
1275 let entity_id = entity.entity_id();
1276 let handle = entity.downgrade();
1277 self.new_subscription(
1278 entity_id,
1279 (
1280 TypeId::of::<Evt>(),
1281 Box::new(move |event, cx| {
1282 let event: &Evt = event.downcast_ref().expect("invalid event type");
1283 if let Some(entity) = handle.upgrade() {
1284 on_event(entity, event, cx)
1285 } else {
1286 false
1287 }
1288 }),
1289 ),
1290 )
1291 }
1292
1293 pub fn windows(&self) -> Vec<AnyWindowHandle> {
1297 self.windows
1298 .ids()
1299 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1300 .collect()
1301 }
1302
1303 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1309 self.platform.window_stack().map(|window_ids| {
1310 window_ids
1311 .into_iter()
1312 .filter_map(|window_id| self.window_handle(window_id))
1313 .collect()
1314 })
1315 }
1316
1317 pub fn active_window(&self) -> Option<AnyWindowHandle> {
1319 self.platform
1320 .active_window()
1321 .and_then(|window_id| self.window_handle(window_id))
1322 }
1323
1324 pub fn window_handle(&self, window_id: WindowId) -> Option<AnyWindowHandle> {
1326 self.window_handles.get(&window_id).copied()
1327 }
1328
1329 pub fn open_window<V: 'static + Render>(
1333 &mut self,
1334 options: crate::WindowOptions,
1335 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1336 ) -> anyhow::Result<WindowHandle<V>> {
1337 self.update(|cx| {
1338 let id = cx.windows.reserve();
1339 let handle = WindowHandle::new(id);
1340 match WindowHost::new(handle.into(), options, cx) {
1341 Ok(mut host) => {
1342 cx.window_update_stack.push(id);
1343 let root_view = host.with_window(|window| build_root_view(window, cx));
1344 cx.window_update_stack.pop();
1345 host.core.root.replace(root_view.into());
1346 host.with_window(|window| {
1347 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1348
1349 let clear = window.draw(cx);
1354 clear.clear(cx);
1355 });
1356
1357 cx.window_handles.insert(id, host.core.handle);
1358 cx.windows.register(id, host);
1359 Ok(handle)
1360 }
1361 Err(e) => {
1362 cx.windows.remove(id);
1363 Err(e)
1364 }
1365 }
1366 })
1367 }
1368
1369 pub fn activate(&self, ignoring_other_apps: bool) {
1371 self.platform.activate(ignoring_other_apps);
1372 }
1373
1374 pub fn hide(&self) {
1376 self.platform.hide();
1377 }
1378
1379 pub fn hide_other_apps(&self) {
1381 self.platform.hide_other_apps();
1382 }
1383
1384 pub fn unhide_other_apps(&self) {
1386 self.platform.unhide_other_apps();
1387 }
1388
1389 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1391 self.platform.displays()
1392 }
1393
1394 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1396 self.platform.primary_display()
1397 }
1398
1399 pub fn is_screen_capture_supported(&self) -> bool {
1401 self.platform.is_screen_capture_supported()
1402 }
1403
1404 pub fn screen_capture_sources(
1406 &self,
1407 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1408 self.platform.screen_capture_sources()
1409 }
1410
1411 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1413 self.displays()
1414 .iter()
1415 .find(|display| display.id() == id)
1416 .cloned()
1417 }
1418
1419 pub fn thermal_state(&self) -> ThermalState {
1421 self.platform.thermal_state()
1422 }
1423
1424 pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1426 self.platform.prevent_idle_sleep(reason)
1427 }
1428
1429 pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1431 where
1432 F: 'static + FnMut(&mut App),
1433 {
1434 let (subscription, activate) = self.thermal_state_observers.insert(
1435 (),
1436 Box::new(move |cx| {
1437 callback(cx);
1438 true
1439 }),
1440 );
1441 activate();
1442 subscription
1443 }
1444
1445 pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1450 where
1451 F: 'static + FnMut(&mut App),
1452 {
1453 let (subscription, activate) = self.system_sleep_observers.insert(
1454 (),
1455 Box::new(move |cx| {
1456 callback(cx);
1457 true
1458 }),
1459 );
1460 activate();
1461 subscription
1462 }
1463
1464 pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1466 where
1467 F: 'static + FnMut(&mut App),
1468 {
1469 let (subscription, activate) = self.system_wake_observers.insert(
1470 (),
1471 Box::new(move |cx| {
1472 callback(cx);
1473 true
1474 }),
1475 );
1476 activate();
1477 subscription
1478 }
1479
1480 pub fn window_appearance(&self) -> WindowAppearance {
1482 self.platform.window_appearance()
1483 }
1484
1485 pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1496 self.platform.set_window_appearance(appearance);
1497 }
1498
1499 pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1501 self.platform.button_layout()
1502 }
1503
1504 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1506 self.platform.read_from_clipboard()
1507 }
1508
1509 pub fn read_from_clipboard_async(
1517 &self,
1518 ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1519 self.platform.read_from_clipboard_async()
1520 }
1521
1522 pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1524 self.text_rendering_mode.set(mode);
1525 }
1526
1527 pub fn text_rendering_mode(&self) -> TextRenderingMode {
1529 self.text_rendering_mode.get()
1530 }
1531
1532 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1534 self.platform.write_to_clipboard(item)
1535 }
1536
1537 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1540 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1541 self.platform.read_from_primary()
1542 }
1543
1544 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1547 pub fn write_to_primary(&self, item: ClipboardItem) {
1548 self.platform.write_to_primary(item)
1549 }
1550
1551 #[cfg(target_os = "macos")]
1557 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1558 self.platform.read_from_find_pasteboard()
1559 }
1560
1561 #[cfg(target_os = "macos")]
1567 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1568 self.platform.write_to_find_pasteboard(item)
1569 }
1570
1571 pub fn write_credentials(
1573 &self,
1574 url: &str,
1575 username: &str,
1576 password: &[u8],
1577 ) -> Task<Result<()>> {
1578 self.platform.write_credentials(url, username, password)
1579 }
1580
1581 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1583 self.platform.read_credentials(url)
1584 }
1585
1586 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1588 self.platform.delete_credentials(url)
1589 }
1590
1591 pub fn open_url(&self, url: &str) {
1593 self.platform.open_url(url);
1594 }
1595
1596 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1603 self.platform.register_url_scheme(scheme)
1604 }
1605
1606 pub fn set_app_identity(&self, identifier: &str, name: &str) {
1613 self.platform.set_app_identity(identifier, name);
1614 }
1615
1616 pub fn show_system_notification(&self, notification: SystemNotification) {
1623 self.platform.show_system_notification(notification);
1624 }
1625
1626 pub fn dismiss_system_notification(&self, tag: &str) {
1631 self.platform.dismiss_system_notification(tag);
1632 }
1633
1634 pub fn on_system_notification_response<F>(&self, mut callback: F)
1638 where
1639 F: 'static + FnMut(SystemNotificationResponse, &mut App),
1640 {
1641 let this = self.this.clone();
1642 self.platform
1643 .on_system_notification_response(Box::new(move |response| {
1644 if let Some(app) = this.upgrade() {
1645 callback(response, &mut app.borrow_mut());
1646 }
1647 }));
1648 }
1649
1650 pub fn app_path(&self) -> Result<PathBuf> {
1654 self.platform.app_path()
1655 }
1656
1657 pub fn compositor_name(&self) -> &'static str {
1661 self.platform.compositor_name()
1662 }
1663
1664 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1666 self.platform.path_for_auxiliary_executable(name)
1667 }
1668
1669 pub fn prompt_for_paths(
1675 &self,
1676 options: PathPromptOptions,
1677 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1678 self.platform.prompt_for_paths(options)
1679 }
1680
1681 pub fn prompt_for_new_path(
1688 &self,
1689 directory: &Path,
1690 suggested_name: Option<&str>,
1691 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1692 self.platform.prompt_for_new_path(directory, suggested_name)
1693 }
1694
1695 pub fn reveal_path(&self, path: &Path) {
1697 self.platform.reveal_path(path)
1698 }
1699
1700 pub fn open_with_system(&self, path: &Path) {
1702 self.platform.open_with_system(path)
1703 }
1704
1705 pub fn should_auto_hide_scrollbars(&self) -> bool {
1707 self.platform.should_auto_hide_scrollbars()
1708 }
1709
1710 pub fn restart(&mut self) {
1712 self.restart_observers
1713 .clone()
1714 .retain(&(), |observer| observer(self));
1715 self.platform.restart(
1716 self.restart_path.take(),
1717 std::mem::take(&mut self.restart_arguments),
1718 )
1719 }
1720
1721 pub fn set_restart_path(&mut self, path: PathBuf) {
1723 self.restart_path = Some(path);
1724 }
1725
1726 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1728 self.http_client.clone()
1729 }
1730
1731 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1733 self.http_client = new_client;
1734 }
1735
1736 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1739 self.quit_mode = mode;
1740 }
1741
1742 pub fn set_initial_windowing(&mut self, request: WindowingRequest) {
1746 self.platform.set_initial_windowing(request);
1747 }
1748
1749 pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
1758 self.platform.set_activation_policy(policy);
1759 }
1760
1761 pub fn svg_renderer(&self) -> SvgRenderer {
1763 self.svg_renderer.clone()
1764 }
1765
1766 pub(crate) fn push_effect(&mut self, effect: Effect) {
1767 match &effect {
1768 Effect::Notify { emitter } => {
1769 if !self.pending_notifications.insert(*emitter) {
1770 return;
1771 }
1772 }
1773 Effect::NotifyGlobalObservers { global_type } => {
1774 if !self.pending_global_notifications.insert(*global_type) {
1775 return;
1776 }
1777 }
1778 _ => {}
1779 };
1780
1781 self.pending_effects.push_back(effect);
1782 }
1783
1784 fn flush_effects(&mut self) {
1788 loop {
1789 self.release_dropped_entities();
1790 self.release_dropped_focus_handles();
1791 if let Some(effect) = self.pending_effects.pop_front() {
1792 match effect {
1793 Effect::Notify { emitter } => {
1794 self.apply_notify_effect(emitter);
1795 }
1796
1797 Effect::Emit {
1798 emitter,
1799 event_type,
1800 event,
1801 } => self.apply_emit_effect(emitter, event_type, &*event),
1802
1803 Effect::RefreshWindows => {
1804 self.apply_refresh_effect();
1805 }
1806
1807 Effect::NotifyGlobalObservers { global_type } => {
1808 self.apply_notify_global_observers_effect(global_type);
1809 }
1810
1811 Effect::Defer { callback } => {
1812 self.apply_defer_effect(callback);
1813 }
1814 Effect::EntityCreated {
1815 entity,
1816 tid,
1817 window,
1818 } => {
1819 self.apply_entity_created_effect(entity, tid, window);
1820 }
1821 }
1822 } else {
1823 #[cfg(any(test, feature = "test-support"))]
1824 if matches!(self.mode, GpuiMode::Test { .. }) {
1825 for handle in self
1826 .windows
1827 .cells()
1828 .filter_map(|cell| {
1829 let host = cell.borrow();
1830 host.core.should_render_frame().then_some(host.core.handle)
1831 })
1832 .collect::<Vec<_>>()
1833 {
1834 self.update_window(handle, |_, window, cx| window.draw(cx).clear(cx))
1835 .unwrap();
1836 }
1837 }
1838
1839 if self.pending_effects.is_empty() {
1840 for cell in self.windows.cells() {
1841 let host = cell.borrow();
1842 if host.core.invalidator.is_dirty()
1843 || host.core.needs_present.get()
1844 || !host.core.next_frame_callbacks.borrow().is_empty()
1845 {
1846 host.core.platform_window.schedule_frame();
1851 }
1852 }
1853
1854 self.event_arena.clear();
1855 break;
1856 }
1857 }
1858 }
1859 }
1860
1861 fn release_dropped_entities(&mut self) {
1865 loop {
1866 let dropped = self.entities.take_dropped();
1867 if dropped.is_empty() {
1868 break;
1869 }
1870
1871 for (entity_id, mut entity) in dropped {
1872 self.observers.remove(&entity_id);
1873 self.event_listeners.remove(&entity_id);
1874 self.window_invalidators_by_entity.remove(&entity_id);
1875 self.current_window_by_entity.remove(&entity_id);
1876 for release_callback in self.release_listeners.remove(&entity_id) {
1877 release_callback(entity.as_mut(), self);
1878 }
1879 }
1880 }
1881 }
1882
1883 fn release_dropped_focus_handles(&mut self) {
1885 self.focus_handles
1886 .clone()
1887 .write()
1888 .retain(|handle_id, focus| {
1889 if focus.ref_count.load(SeqCst) == 0 {
1890 for window_handle in self.windows() {
1891 window_handle
1892 .update(self, |_, window, cx| {
1893 if window.core.focus == Some(handle_id) {
1894 window.blur(cx);
1895 }
1896 })
1897 .unwrap();
1898 }
1899 false
1900 } else {
1901 true
1902 }
1903 });
1904 }
1905
1906 fn apply_notify_effect(&mut self, emitter: EntityId) {
1907 self.pending_notifications.remove(&emitter);
1908
1909 self.observers
1910 .clone()
1911 .retain(&emitter, |handler| handler(self));
1912 }
1913
1914 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1915 self.event_listeners
1916 .clone()
1917 .retain(&emitter, |(stored_type, handler)| {
1918 if *stored_type == event_type {
1919 handler(event, self)
1920 } else {
1921 true
1922 }
1923 });
1924 }
1925
1926 fn apply_refresh_effect(&mut self) {
1927 for cell in self.windows.cells() {
1928 let mut host = cell.borrow_mut();
1929 host.core.refreshing = true;
1930 host.core.invalidator.set_dirty(true);
1931 }
1932 }
1933
1934 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1935 self.pending_global_notifications.remove(&type_id);
1936 self.global_observers
1937 .clone()
1938 .retain(&type_id, |observer| observer(self));
1939 }
1940
1941 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1942 callback(self);
1943 }
1944
1945 fn apply_entity_created_effect(
1946 &mut self,
1947 entity: AnyEntity,
1948 tid: TypeId,
1949 window: Option<WindowId>,
1950 ) {
1951 if let Some(id) = window {
1955 self.current_window_by_entity.insert(entity.entity_id(), id);
1956 }
1957
1958 self.new_entity_observers.clone().retain(&tid, |observer| {
1959 if let Some(id) = window {
1960 self.update_window_id(id, {
1961 let entity = entity.clone();
1962 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1963 })
1964 .expect("All windows should be off the stack when flushing effects");
1965 } else {
1966 (observer)(entity.clone(), &mut None, self)
1967 }
1968 true
1969 });
1970 }
1971
1972 #[inline(always)]
1978 pub fn with_window<R>(
1979 &mut self,
1980 entity_id: EntityId,
1981 f: impl FnOnce(&mut Window, &mut App) -> R,
1982 ) -> Option<R> {
1983 let window_id = *self.current_window_by_entity.get(&entity_id)?;
1984 self.update_window_id(window_id, |_, window, cx| f(window, cx))
1985 .ok()
1986 }
1987
1988 fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1989 self.current_window_by_entity
1990 .entry(entity_id)
1991 .or_insert(window);
1992 }
1993
1994 pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1995 where
1996 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1997 {
1998 self.update(|cx| {
1999 let cell = cx
2000 .windows
2001 .cell(id)
2002 .ok_or_else(|| anyhow!("window {id:?} is not open"))?;
2003 let mut host = cell
2004 .try_borrow_mut()
2005 .map_err(|_| anyhow!("window {id:?} is already being updated"))?;
2006
2007 let root_view = host.core.root.clone().unwrap();
2008
2009 cx.window_update_stack.push(host.core.handle.id);
2010 let result = host.with_window(|window| update(root_view, window, cx));
2011 let removed = host.core.removed;
2012 drop(host);
2013 cx.window_update_stack.pop();
2014
2015 if removed {
2016 cx.end_platform_drag(id);
2017 cx.window_handles.remove(&id);
2018 cx.windows.remove(id);
2019 if let Some(tracked) = cx.tracked_entities.remove(&id) {
2020 for entity_id in tracked {
2021 if let Some(windows) = cx.window_invalidators_by_entity.get_mut(&entity_id)
2022 {
2023 windows.remove(&id);
2024 }
2025 if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
2026 cx.current_window_by_entity.remove(&entity_id);
2027 }
2028 }
2029 }
2030
2031 cx.window_closed_observers.clone().retain(&(), |callback| {
2032 callback(cx, id);
2033 true
2034 });
2035
2036 let quit_on_empty = match cx.quit_mode {
2037 QuitMode::Explicit => false,
2038 QuitMode::LastWindowClosed => true,
2039 QuitMode::Default => cfg!(not(target_os = "macos")),
2040 };
2041
2042 if quit_on_empty && cx.windows.is_empty() {
2043 cx.quit();
2044 }
2045 }
2046
2047 Ok(result)
2048 })
2049 }
2050
2051 pub fn to_async(&self) -> AsyncApp {
2054 AsyncApp {
2055 app: self.this.clone(),
2056 background_executor: self.background_executor.clone(),
2057 foreground_executor: self.foreground_executor.clone(),
2058 }
2059 }
2060
2061 pub fn background_executor(&self) -> &BackgroundExecutor {
2063 &self.background_executor
2064 }
2065
2066 pub fn is_test(&self) -> bool {
2069 self.background_executor.is_test()
2070 }
2071
2072 pub fn foreground_executor(&self) -> &ForegroundExecutor {
2074 if self.quitting {
2075 panic!("Can't spawn on main thread after on_app_quit")
2076 };
2077 &self.foreground_executor
2078 }
2079
2080 #[cfg(feature = "profiler")]
2083 pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2084 self.foreground_journal.clone()
2085 }
2086
2087 #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2104 pub fn start_hang_monitor(
2105 &mut self,
2106 config: crate::profiler::hang::HangMonitorConfig,
2107 on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2108 ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2109 use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2110
2111 if self.hang_monitor.is_some() {
2112 debug_assert!(false, "the hang monitor was started twice");
2113 return Err(HangMonitorError::AlreadyStarted);
2114 }
2115 let detector = HangDetector::new(
2116 self.foreground_journal(),
2117 config.threshold,
2118 config.frame_budget,
2119 );
2120 let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2121 .map_err(HangMonitorError::Spawn)?;
2122 self.hang_monitor = Some(monitor);
2123 Ok(())
2124 }
2125
2126 #[track_caller]
2129 #[inline(always)]
2130 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2131 where
2132 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2133 R: 'static,
2134 {
2135 let mut cx = self.prepare_spawn();
2136
2137 self.foreground_executor
2138 .spawn(async move { f(&mut cx).await }.boxed_local())
2139 }
2140
2141 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2145 where
2146 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2147 R: 'static,
2148 {
2149 if self.quitting {
2150 debug_panic!("Can't spawn on main thread after on_app_quit")
2151 };
2152
2153 let mut cx = self.to_async();
2154
2155 self.foreground_executor
2156 .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2157 }
2158
2159 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2162 self.push_effect(Effect::Defer {
2163 callback: Box::new(f),
2164 });
2165 }
2166
2167 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2169 &self.asset_source
2170 }
2171
2172 pub fn text_system(&self) -> &Arc<dyn TextSystem> {
2174 &self.text_system
2175 }
2176
2177 pub fn enumerate_gpus(&self) -> Vec<GpuAdapterInfo> {
2184 self.platform.enumerate_gpus()
2185 }
2186
2187 pub fn active_gpu(&self) -> Option<GpuAdapterInfo> {
2192 self.platform.active_gpu()
2193 }
2194
2195 pub fn dmabuf_capabilities(&self) -> Option<DmaBufCapabilities> {
2204 self.platform.dmabuf_capabilities()
2205 }
2206
2207 pub fn on_missing_glyphs(
2218 &self,
2219 callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2220 ) -> Subscription {
2221 let registration = self.missing_glyph_callback.replace(Box::new(callback));
2222
2223 if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2224 let callback = self.missing_glyph_callback.clone();
2225 self.spawn(async move |cx| {
2226 while let Some(missing_glyphs) = receiver.recv().await {
2227 cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2228 }
2229 })
2230 .detach();
2231 }
2232 self.text_system.enable_missing_glyph_reporting();
2233
2234 let callback = self.missing_glyph_callback.clone();
2235 let text_system = self.text_system.clone();
2236 Subscription::new(move || {
2237 if callback.remove(®istration) {
2238 text_system.disable_missing_glyph_reporting();
2239 }
2240 })
2241 }
2242
2243 pub fn has_global<G: Global>(&self) -> bool {
2245 self.globals_by_type.contains_key(&TypeId::of::<G>())
2246 }
2247
2248 #[track_caller]
2250 pub fn global<G: Global>(&self) -> &G {
2251 self.globals_by_type
2252 .get(&TypeId::of::<G>())
2253 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2254 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2255 }
2256
2257 pub fn try_global<G: Global>(&self) -> Option<&G> {
2259 self.globals_by_type
2260 .get(&TypeId::of::<G>())
2261 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2262 }
2263
2264 #[track_caller]
2266 pub fn global_mut<G: Global>(&mut self) -> &mut G {
2267 let global_type = TypeId::of::<G>();
2268 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2269 self.globals_by_type
2270 .get_mut(&global_type)
2271 .and_then(|any_state| any_state.downcast_mut::<G>())
2272 .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2273 }
2274
2275 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2278 let global_type = TypeId::of::<G>();
2279 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2280 self.globals_by_type
2281 .entry(global_type)
2282 .or_insert_with(|| Box::<G>::default())
2283 .downcast_mut::<G>()
2284 .unwrap()
2285 }
2286
2287 pub fn set_global<G: Global>(&mut self, global: G) {
2289 let global_type = TypeId::of::<G>();
2290 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2291 self.globals_by_type.insert(global_type, Box::new(global));
2292 }
2293
2294 #[cfg(any(test, feature = "test-support"))]
2296 pub fn clear_globals(&mut self) {
2297 self.globals_by_type.drain();
2298 }
2299
2300 pub fn remove_global<G: Global>(&mut self) -> G {
2302 let global_type = TypeId::of::<G>();
2303 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2304 *self
2305 .globals_by_type
2306 .remove(&global_type)
2307 .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2308 .downcast()
2309 .unwrap()
2310 }
2311
2312 pub fn observe_global<G: Global>(
2314 &mut self,
2315 mut f: impl FnMut(&mut Self) + 'static,
2316 ) -> Subscription {
2317 let (subscription, activate) = self.global_observers.insert(
2318 TypeId::of::<G>(),
2319 Box::new(move |cx| {
2320 f(cx);
2321 true
2322 }),
2323 );
2324 self.defer(move |_| activate());
2325 subscription
2326 }
2327
2328 #[track_caller]
2330 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2331 GlobalLease::new(
2332 self.globals_by_type
2333 .remove(&TypeId::of::<G>())
2334 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2335 .unwrap(),
2336 )
2337 }
2338
2339 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2341 let global_type = TypeId::of::<G>();
2342
2343 self.push_effect(Effect::NotifyGlobalObservers { global_type });
2344 self.globals_by_type.insert(global_type, lease.global);
2345 }
2346
2347 pub(crate) fn new_entity_observer(
2348 &self,
2349 key: TypeId,
2350 value: NewEntityListener,
2351 ) -> Subscription {
2352 let (subscription, activate) = self.new_entity_observers.insert(key, value);
2353 activate();
2354 subscription
2355 }
2356
2357 pub fn observe_new<T: 'static>(
2360 &self,
2361 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2362 ) -> Subscription {
2363 self.new_entity_observer(
2364 TypeId::of::<T>(),
2365 Box::new(
2366 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2367 any_entity
2368 .downcast::<T>()
2369 .unwrap()
2370 .update(cx, |entity_state, cx| {
2371 on_new(entity_state, window.as_deref_mut(), cx)
2372 })
2373 },
2374 ),
2375 )
2376 }
2377
2378 pub fn observe_release<T>(
2381 &self,
2382 handle: &Entity<T>,
2383 on_release: impl FnOnce(&mut T, &mut App) + 'static,
2384 ) -> Subscription
2385 where
2386 T: 'static,
2387 {
2388 let (subscription, activate) = self.release_listeners.insert(
2389 handle.entity_id(),
2390 Box::new(move |entity, cx| {
2391 let entity = entity.downcast_mut().expect("invalid entity type");
2392 on_release(entity, cx)
2393 }),
2394 );
2395 activate();
2396 subscription
2397 }
2398
2399 pub fn observe_release_in<T>(
2402 &self,
2403 handle: &Entity<T>,
2404 window: &Window,
2405 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2406 ) -> Subscription
2407 where
2408 T: 'static,
2409 {
2410 let window_handle = window.core.handle;
2411 self.observe_release(handle, move |entity, cx| {
2412 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2413 })
2414 }
2415
2416 pub fn observe_keystrokes(
2421 &mut self,
2422 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2423 ) -> Subscription {
2424 fn inner(
2425 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2426 handler: KeystrokeObserver,
2427 ) -> Subscription {
2428 let (subscription, activate) = keystroke_observers.insert((), handler);
2429 activate();
2430 subscription
2431 }
2432
2433 inner(
2434 &self.keystroke_observers,
2435 Box::new(move |event, window, cx| {
2436 f(event, window, cx);
2437 true
2438 }),
2439 )
2440 }
2441
2442 pub fn intercept_keystrokes(
2447 &mut self,
2448 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2449 ) -> Subscription {
2450 fn inner(
2451 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2452 handler: KeystrokeObserver,
2453 ) -> Subscription {
2454 let (subscription, activate) = keystroke_interceptors.insert((), handler);
2455 activate();
2456 subscription
2457 }
2458
2459 inner(
2460 &self.keystroke_interceptors,
2461 Box::new(move |event, window, cx| {
2462 f(event, window, cx);
2463 true
2464 }),
2465 )
2466 }
2467
2468 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2470 self.keymap.borrow_mut().add_bindings(bindings);
2471 self.pending_effects.push_back(Effect::RefreshWindows);
2472 }
2473
2474 pub fn clear_key_bindings(&mut self) {
2476 self.keymap.borrow_mut().clear();
2477 self.pending_effects.push_back(Effect::RefreshWindows);
2478 }
2479
2480 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2482 self.keymap.clone()
2483 }
2484
2485 pub fn on_action<A: Action>(
2489 &mut self,
2490 listener: impl Fn(&A, &mut Self) + 'static,
2491 ) -> &mut Self {
2492 self.global_action_listeners
2493 .entry(TypeId::of::<A>())
2494 .or_default()
2495 .push(Rc::new(move |action, phase, cx| {
2496 if phase == DispatchPhase::Bubble {
2497 let action = action.downcast_ref().unwrap();
2498 listener(action, cx)
2499 }
2500 }));
2501 self
2502 }
2503
2504 pub fn stop_propagation(&mut self) {
2509 self.propagate_event = false;
2510 }
2511
2512 pub fn propagate(&mut self) {
2517 self.propagate_event = true;
2518 }
2519
2520 pub fn build_action(
2522 &self,
2523 name: &str,
2524 data: Option<serde_json::Value>,
2525 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2526 self.actions.build_action(name, data)
2527 }
2528
2529 pub fn all_action_names(&self) -> &[&'static str] {
2532 self.actions.all_action_names()
2533 }
2534
2535 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2539 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2540 }
2541
2542 pub fn action_schemas(
2544 &self,
2545 generator: &mut schemars::SchemaGenerator,
2546 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2547 self.actions.action_schemas(generator)
2548 }
2549
2550 pub fn action_schema_by_name(
2555 &self,
2556 name: &str,
2557 generator: &mut schemars::SchemaGenerator,
2558 ) -> Option<Option<schemars::Schema>> {
2559 self.actions.action_schema_by_name(name, generator)
2560 }
2561
2562 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2564 self.actions.deprecated_aliases()
2565 }
2566
2567 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2569 self.actions.deprecation_messages()
2570 }
2571
2572 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2574 self.actions.documentation()
2575 }
2576
2577 pub fn on_app_quit<Fut>(
2580 &self,
2581 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2582 ) -> Subscription
2583 where
2584 Fut: 'static + Future<Output = ()>,
2585 {
2586 let (subscription, activate) = self.quit_observers.insert(
2587 (),
2588 Box::new(move |cx| {
2589 let future = on_quit(cx);
2590 future.boxed_local()
2591 }),
2592 );
2593 activate();
2594 subscription
2595 }
2596
2597 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2601 let (subscription, activate) = self.restart_observers.insert(
2602 (),
2603 Box::new(move |cx| {
2604 on_restart(cx);
2605 true
2606 }),
2607 );
2608 activate();
2609 subscription
2610 }
2611
2612 pub fn on_window_closed(
2615 &self,
2616 mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2617 ) -> Subscription {
2618 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2619 activate();
2620 subscription
2621 }
2622
2623 pub(crate) fn clear_pending_keystrokes(&mut self) {
2624 for window in self.windows() {
2625 window
2626 .update(self, |_, window, cx| {
2627 window.clear_pending_keystrokes(cx);
2628 })
2629 .ok();
2630 }
2631 }
2632
2633 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2636 let mut action_available = false;
2637 if let Some(window) = self.active_window()
2638 && let Ok(window_action_available) =
2639 window.update(self, |_, window, cx| window.is_action_available(action, cx))
2640 {
2641 action_available = window_action_available;
2642 }
2643
2644 action_available
2645 || self
2646 .global_action_listeners
2647 .contains_key(&action.as_any().type_id())
2648 }
2649
2650 pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2652 let owned: Vec<OwnedMenu> = menus.into_iter().map(Menu::owned).collect();
2653 let resolved = {
2654 let keymap = self.keymap.borrow();
2655 let mut actions = self.menu_actions.borrow_mut();
2656 resolve_menus(&owned, &keymap, &mut actions)
2657 };
2658 *self.owned_menus.borrow_mut() = Some(owned);
2659 self.platform.set_menus(resolved);
2660 }
2661
2662 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2664 self.owned_menus.borrow().clone()
2665 }
2666
2667 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2669 let owned: Vec<OwnedMenuItem> = menus.into_iter().map(MenuItem::owned).collect();
2670 let resolved = {
2671 let keymap = self.keymap.borrow();
2672 let mut actions = self.menu_actions.borrow_mut();
2673 resolve_dock_menu(&owned, &keymap, &mut actions)
2674 };
2675 self.platform.set_dock_menu(resolved)
2676 }
2677
2678 pub(crate) fn is_menu_command_available(&mut self, command_id: MenuCommandId) -> bool {
2680 let action = self
2681 .menu_actions
2682 .borrow()
2683 .get(command_id)
2684 .map(|action| action.boxed_clone());
2685 action.is_some_and(|action| self.is_action_available(action.as_ref()))
2686 }
2687
2688 pub(crate) fn dispatch_menu_command(&mut self, command_id: MenuCommandId) {
2690 let action = self
2691 .menu_actions
2692 .borrow()
2693 .get(command_id)
2694 .map(|action| action.boxed_clone());
2695 if let Some(action) = action {
2696 self.dispatch_action(action.as_ref());
2697 }
2698 }
2699
2700 pub fn perform_dock_menu_action(&self, action: usize) {
2702 self.platform.perform_dock_menu_action(action);
2703 }
2704
2705 pub fn add_recent_document(&self, path: &Path) {
2710 self.platform.add_recent_document(path);
2711 }
2712
2713 pub fn update_jump_list(
2716 &self,
2717 menus: Vec<MenuItem>,
2718 entries: Vec<SmallVec<[PathBuf; 2]>>,
2719 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2720 let owned: Vec<OwnedMenuItem> = menus.into_iter().map(MenuItem::owned).collect();
2721 let resolved = {
2722 let keymap = self.keymap.borrow();
2723 let mut actions = self.menu_actions.borrow_mut();
2724 resolve_dock_menu(&owned, &keymap, &mut actions)
2725 };
2726 self.platform.update_jump_list(resolved, entries)
2727 }
2728
2729 pub fn dispatch_action(&mut self, action: &dyn Action) {
2732 if let Some(active_window) = self.active_window() {
2733 active_window
2734 .update(self, |_, window, cx| {
2735 window.dispatch_action(action.boxed_clone(), cx)
2736 })
2737 .log_err();
2738 } else {
2739 self.dispatch_global_action(action);
2740 }
2741 }
2742
2743 fn dispatch_global_action(&mut self, action: &dyn Action) {
2744 self.propagate_event = true;
2745
2746 if let Some(mut global_listeners) = self
2747 .global_action_listeners
2748 .remove(&action.as_any().type_id())
2749 {
2750 for listener in &global_listeners {
2751 listener(action.as_any(), DispatchPhase::Capture, self);
2752 if !self.propagate_event {
2753 break;
2754 }
2755 }
2756
2757 global_listeners.extend(
2758 self.global_action_listeners
2759 .remove(&action.as_any().type_id())
2760 .unwrap_or_default(),
2761 );
2762
2763 self.global_action_listeners
2764 .insert(action.as_any().type_id(), global_listeners);
2765 }
2766
2767 if self.propagate_event
2768 && let Some(mut global_listeners) = self
2769 .global_action_listeners
2770 .remove(&action.as_any().type_id())
2771 {
2772 for listener in global_listeners.iter().rev() {
2773 listener(action.as_any(), DispatchPhase::Bubble, self);
2774 if !self.propagate_event {
2775 break;
2776 }
2777 }
2778
2779 global_listeners.extend(
2780 self.global_action_listeners
2781 .remove(&action.as_any().type_id())
2782 .unwrap_or_default(),
2783 );
2784
2785 self.global_action_listeners
2786 .insert(action.as_any().type_id(), global_listeners);
2787 }
2788 }
2789
2790 pub fn has_active_drag(&self) -> bool {
2792 self.active_drag.is_some()
2793 }
2794
2795 pub fn active_drag_value<T: 'static>(&self) -> Option<&T> {
2800 self.active_drag
2801 .as_ref()
2802 .and_then(|drag| drag.value.downcast_ref::<T>())
2803 }
2804
2805 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2807 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2808 }
2809
2810 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2812 if self.active_drag.is_some() {
2813 self.active_drag = None;
2814 if self.platform_owned_drag.as_ref().is_some_and(|drag| {
2815 drag.source_window == window.window_handle().window_id()
2816 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2817 }) {
2818 self.platform_owned_drag = None;
2819 }
2820 window.refresh();
2821 true
2822 } else {
2823 false
2824 }
2825 }
2826
2827 pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2828 let Some(drag) = self.active_drag.take() else {
2829 return false;
2830 };
2831 self.platform_owned_drag = Some(PlatformOwnedDrag {
2832 source_window,
2833 state: PlatformOwnedDragState::Suspended(drag),
2834 });
2835 true
2836 }
2837
2838 pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
2839 let Some(platform_drag) = self
2840 .platform_owned_drag
2841 .as_mut()
2842 .filter(|drag| drag.source_window == source_window)
2843 else {
2844 return false;
2845 };
2846 let state = std::mem::replace(
2847 &mut platform_drag.state,
2848 PlatformOwnedDragState::RestoredInSourceWindow,
2849 );
2850 let PlatformOwnedDragState::Suspended(drag) = state else {
2851 return false;
2852 };
2853 self.active_drag = Some(drag);
2854 true
2855 }
2856
2857 pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
2858 let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
2859 drag.source_window == source_window
2860 && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
2861 }) else {
2862 return false;
2863 };
2864 let Some(drag) = self.active_drag.take() else {
2865 return false;
2866 };
2867 platform_drag.state = PlatformOwnedDragState::Suspended(drag);
2868 true
2869 }
2870
2871 pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
2872 if !self
2873 .platform_owned_drag
2874 .as_ref()
2875 .is_some_and(|drag| drag.source_window == source_window)
2876 {
2877 return false;
2878 }
2879 self.platform_owned_drag = None;
2880 self.active_drag = None;
2881 true
2882 }
2883
2884 pub fn set_active_drag_cursor_style(
2886 &mut self,
2887 cursor_style: CursorStyle,
2888 window: &mut Window,
2889 ) -> bool {
2890 if let Some(ref mut drag) = self.active_drag {
2891 drag.cursor_style = Some(cursor_style);
2892 window.refresh();
2893 true
2894 } else {
2895 false
2896 }
2897 }
2898
2899 pub fn set_prompt_builder(
2902 &mut self,
2903 renderer: impl Fn(
2904 PromptLevel,
2905 &str,
2906 Option<&str>,
2907 &[PromptButton],
2908 PromptHandle,
2909 &mut Window,
2910 &mut App,
2911 ) -> RenderablePromptHandle
2912 + 'static,
2913 ) {
2914 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2915 }
2916
2917 pub fn reset_prompt_builder(&mut self) {
2919 self.prompt_builder = Some(PromptBuilder::Default);
2920 }
2921
2922 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2924 let asset_id = (TypeId::of::<A>(), hash(source));
2925 self.loading_assets.remove(&asset_id);
2926 }
2927
2928 #[cfg(any(test, feature = "test-support"))]
2931 pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
2932 let asset_id = (TypeId::of::<A>(), hash(source));
2933 self.loading_assets.contains_key(&asset_id)
2934 }
2935
2936 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
2941 self.asset_entry::<A>(source).get()
2942 }
2943
2944 pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
2945 let asset_id = (TypeId::of::<A>(), hash(source));
2946 if !self.loading_assets.contains_key(&asset_id) {
2947 let future = A::load(source.clone(), self);
2948 let entry = CachedLoad::new(future, self);
2949 self.loading_assets.insert(asset_id, Box::new(entry));
2950 }
2951 self.loading_assets
2952 .get(&asset_id)
2953 .and_then(|entry| entry.downcast_ref())
2954 .expect("asset cache entries are keyed by their asset type")
2955 }
2956
2957 #[track_caller]
2960 pub fn focus_handle(&self) -> FocusHandle {
2961 FocusHandle::new(&self.focus_handles)
2962 }
2963
2964 pub fn notify(&mut self, entity_id: EntityId) {
2966 let window_invalidators = mem::take(
2967 self.window_invalidators_by_entity
2968 .entry(entity_id)
2969 .or_default(),
2970 );
2971
2972 let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2977 .iter()
2978 .filter(|(window_id, _)| {
2979 self.tracked_entities
2980 .get(window_id)
2981 .is_some_and(|set| set.contains(&entity_id))
2982 })
2983 .map(|(_, invalidator)| invalidator.clone())
2984 .collect();
2985
2986 if live_invalidators.is_empty() {
2987 if self.pending_notifications.insert(entity_id) {
2988 self.pending_effects
2989 .push_back(Effect::Notify { emitter: entity_id });
2990 }
2991 } else {
2992 for invalidator in &live_invalidators {
2993 invalidator.invalidate_view(entity_id, self);
2994 }
2995 }
2996
2997 self.window_invalidators_by_entity
2998 .insert(entity_id, window_invalidators);
2999 }
3000
3001 #[cfg(any(test, feature = "test-support", debug_assertions))]
3003 pub fn get_name(&self) -> Option<&'static str> {
3004 self.name
3005 }
3006
3007 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3009 self.platform.can_select_mixed_files_and_dirs()
3010 }
3011
3012 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3017 for cell in self.windows.cells() {
3019 let mut host = cell.borrow_mut();
3020 _ = host.with_window(|window| window.drop_image(image.clone()));
3021 }
3022
3023 if let Some(window) = current_window {
3025 _ = window.drop_image(image);
3026 }
3027 }
3028
3029 #[cfg(any(feature = "inspector", debug_assertions))]
3031 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3032 self.inspector_renderer = Some(f);
3033 }
3034
3035 #[cfg(any(feature = "inspector", debug_assertions))]
3037 pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3038 &mut self,
3039 factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3040 ) where
3041 F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3042 {
3043 self.inspector_element_registry.register(factory);
3044 }
3045
3046 pub fn init_colors(&mut self) {
3050 self.set_global(GlobalColors(Arc::new(Colors::default())));
3051 }
3052
3053 #[inline(never)]
3054 fn update_entity_erased(
3055 &mut self,
3056 handle: &AnyEntity,
3057 entity_type: &str,
3058 update: &mut dyn FnMut(&mut dyn Any, &mut App),
3059 ) {
3060 self.update(|cx| {
3061 let mut lease = cx.entities.lease_erased(handle, entity_type);
3062 update(lease.entity.as_deref_mut().unwrap(), cx);
3063 cx.entities.end_lease_erased(handle.entity_id, lease);
3064 });
3065 }
3066
3067 #[inline(never)]
3068 #[track_caller]
3069 fn prepare_spawn(&self) -> AsyncApp {
3070 if self.quitting {
3071 debug_panic!("Can't spawn on main thread after on_app_quit")
3072 };
3073 self.to_async()
3074 }
3075}
3076
3077impl App {
3083 #[doc(hidden)]
3086 pub fn new_app_for_platform(platform: Rc<dyn Platform>) -> Rc<AppCell> {
3087 Self::new_app(platform, Arc::new(()), Arc::new(NullHttpClient))
3088 }
3089
3090 #[doc(hidden)]
3092 pub fn platform(&self) -> Rc<dyn Platform> {
3093 self.platform.clone()
3094 }
3095
3096 #[doc(hidden)]
3098 pub fn set_asset_source(&mut self, asset_source: Arc<dyn AssetSource>) {
3099 self.asset_source = asset_source.clone();
3100 self.svg_renderer = SvgRenderer::new(asset_source);
3101 }
3102
3103 #[doc(hidden)]
3105 pub fn set_layout_engine_factory(&mut self, factory: Rc<dyn Fn() -> Box<dyn LayoutEngine>>) {
3106 self.layout_engine_factory = factory;
3107 }
3108
3109 #[doc(hidden)]
3111 pub fn set_frame_pipeline_factory(
3112 &mut self,
3113 factory: Rc<dyn Fn(WindowId) -> Box<dyn FramePipeline>>,
3114 ) {
3115 self.frame_pipeline_factory = factory;
3116 }
3117
3118 #[doc(hidden)]
3120 pub fn set_text_system(&mut self, text_system: Arc<dyn TextSystem>) {
3121 self.text_system = text_system;
3122 }
3123
3124 #[doc(hidden)]
3126 pub fn set_restart_arguments(&mut self, arguments: Vec<OsString>) {
3127 self.restart_arguments = arguments;
3128 }
3129
3130 #[doc(hidden)]
3132 pub fn set_accessibility_force_disabled(&mut self, disabled: bool) {
3133 self.accessibility_force_disabled = disabled;
3134 }
3135}
3136
3137impl AppContext for App {
3138 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3143 self.update(|cx| {
3144 let slot = cx.entities.reserve();
3145 let handle = slot.clone();
3146 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3147
3148 cx.push_effect(Effect::EntityCreated {
3149 entity: handle.into_any(),
3150 tid: TypeId::of::<T>(),
3151 window: cx.window_update_stack.last().cloned(),
3152 });
3153
3154 cx.entities.insert(slot, entity)
3155 })
3156 }
3157
3158 fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3159 Reservation(self.entities.reserve())
3160 }
3161
3162 fn insert_entity<T: 'static>(
3163 &mut self,
3164 reservation: Reservation<T>,
3165 build_entity: impl FnOnce(&mut Context<T>) -> T,
3166 ) -> Entity<T> {
3167 self.update(|cx| {
3168 let slot = reservation.0;
3169 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3170 cx.entities.insert(slot, entity)
3171 })
3172 }
3173
3174 #[inline(always)]
3177 fn update_entity<T: 'static, R>(
3178 &mut self,
3179 handle: &Entity<T>,
3180 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3181 ) -> R {
3182 let mut update = Some(update);
3183 let mut result = None;
3184 self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3185 let value = update.take().unwrap()(
3186 entity.downcast_mut::<T>().unwrap(),
3187 &mut Context::new_context(cx, handle.downgrade()),
3188 );
3189 result = Some(value);
3190 });
3191 result.unwrap()
3192 }
3193
3194 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3195 where
3196 T: 'static,
3197 {
3198 GpuiBorrow::new(handle.clone(), self)
3199 }
3200
3201 #[inline(always)]
3202 fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3203 where
3204 T: 'static,
3205 {
3206 let entity = self.entities.read(handle);
3207 read(entity, self)
3208 }
3209
3210 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3211 where
3212 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3213 {
3214 self.update_window_id(handle.id, update)
3215 }
3216
3217 fn with_window<R>(
3218 &mut self,
3219 entity_id: EntityId,
3220 f: impl FnOnce(&mut Window, &mut App) -> R,
3221 ) -> Option<R> {
3222 App::with_window(self, entity_id, f)
3223 }
3224
3225 fn read_window<T, R>(
3226 &self,
3227 window: &WindowHandle<T>,
3228 read: impl FnOnce(Entity<T>, &App) -> R,
3229 ) -> Result<R>
3230 where
3231 T: 'static,
3232 {
3233 let cell = self.windows.cell(window.id).context("window not found")?;
3234 let host = cell
3235 .try_borrow()
3236 .expect("attempted to read a window that is already on the stack");
3237
3238 let root_view = host.core.root.clone().unwrap();
3239 let view = root_view
3240 .downcast::<T>()
3241 .map_err(|_| anyhow!("root view's type has changed"))?;
3242
3243 Ok(read(view, self))
3244 }
3245
3246 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3247 where
3248 R: Send + 'static,
3249 {
3250 self.background_executor.spawn(future)
3251 }
3252
3253 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3254 where
3255 G: Global,
3256 {
3257 let mut g = self.global::<G>();
3258 callback(g, self)
3259 }
3260}
3261
3262pub(crate) enum Effect {
3264 Notify {
3265 emitter: EntityId,
3266 },
3267 Emit {
3268 emitter: EntityId,
3269 event_type: TypeId,
3270 event: ArenaBox<dyn Any>,
3271 },
3272 RefreshWindows,
3273 NotifyGlobalObservers {
3274 global_type: TypeId,
3275 },
3276 Defer {
3277 callback: Box<dyn FnOnce(&mut App) + 'static>,
3278 },
3279 EntityCreated {
3280 entity: AnyEntity,
3281 tid: TypeId,
3282 window: Option<WindowId>,
3283 },
3284}
3285
3286impl std::fmt::Debug for Effect {
3287 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3288 match self {
3289 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3290 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3291 Effect::RefreshWindows => write!(f, "RefreshWindows"),
3292 Effect::NotifyGlobalObservers { global_type } => {
3293 write!(f, "NotifyGlobalObservers({:?})", global_type)
3294 }
3295 Effect::Defer { .. } => write!(f, "Defer(..)"),
3296 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3297 }
3298 }
3299}
3300
3301pub(crate) struct GlobalLease<G: Global> {
3303 global: Box<dyn Any>,
3304 global_type: PhantomData<G>,
3305}
3306
3307impl<G: Global> GlobalLease<G> {
3308 fn new(global: Box<dyn Any>) -> Self {
3309 GlobalLease {
3310 global,
3311 global_type: PhantomData,
3312 }
3313 }
3314}
3315
3316impl<G: Global> Deref for GlobalLease<G> {
3317 type Target = G;
3318
3319 fn deref(&self) -> &Self::Target {
3320 self.global.downcast_ref().unwrap()
3321 }
3322}
3323
3324impl<G: Global> DerefMut for GlobalLease<G> {
3325 fn deref_mut(&mut self) -> &mut Self::Target {
3326 self.global.downcast_mut().unwrap()
3327 }
3328}
3329
3330pub struct AnyDrag {
3333 pub view: AnyView,
3335
3336 pub value: Arc<dyn Any>,
3338
3339 pub cursor_offset: Point<Pixels>,
3342
3343 pub cursor_style: Option<CursorStyle>,
3345
3346 pub external_payload_source: Option<ExternalDragPayloadSource>,
3349}
3350
3351pub type ExternalDragPayloadSource =
3354 Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3355
3356#[derive(Clone)]
3359pub struct AnyTooltip {
3360 pub view: AnyView,
3362
3363 pub mouse_position: Point<Pixels>,
3365
3366 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3370}
3371
3372#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3374pub enum InputPreference {
3375 CharacterInput,
3377 KeyBindings,
3379}
3380
3381#[derive(Debug)]
3383pub struct KeystrokeEvent {
3384 pub keystroke: Keystroke,
3386
3387 pub input_preference: InputPreference,
3395
3396 pub action: Option<Box<dyn Action>>,
3398
3399 pub context_stack: Vec<KeyContext>,
3401}
3402
3403struct NullHttpClient;
3404
3405impl HttpClient for NullHttpClient {
3406 fn send(
3407 &self,
3408 _req: http_client::Request<http_client::AsyncBody>,
3409 ) -> futures::future::BoxFuture<
3410 'static,
3411 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3412 > {
3413 async move {
3414 anyhow::bail!("No HttpClient available");
3415 }
3416 .boxed()
3417 }
3418
3419 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3420 None
3421 }
3422
3423 fn proxy(&self) -> Option<&Url> {
3424 None
3425 }
3426}
3427
3428pub struct GpuiBorrow<'a, T> {
3430 inner: Option<Lease<T>>,
3431 app: &'a mut App,
3432}
3433
3434impl<'a, T: 'static> GpuiBorrow<'a, T> {
3435 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3436 app.start_update();
3437 let lease = app.entities.lease(&inner);
3438 Self {
3439 inner: Some(lease),
3440 app,
3441 }
3442 }
3443}
3444
3445impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3446 fn borrow(&self) -> &T {
3447 self.inner.as_ref().unwrap().borrow()
3448 }
3449}
3450
3451impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3452 fn borrow_mut(&mut self) -> &mut T {
3453 self.inner.as_mut().unwrap().borrow_mut()
3454 }
3455}
3456
3457impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3458 type Target = T;
3459
3460 fn deref(&self) -> &Self::Target {
3461 self.inner.as_ref().unwrap()
3462 }
3463}
3464
3465impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3466 fn deref_mut(&mut self) -> &mut T {
3467 self.inner.as_mut().unwrap()
3468 }
3469}
3470
3471impl<'a, T> Drop for GpuiBorrow<'a, T> {
3472 fn drop(&mut self) {
3473 let lease = self.inner.take().unwrap();
3474 self.app.notify(lease.id);
3475 self.app.entities.end_lease(lease);
3476 self.app.finish_update();
3477 }
3478}
3479
3480#[cfg(test)]
3481mod test {
3482 use std::{
3483 cell::{Cell, RefCell},
3484 ffi::OsString,
3485 path::PathBuf,
3486 rc::Rc,
3487 };
3488
3489 #[cfg(unix)]
3490 use std::os::unix::ffi::OsStringExt;
3491
3492 use crate::{
3493 AppContext, Context, DefaultTextSystemExt, Empty, FallbackFontClass, IntoElement,
3494 MissingGlyph, Render, TestAppContext, Window,
3495 };
3496
3497 struct RenderCounter(Rc<Cell<usize>>);
3498
3499 impl Render for RenderCounter {
3500 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3501 self.0.set(self.0.get() + 1);
3502 Empty
3503 }
3504 }
3505
3506 #[gpui::test]
3507 fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3508 let render_count = Rc::new(Cell::new(0));
3509
3510 let _window = cx.add_window({
3511 let render_count = render_count.clone();
3512 move |_, _| RenderCounter(render_count)
3513 });
3514
3515 cx.run_until_parked();
3516 let render_count_before_refresh = render_count.get();
3517
3518 cx.to_async().refresh();
3519
3520 assert_eq!(render_count.get(), render_count_before_refresh + 1);
3521 }
3522
3523 #[gpui::test]
3524 fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3525 let observed = Rc::new(RefCell::new(Vec::new()));
3526 let subscription = cx.update(|cx| {
3527 let observed = observed.clone();
3528 cx.on_missing_glyphs(move |missing_glyphs, _| {
3529 observed.borrow_mut().extend_from_slice(missing_glyphs);
3530 })
3531 });
3532 cx.update(|cx| {
3533 cx.text_system()
3534 .as_default_text_system()
3535 .expect("the test harness installs a DefaultTextSystem")
3536 .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3537 });
3538 cx.run_until_parked();
3539 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3540
3541 let second_observed = Rc::new(RefCell::new(Vec::new()));
3542 let second_subscription = cx.update(|cx| {
3543 let second_observed = second_observed.clone();
3544 cx.on_missing_glyphs(move |missing_glyphs, _| {
3545 second_observed
3546 .borrow_mut()
3547 .extend_from_slice(missing_glyphs);
3548 })
3549 });
3550 cx.update(|cx| {
3551 cx.text_system()
3552 .as_default_text_system()
3553 .expect("the test harness installs a DefaultTextSystem")
3554 .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3555 });
3556 cx.run_until_parked();
3557 assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3558 assert_eq!(
3559 second_observed.borrow().as_slice(),
3560 &[missing_glyph("replacement")]
3561 );
3562
3563 drop(subscription);
3564 cx.update(|cx| {
3565 cx.text_system()
3566 .as_default_text_system()
3567 .expect("the test harness installs a DefaultTextSystem")
3568 .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3569 });
3570 cx.run_until_parked();
3571 assert_eq!(
3572 second_observed.borrow().as_slice(),
3573 &[
3574 missing_glyph("replacement"),
3575 missing_glyph("after old drop")
3576 ]
3577 );
3578
3579 drop(second_subscription);
3580 cx.update(|cx| {
3581 cx.text_system()
3582 .as_default_text_system()
3583 .expect("the test harness installs a DefaultTextSystem")
3584 .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3585 });
3586 cx.run_until_parked();
3587 assert_eq!(second_observed.borrow().len(), 2);
3588 }
3589
3590 #[test]
3591 fn test_gpui_borrow() {
3592 let cx = TestAppContext::single();
3593 let observation_count = Rc::new(RefCell::new(0));
3594
3595 let state = cx.update(|cx| {
3596 let state = cx.new(|_| false);
3597 cx.observe(&state, {
3598 let observation_count = observation_count.clone();
3599 move |_, _| {
3600 let mut count = observation_count.borrow_mut();
3601 *count += 1;
3602 }
3603 })
3604 .detach();
3605
3606 state
3607 });
3608
3609 cx.update(|cx| {
3610 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3612 });
3613
3614 cx.update(|cx| {
3615 state.write(cx, false);
3616 });
3617
3618 assert_eq!(*observation_count.borrow(), 2);
3619 }
3620
3621 #[gpui::test]
3622 async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3623 #[cfg(unix)]
3624 let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3625 #[cfg(not(unix))]
3626 let user_data_dir = OsString::from("C:\\zed data");
3627 let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3628 let restart_path = PathBuf::from("updated-zed");
3629 cx.update(|cx| cx.set_restart_arguments(arguments.clone()));
3630 let restart = cx.expect_restart();
3631
3632 cx.update(|cx| {
3633 cx.set_restart_path(restart_path.clone());
3634 cx.restart();
3635 });
3636
3637 let (path, restart_arguments) = restart.await.expect("restart was not requested");
3638 assert_eq!(path, Some(restart_path));
3639 assert_eq!(restart_arguments, arguments);
3640 }
3641
3642 fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3643 MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3644 }
3645}