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