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