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,
38 AppLiveness, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle,
39 DispatchPhase, DisplayId, EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global,
40 KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu,
41 PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
42 PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton, PromptHandle,
43 PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource,
44 SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextSystem, Window,
45 WindowAppearance, WindowHandle, WindowId, 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 /// Tracks whether this app is still alive. Used to cancel foreground tasks
584 /// when the app is dropped.
585 pub(crate) liveness: AppLiveness,
586 pub(crate) platform: Rc<dyn Platform>,
587 pub(crate) mode: GpuiMode,
588 text_system: Arc<TextSystem>,
589 flushing_effects: bool,
590 pending_updates: usize,
591 pub(crate) actions: Rc<ActionRegistry>,
592 pub(crate) active_drag: Option<AnyDrag>,
593 pub(crate) background_executor: BackgroundExecutor,
594 pub(crate) foreground_executor: ForegroundExecutor,
595 pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
596 asset_source: Arc<dyn AssetSource>,
597 pub(crate) svg_renderer: SvgRenderer,
598 http_client: Arc<dyn HttpClient>,
599 pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
600 pub(crate) entities: EntityMap,
601 pub(crate) window_update_stack: Vec<WindowId>,
602 pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
603 pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
604 pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
605 pub(crate) focus_handles: Arc<FocusMap>,
606 pub(crate) keymap: Rc<RefCell<Keymap>>,
607 pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
608 pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
609 pub(crate) global_action_listeners:
610 FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
611 pending_effects: VecDeque<Effect>,
612 pub(crate) pending_notifications: FxHashSet<EntityId>,
613 pub(crate) pending_global_notifications: FxHashSet<TypeId>,
614 pub(crate) observers: SubscriberSet<EntityId, Handler>,
615 // TypeId is the type of the event that the listener callback expects
616 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
617 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
618 pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
619 pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
620 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
621 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
622 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
623 pub(crate) restart_observers: SubscriberSet<(), Handler>,
624 pub(crate) restart_path: Option<PathBuf>,
625 pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
626 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
627 pub(crate) propagate_event: bool,
628 pub(crate) prompt_builder: Option<PromptBuilder>,
629 pub(crate) window_invalidators_by_entity:
630 FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
631 pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
632 #[cfg(any(feature = "inspector", debug_assertions))]
633 pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
634 #[cfg(any(feature = "inspector", debug_assertions))]
635 pub(crate) inspector_element_registry: InspectorElementRegistry,
636 #[cfg(any(test, feature = "test-support", debug_assertions))]
637 pub(crate) name: Option<&'static str>,
638 quit_mode: QuitMode,
639 quitting: bool,
640}
641
642impl App {
643 #[allow(clippy::new_ret_no_self)]
644 pub(crate) fn new_app(
645 platform: Rc<dyn Platform>,
646 asset_source: Arc<dyn AssetSource>,
647 http_client: Arc<dyn HttpClient>,
648 ) -> Rc<AppCell> {
649 let executor = platform.background_executor();
650 let foreground_executor = platform.foreground_executor();
651 assert!(
652 executor.is_main_thread(),
653 "must construct App on main thread"
654 );
655
656 let text_system = Arc::new(TextSystem::new(platform.text_system()));
657 let entities = EntityMap::new();
658 let keyboard_layout = platform.keyboard_layout();
659 let keyboard_mapper = platform.keyboard_mapper();
660
661 let app = Rc::new_cyclic(|this| AppCell {
662 app: RefCell::new(App {
663 this: this.clone(),
664 liveness: AppLiveness::new(),
665 platform: platform.clone(),
666 text_system,
667 mode: GpuiMode::Production,
668 actions: Rc::new(ActionRegistry::default()),
669 flushing_effects: false,
670 pending_updates: 0,
671 active_drag: None,
672 background_executor: executor,
673 foreground_executor,
674 svg_renderer: SvgRenderer::new(asset_source.clone()),
675 loading_assets: Default::default(),
676 asset_source,
677 http_client,
678 globals_by_type: FxHashMap::default(),
679 entities,
680 new_entity_observers: SubscriberSet::new(),
681 windows: SlotMap::with_key(),
682 window_update_stack: Vec::new(),
683 window_handles: FxHashMap::default(),
684 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
685 keymap: Rc::new(RefCell::new(Keymap::default())),
686 keyboard_layout,
687 keyboard_mapper,
688 global_action_listeners: FxHashMap::default(),
689 pending_effects: VecDeque::new(),
690 pending_notifications: FxHashSet::default(),
691 pending_global_notifications: FxHashSet::default(),
692 observers: SubscriberSet::new(),
693 tracked_entities: FxHashMap::default(),
694 window_invalidators_by_entity: FxHashMap::default(),
695 event_listeners: SubscriberSet::new(),
696 release_listeners: SubscriberSet::new(),
697 keystroke_observers: SubscriberSet::new(),
698 keystroke_interceptors: SubscriberSet::new(),
699 keyboard_layout_observers: SubscriberSet::new(),
700 global_observers: SubscriberSet::new(),
701 quit_observers: SubscriberSet::new(),
702 restart_observers: SubscriberSet::new(),
703 restart_path: None,
704 window_closed_observers: SubscriberSet::new(),
705 layout_id_buffer: Default::default(),
706 propagate_event: true,
707 prompt_builder: Some(PromptBuilder::Default),
708 #[cfg(any(feature = "inspector", debug_assertions))]
709 inspector_renderer: None,
710 #[cfg(any(feature = "inspector", debug_assertions))]
711 inspector_element_registry: InspectorElementRegistry::default(),
712 quit_mode: QuitMode::default(),
713 quitting: false,
714
715 #[cfg(any(test, feature = "test-support", debug_assertions))]
716 name: None,
717 }),
718 });
719
720 init_app_menus(platform.as_ref(), &app.borrow());
721 SystemWindowTabController::init(&mut app.borrow_mut());
722
723 platform.on_keyboard_layout_change(Box::new({
724 let app = Rc::downgrade(&app);
725 move || {
726 if let Some(app) = app.upgrade() {
727 let cx = &mut app.borrow_mut();
728 cx.keyboard_layout = cx.platform.keyboard_layout();
729 cx.keyboard_mapper = cx.platform.keyboard_mapper();
730 cx.keyboard_layout_observers
731 .clone()
732 .retain(&(), move |callback| (callback)(cx));
733 }
734 }
735 }));
736
737 platform.on_quit(Box::new({
738 let cx = app.clone();
739 move || {
740 cx.borrow_mut().shutdown();
741 }
742 }));
743
744 app
745 }
746
747 /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`]
748 /// will be given 100ms to complete before exiting.
749 pub fn shutdown(&mut self) {
750 let mut futures = Vec::new();
751
752 for observer in self.quit_observers.remove(&()) {
753 futures.push(observer(self));
754 }
755
756 self.windows.clear();
757 self.window_handles.clear();
758 self.flush_effects();
759 self.quitting = true;
760
761 let futures = futures::future::join_all(futures);
762 if self
763 .background_executor
764 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
765 .is_err()
766 {
767 log::error!("timed out waiting on app_will_quit");
768 }
769
770 self.quitting = false;
771 }
772
773 /// Get the id of the current keyboard layout
774 pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
775 self.keyboard_layout.as_ref()
776 }
777
778 /// Get the current keyboard mapper.
779 pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
780 &self.keyboard_mapper
781 }
782
783 /// Invokes a handler when the current keyboard layout changes
784 pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
785 where
786 F: 'static + FnMut(&mut App),
787 {
788 let (subscription, activate) = self.keyboard_layout_observers.insert(
789 (),
790 Box::new(move |cx| {
791 callback(cx);
792 true
793 }),
794 );
795 activate();
796 subscription
797 }
798
799 /// Gracefully quit the application via the platform's standard routine.
800 pub fn quit(&self) {
801 self.platform.quit();
802 }
803
804 /// Schedules all windows in the application to be redrawn. This can be called
805 /// multiple times in an update cycle and still result in a single redraw.
806 pub fn refresh_windows(&mut self) {
807 self.pending_effects.push_back(Effect::RefreshWindows);
808 }
809
810 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
811 self.start_update();
812 let result = update(self);
813 self.finish_update();
814 result
815 }
816
817 pub(crate) fn start_update(&mut self) {
818 self.pending_updates += 1;
819 }
820
821 pub(crate) fn finish_update(&mut self) {
822 if !self.flushing_effects && self.pending_updates == 1 {
823 self.flushing_effects = true;
824 self.flush_effects();
825 self.flushing_effects = false;
826 }
827 self.pending_updates -= 1;
828 }
829
830 /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
831 pub fn observe<W>(
832 &mut self,
833 entity: &Entity<W>,
834 mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
835 ) -> Subscription
836 where
837 W: 'static,
838 {
839 self.observe_internal(entity, move |e, cx| {
840 on_notify(e, cx);
841 true
842 })
843 }
844
845 pub(crate) fn detect_accessed_entities<R>(
846 &mut self,
847 callback: impl FnOnce(&mut App) -> R,
848 ) -> (R, FxHashSet<EntityId>) {
849 let accessed_entities_start = self.entities.accessed_entities.borrow().clone();
850 let result = callback(self);
851 let accessed_entities_end = self.entities.accessed_entities.borrow().clone();
852 let entities_accessed_in_callback = accessed_entities_end
853 .difference(&accessed_entities_start)
854 .copied()
855 .collect::<FxHashSet<EntityId>>();
856 (result, entities_accessed_in_callback)
857 }
858
859 pub(crate) fn record_entities_accessed(
860 &mut self,
861 window_handle: AnyWindowHandle,
862 invalidator: WindowInvalidator,
863 entities: &FxHashSet<EntityId>,
864 ) {
865 let mut tracked_entities =
866 std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
867 for entity in tracked_entities.iter() {
868 self.window_invalidators_by_entity
869 .entry(*entity)
870 .and_modify(|windows| {
871 windows.remove(&window_handle.id);
872 });
873 }
874 for entity in entities.iter() {
875 self.window_invalidators_by_entity
876 .entry(*entity)
877 .or_default()
878 .insert(window_handle.id, invalidator.clone());
879 }
880 tracked_entities.clear();
881 tracked_entities.extend(entities.iter().copied());
882 self.tracked_entities
883 .insert(window_handle.id, tracked_entities);
884 }
885
886 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
887 let (subscription, activate) = self.observers.insert(key, value);
888 self.defer(move |_| activate());
889 subscription
890 }
891
892 pub(crate) fn observe_internal<W>(
893 &mut self,
894 entity: &Entity<W>,
895 mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
896 ) -> Subscription
897 where
898 W: 'static,
899 {
900 let entity_id = entity.entity_id();
901 let handle = entity.downgrade();
902 self.new_observer(
903 entity_id,
904 Box::new(move |cx| {
905 if let Some(entity) = handle.upgrade() {
906 on_notify(entity, cx)
907 } else {
908 false
909 }
910 }),
911 )
912 }
913
914 /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
915 /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
916 pub fn subscribe<T, Event>(
917 &mut self,
918 entity: &Entity<T>,
919 mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
920 ) -> Subscription
921 where
922 T: 'static + EventEmitter<Event>,
923 Event: 'static,
924 {
925 self.subscribe_internal(entity, move |entity, event, cx| {
926 on_event(entity, event, cx);
927 true
928 })
929 }
930
931 pub(crate) fn new_subscription(
932 &mut self,
933 key: EntityId,
934 value: (TypeId, Listener),
935 ) -> Subscription {
936 let (subscription, activate) = self.event_listeners.insert(key, value);
937 self.defer(move |_| activate());
938 subscription
939 }
940 pub(crate) fn subscribe_internal<T, Evt>(
941 &mut self,
942 entity: &Entity<T>,
943 mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
944 ) -> Subscription
945 where
946 T: 'static + EventEmitter<Evt>,
947 Evt: 'static,
948 {
949 let entity_id = entity.entity_id();
950 let handle = entity.downgrade();
951 self.new_subscription(
952 entity_id,
953 (
954 TypeId::of::<Evt>(),
955 Box::new(move |event, cx| {
956 let event: &Evt = event.downcast_ref().expect("invalid event type");
957 if let Some(entity) = handle.upgrade() {
958 on_event(entity, event, cx)
959 } else {
960 false
961 }
962 }),
963 ),
964 )
965 }
966
967 /// Returns handles to all open windows in the application.
968 /// Each handle could be downcast to a handle typed for the root view of that window.
969 /// To find all windows of a given type, you could filter on
970 pub fn windows(&self) -> Vec<AnyWindowHandle> {
971 self.windows
972 .keys()
973 .flat_map(|window_id| self.window_handles.get(&window_id).copied())
974 .collect()
975 }
976
977 /// Returns the window handles ordered by their appearance on screen, front to back.
978 ///
979 /// The first window in the returned list is the active/topmost window of the application.
980 ///
981 /// This method returns None if the platform doesn't implement the method yet.
982 pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
983 self.platform.window_stack()
984 }
985
986 /// Returns a handle to the window that is currently focused at the platform level, if one exists.
987 pub fn active_window(&self) -> Option<AnyWindowHandle> {
988 self.platform.active_window()
989 }
990
991 /// Opens a new window with the given option and the root view returned by the given function.
992 /// The function is invoked with a `Window`, which can be used to interact with window-specific
993 /// functionality.
994 pub fn open_window<V: 'static + Render>(
995 &mut self,
996 options: crate::WindowOptions,
997 build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
998 ) -> anyhow::Result<WindowHandle<V>> {
999 self.update(|cx| {
1000 let id = cx.windows.insert(None);
1001 let handle = WindowHandle::new(id);
1002 match Window::new(handle.into(), options, cx) {
1003 Ok(mut window) => {
1004 cx.window_update_stack.push(id);
1005 let root_view = build_root_view(&mut window, cx);
1006 cx.window_update_stack.pop();
1007 window.root.replace(root_view.into());
1008 window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1009
1010 // allow a window to draw at least once before returning
1011 // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
1012 // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
1013 // where DispatchTree::root_node_id asserts on empty nodes
1014 let clear = window.draw(cx);
1015 clear.clear();
1016
1017 cx.window_handles.insert(id, window.handle);
1018 cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1019 Ok(handle)
1020 }
1021 Err(e) => {
1022 cx.windows.remove(id);
1023 Err(e)
1024 }
1025 }
1026 })
1027 }
1028
1029 /// Instructs the platform to activate the application by bringing it to the foreground.
1030 pub fn activate(&self, ignoring_other_apps: bool) {
1031 self.platform.activate(ignoring_other_apps);
1032 }
1033
1034 /// Hide the application at the platform level.
1035 pub fn hide(&self) {
1036 self.platform.hide();
1037 }
1038
1039 /// Hide other applications at the platform level.
1040 pub fn hide_other_apps(&self) {
1041 self.platform.hide_other_apps();
1042 }
1043
1044 /// Unhide other applications at the platform level.
1045 pub fn unhide_other_apps(&self) {
1046 self.platform.unhide_other_apps();
1047 }
1048
1049 /// Returns the list of currently active displays.
1050 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1051 self.platform.displays()
1052 }
1053
1054 /// Returns the primary display that will be used for new windows.
1055 pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1056 self.platform.primary_display()
1057 }
1058
1059 /// Returns whether `screen_capture_sources` may work.
1060 pub fn is_screen_capture_supported(&self) -> bool {
1061 self.platform.is_screen_capture_supported()
1062 }
1063
1064 /// Returns a list of available screen capture sources.
1065 pub fn screen_capture_sources(
1066 &self,
1067 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1068 self.platform.screen_capture_sources()
1069 }
1070
1071 /// Returns the display with the given ID, if one exists.
1072 pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1073 self.displays()
1074 .iter()
1075 .find(|display| display.id() == id)
1076 .cloned()
1077 }
1078
1079 /// Returns the appearance of the application's windows.
1080 pub fn window_appearance(&self) -> WindowAppearance {
1081 self.platform.window_appearance()
1082 }
1083
1084 /// Reads data from the platform clipboard.
1085 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1086 self.platform.read_from_clipboard()
1087 }
1088
1089 /// Writes data to the platform clipboard.
1090 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1091 self.platform.write_to_clipboard(item)
1092 }
1093
1094 /// Reads data from the primary selection buffer.
1095 /// Only available on Linux.
1096 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1097 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1098 self.platform.read_from_primary()
1099 }
1100
1101 /// Writes data to the primary selection buffer.
1102 /// Only available on Linux.
1103 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1104 pub fn write_to_primary(&self, item: ClipboardItem) {
1105 self.platform.write_to_primary(item)
1106 }
1107
1108 /// Reads data from macOS's "Find" pasteboard.
1109 ///
1110 /// Used to share the current search string between apps.
1111 ///
1112 /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1113 #[cfg(target_os = "macos")]
1114 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1115 self.platform.read_from_find_pasteboard()
1116 }
1117
1118 /// Writes data to macOS's "Find" pasteboard.
1119 ///
1120 /// Used to share the current search string between apps.
1121 ///
1122 /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1123 #[cfg(target_os = "macos")]
1124 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1125 self.platform.write_to_find_pasteboard(item)
1126 }
1127
1128 /// Writes credentials to the platform keychain.
1129 pub fn write_credentials(
1130 &self,
1131 url: &str,
1132 username: &str,
1133 password: &[u8],
1134 ) -> Task<Result<()>> {
1135 self.platform.write_credentials(url, username, password)
1136 }
1137
1138 /// Reads credentials from the platform keychain.
1139 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1140 self.platform.read_credentials(url)
1141 }
1142
1143 /// Deletes credentials from the platform keychain.
1144 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1145 self.platform.delete_credentials(url)
1146 }
1147
1148 /// Directs the platform's default browser to open the given URL.
1149 pub fn open_url(&self, url: &str) {
1150 self.platform.open_url(url);
1151 }
1152
1153 /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
1154 /// opened by the current app.
1155 ///
1156 /// On some platforms (e.g. macOS) you may be able to register URL schemes
1157 /// as part of app distribution, but this method exists to let you register
1158 /// schemes at runtime.
1159 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1160 self.platform.register_url_scheme(scheme)
1161 }
1162
1163 /// Returns the full pathname of the current app bundle.
1164 ///
1165 /// Returns an error if the app is not being run from a bundle.
1166 pub fn app_path(&self) -> Result<PathBuf> {
1167 self.platform.app_path()
1168 }
1169
1170 /// On Linux, returns the name of the compositor in use.
1171 ///
1172 /// Returns an empty string on other platforms.
1173 pub fn compositor_name(&self) -> &'static str {
1174 self.platform.compositor_name()
1175 }
1176
1177 /// Returns the file URL of the executable with the specified name in the application bundle
1178 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1179 self.platform.path_for_auxiliary_executable(name)
1180 }
1181
1182 /// Displays a platform modal for selecting paths.
1183 ///
1184 /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
1185 /// If cancelled, a `None` will be relayed instead.
1186 /// May return an error on Linux if the file picker couldn't be opened.
1187 pub fn prompt_for_paths(
1188 &self,
1189 options: PathPromptOptions,
1190 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1191 self.platform.prompt_for_paths(options)
1192 }
1193
1194 /// Displays a platform modal for selecting a new path where a file can be saved.
1195 ///
1196 /// The provided directory will be used to set the initial location.
1197 /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
1198 /// If cancelled, a `None` will be relayed instead.
1199 /// May return an error on Linux if the file picker couldn't be opened.
1200 pub fn prompt_for_new_path(
1201 &self,
1202 directory: &Path,
1203 suggested_name: Option<&str>,
1204 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1205 self.platform.prompt_for_new_path(directory, suggested_name)
1206 }
1207
1208 /// Reveals the specified path at the platform level, such as in Finder on macOS.
1209 pub fn reveal_path(&self, path: &Path) {
1210 self.platform.reveal_path(path)
1211 }
1212
1213 /// Opens the specified path with the system's default application.
1214 pub fn open_with_system(&self, path: &Path) {
1215 self.platform.open_with_system(path)
1216 }
1217
1218 /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
1219 pub fn should_auto_hide_scrollbars(&self) -> bool {
1220 self.platform.should_auto_hide_scrollbars()
1221 }
1222
1223 /// Restarts the application.
1224 pub fn restart(&mut self) {
1225 self.restart_observers
1226 .clone()
1227 .retain(&(), |observer| observer(self));
1228 self.platform.restart(self.restart_path.take())
1229 }
1230
1231 /// Sets the path to use when restarting the application.
1232 pub fn set_restart_path(&mut self, path: PathBuf) {
1233 self.restart_path = Some(path);
1234 }
1235
1236 /// Returns the HTTP client for the application.
1237 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1238 self.http_client.clone()
1239 }
1240
1241 /// Sets the HTTP client for the application.
1242 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1243 self.http_client = new_client;
1244 }
1245
1246 /// Configures when the application should automatically quit.
1247 /// By default, [`QuitMode::Default`] is used.
1248 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1249 self.quit_mode = mode;
1250 }
1251
1252 /// Returns the SVG renderer used by the application.
1253 pub fn svg_renderer(&self) -> SvgRenderer {
1254 self.svg_renderer.clone()
1255 }
1256
1257 pub(crate) fn push_effect(&mut self, effect: Effect) {
1258 match &effect {
1259 Effect::Notify { emitter } => {
1260 if !self.pending_notifications.insert(*emitter) {
1261 return;
1262 }
1263 }
1264 Effect::NotifyGlobalObservers { global_type } => {
1265 if !self.pending_global_notifications.insert(*global_type) {
1266 return;
1267 }
1268 }
1269 _ => {}
1270 };
1271
1272 self.pending_effects.push_back(effect);
1273 }
1274
1275 /// Called at the end of [`App::update`] to complete any side effects
1276 /// such as notifying observers, emitting events, etc. Effects can themselves
1277 /// cause effects, so we continue looping until all effects are processed.
1278 fn flush_effects(&mut self) {
1279 loop {
1280 self.release_dropped_entities();
1281 self.release_dropped_focus_handles();
1282 if let Some(effect) = self.pending_effects.pop_front() {
1283 match effect {
1284 Effect::Notify { emitter } => {
1285 self.apply_notify_effect(emitter);
1286 }
1287
1288 Effect::Emit {
1289 emitter,
1290 event_type,
1291 event,
1292 } => self.apply_emit_effect(emitter, event_type, event),
1293
1294 Effect::RefreshWindows => {
1295 self.apply_refresh_effect();
1296 }
1297
1298 Effect::NotifyGlobalObservers { global_type } => {
1299 self.apply_notify_global_observers_effect(global_type);
1300 }
1301
1302 Effect::Defer { callback } => {
1303 self.apply_defer_effect(callback);
1304 }
1305 Effect::EntityCreated {
1306 entity,
1307 tid,
1308 window,
1309 } => {
1310 self.apply_entity_created_effect(entity, tid, window);
1311 }
1312 }
1313 } else {
1314 #[cfg(any(test, feature = "test-support"))]
1315 for window in self
1316 .windows
1317 .values()
1318 .filter_map(|window| {
1319 let window = window.as_deref()?;
1320 window.invalidator.is_dirty().then_some(window.handle)
1321 })
1322 .collect::<Vec<_>>()
1323 {
1324 self.update_window(window, |_, window, cx| window.draw(cx).clear())
1325 .unwrap();
1326 }
1327
1328 if self.pending_effects.is_empty() {
1329 break;
1330 }
1331 }
1332 }
1333 }
1334
1335 /// Repeatedly called during `flush_effects` to release any entities whose
1336 /// reference count has become zero. We invoke any release observers before dropping
1337 /// each entity.
1338 fn release_dropped_entities(&mut self) {
1339 loop {
1340 let dropped = self.entities.take_dropped();
1341 if dropped.is_empty() {
1342 break;
1343 }
1344
1345 for (entity_id, mut entity) in dropped {
1346 self.observers.remove(&entity_id);
1347 self.event_listeners.remove(&entity_id);
1348 for release_callback in self.release_listeners.remove(&entity_id) {
1349 release_callback(entity.as_mut(), self);
1350 }
1351 }
1352 }
1353 }
1354
1355 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
1356 fn release_dropped_focus_handles(&mut self) {
1357 self.focus_handles
1358 .clone()
1359 .write()
1360 .retain(|handle_id, focus| {
1361 if focus.ref_count.load(SeqCst) == 0 {
1362 for window_handle in self.windows() {
1363 window_handle
1364 .update(self, |_, window, _| {
1365 if window.focus == Some(handle_id) {
1366 window.blur();
1367 }
1368 })
1369 .unwrap();
1370 }
1371 false
1372 } else {
1373 true
1374 }
1375 });
1376 }
1377
1378 fn apply_notify_effect(&mut self, emitter: EntityId) {
1379 self.pending_notifications.remove(&emitter);
1380
1381 self.observers
1382 .clone()
1383 .retain(&emitter, |handler| handler(self));
1384 }
1385
1386 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
1387 self.event_listeners
1388 .clone()
1389 .retain(&emitter, |(stored_type, handler)| {
1390 if *stored_type == event_type {
1391 handler(event.as_ref(), self)
1392 } else {
1393 true
1394 }
1395 });
1396 }
1397
1398 fn apply_refresh_effect(&mut self) {
1399 for window in self.windows.values_mut() {
1400 if let Some(window) = window.as_deref_mut() {
1401 window.refreshing = true;
1402 window.invalidator.set_dirty(true);
1403 }
1404 }
1405 }
1406
1407 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1408 self.pending_global_notifications.remove(&type_id);
1409 self.global_observers
1410 .clone()
1411 .retain(&type_id, |observer| observer(self));
1412 }
1413
1414 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1415 callback(self);
1416 }
1417
1418 fn apply_entity_created_effect(
1419 &mut self,
1420 entity: AnyEntity,
1421 tid: TypeId,
1422 window: Option<WindowId>,
1423 ) {
1424 self.new_entity_observers.clone().retain(&tid, |observer| {
1425 if let Some(id) = window {
1426 self.update_window_id(id, {
1427 let entity = entity.clone();
1428 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1429 })
1430 .expect("All windows should be off the stack when flushing effects");
1431 } else {
1432 (observer)(entity.clone(), &mut None, self)
1433 }
1434 true
1435 });
1436 }
1437
1438 fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1439 where
1440 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1441 {
1442 self.update(|cx| {
1443 let mut window = cx.windows.get_mut(id)?.take()?;
1444
1445 let root_view = window.root.clone().unwrap();
1446
1447 cx.window_update_stack.push(window.handle.id);
1448 let result = update(root_view, &mut window, cx);
1449 cx.window_update_stack.pop();
1450
1451 if window.removed {
1452 cx.window_handles.remove(&id);
1453 cx.windows.remove(id);
1454
1455 cx.window_closed_observers.clone().retain(&(), |callback| {
1456 callback(cx);
1457 true
1458 });
1459
1460 let quit_on_empty = match cx.quit_mode {
1461 QuitMode::Explicit => false,
1462 QuitMode::LastWindowClosed => true,
1463 QuitMode::Default => cfg!(not(target_os = "macos")),
1464 };
1465
1466 if quit_on_empty && cx.windows.is_empty() {
1467 cx.quit();
1468 }
1469 } else {
1470 cx.windows.get_mut(id)?.replace(window);
1471 }
1472
1473 Some(result)
1474 })
1475 .context("window not found")
1476 }
1477
1478 /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1479 /// so it can be held across `await` points.
1480 pub fn to_async(&self) -> AsyncApp {
1481 let liveness_token = self.liveness.token();
1482 AsyncApp {
1483 app: self.this.clone(),
1484 liveness_token,
1485 background_executor: self.background_executor.clone(),
1486 foreground_executor: self.foreground_executor.clone(),
1487 }
1488 }
1489
1490 /// Obtains a reference to the executor, which can be used to spawn futures.
1491 pub fn background_executor(&self) -> &BackgroundExecutor {
1492 &self.background_executor
1493 }
1494
1495 /// Obtains a reference to the executor, which can be used to spawn futures.
1496 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1497 if self.quitting {
1498 panic!("Can't spawn on main thread after on_app_quit")
1499 };
1500 &self.foreground_executor
1501 }
1502
1503 /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1504 /// with [AsyncApp], which allows the application state to be accessed across await points.
1505 #[track_caller]
1506 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1507 where
1508 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1509 R: 'static,
1510 {
1511 if self.quitting {
1512 debug_panic!("Can't spawn on main thread after on_app_quit")
1513 };
1514
1515 let mut cx = self.to_async();
1516
1517 self.foreground_executor
1518 .spawn(async move { f(&mut cx).await })
1519 }
1520
1521 /// Spawns the future returned by the given function on the main thread with
1522 /// the given priority. The closure will be invoked with [AsyncApp], which
1523 /// allows the application state to be accessed across await points.
1524 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1525 where
1526 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1527 R: 'static,
1528 {
1529 if self.quitting {
1530 debug_panic!("Can't spawn on main thread after on_app_quit")
1531 };
1532
1533 let mut cx = self.to_async();
1534
1535 self.foreground_executor
1536 .spawn_with_priority(priority, async move { f(&mut cx).await })
1537 }
1538
1539 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1540 /// that are currently on the stack to be returned to the app.
1541 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1542 self.push_effect(Effect::Defer {
1543 callback: Box::new(f),
1544 });
1545 }
1546
1547 /// Accessor for the application's asset source, which is provided when constructing the `App`.
1548 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1549 &self.asset_source
1550 }
1551
1552 /// Accessor for the text system.
1553 pub fn text_system(&self) -> &Arc<TextSystem> {
1554 &self.text_system
1555 }
1556
1557 /// Check whether a global of the given type has been assigned.
1558 pub fn has_global<G: Global>(&self) -> bool {
1559 self.globals_by_type.contains_key(&TypeId::of::<G>())
1560 }
1561
1562 /// Access the global of the given type. Panics if a global for that type has not been assigned.
1563 #[track_caller]
1564 pub fn global<G: Global>(&self) -> &G {
1565 self.globals_by_type
1566 .get(&TypeId::of::<G>())
1567 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1568 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1569 .unwrap()
1570 }
1571
1572 /// Access the global of the given type if a value has been assigned.
1573 pub fn try_global<G: Global>(&self) -> Option<&G> {
1574 self.globals_by_type
1575 .get(&TypeId::of::<G>())
1576 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1577 }
1578
1579 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1580 #[track_caller]
1581 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1582 let global_type = TypeId::of::<G>();
1583 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1584 self.globals_by_type
1585 .get_mut(&global_type)
1586 .and_then(|any_state| any_state.downcast_mut::<G>())
1587 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1588 .unwrap()
1589 }
1590
1591 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1592 /// yet been assigned.
1593 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1594 let global_type = TypeId::of::<G>();
1595 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1596 self.globals_by_type
1597 .entry(global_type)
1598 .or_insert_with(|| Box::<G>::default())
1599 .downcast_mut::<G>()
1600 .unwrap()
1601 }
1602
1603 /// Sets the value of the global of the given type.
1604 pub fn set_global<G: Global>(&mut self, global: G) {
1605 let global_type = TypeId::of::<G>();
1606 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1607 self.globals_by_type.insert(global_type, Box::new(global));
1608 }
1609
1610 /// Clear all stored globals. Does not notify global observers.
1611 #[cfg(any(test, feature = "test-support"))]
1612 pub fn clear_globals(&mut self) {
1613 self.globals_by_type.drain();
1614 }
1615
1616 /// Remove the global of the given type from the app context. Does not notify global observers.
1617 pub fn remove_global<G: Global>(&mut self) -> G {
1618 let global_type = TypeId::of::<G>();
1619 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1620 *self
1621 .globals_by_type
1622 .remove(&global_type)
1623 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1624 .downcast()
1625 .unwrap()
1626 }
1627
1628 /// Register a callback to be invoked when a global of the given type is updated.
1629 pub fn observe_global<G: Global>(
1630 &mut self,
1631 mut f: impl FnMut(&mut Self) + 'static,
1632 ) -> Subscription {
1633 let (subscription, activate) = self.global_observers.insert(
1634 TypeId::of::<G>(),
1635 Box::new(move |cx| {
1636 f(cx);
1637 true
1638 }),
1639 );
1640 self.defer(move |_| activate());
1641 subscription
1642 }
1643
1644 /// Move the global of the given type to the stack.
1645 #[track_caller]
1646 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1647 GlobalLease::new(
1648 self.globals_by_type
1649 .remove(&TypeId::of::<G>())
1650 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1651 .unwrap(),
1652 )
1653 }
1654
1655 /// Restore the global of the given type after it is moved to the stack.
1656 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1657 let global_type = TypeId::of::<G>();
1658
1659 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1660 self.globals_by_type.insert(global_type, lease.global);
1661 }
1662
1663 pub(crate) fn new_entity_observer(
1664 &self,
1665 key: TypeId,
1666 value: NewEntityListener,
1667 ) -> Subscription {
1668 let (subscription, activate) = self.new_entity_observers.insert(key, value);
1669 activate();
1670 subscription
1671 }
1672
1673 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1674 /// The function will be passed a mutable reference to the view along with an appropriate context.
1675 pub fn observe_new<T: 'static>(
1676 &self,
1677 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1678 ) -> Subscription {
1679 self.new_entity_observer(
1680 TypeId::of::<T>(),
1681 Box::new(
1682 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1683 any_entity
1684 .downcast::<T>()
1685 .unwrap()
1686 .update(cx, |entity_state, cx| {
1687 on_new(entity_state, window.as_deref_mut(), cx)
1688 })
1689 },
1690 ),
1691 )
1692 }
1693
1694 /// Observe the release of a entity. The callback is invoked after the entity
1695 /// has no more strong references but before it has been dropped.
1696 pub fn observe_release<T>(
1697 &self,
1698 handle: &Entity<T>,
1699 on_release: impl FnOnce(&mut T, &mut App) + 'static,
1700 ) -> Subscription
1701 where
1702 T: 'static,
1703 {
1704 let (subscription, activate) = self.release_listeners.insert(
1705 handle.entity_id(),
1706 Box::new(move |entity, cx| {
1707 let entity = entity.downcast_mut().expect("invalid entity type");
1708 on_release(entity, cx)
1709 }),
1710 );
1711 activate();
1712 subscription
1713 }
1714
1715 /// Observe the release of a entity. The callback is invoked after the entity
1716 /// has no more strong references but before it has been dropped.
1717 pub fn observe_release_in<T>(
1718 &self,
1719 handle: &Entity<T>,
1720 window: &Window,
1721 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1722 ) -> Subscription
1723 where
1724 T: 'static,
1725 {
1726 let window_handle = window.handle;
1727 self.observe_release(handle, move |entity, cx| {
1728 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1729 })
1730 }
1731
1732 /// Register a callback to be invoked when a keystroke is received by the application
1733 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1734 /// and that this API will not be invoked if the event's propagation is stopped.
1735 pub fn observe_keystrokes(
1736 &mut self,
1737 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1738 ) -> Subscription {
1739 fn inner(
1740 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1741 handler: KeystrokeObserver,
1742 ) -> Subscription {
1743 let (subscription, activate) = keystroke_observers.insert((), handler);
1744 activate();
1745 subscription
1746 }
1747
1748 inner(
1749 &self.keystroke_observers,
1750 Box::new(move |event, window, cx| {
1751 f(event, window, cx);
1752 true
1753 }),
1754 )
1755 }
1756
1757 /// Register a callback to be invoked when a keystroke is received by the application
1758 /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1759 /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1760 /// within interceptors will prevent action dispatch
1761 pub fn intercept_keystrokes(
1762 &mut self,
1763 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1764 ) -> Subscription {
1765 fn inner(
1766 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1767 handler: KeystrokeObserver,
1768 ) -> Subscription {
1769 let (subscription, activate) = keystroke_interceptors.insert((), handler);
1770 activate();
1771 subscription
1772 }
1773
1774 inner(
1775 &self.keystroke_interceptors,
1776 Box::new(move |event, window, cx| {
1777 f(event, window, cx);
1778 true
1779 }),
1780 )
1781 }
1782
1783 /// Register key bindings.
1784 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1785 self.keymap.borrow_mut().add_bindings(bindings);
1786 self.pending_effects.push_back(Effect::RefreshWindows);
1787 }
1788
1789 /// Clear all key bindings in the app.
1790 pub fn clear_key_bindings(&mut self) {
1791 self.keymap.borrow_mut().clear();
1792 self.pending_effects.push_back(Effect::RefreshWindows);
1793 }
1794
1795 /// Get all key bindings in the app.
1796 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1797 self.keymap.clone()
1798 }
1799
1800 /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1801 /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1802 /// handlers or if they called `cx.propagate()`.
1803 pub fn on_action<A: Action>(
1804 &mut self,
1805 listener: impl Fn(&A, &mut Self) + 'static,
1806 ) -> &mut Self {
1807 self.global_action_listeners
1808 .entry(TypeId::of::<A>())
1809 .or_default()
1810 .push(Rc::new(move |action, phase, cx| {
1811 if phase == DispatchPhase::Bubble {
1812 let action = action.downcast_ref().unwrap();
1813 listener(action, cx)
1814 }
1815 }));
1816 self
1817 }
1818
1819 /// Event handlers propagate events by default. Call this method to stop dispatching to
1820 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1821 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1822 /// calling this method before effects are flushed.
1823 pub fn stop_propagation(&mut self) {
1824 self.propagate_event = false;
1825 }
1826
1827 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1828 /// dispatching to action handlers higher in the element tree. This is the opposite of
1829 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1830 /// this method before effects are flushed.
1831 pub fn propagate(&mut self) {
1832 self.propagate_event = true;
1833 }
1834
1835 /// Build an action from some arbitrary data, typically a keymap entry.
1836 pub fn build_action(
1837 &self,
1838 name: &str,
1839 data: Option<serde_json::Value>,
1840 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1841 self.actions.build_action(name, data)
1842 }
1843
1844 /// Get all action names that have been registered. Note that registration only allows for
1845 /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1846 pub fn all_action_names(&self) -> &[&'static str] {
1847 self.actions.all_action_names()
1848 }
1849
1850 /// Returns key bindings that invoke the given action on the currently focused element, without
1851 /// checking context. Bindings are returned in the order they were added. For display, the last
1852 /// binding should take precedence.
1853 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1854 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1855 }
1856
1857 /// Get all non-internal actions that have been registered, along with their schemas.
1858 pub fn action_schemas(
1859 &self,
1860 generator: &mut schemars::SchemaGenerator,
1861 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1862 self.actions.action_schemas(generator)
1863 }
1864
1865 /// Get a map from a deprecated action name to the canonical name.
1866 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1867 self.actions.deprecated_aliases()
1868 }
1869
1870 /// Get a map from an action name to the deprecation messages.
1871 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1872 self.actions.deprecation_messages()
1873 }
1874
1875 /// Get a map from an action name to the documentation.
1876 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
1877 self.actions.documentation()
1878 }
1879
1880 /// Register a callback to be invoked when the application is about to quit.
1881 /// It is not possible to cancel the quit event at this point.
1882 pub fn on_app_quit<Fut>(
1883 &self,
1884 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1885 ) -> Subscription
1886 where
1887 Fut: 'static + Future<Output = ()>,
1888 {
1889 let (subscription, activate) = self.quit_observers.insert(
1890 (),
1891 Box::new(move |cx| {
1892 let future = on_quit(cx);
1893 future.boxed_local()
1894 }),
1895 );
1896 activate();
1897 subscription
1898 }
1899
1900 /// Register a callback to be invoked when the application is about to restart.
1901 ///
1902 /// These callbacks are called before any `on_app_quit` callbacks.
1903 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
1904 let (subscription, activate) = self.restart_observers.insert(
1905 (),
1906 Box::new(move |cx| {
1907 on_restart(cx);
1908 true
1909 }),
1910 );
1911 activate();
1912 subscription
1913 }
1914
1915 /// Register a callback to be invoked when a window is closed
1916 /// The window is no longer accessible at the point this callback is invoked.
1917 pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1918 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1919 activate();
1920 subscription
1921 }
1922
1923 pub(crate) fn clear_pending_keystrokes(&mut self) {
1924 for window in self.windows() {
1925 window
1926 .update(self, |_, window, cx| {
1927 if window.pending_input_keystrokes().is_some() {
1928 window.clear_pending_keystrokes();
1929 window.pending_input_changed(cx);
1930 }
1931 })
1932 .ok();
1933 }
1934 }
1935
1936 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1937 /// the bindings in the element tree, and any global action listeners.
1938 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1939 let mut action_available = false;
1940 if let Some(window) = self.active_window()
1941 && let Ok(window_action_available) =
1942 window.update(self, |_, window, cx| window.is_action_available(action, cx))
1943 {
1944 action_available = window_action_available;
1945 }
1946
1947 action_available
1948 || self
1949 .global_action_listeners
1950 .contains_key(&action.as_any().type_id())
1951 }
1952
1953 /// Sets the menu bar for this application. This will replace any existing menu bar.
1954 pub fn set_menus(&self, menus: Vec<Menu>) {
1955 self.platform.set_menus(menus, &self.keymap.borrow());
1956 }
1957
1958 /// Gets the menu bar for this application.
1959 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1960 self.platform.get_menus()
1961 }
1962
1963 /// Sets the right click menu for the app icon in the dock
1964 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1965 self.platform.set_dock_menu(menus, &self.keymap.borrow())
1966 }
1967
1968 /// Performs the action associated with the given dock menu item, only used on Windows for now.
1969 pub fn perform_dock_menu_action(&self, action: usize) {
1970 self.platform.perform_dock_menu_action(action);
1971 }
1972
1973 /// Adds given path to the bottom of the list of recent paths for the application.
1974 /// The list is usually shown on the application icon's context menu in the dock,
1975 /// and allows to open the recent files via that context menu.
1976 /// If the path is already in the list, it will be moved to the bottom of the list.
1977 pub fn add_recent_document(&self, path: &Path) {
1978 self.platform.add_recent_document(path);
1979 }
1980
1981 /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
1982 /// Note that this also sets the dock menu on Windows.
1983 pub fn update_jump_list(
1984 &self,
1985 menus: Vec<MenuItem>,
1986 entries: Vec<SmallVec<[PathBuf; 2]>>,
1987 ) -> Vec<SmallVec<[PathBuf; 2]>> {
1988 self.platform.update_jump_list(menus, entries)
1989 }
1990
1991 /// Dispatch an action to the currently active window or global action handler
1992 /// See [`crate::Action`] for more information on how actions work
1993 pub fn dispatch_action(&mut self, action: &dyn Action) {
1994 if let Some(active_window) = self.active_window() {
1995 active_window
1996 .update(self, |_, window, cx| {
1997 window.dispatch_action(action.boxed_clone(), cx)
1998 })
1999 .log_err();
2000 } else {
2001 self.dispatch_global_action(action);
2002 }
2003 }
2004
2005 fn dispatch_global_action(&mut self, action: &dyn Action) {
2006 self.propagate_event = true;
2007
2008 if let Some(mut global_listeners) = self
2009 .global_action_listeners
2010 .remove(&action.as_any().type_id())
2011 {
2012 for listener in &global_listeners {
2013 listener(action.as_any(), DispatchPhase::Capture, self);
2014 if !self.propagate_event {
2015 break;
2016 }
2017 }
2018
2019 global_listeners.extend(
2020 self.global_action_listeners
2021 .remove(&action.as_any().type_id())
2022 .unwrap_or_default(),
2023 );
2024
2025 self.global_action_listeners
2026 .insert(action.as_any().type_id(), global_listeners);
2027 }
2028
2029 if self.propagate_event
2030 && let Some(mut global_listeners) = self
2031 .global_action_listeners
2032 .remove(&action.as_any().type_id())
2033 {
2034 for listener in global_listeners.iter().rev() {
2035 listener(action.as_any(), DispatchPhase::Bubble, self);
2036 if !self.propagate_event {
2037 break;
2038 }
2039 }
2040
2041 global_listeners.extend(
2042 self.global_action_listeners
2043 .remove(&action.as_any().type_id())
2044 .unwrap_or_default(),
2045 );
2046
2047 self.global_action_listeners
2048 .insert(action.as_any().type_id(), global_listeners);
2049 }
2050 }
2051
2052 /// Is there currently something being dragged?
2053 pub fn has_active_drag(&self) -> bool {
2054 self.active_drag.is_some()
2055 }
2056
2057 /// Gets the cursor style of the currently active drag operation.
2058 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2059 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2060 }
2061
2062 /// Stops active drag and clears any related effects.
2063 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2064 if self.active_drag.is_some() {
2065 self.active_drag = None;
2066 window.refresh();
2067 true
2068 } else {
2069 false
2070 }
2071 }
2072
2073 /// Sets the cursor style for the currently active drag operation.
2074 pub fn set_active_drag_cursor_style(
2075 &mut self,
2076 cursor_style: CursorStyle,
2077 window: &mut Window,
2078 ) -> bool {
2079 if let Some(ref mut drag) = self.active_drag {
2080 drag.cursor_style = Some(cursor_style);
2081 window.refresh();
2082 true
2083 } else {
2084 false
2085 }
2086 }
2087
2088 /// Set the prompt renderer for GPUI. This will replace the default or platform specific
2089 /// prompts with this custom implementation.
2090 pub fn set_prompt_builder(
2091 &mut self,
2092 renderer: impl Fn(
2093 PromptLevel,
2094 &str,
2095 Option<&str>,
2096 &[PromptButton],
2097 PromptHandle,
2098 &mut Window,
2099 &mut App,
2100 ) -> RenderablePromptHandle
2101 + 'static,
2102 ) {
2103 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2104 }
2105
2106 /// Reset the prompt builder to the default implementation.
2107 pub fn reset_prompt_builder(&mut self) {
2108 self.prompt_builder = Some(PromptBuilder::Default);
2109 }
2110
2111 /// Remove an asset from GPUI's cache
2112 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2113 let asset_id = (TypeId::of::<A>(), hash(source));
2114 self.loading_assets.remove(&asset_id);
2115 }
2116
2117 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2118 ///
2119 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2120 /// time, and the results of this call will be cached
2121 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2122 let asset_id = (TypeId::of::<A>(), hash(source));
2123 let mut is_first = false;
2124 let task = self
2125 .loading_assets
2126 .remove(&asset_id)
2127 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2128 .unwrap_or_else(|| {
2129 is_first = true;
2130 let future = A::load(source.clone(), self);
2131
2132 self.background_executor().spawn(future).shared()
2133 });
2134
2135 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2136
2137 (task, is_first)
2138 }
2139
2140 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2141 /// for elements rendered within this window.
2142 #[track_caller]
2143 pub fn focus_handle(&self) -> FocusHandle {
2144 FocusHandle::new(&self.focus_handles)
2145 }
2146
2147 /// Tell GPUI that an entity has changed and observers of it should be notified.
2148 pub fn notify(&mut self, entity_id: EntityId) {
2149 let window_invalidators = mem::take(
2150 self.window_invalidators_by_entity
2151 .entry(entity_id)
2152 .or_default(),
2153 );
2154
2155 if window_invalidators.is_empty() {
2156 if self.pending_notifications.insert(entity_id) {
2157 self.pending_effects
2158 .push_back(Effect::Notify { emitter: entity_id });
2159 }
2160 } else {
2161 for invalidator in window_invalidators.values() {
2162 invalidator.invalidate_view(entity_id, self);
2163 }
2164 }
2165
2166 self.window_invalidators_by_entity
2167 .insert(entity_id, window_invalidators);
2168 }
2169
2170 /// Returns the name for this [`App`].
2171 #[cfg(any(test, feature = "test-support", debug_assertions))]
2172 pub fn get_name(&self) -> Option<&'static str> {
2173 self.name
2174 }
2175
2176 /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2177 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2178 self.platform.can_select_mixed_files_and_dirs()
2179 }
2180
2181 /// Removes an image from the sprite atlas on all windows.
2182 ///
2183 /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2184 /// This is a no-op if the image is not in the sprite atlas.
2185 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2186 // remove the texture from all other windows
2187 for window in self.windows.values_mut().flatten() {
2188 _ = window.drop_image(image.clone());
2189 }
2190
2191 // remove the texture from the current window
2192 if let Some(window) = current_window {
2193 _ = window.drop_image(image);
2194 }
2195 }
2196
2197 /// Sets the renderer for the inspector.
2198 #[cfg(any(feature = "inspector", debug_assertions))]
2199 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2200 self.inspector_renderer = Some(f);
2201 }
2202
2203 /// Registers a renderer specific to an inspector state.
2204 #[cfg(any(feature = "inspector", debug_assertions))]
2205 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2206 &mut self,
2207 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2208 ) {
2209 self.inspector_element_registry.register(f);
2210 }
2211
2212 /// Initializes gpui's default colors for the application.
2213 ///
2214 /// These colors can be accessed through `cx.default_colors()`.
2215 pub fn init_colors(&mut self) {
2216 self.set_global(GlobalColors(Arc::new(Colors::default())));
2217 }
2218}
2219
2220impl AppContext for App {
2221 type Result<T> = T;
2222
2223 /// Builds an entity that is owned by the application.
2224 ///
2225 /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2226 /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2227 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2228 self.update(|cx| {
2229 let slot = cx.entities.reserve();
2230 let handle = slot.clone();
2231 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2232
2233 cx.push_effect(Effect::EntityCreated {
2234 entity: handle.clone().into_any(),
2235 tid: TypeId::of::<T>(),
2236 window: cx.window_update_stack.last().cloned(),
2237 });
2238
2239 cx.entities.insert(slot, entity);
2240 handle
2241 })
2242 }
2243
2244 fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
2245 Reservation(self.entities.reserve())
2246 }
2247
2248 fn insert_entity<T: 'static>(
2249 &mut self,
2250 reservation: Reservation<T>,
2251 build_entity: impl FnOnce(&mut Context<T>) -> T,
2252 ) -> Self::Result<Entity<T>> {
2253 self.update(|cx| {
2254 let slot = reservation.0;
2255 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2256 cx.entities.insert(slot, entity)
2257 })
2258 }
2259
2260 /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2261 /// entity along with a `Context` for the entity.
2262 fn update_entity<T: 'static, R>(
2263 &mut self,
2264 handle: &Entity<T>,
2265 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2266 ) -> R {
2267 self.update(|cx| {
2268 let mut entity = cx.entities.lease(handle);
2269 let result = update(
2270 &mut entity,
2271 &mut Context::new_context(cx, handle.downgrade()),
2272 );
2273 cx.entities.end_lease(entity);
2274 result
2275 })
2276 }
2277
2278 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2279 where
2280 T: 'static,
2281 {
2282 GpuiBorrow::new(handle.clone(), self)
2283 }
2284
2285 fn read_entity<T, R>(
2286 &self,
2287 handle: &Entity<T>,
2288 read: impl FnOnce(&T, &App) -> R,
2289 ) -> Self::Result<R>
2290 where
2291 T: 'static,
2292 {
2293 let entity = self.entities.read(handle);
2294 read(entity, self)
2295 }
2296
2297 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2298 where
2299 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2300 {
2301 self.update_window_id(handle.id, update)
2302 }
2303
2304 fn read_window<T, R>(
2305 &self,
2306 window: &WindowHandle<T>,
2307 read: impl FnOnce(Entity<T>, &App) -> R,
2308 ) -> Result<R>
2309 where
2310 T: 'static,
2311 {
2312 let window = self
2313 .windows
2314 .get(window.id)
2315 .context("window not found")?
2316 .as_deref()
2317 .expect("attempted to read a window that is already on the stack");
2318
2319 let root_view = window.root.clone().unwrap();
2320 let view = root_view
2321 .downcast::<T>()
2322 .map_err(|_| anyhow!("root view's type has changed"))?;
2323
2324 Ok(read(view, self))
2325 }
2326
2327 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2328 where
2329 R: Send + 'static,
2330 {
2331 self.background_executor.spawn(future)
2332 }
2333
2334 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
2335 where
2336 G: Global,
2337 {
2338 let mut g = self.global::<G>();
2339 callback(g, self)
2340 }
2341}
2342
2343/// These effects are processed at the end of each application update cycle.
2344pub(crate) enum Effect {
2345 Notify {
2346 emitter: EntityId,
2347 },
2348 Emit {
2349 emitter: EntityId,
2350 event_type: TypeId,
2351 event: Box<dyn Any>,
2352 },
2353 RefreshWindows,
2354 NotifyGlobalObservers {
2355 global_type: TypeId,
2356 },
2357 Defer {
2358 callback: Box<dyn FnOnce(&mut App) + 'static>,
2359 },
2360 EntityCreated {
2361 entity: AnyEntity,
2362 tid: TypeId,
2363 window: Option<WindowId>,
2364 },
2365}
2366
2367impl std::fmt::Debug for Effect {
2368 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2369 match self {
2370 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2371 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2372 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2373 Effect::NotifyGlobalObservers { global_type } => {
2374 write!(f, "NotifyGlobalObservers({:?})", global_type)
2375 }
2376 Effect::Defer { .. } => write!(f, "Defer(..)"),
2377 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2378 }
2379 }
2380}
2381
2382/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2383pub(crate) struct GlobalLease<G: Global> {
2384 global: Box<dyn Any>,
2385 global_type: PhantomData<G>,
2386}
2387
2388impl<G: Global> GlobalLease<G> {
2389 fn new(global: Box<dyn Any>) -> Self {
2390 GlobalLease {
2391 global,
2392 global_type: PhantomData,
2393 }
2394 }
2395}
2396
2397impl<G: Global> Deref for GlobalLease<G> {
2398 type Target = G;
2399
2400 fn deref(&self) -> &Self::Target {
2401 self.global.downcast_ref().unwrap()
2402 }
2403}
2404
2405impl<G: Global> DerefMut for GlobalLease<G> {
2406 fn deref_mut(&mut self) -> &mut Self::Target {
2407 self.global.downcast_mut().unwrap()
2408 }
2409}
2410
2411/// Contains state associated with an active drag operation, started by dragging an element
2412/// within the window or by dragging into the app from the underlying platform.
2413pub struct AnyDrag {
2414 /// The view used to render this drag
2415 pub view: AnyView,
2416
2417 /// The value of the dragged item, to be dropped
2418 pub value: Arc<dyn Any>,
2419
2420 /// This is used to render the dragged item in the same place
2421 /// on the original element that the drag was initiated
2422 pub cursor_offset: Point<Pixels>,
2423
2424 /// The cursor style to use while dragging
2425 pub cursor_style: Option<CursorStyle>,
2426}
2427
2428/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2429/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2430#[derive(Clone)]
2431pub struct AnyTooltip {
2432 /// The view used to display the tooltip
2433 pub view: AnyView,
2434
2435 /// The absolute position of the mouse when the tooltip was deployed.
2436 pub mouse_position: Point<Pixels>,
2437
2438 /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2439 /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2440 /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2441 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2442}
2443
2444/// A keystroke event, and potentially the associated action
2445#[derive(Debug)]
2446pub struct KeystrokeEvent {
2447 /// The keystroke that occurred
2448 pub keystroke: Keystroke,
2449
2450 /// The action that was resolved for the keystroke, if any
2451 pub action: Option<Box<dyn Action>>,
2452
2453 /// The context stack at the time
2454 pub context_stack: Vec<KeyContext>,
2455}
2456
2457struct NullHttpClient;
2458
2459impl HttpClient for NullHttpClient {
2460 fn send(
2461 &self,
2462 _req: http_client::Request<http_client::AsyncBody>,
2463 ) -> futures::future::BoxFuture<
2464 'static,
2465 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2466 > {
2467 async move {
2468 anyhow::bail!("No HttpClient available");
2469 }
2470 .boxed()
2471 }
2472
2473 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2474 None
2475 }
2476
2477 fn proxy(&self) -> Option<&Url> {
2478 None
2479 }
2480}
2481
2482/// A mutable reference to an entity owned by GPUI
2483pub struct GpuiBorrow<'a, T> {
2484 inner: Option<Lease<T>>,
2485 app: &'a mut App,
2486}
2487
2488impl<'a, T: 'static> GpuiBorrow<'a, T> {
2489 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2490 app.start_update();
2491 let lease = app.entities.lease(&inner);
2492 Self {
2493 inner: Some(lease),
2494 app,
2495 }
2496 }
2497}
2498
2499impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2500 fn borrow(&self) -> &T {
2501 self.inner.as_ref().unwrap().borrow()
2502 }
2503}
2504
2505impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2506 fn borrow_mut(&mut self) -> &mut T {
2507 self.inner.as_mut().unwrap().borrow_mut()
2508 }
2509}
2510
2511impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
2512 type Target = T;
2513
2514 fn deref(&self) -> &Self::Target {
2515 self.inner.as_ref().unwrap()
2516 }
2517}
2518
2519impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
2520 fn deref_mut(&mut self) -> &mut T {
2521 self.inner.as_mut().unwrap()
2522 }
2523}
2524
2525impl<'a, T> Drop for GpuiBorrow<'a, T> {
2526 fn drop(&mut self) {
2527 let lease = self.inner.take().unwrap();
2528 self.app.notify(lease.id);
2529 self.app.entities.end_lease(lease);
2530 self.app.finish_update();
2531 }
2532}
2533
2534#[cfg(test)]
2535mod test {
2536 use std::{cell::RefCell, rc::Rc};
2537
2538 use crate::{AppContext, TestAppContext};
2539
2540 #[test]
2541 fn test_gpui_borrow() {
2542 let cx = TestAppContext::single();
2543 let observation_count = Rc::new(RefCell::new(0));
2544
2545 let state = cx.update(|cx| {
2546 let state = cx.new(|_| false);
2547 cx.observe(&state, {
2548 let observation_count = observation_count.clone();
2549 move |_, _| {
2550 let mut count = observation_count.borrow_mut();
2551 *count += 1;
2552 }
2553 })
2554 .detach();
2555
2556 state
2557 });
2558
2559 cx.update(|cx| {
2560 // Calling this like this so that we don't clobber the borrow_mut above
2561 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2562 });
2563
2564 cx.update(|cx| {
2565 state.write(cx, false);
2566 });
2567
2568 assert_eq!(*observation_count.borrow(), 2);
2569 }
2570}