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