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