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