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