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 /// Reads data from the platform clipboard.
1081 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1082 self.platform.read_from_clipboard()
1083 }
1084
1085 /// Writes data to the platform clipboard.
1086 pub fn write_to_clipboard(&self, item: ClipboardItem) {
1087 self.platform.write_to_clipboard(item)
1088 }
1089
1090 /// Reads data from the primary selection buffer.
1091 /// Only available on Linux.
1092 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1093 pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1094 self.platform.read_from_primary()
1095 }
1096
1097 /// Writes data to the primary selection buffer.
1098 /// Only available on Linux.
1099 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1100 pub fn write_to_primary(&self, item: ClipboardItem) {
1101 self.platform.write_to_primary(item)
1102 }
1103
1104 /// Reads data from macOS's "Find" pasteboard.
1105 ///
1106 /// Used to share the current search string between apps.
1107 ///
1108 /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1109 #[cfg(target_os = "macos")]
1110 pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1111 self.platform.read_from_find_pasteboard()
1112 }
1113
1114 /// Writes data to macOS's "Find" pasteboard.
1115 ///
1116 /// Used to share the current search string between apps.
1117 ///
1118 /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1119 #[cfg(target_os = "macos")]
1120 pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1121 self.platform.write_to_find_pasteboard(item)
1122 }
1123
1124 /// Writes credentials to the platform keychain.
1125 pub fn write_credentials(
1126 &self,
1127 url: &str,
1128 username: &str,
1129 password: &[u8],
1130 ) -> Task<Result<()>> {
1131 self.platform.write_credentials(url, username, password)
1132 }
1133
1134 /// Reads credentials from the platform keychain.
1135 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1136 self.platform.read_credentials(url)
1137 }
1138
1139 /// Deletes credentials from the platform keychain.
1140 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1141 self.platform.delete_credentials(url)
1142 }
1143
1144 /// Directs the platform's default browser to open the given URL.
1145 pub fn open_url(&self, url: &str) {
1146 self.platform.open_url(url);
1147 }
1148
1149 /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
1150 /// opened by the current app.
1151 ///
1152 /// On some platforms (e.g. macOS) you may be able to register URL schemes
1153 /// as part of app distribution, but this method exists to let you register
1154 /// schemes at runtime.
1155 pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1156 self.platform.register_url_scheme(scheme)
1157 }
1158
1159 /// Returns the full pathname of the current app bundle.
1160 ///
1161 /// Returns an error if the app is not being run from a bundle.
1162 pub fn app_path(&self) -> Result<PathBuf> {
1163 self.platform.app_path()
1164 }
1165
1166 /// On Linux, returns the name of the compositor in use.
1167 ///
1168 /// Returns an empty string on other platforms.
1169 pub fn compositor_name(&self) -> &'static str {
1170 self.platform.compositor_name()
1171 }
1172
1173 /// Returns the file URL of the executable with the specified name in the application bundle
1174 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1175 self.platform.path_for_auxiliary_executable(name)
1176 }
1177
1178 /// Displays a platform modal for selecting paths.
1179 ///
1180 /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
1181 /// If cancelled, a `None` will be relayed instead.
1182 /// May return an error on Linux if the file picker couldn't be opened.
1183 pub fn prompt_for_paths(
1184 &self,
1185 options: PathPromptOptions,
1186 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1187 self.platform.prompt_for_paths(options)
1188 }
1189
1190 /// Displays a platform modal for selecting a new path where a file can be saved.
1191 ///
1192 /// The provided directory will be used to set the initial location.
1193 /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
1194 /// If cancelled, a `None` will be relayed instead.
1195 /// May return an error on Linux if the file picker couldn't be opened.
1196 pub fn prompt_for_new_path(
1197 &self,
1198 directory: &Path,
1199 suggested_name: Option<&str>,
1200 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1201 self.platform.prompt_for_new_path(directory, suggested_name)
1202 }
1203
1204 /// Reveals the specified path at the platform level, such as in Finder on macOS.
1205 pub fn reveal_path(&self, path: &Path) {
1206 self.platform.reveal_path(path)
1207 }
1208
1209 /// Opens the specified path with the system's default application.
1210 pub fn open_with_system(&self, path: &Path) {
1211 self.platform.open_with_system(path)
1212 }
1213
1214 /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
1215 pub fn should_auto_hide_scrollbars(&self) -> bool {
1216 self.platform.should_auto_hide_scrollbars()
1217 }
1218
1219 /// Restarts the application.
1220 pub fn restart(&mut self) {
1221 self.restart_observers
1222 .clone()
1223 .retain(&(), |observer| observer(self));
1224 self.platform.restart(self.restart_path.take())
1225 }
1226
1227 /// Sets the path to use when restarting the application.
1228 pub fn set_restart_path(&mut self, path: PathBuf) {
1229 self.restart_path = Some(path);
1230 }
1231
1232 /// Returns the HTTP client for the application.
1233 pub fn http_client(&self) -> Arc<dyn HttpClient> {
1234 self.http_client.clone()
1235 }
1236
1237 /// Sets the HTTP client for the application.
1238 pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1239 self.http_client = new_client;
1240 }
1241
1242 /// Configures when the application should automatically quit.
1243 /// By default, [`QuitMode::Default`] is used.
1244 pub fn set_quit_mode(&mut self, mode: QuitMode) {
1245 self.quit_mode = mode;
1246 }
1247
1248 /// Returns the SVG renderer used by the application.
1249 pub fn svg_renderer(&self) -> SvgRenderer {
1250 self.svg_renderer.clone()
1251 }
1252
1253 pub(crate) fn push_effect(&mut self, effect: Effect) {
1254 match &effect {
1255 Effect::Notify { emitter } => {
1256 if !self.pending_notifications.insert(*emitter) {
1257 return;
1258 }
1259 }
1260 Effect::NotifyGlobalObservers { global_type } => {
1261 if !self.pending_global_notifications.insert(*global_type) {
1262 return;
1263 }
1264 }
1265 _ => {}
1266 };
1267
1268 self.pending_effects.push_back(effect);
1269 }
1270
1271 /// Called at the end of [`App::update`] to complete any side effects
1272 /// such as notifying observers, emitting events, etc. Effects can themselves
1273 /// cause effects, so we continue looping until all effects are processed.
1274 fn flush_effects(&mut self) {
1275 loop {
1276 self.release_dropped_entities();
1277 self.release_dropped_focus_handles();
1278 if let Some(effect) = self.pending_effects.pop_front() {
1279 match effect {
1280 Effect::Notify { emitter } => {
1281 self.apply_notify_effect(emitter);
1282 }
1283
1284 Effect::Emit {
1285 emitter,
1286 event_type,
1287 event,
1288 } => self.apply_emit_effect(emitter, event_type, event),
1289
1290 Effect::RefreshWindows => {
1291 self.apply_refresh_effect();
1292 }
1293
1294 Effect::NotifyGlobalObservers { global_type } => {
1295 self.apply_notify_global_observers_effect(global_type);
1296 }
1297
1298 Effect::Defer { callback } => {
1299 self.apply_defer_effect(callback);
1300 }
1301 Effect::EntityCreated {
1302 entity,
1303 tid,
1304 window,
1305 } => {
1306 self.apply_entity_created_effect(entity, tid, window);
1307 }
1308 }
1309 } else {
1310 #[cfg(any(test, feature = "test-support"))]
1311 for window in self
1312 .windows
1313 .values()
1314 .filter_map(|window| {
1315 let window = window.as_deref()?;
1316 window.invalidator.is_dirty().then_some(window.handle)
1317 })
1318 .collect::<Vec<_>>()
1319 {
1320 self.update_window(window, |_, window, cx| window.draw(cx).clear())
1321 .unwrap();
1322 }
1323
1324 if self.pending_effects.is_empty() {
1325 break;
1326 }
1327 }
1328 }
1329 }
1330
1331 /// Repeatedly called during `flush_effects` to release any entities whose
1332 /// reference count has become zero. We invoke any release observers before dropping
1333 /// each entity.
1334 fn release_dropped_entities(&mut self) {
1335 loop {
1336 let dropped = self.entities.take_dropped();
1337 if dropped.is_empty() {
1338 break;
1339 }
1340
1341 for (entity_id, mut entity) in dropped {
1342 self.observers.remove(&entity_id);
1343 self.event_listeners.remove(&entity_id);
1344 for release_callback in self.release_listeners.remove(&entity_id) {
1345 release_callback(entity.as_mut(), self);
1346 }
1347 }
1348 }
1349 }
1350
1351 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
1352 fn release_dropped_focus_handles(&mut self) {
1353 self.focus_handles
1354 .clone()
1355 .write()
1356 .retain(|handle_id, focus| {
1357 if focus.ref_count.load(SeqCst) == 0 {
1358 for window_handle in self.windows() {
1359 window_handle
1360 .update(self, |_, window, _| {
1361 if window.focus == Some(handle_id) {
1362 window.blur();
1363 }
1364 })
1365 .unwrap();
1366 }
1367 false
1368 } else {
1369 true
1370 }
1371 });
1372 }
1373
1374 fn apply_notify_effect(&mut self, emitter: EntityId) {
1375 self.pending_notifications.remove(&emitter);
1376
1377 self.observers
1378 .clone()
1379 .retain(&emitter, |handler| handler(self));
1380 }
1381
1382 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
1383 self.event_listeners
1384 .clone()
1385 .retain(&emitter, |(stored_type, handler)| {
1386 if *stored_type == event_type {
1387 handler(event.as_ref(), self)
1388 } else {
1389 true
1390 }
1391 });
1392 }
1393
1394 fn apply_refresh_effect(&mut self) {
1395 for window in self.windows.values_mut() {
1396 if let Some(window) = window.as_deref_mut() {
1397 window.refreshing = true;
1398 window.invalidator.set_dirty(true);
1399 }
1400 }
1401 }
1402
1403 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1404 self.pending_global_notifications.remove(&type_id);
1405 self.global_observers
1406 .clone()
1407 .retain(&type_id, |observer| observer(self));
1408 }
1409
1410 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1411 callback(self);
1412 }
1413
1414 fn apply_entity_created_effect(
1415 &mut self,
1416 entity: AnyEntity,
1417 tid: TypeId,
1418 window: Option<WindowId>,
1419 ) {
1420 self.new_entity_observers.clone().retain(&tid, |observer| {
1421 if let Some(id) = window {
1422 self.update_window_id(id, {
1423 let entity = entity.clone();
1424 |_, window, cx| (observer)(entity, &mut Some(window), cx)
1425 })
1426 .expect("All windows should be off the stack when flushing effects");
1427 } else {
1428 (observer)(entity.clone(), &mut None, self)
1429 }
1430 true
1431 });
1432 }
1433
1434 fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1435 where
1436 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1437 {
1438 self.update(|cx| {
1439 let mut window = cx.windows.get_mut(id)?.take()?;
1440
1441 let root_view = window.root.clone().unwrap();
1442
1443 cx.window_update_stack.push(window.handle.id);
1444 let result = update(root_view, &mut window, cx);
1445 cx.window_update_stack.pop();
1446
1447 if window.removed {
1448 cx.window_handles.remove(&id);
1449 cx.windows.remove(id);
1450
1451 cx.window_closed_observers.clone().retain(&(), |callback| {
1452 callback(cx);
1453 true
1454 });
1455
1456 let quit_on_empty = match cx.quit_mode {
1457 QuitMode::Explicit => false,
1458 QuitMode::LastWindowClosed => true,
1459 QuitMode::Default => cfg!(not(target_os = "macos")),
1460 };
1461
1462 if quit_on_empty && cx.windows.is_empty() {
1463 cx.quit();
1464 }
1465 } else {
1466 cx.windows.get_mut(id)?.replace(window);
1467 }
1468
1469 Some(result)
1470 })
1471 .context("window not found")
1472 }
1473
1474 /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1475 /// so it can be held across `await` points.
1476 pub fn to_async(&self) -> AsyncApp {
1477 AsyncApp {
1478 app: self.this.clone(),
1479 background_executor: self.background_executor.clone(),
1480 foreground_executor: self.foreground_executor.clone(),
1481 }
1482 }
1483
1484 /// Obtains a reference to the executor, which can be used to spawn futures.
1485 pub fn background_executor(&self) -> &BackgroundExecutor {
1486 &self.background_executor
1487 }
1488
1489 /// Obtains a reference to the executor, which can be used to spawn futures.
1490 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1491 if self.quitting {
1492 panic!("Can't spawn on main thread after on_app_quit")
1493 };
1494 &self.foreground_executor
1495 }
1496
1497 /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1498 /// with [AsyncApp], which allows the application state to be accessed across await points.
1499 #[track_caller]
1500 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1501 where
1502 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1503 R: 'static,
1504 {
1505 if self.quitting {
1506 debug_panic!("Can't spawn on main thread after on_app_quit")
1507 };
1508
1509 let mut cx = self.to_async();
1510
1511 self.foreground_executor
1512 .spawn(async move { f(&mut cx).await })
1513 }
1514
1515 /// Spawns the future returned by the given function on the main thread with
1516 /// the given priority. The closure will be invoked with [AsyncApp], which
1517 /// allows the application state to be accessed across await points.
1518 pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1519 where
1520 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1521 R: 'static,
1522 {
1523 if self.quitting {
1524 debug_panic!("Can't spawn on main thread after on_app_quit")
1525 };
1526
1527 let mut cx = self.to_async();
1528
1529 self.foreground_executor
1530 .spawn_with_priority(priority, async move { f(&mut cx).await })
1531 }
1532
1533 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1534 /// that are currently on the stack to be returned to the app.
1535 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1536 self.push_effect(Effect::Defer {
1537 callback: Box::new(f),
1538 });
1539 }
1540
1541 /// Accessor for the application's asset source, which is provided when constructing the `App`.
1542 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1543 &self.asset_source
1544 }
1545
1546 /// Accessor for the text system.
1547 pub fn text_system(&self) -> &Arc<TextSystem> {
1548 &self.text_system
1549 }
1550
1551 /// Check whether a global of the given type has been assigned.
1552 pub fn has_global<G: Global>(&self) -> bool {
1553 self.globals_by_type.contains_key(&TypeId::of::<G>())
1554 }
1555
1556 /// Access the global of the given type. Panics if a global for that type has not been assigned.
1557 #[track_caller]
1558 pub fn global<G: Global>(&self) -> &G {
1559 self.globals_by_type
1560 .get(&TypeId::of::<G>())
1561 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1562 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1563 .unwrap()
1564 }
1565
1566 /// Access the global of the given type if a value has been assigned.
1567 pub fn try_global<G: Global>(&self) -> Option<&G> {
1568 self.globals_by_type
1569 .get(&TypeId::of::<G>())
1570 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1571 }
1572
1573 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1574 #[track_caller]
1575 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1576 let global_type = TypeId::of::<G>();
1577 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1578 self.globals_by_type
1579 .get_mut(&global_type)
1580 .and_then(|any_state| any_state.downcast_mut::<G>())
1581 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1582 .unwrap()
1583 }
1584
1585 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1586 /// yet been assigned.
1587 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1588 let global_type = TypeId::of::<G>();
1589 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1590 self.globals_by_type
1591 .entry(global_type)
1592 .or_insert_with(|| Box::<G>::default())
1593 .downcast_mut::<G>()
1594 .unwrap()
1595 }
1596
1597 /// Sets the value of the global of the given type.
1598 pub fn set_global<G: Global>(&mut self, global: G) {
1599 let global_type = TypeId::of::<G>();
1600 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1601 self.globals_by_type.insert(global_type, Box::new(global));
1602 }
1603
1604 /// Clear all stored globals. Does not notify global observers.
1605 #[cfg(any(test, feature = "test-support"))]
1606 pub fn clear_globals(&mut self) {
1607 self.globals_by_type.drain();
1608 }
1609
1610 /// Remove the global of the given type from the app context. Does not notify global observers.
1611 pub fn remove_global<G: Global>(&mut self) -> G {
1612 let global_type = TypeId::of::<G>();
1613 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1614 *self
1615 .globals_by_type
1616 .remove(&global_type)
1617 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1618 .downcast()
1619 .unwrap()
1620 }
1621
1622 /// Register a callback to be invoked when a global of the given type is updated.
1623 pub fn observe_global<G: Global>(
1624 &mut self,
1625 mut f: impl FnMut(&mut Self) + 'static,
1626 ) -> Subscription {
1627 let (subscription, activate) = self.global_observers.insert(
1628 TypeId::of::<G>(),
1629 Box::new(move |cx| {
1630 f(cx);
1631 true
1632 }),
1633 );
1634 self.defer(move |_| activate());
1635 subscription
1636 }
1637
1638 /// Move the global of the given type to the stack.
1639 #[track_caller]
1640 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1641 GlobalLease::new(
1642 self.globals_by_type
1643 .remove(&TypeId::of::<G>())
1644 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1645 .unwrap(),
1646 )
1647 }
1648
1649 /// Restore the global of the given type after it is moved to the stack.
1650 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1651 let global_type = TypeId::of::<G>();
1652
1653 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1654 self.globals_by_type.insert(global_type, lease.global);
1655 }
1656
1657 pub(crate) fn new_entity_observer(
1658 &self,
1659 key: TypeId,
1660 value: NewEntityListener,
1661 ) -> Subscription {
1662 let (subscription, activate) = self.new_entity_observers.insert(key, value);
1663 activate();
1664 subscription
1665 }
1666
1667 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1668 /// The function will be passed a mutable reference to the view along with an appropriate context.
1669 pub fn observe_new<T: 'static>(
1670 &self,
1671 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1672 ) -> Subscription {
1673 self.new_entity_observer(
1674 TypeId::of::<T>(),
1675 Box::new(
1676 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1677 any_entity
1678 .downcast::<T>()
1679 .unwrap()
1680 .update(cx, |entity_state, cx| {
1681 on_new(entity_state, window.as_deref_mut(), cx)
1682 })
1683 },
1684 ),
1685 )
1686 }
1687
1688 /// Observe the release of a entity. The callback is invoked after the entity
1689 /// has no more strong references but before it has been dropped.
1690 pub fn observe_release<T>(
1691 &self,
1692 handle: &Entity<T>,
1693 on_release: impl FnOnce(&mut T, &mut App) + 'static,
1694 ) -> Subscription
1695 where
1696 T: 'static,
1697 {
1698 let (subscription, activate) = self.release_listeners.insert(
1699 handle.entity_id(),
1700 Box::new(move |entity, cx| {
1701 let entity = entity.downcast_mut().expect("invalid entity type");
1702 on_release(entity, cx)
1703 }),
1704 );
1705 activate();
1706 subscription
1707 }
1708
1709 /// Observe the release of a entity. The callback is invoked after the entity
1710 /// has no more strong references but before it has been dropped.
1711 pub fn observe_release_in<T>(
1712 &self,
1713 handle: &Entity<T>,
1714 window: &Window,
1715 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1716 ) -> Subscription
1717 where
1718 T: 'static,
1719 {
1720 let window_handle = window.handle;
1721 self.observe_release(handle, move |entity, cx| {
1722 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1723 })
1724 }
1725
1726 /// Register a callback to be invoked when a keystroke is received by the application
1727 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1728 /// and that this API will not be invoked if the event's propagation is stopped.
1729 pub fn observe_keystrokes(
1730 &mut self,
1731 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1732 ) -> Subscription {
1733 fn inner(
1734 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1735 handler: KeystrokeObserver,
1736 ) -> Subscription {
1737 let (subscription, activate) = keystroke_observers.insert((), handler);
1738 activate();
1739 subscription
1740 }
1741
1742 inner(
1743 &self.keystroke_observers,
1744 Box::new(move |event, window, cx| {
1745 f(event, window, cx);
1746 true
1747 }),
1748 )
1749 }
1750
1751 /// Register a callback to be invoked when a keystroke is received by the application
1752 /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1753 /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1754 /// within interceptors will prevent action dispatch
1755 pub fn intercept_keystrokes(
1756 &mut self,
1757 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1758 ) -> Subscription {
1759 fn inner(
1760 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1761 handler: KeystrokeObserver,
1762 ) -> Subscription {
1763 let (subscription, activate) = keystroke_interceptors.insert((), handler);
1764 activate();
1765 subscription
1766 }
1767
1768 inner(
1769 &self.keystroke_interceptors,
1770 Box::new(move |event, window, cx| {
1771 f(event, window, cx);
1772 true
1773 }),
1774 )
1775 }
1776
1777 /// Register key bindings.
1778 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1779 self.keymap.borrow_mut().add_bindings(bindings);
1780 self.pending_effects.push_back(Effect::RefreshWindows);
1781 }
1782
1783 /// Clear all key bindings in the app.
1784 pub fn clear_key_bindings(&mut self) {
1785 self.keymap.borrow_mut().clear();
1786 self.pending_effects.push_back(Effect::RefreshWindows);
1787 }
1788
1789 /// Get all key bindings in the app.
1790 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1791 self.keymap.clone()
1792 }
1793
1794 /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1795 /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1796 /// handlers or if they called `cx.propagate()`.
1797 pub fn on_action<A: Action>(
1798 &mut self,
1799 listener: impl Fn(&A, &mut Self) + 'static,
1800 ) -> &mut Self {
1801 self.global_action_listeners
1802 .entry(TypeId::of::<A>())
1803 .or_default()
1804 .push(Rc::new(move |action, phase, cx| {
1805 if phase == DispatchPhase::Bubble {
1806 let action = action.downcast_ref().unwrap();
1807 listener(action, cx)
1808 }
1809 }));
1810 self
1811 }
1812
1813 /// Event handlers propagate events by default. Call this method to stop dispatching to
1814 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1815 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1816 /// calling this method before effects are flushed.
1817 pub fn stop_propagation(&mut self) {
1818 self.propagate_event = false;
1819 }
1820
1821 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1822 /// dispatching to action handlers higher in the element tree. This is the opposite of
1823 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1824 /// this method before effects are flushed.
1825 pub fn propagate(&mut self) {
1826 self.propagate_event = true;
1827 }
1828
1829 /// Build an action from some arbitrary data, typically a keymap entry.
1830 pub fn build_action(
1831 &self,
1832 name: &str,
1833 data: Option<serde_json::Value>,
1834 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1835 self.actions.build_action(name, data)
1836 }
1837
1838 /// Get all action names that have been registered. Note that registration only allows for
1839 /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1840 pub fn all_action_names(&self) -> &[&'static str] {
1841 self.actions.all_action_names()
1842 }
1843
1844 /// Returns key bindings that invoke the given action on the currently focused element, without
1845 /// checking context. Bindings are returned in the order they were added. For display, the last
1846 /// binding should take precedence.
1847 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1848 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1849 }
1850
1851 /// Get all non-internal actions that have been registered, along with their schemas.
1852 pub fn action_schemas(
1853 &self,
1854 generator: &mut schemars::SchemaGenerator,
1855 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1856 self.actions.action_schemas(generator)
1857 }
1858
1859 /// Get a map from a deprecated action name to the canonical name.
1860 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1861 self.actions.deprecated_aliases()
1862 }
1863
1864 /// Get a map from an action name to the deprecation messages.
1865 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1866 self.actions.deprecation_messages()
1867 }
1868
1869 /// Get a map from an action name to the documentation.
1870 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
1871 self.actions.documentation()
1872 }
1873
1874 /// Register a callback to be invoked when the application is about to quit.
1875 /// It is not possible to cancel the quit event at this point.
1876 pub fn on_app_quit<Fut>(
1877 &self,
1878 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1879 ) -> Subscription
1880 where
1881 Fut: 'static + Future<Output = ()>,
1882 {
1883 let (subscription, activate) = self.quit_observers.insert(
1884 (),
1885 Box::new(move |cx| {
1886 let future = on_quit(cx);
1887 future.boxed_local()
1888 }),
1889 );
1890 activate();
1891 subscription
1892 }
1893
1894 /// Register a callback to be invoked when the application is about to restart.
1895 ///
1896 /// These callbacks are called before any `on_app_quit` callbacks.
1897 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
1898 let (subscription, activate) = self.restart_observers.insert(
1899 (),
1900 Box::new(move |cx| {
1901 on_restart(cx);
1902 true
1903 }),
1904 );
1905 activate();
1906 subscription
1907 }
1908
1909 /// Register a callback to be invoked when a window is closed
1910 /// The window is no longer accessible at the point this callback is invoked.
1911 pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1912 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1913 activate();
1914 subscription
1915 }
1916
1917 pub(crate) fn clear_pending_keystrokes(&mut self) {
1918 for window in self.windows() {
1919 window
1920 .update(self, |_, window, cx| {
1921 if window.pending_input_keystrokes().is_some() {
1922 window.clear_pending_keystrokes();
1923 window.pending_input_changed(cx);
1924 }
1925 })
1926 .ok();
1927 }
1928 }
1929
1930 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1931 /// the bindings in the element tree, and any global action listeners.
1932 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1933 let mut action_available = false;
1934 if let Some(window) = self.active_window()
1935 && let Ok(window_action_available) =
1936 window.update(self, |_, window, cx| window.is_action_available(action, cx))
1937 {
1938 action_available = window_action_available;
1939 }
1940
1941 action_available
1942 || self
1943 .global_action_listeners
1944 .contains_key(&action.as_any().type_id())
1945 }
1946
1947 /// Sets the menu bar for this application. This will replace any existing menu bar.
1948 pub fn set_menus(&self, menus: Vec<Menu>) {
1949 self.platform.set_menus(menus, &self.keymap.borrow());
1950 }
1951
1952 /// Gets the menu bar for this application.
1953 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1954 self.platform.get_menus()
1955 }
1956
1957 /// Sets the right click menu for the app icon in the dock
1958 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1959 self.platform.set_dock_menu(menus, &self.keymap.borrow())
1960 }
1961
1962 /// Performs the action associated with the given dock menu item, only used on Windows for now.
1963 pub fn perform_dock_menu_action(&self, action: usize) {
1964 self.platform.perform_dock_menu_action(action);
1965 }
1966
1967 /// Adds given path to the bottom of the list of recent paths for the application.
1968 /// The list is usually shown on the application icon's context menu in the dock,
1969 /// and allows to open the recent files via that context menu.
1970 /// If the path is already in the list, it will be moved to the bottom of the list.
1971 pub fn add_recent_document(&self, path: &Path) {
1972 self.platform.add_recent_document(path);
1973 }
1974
1975 /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
1976 /// Note that this also sets the dock menu on Windows.
1977 pub fn update_jump_list(
1978 &self,
1979 menus: Vec<MenuItem>,
1980 entries: Vec<SmallVec<[PathBuf; 2]>>,
1981 ) -> Vec<SmallVec<[PathBuf; 2]>> {
1982 self.platform.update_jump_list(menus, entries)
1983 }
1984
1985 /// Dispatch an action to the currently active window or global action handler
1986 /// See [`crate::Action`] for more information on how actions work
1987 pub fn dispatch_action(&mut self, action: &dyn Action) {
1988 if let Some(active_window) = self.active_window() {
1989 active_window
1990 .update(self, |_, window, cx| {
1991 window.dispatch_action(action.boxed_clone(), cx)
1992 })
1993 .log_err();
1994 } else {
1995 self.dispatch_global_action(action);
1996 }
1997 }
1998
1999 fn dispatch_global_action(&mut self, action: &dyn Action) {
2000 self.propagate_event = true;
2001
2002 if let Some(mut global_listeners) = self
2003 .global_action_listeners
2004 .remove(&action.as_any().type_id())
2005 {
2006 for listener in &global_listeners {
2007 listener(action.as_any(), DispatchPhase::Capture, self);
2008 if !self.propagate_event {
2009 break;
2010 }
2011 }
2012
2013 global_listeners.extend(
2014 self.global_action_listeners
2015 .remove(&action.as_any().type_id())
2016 .unwrap_or_default(),
2017 );
2018
2019 self.global_action_listeners
2020 .insert(action.as_any().type_id(), global_listeners);
2021 }
2022
2023 if self.propagate_event
2024 && let Some(mut global_listeners) = self
2025 .global_action_listeners
2026 .remove(&action.as_any().type_id())
2027 {
2028 for listener in global_listeners.iter().rev() {
2029 listener(action.as_any(), DispatchPhase::Bubble, self);
2030 if !self.propagate_event {
2031 break;
2032 }
2033 }
2034
2035 global_listeners.extend(
2036 self.global_action_listeners
2037 .remove(&action.as_any().type_id())
2038 .unwrap_or_default(),
2039 );
2040
2041 self.global_action_listeners
2042 .insert(action.as_any().type_id(), global_listeners);
2043 }
2044 }
2045
2046 /// Is there currently something being dragged?
2047 pub fn has_active_drag(&self) -> bool {
2048 self.active_drag.is_some()
2049 }
2050
2051 /// Gets the cursor style of the currently active drag operation.
2052 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2053 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2054 }
2055
2056 /// Stops active drag and clears any related effects.
2057 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2058 if self.active_drag.is_some() {
2059 self.active_drag = None;
2060 window.refresh();
2061 true
2062 } else {
2063 false
2064 }
2065 }
2066
2067 /// Sets the cursor style for the currently active drag operation.
2068 pub fn set_active_drag_cursor_style(
2069 &mut self,
2070 cursor_style: CursorStyle,
2071 window: &mut Window,
2072 ) -> bool {
2073 if let Some(ref mut drag) = self.active_drag {
2074 drag.cursor_style = Some(cursor_style);
2075 window.refresh();
2076 true
2077 } else {
2078 false
2079 }
2080 }
2081
2082 /// Set the prompt renderer for GPUI. This will replace the default or platform specific
2083 /// prompts with this custom implementation.
2084 pub fn set_prompt_builder(
2085 &mut self,
2086 renderer: impl Fn(
2087 PromptLevel,
2088 &str,
2089 Option<&str>,
2090 &[PromptButton],
2091 PromptHandle,
2092 &mut Window,
2093 &mut App,
2094 ) -> RenderablePromptHandle
2095 + 'static,
2096 ) {
2097 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2098 }
2099
2100 /// Reset the prompt builder to the default implementation.
2101 pub fn reset_prompt_builder(&mut self) {
2102 self.prompt_builder = Some(PromptBuilder::Default);
2103 }
2104
2105 /// Remove an asset from GPUI's cache
2106 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2107 let asset_id = (TypeId::of::<A>(), hash(source));
2108 self.loading_assets.remove(&asset_id);
2109 }
2110
2111 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2112 ///
2113 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2114 /// time, and the results of this call will be cached
2115 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2116 let asset_id = (TypeId::of::<A>(), hash(source));
2117 let mut is_first = false;
2118 let task = self
2119 .loading_assets
2120 .remove(&asset_id)
2121 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2122 .unwrap_or_else(|| {
2123 is_first = true;
2124 let future = A::load(source.clone(), self);
2125
2126 self.background_executor().spawn(future).shared()
2127 });
2128
2129 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2130
2131 (task, is_first)
2132 }
2133
2134 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2135 /// for elements rendered within this window.
2136 #[track_caller]
2137 pub fn focus_handle(&self) -> FocusHandle {
2138 FocusHandle::new(&self.focus_handles)
2139 }
2140
2141 /// Tell GPUI that an entity has changed and observers of it should be notified.
2142 pub fn notify(&mut self, entity_id: EntityId) {
2143 let window_invalidators = mem::take(
2144 self.window_invalidators_by_entity
2145 .entry(entity_id)
2146 .or_default(),
2147 );
2148
2149 if window_invalidators.is_empty() {
2150 if self.pending_notifications.insert(entity_id) {
2151 self.pending_effects
2152 .push_back(Effect::Notify { emitter: entity_id });
2153 }
2154 } else {
2155 for invalidator in window_invalidators.values() {
2156 invalidator.invalidate_view(entity_id, self);
2157 }
2158 }
2159
2160 self.window_invalidators_by_entity
2161 .insert(entity_id, window_invalidators);
2162 }
2163
2164 /// Returns the name for this [`App`].
2165 #[cfg(any(test, feature = "test-support", debug_assertions))]
2166 pub fn get_name(&self) -> Option<&'static str> {
2167 self.name
2168 }
2169
2170 /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2171 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2172 self.platform.can_select_mixed_files_and_dirs()
2173 }
2174
2175 /// Removes an image from the sprite atlas on all windows.
2176 ///
2177 /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2178 /// This is a no-op if the image is not in the sprite atlas.
2179 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2180 // remove the texture from all other windows
2181 for window in self.windows.values_mut().flatten() {
2182 _ = window.drop_image(image.clone());
2183 }
2184
2185 // remove the texture from the current window
2186 if let Some(window) = current_window {
2187 _ = window.drop_image(image);
2188 }
2189 }
2190
2191 /// Sets the renderer for the inspector.
2192 #[cfg(any(feature = "inspector", debug_assertions))]
2193 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2194 self.inspector_renderer = Some(f);
2195 }
2196
2197 /// Registers a renderer specific to an inspector state.
2198 #[cfg(any(feature = "inspector", debug_assertions))]
2199 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2200 &mut self,
2201 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2202 ) {
2203 self.inspector_element_registry.register(f);
2204 }
2205
2206 /// Initializes gpui's default colors for the application.
2207 ///
2208 /// These colors can be accessed through `cx.default_colors()`.
2209 pub fn init_colors(&mut self) {
2210 self.set_global(GlobalColors(Arc::new(Colors::default())));
2211 }
2212}
2213
2214impl AppContext for App {
2215 type Result<T> = T;
2216
2217 /// Builds an entity that is owned by the application.
2218 ///
2219 /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2220 /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2221 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2222 self.update(|cx| {
2223 let slot = cx.entities.reserve();
2224 let handle = slot.clone();
2225 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2226
2227 cx.push_effect(Effect::EntityCreated {
2228 entity: handle.clone().into_any(),
2229 tid: TypeId::of::<T>(),
2230 window: cx.window_update_stack.last().cloned(),
2231 });
2232
2233 cx.entities.insert(slot, entity);
2234 handle
2235 })
2236 }
2237
2238 fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
2239 Reservation(self.entities.reserve())
2240 }
2241
2242 fn insert_entity<T: 'static>(
2243 &mut self,
2244 reservation: Reservation<T>,
2245 build_entity: impl FnOnce(&mut Context<T>) -> T,
2246 ) -> Self::Result<Entity<T>> {
2247 self.update(|cx| {
2248 let slot = reservation.0;
2249 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2250 cx.entities.insert(slot, entity)
2251 })
2252 }
2253
2254 /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2255 /// entity along with a `Context` for the entity.
2256 fn update_entity<T: 'static, R>(
2257 &mut self,
2258 handle: &Entity<T>,
2259 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2260 ) -> R {
2261 self.update(|cx| {
2262 let mut entity = cx.entities.lease(handle);
2263 let result = update(
2264 &mut entity,
2265 &mut Context::new_context(cx, handle.downgrade()),
2266 );
2267 cx.entities.end_lease(entity);
2268 result
2269 })
2270 }
2271
2272 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2273 where
2274 T: 'static,
2275 {
2276 GpuiBorrow::new(handle.clone(), self)
2277 }
2278
2279 fn read_entity<T, R>(
2280 &self,
2281 handle: &Entity<T>,
2282 read: impl FnOnce(&T, &App) -> R,
2283 ) -> Self::Result<R>
2284 where
2285 T: 'static,
2286 {
2287 let entity = self.entities.read(handle);
2288 read(entity, self)
2289 }
2290
2291 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2292 where
2293 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2294 {
2295 self.update_window_id(handle.id, update)
2296 }
2297
2298 fn read_window<T, R>(
2299 &self,
2300 window: &WindowHandle<T>,
2301 read: impl FnOnce(Entity<T>, &App) -> R,
2302 ) -> Result<R>
2303 where
2304 T: 'static,
2305 {
2306 let window = self
2307 .windows
2308 .get(window.id)
2309 .context("window not found")?
2310 .as_deref()
2311 .expect("attempted to read a window that is already on the stack");
2312
2313 let root_view = window.root.clone().unwrap();
2314 let view = root_view
2315 .downcast::<T>()
2316 .map_err(|_| anyhow!("root view's type has changed"))?;
2317
2318 Ok(read(view, self))
2319 }
2320
2321 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2322 where
2323 R: Send + 'static,
2324 {
2325 self.background_executor.spawn(future)
2326 }
2327
2328 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
2329 where
2330 G: Global,
2331 {
2332 let mut g = self.global::<G>();
2333 callback(g, self)
2334 }
2335}
2336
2337/// These effects are processed at the end of each application update cycle.
2338pub(crate) enum Effect {
2339 Notify {
2340 emitter: EntityId,
2341 },
2342 Emit {
2343 emitter: EntityId,
2344 event_type: TypeId,
2345 event: Box<dyn Any>,
2346 },
2347 RefreshWindows,
2348 NotifyGlobalObservers {
2349 global_type: TypeId,
2350 },
2351 Defer {
2352 callback: Box<dyn FnOnce(&mut App) + 'static>,
2353 },
2354 EntityCreated {
2355 entity: AnyEntity,
2356 tid: TypeId,
2357 window: Option<WindowId>,
2358 },
2359}
2360
2361impl std::fmt::Debug for Effect {
2362 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2363 match self {
2364 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2365 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2366 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2367 Effect::NotifyGlobalObservers { global_type } => {
2368 write!(f, "NotifyGlobalObservers({:?})", global_type)
2369 }
2370 Effect::Defer { .. } => write!(f, "Defer(..)"),
2371 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2372 }
2373 }
2374}
2375
2376/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2377pub(crate) struct GlobalLease<G: Global> {
2378 global: Box<dyn Any>,
2379 global_type: PhantomData<G>,
2380}
2381
2382impl<G: Global> GlobalLease<G> {
2383 fn new(global: Box<dyn Any>) -> Self {
2384 GlobalLease {
2385 global,
2386 global_type: PhantomData,
2387 }
2388 }
2389}
2390
2391impl<G: Global> Deref for GlobalLease<G> {
2392 type Target = G;
2393
2394 fn deref(&self) -> &Self::Target {
2395 self.global.downcast_ref().unwrap()
2396 }
2397}
2398
2399impl<G: Global> DerefMut for GlobalLease<G> {
2400 fn deref_mut(&mut self) -> &mut Self::Target {
2401 self.global.downcast_mut().unwrap()
2402 }
2403}
2404
2405/// Contains state associated with an active drag operation, started by dragging an element
2406/// within the window or by dragging into the app from the underlying platform.
2407pub struct AnyDrag {
2408 /// The view used to render this drag
2409 pub view: AnyView,
2410
2411 /// The value of the dragged item, to be dropped
2412 pub value: Arc<dyn Any>,
2413
2414 /// This is used to render the dragged item in the same place
2415 /// on the original element that the drag was initiated
2416 pub cursor_offset: Point<Pixels>,
2417
2418 /// The cursor style to use while dragging
2419 pub cursor_style: Option<CursorStyle>,
2420}
2421
2422/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2423/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2424#[derive(Clone)]
2425pub struct AnyTooltip {
2426 /// The view used to display the tooltip
2427 pub view: AnyView,
2428
2429 /// The absolute position of the mouse when the tooltip was deployed.
2430 pub mouse_position: Point<Pixels>,
2431
2432 /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2433 /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2434 /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2435 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2436}
2437
2438/// A keystroke event, and potentially the associated action
2439#[derive(Debug)]
2440pub struct KeystrokeEvent {
2441 /// The keystroke that occurred
2442 pub keystroke: Keystroke,
2443
2444 /// The action that was resolved for the keystroke, if any
2445 pub action: Option<Box<dyn Action>>,
2446
2447 /// The context stack at the time
2448 pub context_stack: Vec<KeyContext>,
2449}
2450
2451struct NullHttpClient;
2452
2453impl HttpClient for NullHttpClient {
2454 fn send(
2455 &self,
2456 _req: http_client::Request<http_client::AsyncBody>,
2457 ) -> futures::future::BoxFuture<
2458 'static,
2459 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2460 > {
2461 async move {
2462 anyhow::bail!("No HttpClient available");
2463 }
2464 .boxed()
2465 }
2466
2467 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2468 None
2469 }
2470
2471 fn proxy(&self) -> Option<&Url> {
2472 None
2473 }
2474}
2475
2476/// A mutable reference to an entity owned by GPUI
2477pub struct GpuiBorrow<'a, T> {
2478 inner: Option<Lease<T>>,
2479 app: &'a mut App,
2480}
2481
2482impl<'a, T: 'static> GpuiBorrow<'a, T> {
2483 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2484 app.start_update();
2485 let lease = app.entities.lease(&inner);
2486 Self {
2487 inner: Some(lease),
2488 app,
2489 }
2490 }
2491}
2492
2493impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2494 fn borrow(&self) -> &T {
2495 self.inner.as_ref().unwrap().borrow()
2496 }
2497}
2498
2499impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2500 fn borrow_mut(&mut self) -> &mut T {
2501 self.inner.as_mut().unwrap().borrow_mut()
2502 }
2503}
2504
2505impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
2506 type Target = T;
2507
2508 fn deref(&self) -> &Self::Target {
2509 self.inner.as_ref().unwrap()
2510 }
2511}
2512
2513impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
2514 fn deref_mut(&mut self) -> &mut T {
2515 self.inner.as_mut().unwrap()
2516 }
2517}
2518
2519impl<'a, T> Drop for GpuiBorrow<'a, T> {
2520 fn drop(&mut self) {
2521 let lease = self.inner.take().unwrap();
2522 self.app.notify(lease.id);
2523 self.app.entities.end_lease(lease);
2524 self.app.finish_update();
2525 }
2526}
2527
2528#[cfg(test)]
2529mod test {
2530 use std::{cell::RefCell, rc::Rc};
2531
2532 use crate::{AppContext, TestAppContext};
2533
2534 #[test]
2535 fn test_gpui_borrow() {
2536 let cx = TestAppContext::single();
2537 let observation_count = Rc::new(RefCell::new(0));
2538
2539 let state = cx.update(|cx| {
2540 let state = cx.new(|_| false);
2541 cx.observe(&state, {
2542 let observation_count = observation_count.clone();
2543 move |_, _| {
2544 let mut count = observation_count.borrow_mut();
2545 *count += 1;
2546 }
2547 })
2548 .detach();
2549
2550 state
2551 });
2552
2553 cx.update(|cx| {
2554 // Calling this like this so that we don't clobber the borrow_mut above
2555 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2556 });
2557
2558 cx.update(|cx| {
2559 state.write(cx, false);
2560 });
2561
2562 assert_eq!(*observation_count.borrow(), 2);
2563 }
2564}