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