1use std::{
2 any::{TypeId, type_name},
3 cell::{BorrowMutError, Ref, RefCell, RefMut},
4 marker::PhantomData,
5 mem,
6 ops::{Deref, DerefMut},
7 path::{Path, PathBuf},
8 rc::{Rc, Weak},
9 sync::{Arc, atomic::Ordering::SeqCst},
10 time::{Duration, Instant},
11};
12
13use anyhow::{Context as _, Result, anyhow};
14use derive_more::{Deref, DerefMut};
15use futures::{
16 Future, FutureExt,
17 channel::oneshot,
18 future::{LocalBoxFuture, Shared},
19};
20use itertools::Itertools;
21use parking_lot::RwLock;
22use slotmap::SlotMap;
23
24pub use async_context::*;
25use collections::{FxHashMap, FxHashSet, HashMap, VecDeque};
26pub use context::*;
27pub use entity_map::*;
28use http_client::{HttpClient, Url};
29use smallvec::SmallVec;
30#[cfg(any(test, feature = "test-support"))]
31pub use test_context::*;
32use util::{ResultExt, debug_panic};
33
34#[cfg(any(feature = "inspector", debug_assertions))]
35use crate::InspectorElementRegistry;
36use crate::{
37 Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Asset,
38 AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DispatchPhase, DisplayId,
39 EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext,
40 Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform,
41 PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority,
42 PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
43 RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
44 Subscription, SvgRenderer, Task, TextSystem, Window, WindowAppearance, WindowHandle, WindowId,
45 WindowInvalidator,
46 colors::{Colors, GlobalColors},
47 current_platform, hash, init_app_menus,
48};
49
50mod async_context;
51mod context;
52mod entity_map;
53#[cfg(any(test, feature = "test-support"))]
54mod test_context;
55
56/// The duration for which futures returned from [Context::on_app_quit] can run before the application fully quits.
57pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
58
59/// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows.
60/// Strongly consider removing after stabilization.
61#[doc(hidden)]
62pub struct AppCell {
63 app: RefCell<App>,
64}
65
66impl AppCell {
67 #[doc(hidden)]
68 #[track_caller]
69 pub fn borrow(&self) -> AppRef<'_> {
70 if option_env!("TRACK_THREAD_BORROWS").is_some() {
71 let thread_id = std::thread::current().id();
72 eprintln!("borrowed {thread_id:?}");
73 }
74 AppRef(self.app.borrow())
75 }
76
77 #[doc(hidden)]
78 #[track_caller]
79 pub fn borrow_mut(&self) -> AppRefMut<'_> {
80 if option_env!("TRACK_THREAD_BORROWS").is_some() {
81 let thread_id = std::thread::current().id();
82 eprintln!("borrowed {thread_id:?}");
83 }
84 AppRefMut(self.app.borrow_mut())
85 }
86
87 #[doc(hidden)]
88 #[track_caller]
89 pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
90 if option_env!("TRACK_THREAD_BORROWS").is_some() {
91 let thread_id = std::thread::current().id();
92 eprintln!("borrowed {thread_id:?}");
93 }
94 Ok(AppRefMut(self.app.try_borrow_mut()?))
95 }
96}
97
98#[doc(hidden)]
99#[derive(Deref, DerefMut)]
100pub struct AppRef<'a>(Ref<'a, App>);
101
102impl Drop for AppRef<'_> {
103 fn drop(&mut self) {
104 if option_env!("TRACK_THREAD_BORROWS").is_some() {
105 let thread_id = std::thread::current().id();
106 eprintln!("dropped borrow from {thread_id:?}");
107 }
108 }
109}
110
111#[doc(hidden)]
112#[derive(Deref, DerefMut)]
113pub struct AppRefMut<'a>(RefMut<'a, App>);
114
115impl Drop for AppRefMut<'_> {
116 fn drop(&mut self) {
117 if option_env!("TRACK_THREAD_BORROWS").is_some() {
118 let thread_id = std::thread::current().id();
119 eprintln!("dropped {thread_id:?}");
120 }
121 }
122}
123
124/// A reference to a GPUI application, typically constructed in the `main` function of your app.
125/// You won't interact with this type much outside of initial configuration and startup.
126pub struct Application(Rc<AppCell>);
127
128/// Represents an application before it is fully launched. Once your app is
129/// configured, you'll start the app with `App::run`.
130impl Application {
131 /// Builds an app with the given asset source.
132 #[allow(clippy::new_without_default)]
133 pub fn new() -> Self {
134 #[cfg(any(test, feature = "test-support"))]
135 log::info!("GPUI was compiled in test mode");
136
137 Self(App::new_app(
138 current_platform(false),
139 Arc::new(()),
140 Arc::new(NullHttpClient),
141 ))
142 }
143
144 /// Build an app in headless mode. This prevents opening windows,
145 /// but makes it possible to run an application in an context like
146 /// SSH, where GUI applications are not allowed.
147 pub fn headless() -> Self {
148 Self(App::new_app(
149 current_platform(true),
150 Arc::new(()),
151 Arc::new(NullHttpClient),
152 ))
153 }
154
155 /// Assign
156 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
157 let mut context_lock = self.0.borrow_mut();
158 let asset_source = Arc::new(asset_source);
159 context_lock.asset_source = asset_source.clone();
160 context_lock.svg_renderer = SvgRenderer::new(asset_source);
161 drop(context_lock);
162 self
163 }
164
165 /// Sets the HTTP client for the application.
166 pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
167 let mut context_lock = self.0.borrow_mut();
168 context_lock.http_client = http_client;
169 drop(context_lock);
170 self
171 }
172
173 /// Configures when the application should automatically quit.
174 /// By default, [`QuitMode::Default`] is used.
175 pub fn with_quit_mode(self, mode: QuitMode) -> Self {
176 self.0.borrow_mut().quit_mode = mode;
177 self
178 }
179
180 /// Start the application. The provided callback will be called once the
181 /// app is fully launched.
182 pub fn run<F>(self, on_finish_launching: F)
183 where
184 F: 'static + FnOnce(&mut App),
185 {
186 let this = self.0.clone();
187 let platform = self.0.borrow().platform.clone();
188 platform.run(Box::new(move || {
189 let cx = &mut *this.borrow_mut();
190 on_finish_launching(cx);
191 }));
192 }
193
194 /// Register a handler to be invoked when the platform instructs the application
195 /// to open one or more URLs.
196 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
197 where
198 F: 'static + FnMut(Vec<String>),
199 {
200 self.0.borrow().platform.on_open_urls(Box::new(callback));
201 self
202 }
203
204 /// Invokes a handler when an already-running application is launched.
205 /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
206 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
207 where
208 F: 'static + FnMut(&mut App),
209 {
210 let this = Rc::downgrade(&self.0);
211 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
212 if let Some(app) = this.upgrade() {
213 callback(&mut app.borrow_mut());
214 }
215 }));
216 self
217 }
218
219 /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
220 pub fn background_executor(&self) -> BackgroundExecutor {
221 self.0.borrow().background_executor.clone()
222 }
223
224 /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
225 pub fn foreground_executor(&self) -> ForegroundExecutor {
226 self.0.borrow().foreground_executor.clone()
227 }
228
229 /// Returns a reference to the [`TextSystem`] associated with this app.
230 pub fn text_system(&self) -> Arc<TextSystem> {
231 self.0.borrow().text_system.clone()
232 }
233
234 /// Returns the file URL of the executable with the specified name in the application bundle
235 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
236 self.0.borrow().path_for_auxiliary_executable(name)
237 }
238}
239
240type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
241type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
242pub(crate) type KeystrokeObserver =
243 Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
244type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
245type WindowClosedHandler = Box<dyn FnMut(&mut App)>;
246type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
247type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
248
249/// Defines when the application should automatically quit.
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
251pub enum QuitMode {
252 /// Use [`QuitMode::Explicit`] on macOS and [`QuitMode::LastWindowClosed`] on other platforms.
253 #[default]
254 Default,
255 /// Quit automatically when the last window is closed.
256 LastWindowClosed,
257 /// Quit only when requested via [`App::quit`].
258 Explicit,
259}
260
261#[doc(hidden)]
262#[derive(Clone, PartialEq, Eq)]
263pub struct SystemWindowTab {
264 pub id: WindowId,
265 pub title: SharedString,
266 pub handle: AnyWindowHandle,
267 pub last_active_at: Instant,
268}
269
270impl SystemWindowTab {
271 /// Create a new instance of the window tab.
272 pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
273 Self {
274 id: handle.id,
275 title,
276 handle,
277 last_active_at: Instant::now(),
278 }
279 }
280}
281
282/// A controller for managing window tabs.
283#[derive(Default)]
284pub struct SystemWindowTabController {
285 visible: Option<bool>,
286 tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
287}
288
289impl Global for SystemWindowTabController {}
290
291impl SystemWindowTabController {
292 /// Create a new instance of the window tab controller.
293 pub fn new() -> Self {
294 Self {
295 visible: None,
296 tab_groups: FxHashMap::default(),
297 }
298 }
299
300 /// Initialize the global window tab controller.
301 pub fn init(cx: &mut App) {
302 cx.set_global(SystemWindowTabController::new());
303 }
304
305 /// Get all tab groups.
306 pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
307 &self.tab_groups
308 }
309
310 /// Get the next tab group window handle.
311 pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
312 let controller = cx.global::<SystemWindowTabController>();
313 let current_group = controller
314 .tab_groups
315 .iter()
316 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
317
318 let current_group = current_group?;
319 // TODO: `.keys()` returns arbitrary order, what does "next" mean?
320 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
321 let idx = group_ids.iter().position(|g| *g == current_group)?;
322 let next_idx = (idx + 1) % group_ids.len();
323
324 controller
325 .tab_groups
326 .get(group_ids[next_idx])
327 .and_then(|tabs| {
328 tabs.iter()
329 .max_by_key(|tab| tab.last_active_at)
330 .or_else(|| tabs.first())
331 .map(|tab| &tab.handle)
332 })
333 }
334
335 /// Get the previous tab group window handle.
336 pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
337 let controller = cx.global::<SystemWindowTabController>();
338 let current_group = controller
339 .tab_groups
340 .iter()
341 .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
342
343 let current_group = current_group?;
344 // TODO: `.keys()` returns arbitrary order, what does "previous" mean?
345 let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
346 let idx = group_ids.iter().position(|g| *g == current_group)?;
347 let prev_idx = if idx == 0 {
348 group_ids.len() - 1
349 } else {
350 idx - 1
351 };
352
353 controller
354 .tab_groups
355 .get(group_ids[prev_idx])
356 .and_then(|tabs| {
357 tabs.iter()
358 .max_by_key(|tab| tab.last_active_at)
359 .or_else(|| tabs.first())
360 .map(|tab| &tab.handle)
361 })
362 }
363
364 /// Get all tabs in the same window.
365 pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
366 self.tab_groups
367 .values()
368 .find(|tabs| tabs.iter().any(|tab| tab.id == id))
369 }
370
371 /// Initialize the visibility of the system window tab controller.
372 pub fn init_visible(cx: &mut App, visible: bool) {
373 let mut controller = cx.global_mut::<SystemWindowTabController>();
374 if controller.visible.is_none() {
375 controller.visible = Some(visible);
376 }
377 }
378
379 /// Get the visibility of the system window tab controller.
380 pub fn is_visible(&self) -> bool {
381 self.visible.unwrap_or(false)
382 }
383
384 /// Set the visibility of the system window tab controller.
385 pub fn set_visible(cx: &mut App, visible: bool) {
386 let mut controller = cx.global_mut::<SystemWindowTabController>();
387 controller.visible = Some(visible);
388 }
389
390 /// Update the last active of a window.
391 pub fn update_last_active(cx: &mut App, id: WindowId) {
392 let mut controller = cx.global_mut::<SystemWindowTabController>();
393 for windows in controller.tab_groups.values_mut() {
394 for tab in windows.iter_mut() {
395 if tab.id == id {
396 tab.last_active_at = Instant::now();
397 }
398 }
399 }
400 }
401
402 /// Update the position of a tab within its group.
403 pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
404 let mut controller = cx.global_mut::<SystemWindowTabController>();
405 for (_, windows) in controller.tab_groups.iter_mut() {
406 if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
407 if ix < windows.len() && current_pos != ix {
408 let window_tab = windows.remove(current_pos);
409 windows.insert(ix, window_tab);
410 }
411 break;
412 }
413 }
414 }
415
416 /// Update the title of a tab.
417 pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
418 let controller = cx.global::<SystemWindowTabController>();
419 let tab = controller
420 .tab_groups
421 .values()
422 .flat_map(|windows| windows.iter())
423 .find(|tab| tab.id == id);
424
425 if tab.map_or(true, |t| t.title == title) {
426 return;
427 }
428
429 let mut controller = cx.global_mut::<SystemWindowTabController>();
430 for windows in controller.tab_groups.values_mut() {
431 for tab in windows.iter_mut() {
432 if tab.id == id {
433 tab.title = title;
434 return;
435 }
436 }
437 }
438 }
439
440 /// Insert a tab into a tab group.
441 pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
442 let mut controller = cx.global_mut::<SystemWindowTabController>();
443 let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
444 return;
445 };
446
447 let mut expected_tab_ids: Vec<_> = tabs
448 .iter()
449 .filter(|tab| tab.id != id)
450 .map(|tab| tab.id)
451 .sorted()
452 .collect();
453
454 let mut tab_group_id = None;
455 for (group_id, group_tabs) in &controller.tab_groups {
456 let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
457 if tab_ids == expected_tab_ids {
458 tab_group_id = Some(*group_id);
459 break;
460 }
461 }
462
463 if let Some(tab_group_id) = tab_group_id {
464 if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
465 tabs.push(tab);
466 }
467 } else {
468 let new_group_id = controller.tab_groups.len();
469 controller.tab_groups.insert(new_group_id, tabs);
470 }
471 }
472
473 /// Remove a tab from a tab group.
474 pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
475 let mut controller = cx.global_mut::<SystemWindowTabController>();
476 let mut removed_tab = None;
477
478 controller.tab_groups.retain(|_, tabs| {
479 if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
480 removed_tab = Some(tabs.remove(pos));
481 }
482 !tabs.is_empty()
483 });
484
485 removed_tab
486 }
487
488 /// Move a tab to a new tab group.
489 pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
490 let mut removed_tab = Self::remove_tab(cx, id);
491 let mut controller = cx.global_mut::<SystemWindowTabController>();
492
493 if let Some(tab) = removed_tab {
494 let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
495 controller.tab_groups.insert(new_group_id, vec![tab]);
496 }
497 }
498
499 /// Merge all tab groups into a single group.
500 pub fn merge_all_windows(cx: &mut App, id: WindowId) {
501 let mut controller = cx.global_mut::<SystemWindowTabController>();
502 let Some(initial_tabs) = controller.tabs(id) else {
503 return;
504 };
505
506 let initial_tabs_len = initial_tabs.len();
507 let mut all_tabs = initial_tabs.clone();
508
509 for (_, mut tabs) in controller.tab_groups.drain() {
510 tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
511 all_tabs.extend(tabs);
512 }
513
514 controller.tab_groups.insert(0, all_tabs);
515 }
516
517 /// Selects the next tab in the tab group in the trailing direction.
518 pub fn select_next_tab(cx: &mut App, id: WindowId) {
519 let mut controller = cx.global_mut::<SystemWindowTabController>();
520 let Some(tabs) = controller.tabs(id) else {
521 return;
522 };
523
524 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
525 let next_index = (current_index + 1) % tabs.len();
526
527 let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
528 window.activate_window();
529 });
530 }
531
532 /// Selects the previous tab in the tab group in the leading direction.
533 pub fn select_previous_tab(cx: &mut App, id: WindowId) {
534 let mut controller = cx.global_mut::<SystemWindowTabController>();
535 let Some(tabs) = controller.tabs(id) else {
536 return;
537 };
538
539 let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
540 let previous_index = if current_index == 0 {
541 tabs.len() - 1
542 } else {
543 current_index - 1
544 };
545
546 let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
547 window.activate_window();
548 });
549 }
550}
551
552pub(crate) enum GpuiMode {
553 #[cfg(any(test, feature = "test-support"))]
554 Test {
555 skip_drawing: bool,
556 },
557 Production,
558}
559
560impl GpuiMode {
561 #[cfg(any(test, feature = "test-support"))]
562 pub fn test() -> Self {
563 GpuiMode::Test {
564 skip_drawing: false,
565 }
566 }
567
568 #[inline]
569 pub(crate) fn skip_drawing(&self) -> bool {
570 match self {
571 #[cfg(any(test, feature = "test-support"))]
572 GpuiMode::Test { skip_drawing } => *skip_drawing,
573 GpuiMode::Production => false,
574 }
575 }
576}
577
578/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
579/// Other [Context] derefs to this type.
580/// You need a reference to an `App` to access the state of a [Entity].
581pub struct App {
582 pub(crate) this: Weak<AppCell>,
583 pub(crate) platform: Rc<dyn Platform>,
584 pub(crate) mode: GpuiMode,
585 text_system: Arc<TextSystem>,
586 flushing_effects: bool,
587 pending_updates: usize,
588 pub(crate) actions: Rc<ActionRegistry>,
589 pub(crate) active_drag: Option<AnyDrag>,
590 pub(crate) background_executor: BackgroundExecutor,
591 pub(crate) foreground_executor: ForegroundExecutor,
592 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
593 asset_source: Arc<dyn AssetSource>,
594 pub(crate) svg_renderer: SvgRenderer,
595 http_client: Arc<dyn HttpClient>,
596 pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
597 pub(crate) entities: EntityMap,
598 pub(crate) window_update_stack: Vec<WindowId>,
599 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
600 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
601 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
602 pub(crate) focus_handles: Arc<FocusMap>,
603 pub(crate) keymap: Rc<RefCell<Keymap>>,
604 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
605 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
606 pub(crate) global_action_listeners:
607 FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
608 pending_effects: VecDeque<Effect>,
609 pub(crate) pending_notifications: FxHashSet<EntityId>,
610 pub(crate) pending_global_notifications: FxHashSet<TypeId>,
611 pub(crate) observers: SubscriberSet<EntityId, Handler>,
612 // TypeId is the type of the event that the listener callback expects
613 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
614 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
615 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
616 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
617 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
618 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
619 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
620 pub(crate) restart_observers: SubscriberSet<(), Handler>,
621 pub(crate) restart_path: Option<PathBuf>,
622 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
623 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
624 pub(crate) propagate_event: bool,
625 pub(crate) prompt_builder: Option<PromptBuilder>,
626 pub(crate) window_invalidators_by_entity:
627 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
628 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
629 #[cfg(any(feature = "inspector", debug_assertions))]
630 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
631 #[cfg(any(feature = "inspector", debug_assertions))]
632 pub(crate) inspector_element_registry: InspectorElementRegistry,
633 #[cfg(any(test, feature = "test-support", debug_assertions))]
634 pub(crate) name: Option<&'static str>,
635 quit_mode: QuitMode,
636 quitting: bool,
637}
638
639impl App {
640 #[allow(clippy::new_ret_no_self)]
641 pub(crate) fn new_app(
642 platform: Rc<dyn Platform>,
643 asset_source: Arc<dyn AssetSource>,
644 http_client: Arc<dyn HttpClient>,
645 ) -> Rc<AppCell> {
646 let executor = platform.background_executor();
647 let foreground_executor = platform.foreground_executor();
648 assert!(
649 executor.is_main_thread(),
650 "must construct App on main thread"
651 );
652
653 let text_system = Arc::new(TextSystem::new(platform.text_system()));
654 let entities = EntityMap::new();
655 let keyboard_layout = platform.keyboard_layout();
656 let keyboard_mapper = platform.keyboard_mapper();
657
658 let app = Rc::new_cyclic(|this| AppCell {
659 app: RefCell::new(App {
660 this: this.clone(),
661 platform: platform.clone(),
662 text_system,
663 mode: GpuiMode::Production,
664 actions: Rc::new(ActionRegistry::default()),
665 flushing_effects: false,
666 pending_updates: 0,
667 active_drag: None,
668 background_executor: executor,
669 foreground_executor,
670 svg_renderer: SvgRenderer::new(asset_source.clone()),
671 loading_assets: Default::default(),
672 asset_source,
673 http_client,
674 globals_by_type: FxHashMap::default(),
675 entities,
676 new_entity_observers: SubscriberSet::new(),
677 windows: SlotMap::with_key(),
678 window_update_stack: Vec::new(),
679 window_handles: FxHashMap::default(),
680 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
681 keymap: Rc::new(RefCell::new(Keymap::default())),
682 keyboard_layout,
683 keyboard_mapper,
684 global_action_listeners: FxHashMap::default(),
685 pending_effects: VecDeque::new(),
686 pending_notifications: FxHashSet::default(),
687 pending_global_notifications: FxHashSet::default(),
688 observers: SubscriberSet::new(),
689 tracked_entities: FxHashMap::default(),
690 window_invalidators_by_entity: FxHashMap::default(),
691 event_listeners: SubscriberSet::new(),
692 release_listeners: SubscriberSet::new(),
693 keystroke_observers: SubscriberSet::new(),
694 keystroke_interceptors: SubscriberSet::new(),
695 keyboard_layout_observers: SubscriberSet::new(),
696 global_observers: SubscriberSet::new(),
697 quit_observers: SubscriberSet::new(),
698 restart_observers: SubscriberSet::new(),
699 restart_path: None,
700 window_closed_observers: SubscriberSet::new(),
701 layout_id_buffer: Default::default(),
702 propagate_event: true,
703 prompt_builder: Some(PromptBuilder::Default),
704 #[cfg(any(feature = "inspector", debug_assertions))]
705 inspector_renderer: None,
706 #[cfg(any(feature = "inspector", debug_assertions))]
707 inspector_element_registry: InspectorElementRegistry::default(),
708 quit_mode: QuitMode::default(),
709 quitting: false,
710
711 #[cfg(any(test, feature = "test-support", debug_assertions))]
712 name: None,
713 }),
714 });
715
716 init_app_menus(platform.as_ref(), &app.borrow());
717 SystemWindowTabController::init(&mut app.borrow_mut());
718
719 platform.on_keyboard_layout_change(Box::new({
720 let app = Rc::downgrade(&app);
721 move || {
722 if let Some(app) = app.upgrade() {
723 let cx = &mut app.borrow_mut();
724 cx.keyboard_layout = cx.platform.keyboard_layout();
725 cx.keyboard_mapper = cx.platform.keyboard_mapper();
726 cx.keyboard_layout_observers
727 .clone()
728 .retain(&(), move |callback| (callback)(cx));
729 }
730 }
731 }));
732
733 platform.on_quit(Box::new({
734 let cx = app.clone();
735 move || {
736 cx.borrow_mut().shutdown();
737 }
738 }));
739
740 app
741 }
742
743 /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`]
744 /// will be given 100ms to complete before exiting.
745 pub fn shutdown(&mut self) {
746 let mut futures = Vec::new();
747
748 for observer in self.quit_observers.remove(&()) {
749 futures.push(observer(self));
750 }
751
752 self.windows.clear();
753 self.window_handles.clear();
754 self.flush_effects();
755 self.quitting = true;
756
757 let futures = futures::future::join_all(futures);
758 if self
759 .background_executor
760 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
761 .is_err()
762 {
763 log::error!("timed out waiting on app_will_quit");
764 }
765
766 self.quitting = false;
767 }
768
769 /// Get the id of the current keyboard layout
770 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
771 self.keyboard_layout.as_ref()
772 }
773
774 /// Get the current keyboard mapper.
775 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
776 &self.keyboard_mapper
777 }
778
779 /// Invokes a handler when the current keyboard layout changes
780 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
781 where
782 F: 'static + FnMut(&mut App),
783 {
784 let (subscription, activate) = self.keyboard_layout_observers.insert(
785 (),
786 Box::new(move |cx| {
787 callback(cx);
788 true
789 }),
790 );
791 activate();
792 subscription
793 }
794
795 /// Gracefully quit the application via the platform's standard routine.
796 pub fn quit(&self) {
797 self.platform.quit();
798 }
799
800 /// Schedules all windows in the application to be redrawn. This can be called
801 /// multiple times in an update cycle and still result in a single redraw.
802 pub fn refresh_windows(&mut self) {
803 self.pending_effects.push_back(Effect::RefreshWindows);
804 }
805
806 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
807 self.start_update();
808 let result = update(self);
809 self.finish_update();
810 result
811 }
812
813 pub(crate) fn start_update(&mut self) {
814 self.pending_updates += 1;
815 }
816
817 pub(crate) fn finish_update(&mut self) {
818 if !self.flushing_effects && self.pending_updates == 1 {
819 self.flushing_effects = true;
820 self.flush_effects();
821 self.flushing_effects = false;
822 }
823 self.pending_updates -= 1;
824 }
825
826 /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
827 pub fn observe<W>(
828 &mut self,
829 entity: &Entity<W>,
830 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
831 ) -> Subscription
832 where
833 W: 'static,
834 {
835 self.observe_internal(entity, move |e, cx| {
836 on_notify(e, cx);
837 true
838 })
839 }
840
841 pub(crate) fn detect_accessed_entities<R>(
842 &mut self,
843 callback: impl FnOnce(&mut App) -> R,
844 ) -> (R, FxHashSet<EntityId>) {
845 let accessed_entities_start = self.entities.accessed_entities.borrow().clone();
846 let result = callback(self);
847 let accessed_entities_end = self.entities.accessed_entities.borrow().clone();
848 let entities_accessed_in_callback = accessed_entities_end
849 .difference(&accessed_entities_start)
850 .copied()
851 .collect::<FxHashSet<EntityId>>();
852 (result, entities_accessed_in_callback)
853 }
854
855 pub(crate) fn record_entities_accessed(
856 &mut self,
857 window_handle: AnyWindowHandle,
858 invalidator: WindowInvalidator,
859 entities: &FxHashSet<EntityId>,
860 ) {
861 let mut tracked_entities =
862 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
863 for entity in tracked_entities.iter() {
864 self.window_invalidators_by_entity
865 .entry(*entity)
866 .and_modify(|windows| {
867 windows.remove(&window_handle.id);
868 });
869 }
870 for entity in entities.iter() {
871 self.window_invalidators_by_entity
872 .entry(*entity)
873 .or_default()
874 .insert(window_handle.id, invalidator.clone());
875 }
876 tracked_entities.clear();
877 tracked_entities.extend(entities.iter().copied());
878 self.tracked_entities
879 .insert(window_handle.id, tracked_entities);
880 }
881
882 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
883 let (subscription, activate) = self.observers.insert(key, value);
884 self.defer(move |_| activate());
885 subscription
886 }
887
888 pub(crate) fn observe_internal<W>(
889 &mut self,
890 entity: &Entity<W>,
891 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
892 ) -> Subscription
893 where
894 W: 'static,
895 {
896 let entity_id = entity.entity_id();
897 let handle = entity.downgrade();
898 self.new_observer(
899 entity_id,
900 Box::new(move |cx| {
901 if let Some(entity) = handle.upgrade() {
902 on_notify(entity, cx)
903 } else {
904 false
905 }
906 }),
907 )
908 }
909
910 /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
911 /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
912 pub fn subscribe<T, Event>(
913 &mut self,
914 entity: &Entity<T>,
915 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
916 ) -> Subscription
917 where
918 T: 'static + EventEmitter<Event>,
919 Event: 'static,
920 {
921 self.subscribe_internal(entity, move |entity, event, cx| {
922 on_event(entity, event, cx);
923 true
924 })
925 }
926
927 pub(crate) fn new_subscription(
928 &mut self,
929 key: EntityId,
930 value: (TypeId, Listener),
931 ) -> Subscription {
932 let (subscription, activate) = self.event_listeners.insert(key, value);
933 self.defer(move |_| activate());
934 subscription
935 }
936 pub(crate) fn subscribe_internal<T, Evt>(
937 &mut self,
938 entity: &Entity<T>,
939 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
940 ) -> Subscription
941 where
942 T: 'static + EventEmitter<Evt>,
943 Evt: 'static,
944 {
945 let entity_id = entity.entity_id();
946 let handle = entity.downgrade();
947 self.new_subscription(
948 entity_id,
949 (
950 TypeId::of::<Evt>(),
951 Box::new(move |event, cx| {
952 let event: &Evt = event.downcast_ref().expect("invalid event type");
953 if let Some(entity) = handle.upgrade() {
954 on_event(entity, event, cx)
955 } else {
956 false
957 }
958 }),
959 ),
960 )
961 }
962
963 /// Returns handles to all open windows in the application.
964 /// Each handle could be downcast to a handle typed for the root view of that window.
965 /// To find all windows of a given type, you could filter on
966 pub fn windows(&self) -> Vec<AnyWindowHandle> {
967 self.windows
968 .keys()
969 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
970 .collect()
971 }
972
973 /// Returns the window handles ordered by their appearance on screen, front to back.
974 ///
975 /// The first window in the returned list is the active/topmost window of the application.
976 ///
977 /// This method returns None if the platform doesn't implement the method yet.
978 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
979 self.platform.window_stack()
980 }
981
982 /// Returns a handle to the window that is currently focused at the platform level, if one exists.
983 pub fn active_window(&self) -> Option<AnyWindowHandle> {
984 self.platform.active_window()
985 }
986
987 /// Opens a new window with the given option and the root view returned by the given function.
988 /// The function is invoked with a `Window`, which can be used to interact with window-specific
989 /// functionality.
990 pub fn open_window<V: 'static + Render>(
991 &mut self,
992 options: crate::WindowOptions,
993 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
994 ) -> anyhow::Result<WindowHandle<V>> {
995 self.update(|cx| {
996 let id = cx.windows.insert(None);
997 let handle = WindowHandle::new(id);
998 match Window::new(handle.into(), options, cx) {
999 Ok(mut window) => {
1000 cx.window_update_stack.push(id);
1001 let root_view = build_root_view(&mut window, cx);
1002 cx.window_update_stack.pop();
1003 window.root.replace(root_view.into());
1004 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1005
1006 // allow a window to draw at least once before returning
1007 // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
1008 // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
1009 // where DispatchTree::root_node_id asserts on empty nodes
1010 let clear = window.draw(cx);
1011 clear.clear();
1012
1013 cx.window_handles.insert(id, window.handle);
1014 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1015 Ok(handle)
1016 }
1017 Err(e) => {
1018 cx.windows.remove(id);
1019 Err(e)
1020 }
1021 }
1022 })
1023 }
1024
1025 /// Instructs the platform to activate the application by bringing it to the foreground.
1026 pub fn activate(&self, ignoring_other_apps: bool) {
1027 self.platform.activate(ignoring_other_apps);
1028 }
1029
1030 /// Hide the application at the platform level.
1031 pub fn hide(&self) {
1032 self.platform.hide();
1033 }
1034
1035 /// Hide other applications at the platform level.
1036 pub fn hide_other_apps(&self) {
1037 self.platform.hide_other_apps();
1038 }
1039
1040 /// Unhide other applications at the platform level.
1041 pub fn unhide_other_apps(&self) {
1042 self.platform.unhide_other_apps();
1043 }
1044
1045 /// Returns the list of currently active displays.
1046 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1047 self.platform.displays()
1048 }
1049
1050 /// Returns the primary display that will be used for new windows.
1051 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1052 self.platform.primary_display()
1053 }
1054
1055 /// Returns whether `screen_capture_sources` may work.
1056 pub fn is_screen_capture_supported(&self) -> bool {
1057 self.platform.is_screen_capture_supported()
1058 }
1059
1060 /// Returns a list of available screen capture sources.
1061 pub fn screen_capture_sources(
1062 &self,
1063 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1064 self.platform.screen_capture_sources()
1065 }
1066
1067 /// Returns the display with the given ID, if one exists.
1068 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1069 self.displays()
1070 .iter()
1071 .find(|display| display.id() == id)
1072 .cloned()
1073 }
1074
1075 /// Returns the appearance of the application's windows.
1076 pub fn window_appearance(&self) -> WindowAppearance {
1077 self.platform.window_appearance()
1078 }
1079
1080 /// Writes data to the primary selection buffer.
1081 /// Only available on Linux.
1082 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1083 pub fn write_to_primary(&self, item: ClipboardItem) {
1084 self.platform.write_to_primary(item)
1085 }
1086
1087 /// Writes data to the platform clipboard.
1088 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1089 self.platform.write_to_clipboard(item)
1090 }
1091
1092 /// Reads data from the primary selection buffer.
1093 /// Only available on Linux.
1094 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1095 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1096 self.platform.read_from_primary()
1097 }
1098
1099 /// Reads data from the platform clipboard.
1100 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1101 self.platform.read_from_clipboard()
1102 }
1103
1104 /// Writes credentials to the platform keychain.
1105 pub fn write_credentials(
1106 &self,
1107 url: &str,
1108 username: &str,
1109 password: &[u8],
1110 ) -> Task<Result<()>> {
1111 self.platform.write_credentials(url, username, password)
1112 }
1113
1114 /// Reads credentials from the platform keychain.
1115 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1116 self.platform.read_credentials(url)
1117 }
1118
1119 /// Deletes credentials from the platform keychain.
1120 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1121 self.platform.delete_credentials(url)
1122 }
1123
1124 /// Directs the platform's default browser to open the given URL.
1125 pub fn open_url(&self, url: &str) {
1126 self.platform.open_url(url);
1127 }
1128
1129 /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
1130 /// opened by the current app.
1131 ///
1132 /// On some platforms (e.g. macOS) you may be able to register URL schemes
1133 /// as part of app distribution, but this method exists to let you register
1134 /// schemes at runtime.
1135 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1136 self.platform.register_url_scheme(scheme)
1137 }
1138
1139 /// Returns the full pathname of the current app bundle.
1140 ///
1141 /// Returns an error if the app is not being run from a bundle.
1142 pub fn app_path(&self) -> Result<PathBuf> {
1143 self.platform.app_path()
1144 }
1145
1146 /// On Linux, returns the name of the compositor in use.
1147 ///
1148 /// Returns an empty string on other platforms.
1149 pub fn compositor_name(&self) -> &'static str {
1150 self.platform.compositor_name()
1151 }
1152
1153 /// Returns the file URL of the executable with the specified name in the application bundle
1154 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1155 self.platform.path_for_auxiliary_executable(name)
1156 }
1157
1158 /// Displays a platform modal for selecting paths.
1159 ///
1160 /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
1161 /// If cancelled, a `None` will be relayed instead.
1162 /// May return an error on Linux if the file picker couldn't be opened.
1163 pub fn prompt_for_paths(
1164 &self,
1165 options: PathPromptOptions,
1166 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1167 self.platform.prompt_for_paths(options)
1168 }
1169
1170 /// Displays a platform modal for selecting a new path where a file can be saved.
1171 ///
1172 /// The provided directory will be used to set the initial location.
1173 /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
1174 /// If cancelled, a `None` will be relayed instead.
1175 /// May return an error on Linux if the file picker couldn't be opened.
1176 pub fn prompt_for_new_path(
1177 &self,
1178 directory: &Path,
1179 suggested_name: Option<&str>,
1180 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1181 self.platform.prompt_for_new_path(directory, suggested_name)
1182 }
1183
1184 /// Reveals the specified path at the platform level, such as in Finder on macOS.
1185 pub fn reveal_path(&self, path: &Path) {
1186 self.platform.reveal_path(path)
1187 }
1188
1189 /// Opens the specified path with the system's default application.
1190 pub fn open_with_system(&self, path: &Path) {
1191 self.platform.open_with_system(path)
1192 }
1193
1194 /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
1195 pub fn should_auto_hide_scrollbars(&self) -> bool {
1196 self.platform.should_auto_hide_scrollbars()
1197 }
1198
1199 /// Restarts the application.
1200 pub fn restart(&mut self) {
1201 self.restart_observers
1202 .clone()
1203 .retain(&(), |observer| observer(self));
1204 self.platform.restart(self.restart_path.take())
1205 }
1206
1207 /// Sets the path to use when restarting the application.
1208 pub fn set_restart_path(&mut self, path: PathBuf) {
1209 self.restart_path = Some(path);
1210 }
1211
1212 /// Returns the HTTP client for the application.
1213 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1214 self.http_client.clone()
1215 }
1216
1217 /// Sets the HTTP client for the application.
1218 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1219 self.http_client = new_client;
1220 }
1221
1222 /// Configures when the application should automatically quit.
1223 /// By default, [`QuitMode::Default`] is used.
1224 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1225 self.quit_mode = mode;
1226 }
1227
1228 /// Returns the SVG renderer used by the application.
1229 pub fn svg_renderer(&self) -> SvgRenderer {
1230 self.svg_renderer.clone()
1231 }
1232
1233 pub(crate) fn push_effect(&mut self, effect: Effect) {
1234 match &effect {
1235 Effect::Notify { emitter } => {
1236 if !self.pending_notifications.insert(*emitter) {
1237 return;
1238 }
1239 }
1240 Effect::NotifyGlobalObservers { global_type } => {
1241 if !self.pending_global_notifications.insert(*global_type) {
1242 return;
1243 }
1244 }
1245 _ => {}
1246 };
1247
1248 self.pending_effects.push_back(effect);
1249 }
1250
1251 /// Called at the end of [`App::update`] to complete any side effects
1252 /// such as notifying observers, emitting events, etc. Effects can themselves
1253 /// cause effects, so we continue looping until all effects are processed.
1254 fn flush_effects(&mut self) {
1255 loop {
1256 self.release_dropped_entities();
1257 self.release_dropped_focus_handles();
1258 if let Some(effect) = self.pending_effects.pop_front() {
1259 match effect {
1260 Effect::Notify { emitter } => {
1261 self.apply_notify_effect(emitter);
1262 }
1263
1264 Effect::Emit {
1265 emitter,
1266 event_type,
1267 event,
1268 } => self.apply_emit_effect(emitter, event_type, event),
1269
1270 Effect::RefreshWindows => {
1271 self.apply_refresh_effect();
1272 }
1273
1274 Effect::NotifyGlobalObservers { global_type } => {
1275 self.apply_notify_global_observers_effect(global_type);
1276 }
1277
1278 Effect::Defer { callback } => {
1279 self.apply_defer_effect(callback);
1280 }
1281 Effect::EntityCreated {
1282 entity,
1283 tid,
1284 window,
1285 } => {
1286 self.apply_entity_created_effect(entity, tid, window);
1287 }
1288 }
1289 } else {
1290 #[cfg(any(test, feature = "test-support"))]
1291 for window in self
1292 .windows
1293 .values()
1294 .filter_map(|window| {
1295 let window = window.as_deref()?;
1296 window.invalidator.is_dirty().then_some(window.handle)
1297 })
1298 .collect::<Vec<_>>()
1299 {
1300 self.update_window(window, |_, window, cx| window.draw(cx).clear())
1301 .unwrap();
1302 }
1303
1304 if self.pending_effects.is_empty() {
1305 break;
1306 }
1307 }
1308 }
1309 }
1310
1311 /// Repeatedly called during `flush_effects` to release any entities whose
1312 /// reference count has become zero. We invoke any release observers before dropping
1313 /// each entity.
1314 fn release_dropped_entities(&mut self) {
1315 loop {
1316 let dropped = self.entities.take_dropped();
1317 if dropped.is_empty() {
1318 break;
1319 }
1320
1321 for (entity_id, mut entity) in dropped {
1322 self.observers.remove(&entity_id);
1323 self.event_listeners.remove(&entity_id);
1324 for release_callback in self.release_listeners.remove(&entity_id) {
1325 release_callback(entity.as_mut(), self);
1326 }
1327 }
1328 }
1329 }
1330
1331 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
1332 fn release_dropped_focus_handles(&mut self) {
1333 self.focus_handles
1334 .clone()
1335 .write()
1336 .retain(|handle_id, focus| {
1337 if focus.ref_count.load(SeqCst) == 0 {
1338 for window_handle in self.windows() {
1339 window_handle
1340 .update(self, |_, window, _| {
1341 if window.focus == Some(handle_id) {
1342 window.blur();
1343 }
1344 })
1345 .unwrap();
1346 }
1347 false
1348 } else {
1349 true
1350 }
1351 });
1352 }
1353
1354 fn apply_notify_effect(&mut self, emitter: EntityId) {
1355 self.pending_notifications.remove(&emitter);
1356
1357 self.observers
1358 .clone()
1359 .retain(&emitter, |handler| handler(self));
1360 }
1361
1362 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
1363 self.event_listeners
1364 .clone()
1365 .retain(&emitter, |(stored_type, handler)| {
1366 if *stored_type == event_type {
1367 handler(event.as_ref(), self)
1368 } else {
1369 true
1370 }
1371 });
1372 }
1373
1374 fn apply_refresh_effect(&mut self) {
1375 for window in self.windows.values_mut() {
1376 if let Some(window) = window.as_deref_mut() {
1377 window.refreshing = true;
1378 window.invalidator.set_dirty(true);
1379 }
1380 }
1381 }
1382
1383 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1384 self.pending_global_notifications.remove(&type_id);
1385 self.global_observers
1386 .clone()
1387 .retain(&type_id, |observer| observer(self));
1388 }
1389
1390 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1391 callback(self);
1392 }
1393
1394 fn apply_entity_created_effect(
1395 &mut self,
1396 entity: AnyEntity,
1397 tid: TypeId,
1398 window: Option<WindowId>,
1399 ) {
1400 self.new_entity_observers.clone().retain(&tid, |observer| {
1401 if let Some(id) = window {
1402 self.update_window_id(id, {
1403 let entity = entity.clone();
1404 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1405 })
1406 .expect("All windows should be off the stack when flushing effects");
1407 } else {
1408 (observer)(entity.clone(), &mut None, self)
1409 }
1410 true
1411 });
1412 }
1413
1414 fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1415 where
1416 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1417 {
1418 self.update(|cx| {
1419 let mut window = cx.windows.get_mut(id)?.take()?;
1420
1421 let root_view = window.root.clone().unwrap();
1422
1423 cx.window_update_stack.push(window.handle.id);
1424 let result = update(root_view, &mut window, cx);
1425 cx.window_update_stack.pop();
1426
1427 if window.removed {
1428 cx.window_handles.remove(&id);
1429 cx.windows.remove(id);
1430
1431 cx.window_closed_observers.clone().retain(&(), |callback| {
1432 callback(cx);
1433 true
1434 });
1435
1436 let quit_on_empty = match cx.quit_mode {
1437 QuitMode::Explicit => false,
1438 QuitMode::LastWindowClosed => true,
1439 QuitMode::Default => cfg!(not(target_os = "macos")),
1440 };
1441
1442 if quit_on_empty && cx.windows.is_empty() {
1443 cx.quit();
1444 }
1445 } else {
1446 cx.windows.get_mut(id)?.replace(window);
1447 }
1448
1449 Some(result)
1450 })
1451 .context("window not found")
1452 }
1453
1454 /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1455 /// so it can be held across `await` points.
1456 pub fn to_async(&self) -> AsyncApp {
1457 AsyncApp {
1458 app: self.this.clone(),
1459 background_executor: self.background_executor.clone(),
1460 foreground_executor: self.foreground_executor.clone(),
1461 }
1462 }
1463
1464 /// Obtains a reference to the executor, which can be used to spawn futures.
1465 pub fn background_executor(&self) -> &BackgroundExecutor {
1466 &self.background_executor
1467 }
1468
1469 /// Obtains a reference to the executor, which can be used to spawn futures.
1470 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1471 if self.quitting {
1472 panic!("Can't spawn on main thread after on_app_quit")
1473 };
1474 &self.foreground_executor
1475 }
1476
1477 /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1478 /// with [AsyncApp], which allows the application state to be accessed across await points.
1479 #[track_caller]
1480 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1481 where
1482 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1483 R: 'static,
1484 {
1485 if self.quitting {
1486 debug_panic!("Can't spawn on main thread after on_app_quit")
1487 };
1488
1489 let mut cx = self.to_async();
1490
1491 self.foreground_executor
1492 .spawn(async move { f(&mut cx).await })
1493 }
1494
1495 /// Spawns the future returned by the given function on the main thread with
1496 /// the given priority. The closure will be invoked with [AsyncApp], which
1497 /// allows the application state to be accessed across await points.
1498 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1499 where
1500 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1501 R: 'static,
1502 {
1503 if self.quitting {
1504 debug_panic!("Can't spawn on main thread after on_app_quit")
1505 };
1506
1507 let mut cx = self.to_async();
1508
1509 self.foreground_executor
1510 .spawn_with_priority(priority, async move { f(&mut cx).await })
1511 }
1512
1513 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1514 /// that are currently on the stack to be returned to the app.
1515 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1516 self.push_effect(Effect::Defer {
1517 callback: Box::new(f),
1518 });
1519 }
1520
1521 /// Accessor for the application's asset source, which is provided when constructing the `App`.
1522 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1523 &self.asset_source
1524 }
1525
1526 /// Accessor for the text system.
1527 pub fn text_system(&self) -> &Arc<TextSystem> {
1528 &self.text_system
1529 }
1530
1531 /// Check whether a global of the given type has been assigned.
1532 pub fn has_global<G: Global>(&self) -> bool {
1533 self.globals_by_type.contains_key(&TypeId::of::<G>())
1534 }
1535
1536 /// Access the global of the given type. Panics if a global for that type has not been assigned.
1537 #[track_caller]
1538 pub fn global<G: Global>(&self) -> &G {
1539 self.globals_by_type
1540 .get(&TypeId::of::<G>())
1541 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1542 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1543 .unwrap()
1544 }
1545
1546 /// Access the global of the given type if a value has been assigned.
1547 pub fn try_global<G: Global>(&self) -> Option<&G> {
1548 self.globals_by_type
1549 .get(&TypeId::of::<G>())
1550 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1551 }
1552
1553 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1554 #[track_caller]
1555 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1556 let global_type = TypeId::of::<G>();
1557 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1558 self.globals_by_type
1559 .get_mut(&global_type)
1560 .and_then(|any_state| any_state.downcast_mut::<G>())
1561 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1562 .unwrap()
1563 }
1564
1565 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1566 /// yet been assigned.
1567 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1568 let global_type = TypeId::of::<G>();
1569 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1570 self.globals_by_type
1571 .entry(global_type)
1572 .or_insert_with(|| Box::<G>::default())
1573 .downcast_mut::<G>()
1574 .unwrap()
1575 }
1576
1577 /// Sets the value of the global of the given type.
1578 pub fn set_global<G: Global>(&mut self, global: G) {
1579 let global_type = TypeId::of::<G>();
1580 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1581 self.globals_by_type.insert(global_type, Box::new(global));
1582 }
1583
1584 /// Clear all stored globals. Does not notify global observers.
1585 #[cfg(any(test, feature = "test-support"))]
1586 pub fn clear_globals(&mut self) {
1587 self.globals_by_type.drain();
1588 }
1589
1590 /// Remove the global of the given type from the app context. Does not notify global observers.
1591 pub fn remove_global<G: Global>(&mut self) -> G {
1592 let global_type = TypeId::of::<G>();
1593 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1594 *self
1595 .globals_by_type
1596 .remove(&global_type)
1597 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1598 .downcast()
1599 .unwrap()
1600 }
1601
1602 /// Register a callback to be invoked when a global of the given type is updated.
1603 pub fn observe_global<G: Global>(
1604 &mut self,
1605 mut f: impl FnMut(&mut Self) + 'static,
1606 ) -> Subscription {
1607 let (subscription, activate) = self.global_observers.insert(
1608 TypeId::of::<G>(),
1609 Box::new(move |cx| {
1610 f(cx);
1611 true
1612 }),
1613 );
1614 self.defer(move |_| activate());
1615 subscription
1616 }
1617
1618 /// Move the global of the given type to the stack.
1619 #[track_caller]
1620 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1621 GlobalLease::new(
1622 self.globals_by_type
1623 .remove(&TypeId::of::<G>())
1624 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1625 .unwrap(),
1626 )
1627 }
1628
1629 /// Restore the global of the given type after it is moved to the stack.
1630 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1631 let global_type = TypeId::of::<G>();
1632
1633 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1634 self.globals_by_type.insert(global_type, lease.global);
1635 }
1636
1637 pub(crate) fn new_entity_observer(
1638 &self,
1639 key: TypeId,
1640 value: NewEntityListener,
1641 ) -> Subscription {
1642 let (subscription, activate) = self.new_entity_observers.insert(key, value);
1643 activate();
1644 subscription
1645 }
1646
1647 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1648 /// The function will be passed a mutable reference to the view along with an appropriate context.
1649 pub fn observe_new<T: 'static>(
1650 &self,
1651 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1652 ) -> Subscription {
1653 self.new_entity_observer(
1654 TypeId::of::<T>(),
1655 Box::new(
1656 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1657 any_entity
1658 .downcast::<T>()
1659 .unwrap()
1660 .update(cx, |entity_state, cx| {
1661 on_new(entity_state, window.as_deref_mut(), cx)
1662 })
1663 },
1664 ),
1665 )
1666 }
1667
1668 /// Observe the release of a entity. The callback is invoked after the entity
1669 /// has no more strong references but before it has been dropped.
1670 pub fn observe_release<T>(
1671 &self,
1672 handle: &Entity<T>,
1673 on_release: impl FnOnce(&mut T, &mut App) + 'static,
1674 ) -> Subscription
1675 where
1676 T: 'static,
1677 {
1678 let (subscription, activate) = self.release_listeners.insert(
1679 handle.entity_id(),
1680 Box::new(move |entity, cx| {
1681 let entity = entity.downcast_mut().expect("invalid entity type");
1682 on_release(entity, cx)
1683 }),
1684 );
1685 activate();
1686 subscription
1687 }
1688
1689 /// Observe the release of a entity. The callback is invoked after the entity
1690 /// has no more strong references but before it has been dropped.
1691 pub fn observe_release_in<T>(
1692 &self,
1693 handle: &Entity<T>,
1694 window: &Window,
1695 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1696 ) -> Subscription
1697 where
1698 T: 'static,
1699 {
1700 let window_handle = window.handle;
1701 self.observe_release(handle, move |entity, cx| {
1702 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1703 })
1704 }
1705
1706 /// Register a callback to be invoked when a keystroke is received by the application
1707 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1708 /// and that this API will not be invoked if the event's propagation is stopped.
1709 pub fn observe_keystrokes(
1710 &mut self,
1711 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1712 ) -> Subscription {
1713 fn inner(
1714 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1715 handler: KeystrokeObserver,
1716 ) -> Subscription {
1717 let (subscription, activate) = keystroke_observers.insert((), handler);
1718 activate();
1719 subscription
1720 }
1721
1722 inner(
1723 &self.keystroke_observers,
1724 Box::new(move |event, window, cx| {
1725 f(event, window, cx);
1726 true
1727 }),
1728 )
1729 }
1730
1731 /// Register a callback to be invoked when a keystroke is received by the application
1732 /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1733 /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1734 /// within interceptors will prevent action dispatch
1735 pub fn intercept_keystrokes(
1736 &mut self,
1737 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1738 ) -> Subscription {
1739 fn inner(
1740 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1741 handler: KeystrokeObserver,
1742 ) -> Subscription {
1743 let (subscription, activate) = keystroke_interceptors.insert((), handler);
1744 activate();
1745 subscription
1746 }
1747
1748 inner(
1749 &self.keystroke_interceptors,
1750 Box::new(move |event, window, cx| {
1751 f(event, window, cx);
1752 true
1753 }),
1754 )
1755 }
1756
1757 /// Register key bindings.
1758 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1759 self.keymap.borrow_mut().add_bindings(bindings);
1760 self.pending_effects.push_back(Effect::RefreshWindows);
1761 }
1762
1763 /// Clear all key bindings in the app.
1764 pub fn clear_key_bindings(&mut self) {
1765 self.keymap.borrow_mut().clear();
1766 self.pending_effects.push_back(Effect::RefreshWindows);
1767 }
1768
1769 /// Get all key bindings in the app.
1770 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1771 self.keymap.clone()
1772 }
1773
1774 /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1775 /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1776 /// handlers or if they called `cx.propagate()`.
1777 pub fn on_action<A: Action>(
1778 &mut self,
1779 listener: impl Fn(&A, &mut Self) + 'static,
1780 ) -> &mut Self {
1781 self.global_action_listeners
1782 .entry(TypeId::of::<A>())
1783 .or_default()
1784 .push(Rc::new(move |action, phase, cx| {
1785 if phase == DispatchPhase::Bubble {
1786 let action = action.downcast_ref().unwrap();
1787 listener(action, cx)
1788 }
1789 }));
1790 self
1791 }
1792
1793 /// Event handlers propagate events by default. Call this method to stop dispatching to
1794 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1795 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1796 /// calling this method before effects are flushed.
1797 pub fn stop_propagation(&mut self) {
1798 self.propagate_event = false;
1799 }
1800
1801 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1802 /// dispatching to action handlers higher in the element tree. This is the opposite of
1803 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1804 /// this method before effects are flushed.
1805 pub fn propagate(&mut self) {
1806 self.propagate_event = true;
1807 }
1808
1809 /// Build an action from some arbitrary data, typically a keymap entry.
1810 pub fn build_action(
1811 &self,
1812 name: &str,
1813 data: Option<serde_json::Value>,
1814 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1815 self.actions.build_action(name, data)
1816 }
1817
1818 /// Get all action names that have been registered. Note that registration only allows for
1819 /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1820 pub fn all_action_names(&self) -> &[&'static str] {
1821 self.actions.all_action_names()
1822 }
1823
1824 /// Returns key bindings that invoke the given action on the currently focused element, without
1825 /// checking context. Bindings are returned in the order they were added. For display, the last
1826 /// binding should take precedence.
1827 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1828 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1829 }
1830
1831 /// Get all non-internal actions that have been registered, along with their schemas.
1832 pub fn action_schemas(
1833 &self,
1834 generator: &mut schemars::SchemaGenerator,
1835 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1836 self.actions.action_schemas(generator)
1837 }
1838
1839 /// Get a map from a deprecated action name to the canonical name.
1840 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1841 self.actions.deprecated_aliases()
1842 }
1843
1844 /// Get a map from an action name to the deprecation messages.
1845 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1846 self.actions.deprecation_messages()
1847 }
1848
1849 /// Get a map from an action name to the documentation.
1850 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
1851 self.actions.documentation()
1852 }
1853
1854 /// Register a callback to be invoked when the application is about to quit.
1855 /// It is not possible to cancel the quit event at this point.
1856 pub fn on_app_quit<Fut>(
1857 &self,
1858 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1859 ) -> Subscription
1860 where
1861 Fut: 'static + Future<Output = ()>,
1862 {
1863 let (subscription, activate) = self.quit_observers.insert(
1864 (),
1865 Box::new(move |cx| {
1866 let future = on_quit(cx);
1867 future.boxed_local()
1868 }),
1869 );
1870 activate();
1871 subscription
1872 }
1873
1874 /// Register a callback to be invoked when the application is about to restart.
1875 ///
1876 /// These callbacks are called before any `on_app_quit` callbacks.
1877 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
1878 let (subscription, activate) = self.restart_observers.insert(
1879 (),
1880 Box::new(move |cx| {
1881 on_restart(cx);
1882 true
1883 }),
1884 );
1885 activate();
1886 subscription
1887 }
1888
1889 /// Register a callback to be invoked when a window is closed
1890 /// The window is no longer accessible at the point this callback is invoked.
1891 pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1892 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1893 activate();
1894 subscription
1895 }
1896
1897 pub(crate) fn clear_pending_keystrokes(&mut self) {
1898 for window in self.windows() {
1899 window
1900 .update(self, |_, window, cx| {
1901 if window.pending_input_keystrokes().is_some() {
1902 window.clear_pending_keystrokes();
1903 window.pending_input_changed(cx);
1904 }
1905 })
1906 .ok();
1907 }
1908 }
1909
1910 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1911 /// the bindings in the element tree, and any global action listeners.
1912 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1913 let mut action_available = false;
1914 if let Some(window) = self.active_window()
1915 && let Ok(window_action_available) =
1916 window.update(self, |_, window, cx| window.is_action_available(action, cx))
1917 {
1918 action_available = window_action_available;
1919 }
1920
1921 action_available
1922 || self
1923 .global_action_listeners
1924 .contains_key(&action.as_any().type_id())
1925 }
1926
1927 /// Sets the menu bar for this application. This will replace any existing menu bar.
1928 pub fn set_menus(&self, menus: Vec<Menu>) {
1929 self.platform.set_menus(menus, &self.keymap.borrow());
1930 }
1931
1932 /// Gets the menu bar for this application.
1933 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1934 self.platform.get_menus()
1935 }
1936
1937 /// Sets the right click menu for the app icon in the dock
1938 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1939 self.platform.set_dock_menu(menus, &self.keymap.borrow())
1940 }
1941
1942 /// Performs the action associated with the given dock menu item, only used on Windows for now.
1943 pub fn perform_dock_menu_action(&self, action: usize) {
1944 self.platform.perform_dock_menu_action(action);
1945 }
1946
1947 /// Adds given path to the bottom of the list of recent paths for the application.
1948 /// The list is usually shown on the application icon's context menu in the dock,
1949 /// and allows to open the recent files via that context menu.
1950 /// If the path is already in the list, it will be moved to the bottom of the list.
1951 pub fn add_recent_document(&self, path: &Path) {
1952 self.platform.add_recent_document(path);
1953 }
1954
1955 /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
1956 /// Note that this also sets the dock menu on Windows.
1957 pub fn update_jump_list(
1958 &self,
1959 menus: Vec<MenuItem>,
1960 entries: Vec<SmallVec<[PathBuf; 2]>>,
1961 ) -> Vec<SmallVec<[PathBuf; 2]>> {
1962 self.platform.update_jump_list(menus, entries)
1963 }
1964
1965 /// Dispatch an action to the currently active window or global action handler
1966 /// See [`crate::Action`] for more information on how actions work
1967 pub fn dispatch_action(&mut self, action: &dyn Action) {
1968 if let Some(active_window) = self.active_window() {
1969 active_window
1970 .update(self, |_, window, cx| {
1971 window.dispatch_action(action.boxed_clone(), cx)
1972 })
1973 .log_err();
1974 } else {
1975 self.dispatch_global_action(action);
1976 }
1977 }
1978
1979 fn dispatch_global_action(&mut self, action: &dyn Action) {
1980 self.propagate_event = true;
1981
1982 if let Some(mut global_listeners) = self
1983 .global_action_listeners
1984 .remove(&action.as_any().type_id())
1985 {
1986 for listener in &global_listeners {
1987 listener(action.as_any(), DispatchPhase::Capture, self);
1988 if !self.propagate_event {
1989 break;
1990 }
1991 }
1992
1993 global_listeners.extend(
1994 self.global_action_listeners
1995 .remove(&action.as_any().type_id())
1996 .unwrap_or_default(),
1997 );
1998
1999 self.global_action_listeners
2000 .insert(action.as_any().type_id(), global_listeners);
2001 }
2002
2003 if self.propagate_event
2004 && let Some(mut global_listeners) = self
2005 .global_action_listeners
2006 .remove(&action.as_any().type_id())
2007 {
2008 for listener in global_listeners.iter().rev() {
2009 listener(action.as_any(), DispatchPhase::Bubble, self);
2010 if !self.propagate_event {
2011 break;
2012 }
2013 }
2014
2015 global_listeners.extend(
2016 self.global_action_listeners
2017 .remove(&action.as_any().type_id())
2018 .unwrap_or_default(),
2019 );
2020
2021 self.global_action_listeners
2022 .insert(action.as_any().type_id(), global_listeners);
2023 }
2024 }
2025
2026 /// Is there currently something being dragged?
2027 pub fn has_active_drag(&self) -> bool {
2028 self.active_drag.is_some()
2029 }
2030
2031 /// Gets the cursor style of the currently active drag operation.
2032 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2033 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2034 }
2035
2036 /// Stops active drag and clears any related effects.
2037 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2038 if self.active_drag.is_some() {
2039 self.active_drag = None;
2040 window.refresh();
2041 true
2042 } else {
2043 false
2044 }
2045 }
2046
2047 /// Sets the cursor style for the currently active drag operation.
2048 pub fn set_active_drag_cursor_style(
2049 &mut self,
2050 cursor_style: CursorStyle,
2051 window: &mut Window,
2052 ) -> bool {
2053 if let Some(ref mut drag) = self.active_drag {
2054 drag.cursor_style = Some(cursor_style);
2055 window.refresh();
2056 true
2057 } else {
2058 false
2059 }
2060 }
2061
2062 /// Set the prompt renderer for GPUI. This will replace the default or platform specific
2063 /// prompts with this custom implementation.
2064 pub fn set_prompt_builder(
2065 &mut self,
2066 renderer: impl Fn(
2067 PromptLevel,
2068 &str,
2069 Option<&str>,
2070 &[PromptButton],
2071 PromptHandle,
2072 &mut Window,
2073 &mut App,
2074 ) -> RenderablePromptHandle
2075 + 'static,
2076 ) {
2077 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2078 }
2079
2080 /// Reset the prompt builder to the default implementation.
2081 pub fn reset_prompt_builder(&mut self) {
2082 self.prompt_builder = Some(PromptBuilder::Default);
2083 }
2084
2085 /// Remove an asset from GPUI's cache
2086 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2087 let asset_id = (TypeId::of::<A>(), hash(source));
2088 self.loading_assets.remove(&asset_id);
2089 }
2090
2091 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2092 ///
2093 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2094 /// time, and the results of this call will be cached
2095 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2096 let asset_id = (TypeId::of::<A>(), hash(source));
2097 let mut is_first = false;
2098 let task = self
2099 .loading_assets
2100 .remove(&asset_id)
2101 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2102 .unwrap_or_else(|| {
2103 is_first = true;
2104 let future = A::load(source.clone(), self);
2105
2106 self.background_executor().spawn(future).shared()
2107 });
2108
2109 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2110
2111 (task, is_first)
2112 }
2113
2114 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2115 /// for elements rendered within this window.
2116 #[track_caller]
2117 pub fn focus_handle(&self) -> FocusHandle {
2118 FocusHandle::new(&self.focus_handles)
2119 }
2120
2121 /// Tell GPUI that an entity has changed and observers of it should be notified.
2122 pub fn notify(&mut self, entity_id: EntityId) {
2123 let window_invalidators = mem::take(
2124 self.window_invalidators_by_entity
2125 .entry(entity_id)
2126 .or_default(),
2127 );
2128
2129 if window_invalidators.is_empty() {
2130 if self.pending_notifications.insert(entity_id) {
2131 self.pending_effects
2132 .push_back(Effect::Notify { emitter: entity_id });
2133 }
2134 } else {
2135 for invalidator in window_invalidators.values() {
2136 invalidator.invalidate_view(entity_id, self);
2137 }
2138 }
2139
2140 self.window_invalidators_by_entity
2141 .insert(entity_id, window_invalidators);
2142 }
2143
2144 /// Returns the name for this [`App`].
2145 #[cfg(any(test, feature = "test-support", debug_assertions))]
2146 pub fn get_name(&self) -> Option<&'static str> {
2147 self.name
2148 }
2149
2150 /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2151 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2152 self.platform.can_select_mixed_files_and_dirs()
2153 }
2154
2155 /// Removes an image from the sprite atlas on all windows.
2156 ///
2157 /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2158 /// This is a no-op if the image is not in the sprite atlas.
2159 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2160 // remove the texture from all other windows
2161 for window in self.windows.values_mut().flatten() {
2162 _ = window.drop_image(image.clone());
2163 }
2164
2165 // remove the texture from the current window
2166 if let Some(window) = current_window {
2167 _ = window.drop_image(image);
2168 }
2169 }
2170
2171 /// Sets the renderer for the inspector.
2172 #[cfg(any(feature = "inspector", debug_assertions))]
2173 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2174 self.inspector_renderer = Some(f);
2175 }
2176
2177 /// Registers a renderer specific to an inspector state.
2178 #[cfg(any(feature = "inspector", debug_assertions))]
2179 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2180 &mut self,
2181 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2182 ) {
2183 self.inspector_element_registry.register(f);
2184 }
2185
2186 /// Initializes gpui's default colors for the application.
2187 ///
2188 /// These colors can be accessed through `cx.default_colors()`.
2189 pub fn init_colors(&mut self) {
2190 self.set_global(GlobalColors(Arc::new(Colors::default())));
2191 }
2192}
2193
2194impl AppContext for App {
2195 type Result<T> = T;
2196
2197 /// Builds an entity that is owned by the application.
2198 ///
2199 /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2200 /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2201 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2202 self.update(|cx| {
2203 let slot = cx.entities.reserve();
2204 let handle = slot.clone();
2205 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2206
2207 cx.push_effect(Effect::EntityCreated {
2208 entity: handle.clone().into_any(),
2209 tid: TypeId::of::<T>(),
2210 window: cx.window_update_stack.last().cloned(),
2211 });
2212
2213 cx.entities.insert(slot, entity);
2214 handle
2215 })
2216 }
2217
2218 fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
2219 Reservation(self.entities.reserve())
2220 }
2221
2222 fn insert_entity<T: 'static>(
2223 &mut self,
2224 reservation: Reservation<T>,
2225 build_entity: impl FnOnce(&mut Context<T>) -> T,
2226 ) -> Self::Result<Entity<T>> {
2227 self.update(|cx| {
2228 let slot = reservation.0;
2229 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2230 cx.entities.insert(slot, entity)
2231 })
2232 }
2233
2234 /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2235 /// entity along with a `Context` for the entity.
2236 fn update_entity<T: 'static, R>(
2237 &mut self,
2238 handle: &Entity<T>,
2239 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2240 ) -> R {
2241 self.update(|cx| {
2242 let mut entity = cx.entities.lease(handle);
2243 let result = update(
2244 &mut entity,
2245 &mut Context::new_context(cx, handle.downgrade()),
2246 );
2247 cx.entities.end_lease(entity);
2248 result
2249 })
2250 }
2251
2252 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2253 where
2254 T: 'static,
2255 {
2256 GpuiBorrow::new(handle.clone(), self)
2257 }
2258
2259 fn read_entity<T, R>(
2260 &self,
2261 handle: &Entity<T>,
2262 read: impl FnOnce(&T, &App) -> R,
2263 ) -> Self::Result<R>
2264 where
2265 T: 'static,
2266 {
2267 let entity = self.entities.read(handle);
2268 read(entity, self)
2269 }
2270
2271 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2272 where
2273 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2274 {
2275 self.update_window_id(handle.id, update)
2276 }
2277
2278 fn read_window<T, R>(
2279 &self,
2280 window: &WindowHandle<T>,
2281 read: impl FnOnce(Entity<T>, &App) -> R,
2282 ) -> Result<R>
2283 where
2284 T: 'static,
2285 {
2286 let window = self
2287 .windows
2288 .get(window.id)
2289 .context("window not found")?
2290 .as_deref()
2291 .expect("attempted to read a window that is already on the stack");
2292
2293 let root_view = window.root.clone().unwrap();
2294 let view = root_view
2295 .downcast::<T>()
2296 .map_err(|_| anyhow!("root view's type has changed"))?;
2297
2298 Ok(read(view, self))
2299 }
2300
2301 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2302 where
2303 R: Send + 'static,
2304 {
2305 self.background_executor.spawn(future)
2306 }
2307
2308 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
2309 where
2310 G: Global,
2311 {
2312 let mut g = self.global::<G>();
2313 callback(g, self)
2314 }
2315}
2316
2317/// These effects are processed at the end of each application update cycle.
2318pub(crate) enum Effect {
2319 Notify {
2320 emitter: EntityId,
2321 },
2322 Emit {
2323 emitter: EntityId,
2324 event_type: TypeId,
2325 event: Box<dyn Any>,
2326 },
2327 RefreshWindows,
2328 NotifyGlobalObservers {
2329 global_type: TypeId,
2330 },
2331 Defer {
2332 callback: Box<dyn FnOnce(&mut App) + 'static>,
2333 },
2334 EntityCreated {
2335 entity: AnyEntity,
2336 tid: TypeId,
2337 window: Option<WindowId>,
2338 },
2339}
2340
2341impl std::fmt::Debug for Effect {
2342 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2343 match self {
2344 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2345 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2346 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2347 Effect::NotifyGlobalObservers { global_type } => {
2348 write!(f, "NotifyGlobalObservers({:?})", global_type)
2349 }
2350 Effect::Defer { .. } => write!(f, "Defer(..)"),
2351 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2352 }
2353 }
2354}
2355
2356/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2357pub(crate) struct GlobalLease<G: Global> {
2358 global: Box<dyn Any>,
2359 global_type: PhantomData<G>,
2360}
2361
2362impl<G: Global> GlobalLease<G> {
2363 fn new(global: Box<dyn Any>) -> Self {
2364 GlobalLease {
2365 global,
2366 global_type: PhantomData,
2367 }
2368 }
2369}
2370
2371impl<G: Global> Deref for GlobalLease<G> {
2372 type Target = G;
2373
2374 fn deref(&self) -> &Self::Target {
2375 self.global.downcast_ref().unwrap()
2376 }
2377}
2378
2379impl<G: Global> DerefMut for GlobalLease<G> {
2380 fn deref_mut(&mut self) -> &mut Self::Target {
2381 self.global.downcast_mut().unwrap()
2382 }
2383}
2384
2385/// Contains state associated with an active drag operation, started by dragging an element
2386/// within the window or by dragging into the app from the underlying platform.
2387pub struct AnyDrag {
2388 /// The view used to render this drag
2389 pub view: AnyView,
2390
2391 /// The value of the dragged item, to be dropped
2392 pub value: Arc<dyn Any>,
2393
2394 /// This is used to render the dragged item in the same place
2395 /// on the original element that the drag was initiated
2396 pub cursor_offset: Point<Pixels>,
2397
2398 /// The cursor style to use while dragging
2399 pub cursor_style: Option<CursorStyle>,
2400}
2401
2402/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2403/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2404#[derive(Clone)]
2405pub struct AnyTooltip {
2406 /// The view used to display the tooltip
2407 pub view: AnyView,
2408
2409 /// The absolute position of the mouse when the tooltip was deployed.
2410 pub mouse_position: Point<Pixels>,
2411
2412 /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2413 /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2414 /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2415 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2416}
2417
2418/// A keystroke event, and potentially the associated action
2419#[derive(Debug)]
2420pub struct KeystrokeEvent {
2421 /// The keystroke that occurred
2422 pub keystroke: Keystroke,
2423
2424 /// The action that was resolved for the keystroke, if any
2425 pub action: Option<Box<dyn Action>>,
2426
2427 /// The context stack at the time
2428 pub context_stack: Vec<KeyContext>,
2429}
2430
2431struct NullHttpClient;
2432
2433impl HttpClient for NullHttpClient {
2434 fn send(
2435 &self,
2436 _req: http_client::Request<http_client::AsyncBody>,
2437 ) -> futures::future::BoxFuture<
2438 'static,
2439 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2440 > {
2441 async move {
2442 anyhow::bail!("No HttpClient available");
2443 }
2444 .boxed()
2445 }
2446
2447 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2448 None
2449 }
2450
2451 fn proxy(&self) -> Option<&Url> {
2452 None
2453 }
2454}
2455
2456/// A mutable reference to an entity owned by GPUI
2457pub struct GpuiBorrow<'a, T> {
2458 inner: Option<Lease<T>>,
2459 app: &'a mut App,
2460}
2461
2462impl<'a, T: 'static> GpuiBorrow<'a, T> {
2463 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2464 app.start_update();
2465 let lease = app.entities.lease(&inner);
2466 Self {
2467 inner: Some(lease),
2468 app,
2469 }
2470 }
2471}
2472
2473impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2474 fn borrow(&self) -> &T {
2475 self.inner.as_ref().unwrap().borrow()
2476 }
2477}
2478
2479impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2480 fn borrow_mut(&mut self) -> &mut T {
2481 self.inner.as_mut().unwrap().borrow_mut()
2482 }
2483}
2484
2485impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
2486 type Target = T;
2487
2488 fn deref(&self) -> &Self::Target {
2489 self.inner.as_ref().unwrap()
2490 }
2491}
2492
2493impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
2494 fn deref_mut(&mut self) -> &mut T {
2495 self.inner.as_mut().unwrap()
2496 }
2497}
2498
2499impl<'a, T> Drop for GpuiBorrow<'a, T> {
2500 fn drop(&mut self) {
2501 let lease = self.inner.take().unwrap();
2502 self.app.notify(lease.id);
2503 self.app.entities.end_lease(lease);
2504 self.app.finish_update();
2505 }
2506}
2507
2508#[cfg(test)]
2509mod test {
2510 use std::{cell::RefCell, rc::Rc};
2511
2512 use crate::{AppContext, TestAppContext};
2513
2514 #[test]
2515 fn test_gpui_borrow() {
2516 let cx = TestAppContext::single();
2517 let observation_count = Rc::new(RefCell::new(0));
2518
2519 let state = cx.update(|cx| {
2520 let state = cx.new(|_| false);
2521 cx.observe(&state, {
2522 let observation_count = observation_count.clone();
2523 move |_, _| {
2524 let mut count = observation_count.borrow_mut();
2525 *count += 1;
2526 }
2527 })
2528 .detach();
2529
2530 state
2531 });
2532
2533 cx.update(|cx| {
2534 // Calling this like this so that we don't clobber the borrow_mut above
2535 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2536 });
2537
2538 cx.update(|cx| {
2539 state.write(cx, false);
2540 });
2541
2542 assert_eq!(*observation_count.borrow(), 2);
2543 }
2544}