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