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
1362 .windows
1363 .get_mut(id)
1364 .context("window not found")?
1365 .take()
1366 .context("window not found")?;
1367
1368 let root_view = window.root.clone().unwrap();
1369
1370 cx.window_update_stack.push(window.handle.id);
1371 let result = update(root_view, &mut window, cx);
1372 cx.window_update_stack.pop();
1373
1374 if window.removed {
1375 cx.window_handles.remove(&id);
1376 cx.windows.remove(id);
1377
1378 cx.window_closed_observers.clone().retain(&(), |callback| {
1379 callback(cx);
1380 true
1381 });
1382 } else {
1383 cx.windows
1384 .get_mut(id)
1385 .context("window not found")?
1386 .replace(window);
1387 }
1388
1389 Ok(result)
1390 })
1391 }
1392 /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1393 /// so it can be held across `await` points.
1394 pub fn to_async(&self) -> AsyncApp {
1395 AsyncApp {
1396 app: self.this.clone(),
1397 background_executor: self.background_executor.clone(),
1398 foreground_executor: self.foreground_executor.clone(),
1399 }
1400 }
1401
1402 /// Obtains a reference to the executor, which can be used to spawn futures.
1403 pub fn background_executor(&self) -> &BackgroundExecutor {
1404 &self.background_executor
1405 }
1406
1407 /// Obtains a reference to the executor, which can be used to spawn futures.
1408 pub fn foreground_executor(&self) -> &ForegroundExecutor {
1409 if self.quitting {
1410 panic!("Can't spawn on main thread after on_app_quit")
1411 };
1412 &self.foreground_executor
1413 }
1414
1415 /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1416 /// with [AsyncApp], which allows the application state to be accessed across await points.
1417 #[track_caller]
1418 pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1419 where
1420 AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1421 R: 'static,
1422 {
1423 if self.quitting {
1424 debug_panic!("Can't spawn on main thread after on_app_quit")
1425 };
1426
1427 let mut cx = self.to_async();
1428
1429 self.foreground_executor
1430 .spawn(async move { f(&mut cx).await })
1431 }
1432
1433 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1434 /// that are currently on the stack to be returned to the app.
1435 pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1436 self.push_effect(Effect::Defer {
1437 callback: Box::new(f),
1438 });
1439 }
1440
1441 /// Accessor for the application's asset source, which is provided when constructing the `App`.
1442 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1443 &self.asset_source
1444 }
1445
1446 /// Accessor for the text system.
1447 pub fn text_system(&self) -> &Arc<TextSystem> {
1448 &self.text_system
1449 }
1450
1451 /// Check whether a global of the given type has been assigned.
1452 pub fn has_global<G: Global>(&self) -> bool {
1453 self.globals_by_type.contains_key(&TypeId::of::<G>())
1454 }
1455
1456 /// Access the global of the given type. Panics if a global for that type has not been assigned.
1457 #[track_caller]
1458 pub fn global<G: Global>(&self) -> &G {
1459 self.globals_by_type
1460 .get(&TypeId::of::<G>())
1461 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1462 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1463 .unwrap()
1464 }
1465
1466 /// Access the global of the given type if a value has been assigned.
1467 pub fn try_global<G: Global>(&self) -> Option<&G> {
1468 self.globals_by_type
1469 .get(&TypeId::of::<G>())
1470 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1471 }
1472
1473 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1474 #[track_caller]
1475 pub fn global_mut<G: Global>(&mut self) -> &mut G {
1476 let global_type = TypeId::of::<G>();
1477 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1478 self.globals_by_type
1479 .get_mut(&global_type)
1480 .and_then(|any_state| any_state.downcast_mut::<G>())
1481 .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1482 .unwrap()
1483 }
1484
1485 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1486 /// yet been assigned.
1487 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1488 let global_type = TypeId::of::<G>();
1489 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1490 self.globals_by_type
1491 .entry(global_type)
1492 .or_insert_with(|| Box::<G>::default())
1493 .downcast_mut::<G>()
1494 .unwrap()
1495 }
1496
1497 /// Sets the value of the global of the given type.
1498 pub fn set_global<G: Global>(&mut self, global: G) {
1499 let global_type = TypeId::of::<G>();
1500 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1501 self.globals_by_type.insert(global_type, Box::new(global));
1502 }
1503
1504 /// Clear all stored globals. Does not notify global observers.
1505 #[cfg(any(test, feature = "test-support"))]
1506 pub fn clear_globals(&mut self) {
1507 self.globals_by_type.drain();
1508 }
1509
1510 /// Remove the global of the given type from the app context. Does not notify global observers.
1511 pub fn remove_global<G: Global>(&mut self) -> G {
1512 let global_type = TypeId::of::<G>();
1513 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1514 *self
1515 .globals_by_type
1516 .remove(&global_type)
1517 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1518 .downcast()
1519 .unwrap()
1520 }
1521
1522 /// Register a callback to be invoked when a global of the given type is updated.
1523 pub fn observe_global<G: Global>(
1524 &mut self,
1525 mut f: impl FnMut(&mut Self) + 'static,
1526 ) -> Subscription {
1527 let (subscription, activate) = self.global_observers.insert(
1528 TypeId::of::<G>(),
1529 Box::new(move |cx| {
1530 f(cx);
1531 true
1532 }),
1533 );
1534 self.defer(move |_| activate());
1535 subscription
1536 }
1537
1538 /// Move the global of the given type to the stack.
1539 #[track_caller]
1540 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1541 GlobalLease::new(
1542 self.globals_by_type
1543 .remove(&TypeId::of::<G>())
1544 .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1545 .unwrap(),
1546 )
1547 }
1548
1549 /// Restore the global of the given type after it is moved to the stack.
1550 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1551 let global_type = TypeId::of::<G>();
1552
1553 self.push_effect(Effect::NotifyGlobalObservers { global_type });
1554 self.globals_by_type.insert(global_type, lease.global);
1555 }
1556
1557 pub(crate) fn new_entity_observer(
1558 &self,
1559 key: TypeId,
1560 value: NewEntityListener,
1561 ) -> Subscription {
1562 let (subscription, activate) = self.new_entity_observers.insert(key, value);
1563 activate();
1564 subscription
1565 }
1566
1567 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1568 /// The function will be passed a mutable reference to the view along with an appropriate context.
1569 pub fn observe_new<T: 'static>(
1570 &self,
1571 on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1572 ) -> Subscription {
1573 self.new_entity_observer(
1574 TypeId::of::<T>(),
1575 Box::new(
1576 move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1577 any_entity
1578 .downcast::<T>()
1579 .unwrap()
1580 .update(cx, |entity_state, cx| {
1581 on_new(entity_state, window.as_deref_mut(), cx)
1582 })
1583 },
1584 ),
1585 )
1586 }
1587
1588 /// Observe the release of a entity. The callback is invoked after the entity
1589 /// has no more strong references but before it has been dropped.
1590 pub fn observe_release<T>(
1591 &self,
1592 handle: &Entity<T>,
1593 on_release: impl FnOnce(&mut T, &mut App) + 'static,
1594 ) -> Subscription
1595 where
1596 T: 'static,
1597 {
1598 let (subscription, activate) = self.release_listeners.insert(
1599 handle.entity_id(),
1600 Box::new(move |entity, cx| {
1601 let entity = entity.downcast_mut().expect("invalid entity type");
1602 on_release(entity, cx)
1603 }),
1604 );
1605 activate();
1606 subscription
1607 }
1608
1609 /// Observe the release of a entity. The callback is invoked after the entity
1610 /// has no more strong references but before it has been dropped.
1611 pub fn observe_release_in<T>(
1612 &self,
1613 handle: &Entity<T>,
1614 window: &Window,
1615 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1616 ) -> Subscription
1617 where
1618 T: 'static,
1619 {
1620 let window_handle = window.handle;
1621 self.observe_release(handle, move |entity, cx| {
1622 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1623 })
1624 }
1625
1626 /// Register a callback to be invoked when a keystroke is received by the application
1627 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1628 /// and that this API will not be invoked if the event's propagation is stopped.
1629 pub fn observe_keystrokes(
1630 &mut self,
1631 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1632 ) -> Subscription {
1633 fn inner(
1634 keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1635 handler: KeystrokeObserver,
1636 ) -> Subscription {
1637 let (subscription, activate) = keystroke_observers.insert((), handler);
1638 activate();
1639 subscription
1640 }
1641
1642 inner(
1643 &self.keystroke_observers,
1644 Box::new(move |event, window, cx| {
1645 f(event, window, cx);
1646 true
1647 }),
1648 )
1649 }
1650
1651 /// Register a callback to be invoked when a keystroke is received by the application
1652 /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1653 /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1654 /// within interceptors will prevent action dispatch
1655 pub fn intercept_keystrokes(
1656 &mut self,
1657 mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1658 ) -> Subscription {
1659 fn inner(
1660 keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1661 handler: KeystrokeObserver,
1662 ) -> Subscription {
1663 let (subscription, activate) = keystroke_interceptors.insert((), handler);
1664 activate();
1665 subscription
1666 }
1667
1668 inner(
1669 &self.keystroke_interceptors,
1670 Box::new(move |event, window, cx| {
1671 f(event, window, cx);
1672 true
1673 }),
1674 )
1675 }
1676
1677 /// Register key bindings.
1678 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1679 self.keymap.borrow_mut().add_bindings(bindings);
1680 self.pending_effects.push_back(Effect::RefreshWindows);
1681 }
1682
1683 /// Clear all key bindings in the app.
1684 pub fn clear_key_bindings(&mut self) {
1685 self.keymap.borrow_mut().clear();
1686 self.pending_effects.push_back(Effect::RefreshWindows);
1687 }
1688
1689 /// Get all key bindings in the app.
1690 pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1691 self.keymap.clone()
1692 }
1693
1694 /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1695 /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1696 /// handlers or if they called `cx.propagate()`.
1697 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1698 self.global_action_listeners
1699 .entry(TypeId::of::<A>())
1700 .or_default()
1701 .push(Rc::new(move |action, phase, cx| {
1702 if phase == DispatchPhase::Bubble {
1703 let action = action.downcast_ref().unwrap();
1704 listener(action, cx)
1705 }
1706 }));
1707 }
1708
1709 /// Event handlers propagate events by default. Call this method to stop dispatching to
1710 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1711 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1712 /// calling this method before effects are flushed.
1713 pub fn stop_propagation(&mut self) {
1714 self.propagate_event = false;
1715 }
1716
1717 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1718 /// dispatching to action handlers higher in the element tree. This is the opposite of
1719 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1720 /// this method before effects are flushed.
1721 pub fn propagate(&mut self) {
1722 self.propagate_event = true;
1723 }
1724
1725 /// Build an action from some arbitrary data, typically a keymap entry.
1726 pub fn build_action(
1727 &self,
1728 name: &str,
1729 data: Option<serde_json::Value>,
1730 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1731 self.actions.build_action(name, data)
1732 }
1733
1734 /// Get all action names that have been registered. Note that registration only allows for
1735 /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1736 pub fn all_action_names(&self) -> &[&'static str] {
1737 self.actions.all_action_names()
1738 }
1739
1740 /// Returns key bindings that invoke the given action on the currently focused element, without
1741 /// checking context. Bindings are returned in the order they were added. For display, the last
1742 /// binding should take precedence.
1743 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1744 RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1745 }
1746
1747 /// Get all non-internal actions that have been registered, along with their schemas.
1748 pub fn action_schemas(
1749 &self,
1750 generator: &mut schemars::SchemaGenerator,
1751 ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1752 self.actions.action_schemas(generator)
1753 }
1754
1755 /// Get a map from a deprecated action name to the canonical name.
1756 pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1757 self.actions.deprecated_aliases()
1758 }
1759
1760 /// Get a map from an action name to the deprecation messages.
1761 pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1762 self.actions.deprecation_messages()
1763 }
1764
1765 /// Get a map from an action name to the documentation.
1766 pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
1767 self.actions.documentation()
1768 }
1769
1770 /// Register a callback to be invoked when the application is about to quit.
1771 /// It is not possible to cancel the quit event at this point.
1772 pub fn on_app_quit<Fut>(
1773 &self,
1774 mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1775 ) -> Subscription
1776 where
1777 Fut: 'static + Future<Output = ()>,
1778 {
1779 let (subscription, activate) = self.quit_observers.insert(
1780 (),
1781 Box::new(move |cx| {
1782 let future = on_quit(cx);
1783 future.boxed_local()
1784 }),
1785 );
1786 activate();
1787 subscription
1788 }
1789
1790 /// Register a callback to be invoked when the application is about to restart.
1791 ///
1792 /// These callbacks are called before any `on_app_quit` callbacks.
1793 pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
1794 let (subscription, activate) = self.restart_observers.insert(
1795 (),
1796 Box::new(move |cx| {
1797 on_restart(cx);
1798 true
1799 }),
1800 );
1801 activate();
1802 subscription
1803 }
1804
1805 /// Register a callback to be invoked when a window is closed
1806 /// The window is no longer accessible at the point this callback is invoked.
1807 pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1808 let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1809 activate();
1810 subscription
1811 }
1812
1813 pub(crate) fn clear_pending_keystrokes(&mut self) {
1814 for window in self.windows() {
1815 window
1816 .update(self, |_, window, _| {
1817 window.clear_pending_keystrokes();
1818 })
1819 .ok();
1820 }
1821 }
1822
1823 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1824 /// the bindings in the element tree, and any global action listeners.
1825 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1826 let mut action_available = false;
1827 if let Some(window) = self.active_window()
1828 && let Ok(window_action_available) =
1829 window.update(self, |_, window, cx| window.is_action_available(action, cx))
1830 {
1831 action_available = window_action_available;
1832 }
1833
1834 action_available
1835 || self
1836 .global_action_listeners
1837 .contains_key(&action.as_any().type_id())
1838 }
1839
1840 /// Sets the menu bar for this application. This will replace any existing menu bar.
1841 pub fn set_menus(&self, menus: Vec<Menu>) {
1842 self.platform.set_menus(menus, &self.keymap.borrow());
1843 }
1844
1845 /// Gets the menu bar for this application.
1846 pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1847 self.platform.get_menus()
1848 }
1849
1850 /// Sets the right click menu for the app icon in the dock
1851 pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1852 self.platform.set_dock_menu(menus, &self.keymap.borrow())
1853 }
1854
1855 /// Performs the action associated with the given dock menu item, only used on Windows for now.
1856 pub fn perform_dock_menu_action(&self, action: usize) {
1857 self.platform.perform_dock_menu_action(action);
1858 }
1859
1860 /// Adds given path to the bottom of the list of recent paths for the application.
1861 /// The list is usually shown on the application icon's context menu in the dock,
1862 /// and allows to open the recent files via that context menu.
1863 /// If the path is already in the list, it will be moved to the bottom of the list.
1864 pub fn add_recent_document(&self, path: &Path) {
1865 self.platform.add_recent_document(path);
1866 }
1867
1868 /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
1869 /// Note that this also sets the dock menu on Windows.
1870 pub fn update_jump_list(
1871 &self,
1872 menus: Vec<MenuItem>,
1873 entries: Vec<SmallVec<[PathBuf; 2]>>,
1874 ) -> Vec<SmallVec<[PathBuf; 2]>> {
1875 self.platform.update_jump_list(menus, entries)
1876 }
1877
1878 /// Dispatch an action to the currently active window or global action handler
1879 /// See [`crate::Action`] for more information on how actions work
1880 pub fn dispatch_action(&mut self, action: &dyn Action) {
1881 if let Some(active_window) = self.active_window() {
1882 active_window
1883 .update(self, |_, window, cx| {
1884 window.dispatch_action(action.boxed_clone(), cx)
1885 })
1886 .log_err();
1887 } else {
1888 self.dispatch_global_action(action);
1889 }
1890 }
1891
1892 fn dispatch_global_action(&mut self, action: &dyn Action) {
1893 self.propagate_event = true;
1894
1895 if let Some(mut global_listeners) = self
1896 .global_action_listeners
1897 .remove(&action.as_any().type_id())
1898 {
1899 for listener in &global_listeners {
1900 listener(action.as_any(), DispatchPhase::Capture, self);
1901 if !self.propagate_event {
1902 break;
1903 }
1904 }
1905
1906 global_listeners.extend(
1907 self.global_action_listeners
1908 .remove(&action.as_any().type_id())
1909 .unwrap_or_default(),
1910 );
1911
1912 self.global_action_listeners
1913 .insert(action.as_any().type_id(), global_listeners);
1914 }
1915
1916 if self.propagate_event
1917 && let Some(mut global_listeners) = self
1918 .global_action_listeners
1919 .remove(&action.as_any().type_id())
1920 {
1921 for listener in global_listeners.iter().rev() {
1922 listener(action.as_any(), DispatchPhase::Bubble, self);
1923 if !self.propagate_event {
1924 break;
1925 }
1926 }
1927
1928 global_listeners.extend(
1929 self.global_action_listeners
1930 .remove(&action.as_any().type_id())
1931 .unwrap_or_default(),
1932 );
1933
1934 self.global_action_listeners
1935 .insert(action.as_any().type_id(), global_listeners);
1936 }
1937 }
1938
1939 /// Is there currently something being dragged?
1940 pub fn has_active_drag(&self) -> bool {
1941 self.active_drag.is_some()
1942 }
1943
1944 /// Gets the cursor style of the currently active drag operation.
1945 pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
1946 self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
1947 }
1948
1949 /// Stops active drag and clears any related effects.
1950 pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
1951 if self.active_drag.is_some() {
1952 self.active_drag = None;
1953 window.refresh();
1954 true
1955 } else {
1956 false
1957 }
1958 }
1959
1960 /// Sets the cursor style for the currently active drag operation.
1961 pub fn set_active_drag_cursor_style(
1962 &mut self,
1963 cursor_style: CursorStyle,
1964 window: &mut Window,
1965 ) -> bool {
1966 if let Some(ref mut drag) = self.active_drag {
1967 drag.cursor_style = Some(cursor_style);
1968 window.refresh();
1969 true
1970 } else {
1971 false
1972 }
1973 }
1974
1975 /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1976 /// prompts with this custom implementation.
1977 pub fn set_prompt_builder(
1978 &mut self,
1979 renderer: impl Fn(
1980 PromptLevel,
1981 &str,
1982 Option<&str>,
1983 &[PromptButton],
1984 PromptHandle,
1985 &mut Window,
1986 &mut App,
1987 ) -> RenderablePromptHandle
1988 + 'static,
1989 ) {
1990 self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
1991 }
1992
1993 /// Reset the prompt builder to the default implementation.
1994 pub fn reset_prompt_builder(&mut self) {
1995 self.prompt_builder = Some(PromptBuilder::Default);
1996 }
1997
1998 /// Remove an asset from GPUI's cache
1999 pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2000 let asset_id = (TypeId::of::<A>(), hash(source));
2001 self.loading_assets.remove(&asset_id);
2002 }
2003
2004 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2005 ///
2006 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2007 /// time, and the results of this call will be cached
2008 pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2009 let asset_id = (TypeId::of::<A>(), hash(source));
2010 let mut is_first = false;
2011 let task = self
2012 .loading_assets
2013 .remove(&asset_id)
2014 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2015 .unwrap_or_else(|| {
2016 is_first = true;
2017 let future = A::load(source.clone(), self);
2018
2019 self.background_executor().spawn(future).shared()
2020 });
2021
2022 self.loading_assets.insert(asset_id, Box::new(task.clone()));
2023
2024 (task, is_first)
2025 }
2026
2027 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2028 /// for elements rendered within this window.
2029 #[track_caller]
2030 pub fn focus_handle(&self) -> FocusHandle {
2031 FocusHandle::new(&self.focus_handles)
2032 }
2033
2034 /// Tell GPUI that an entity has changed and observers of it should be notified.
2035 pub fn notify(&mut self, entity_id: EntityId) {
2036 let window_invalidators = mem::take(
2037 self.window_invalidators_by_entity
2038 .entry(entity_id)
2039 .or_default(),
2040 );
2041
2042 if window_invalidators.is_empty() {
2043 if self.pending_notifications.insert(entity_id) {
2044 self.pending_effects
2045 .push_back(Effect::Notify { emitter: entity_id });
2046 }
2047 } else {
2048 for invalidator in window_invalidators.values() {
2049 invalidator.invalidate_view(entity_id, self);
2050 }
2051 }
2052
2053 self.window_invalidators_by_entity
2054 .insert(entity_id, window_invalidators);
2055 }
2056
2057 /// Returns the name for this [`App`].
2058 #[cfg(any(test, feature = "test-support", debug_assertions))]
2059 pub fn get_name(&self) -> Option<&'static str> {
2060 self.name
2061 }
2062
2063 /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2064 pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2065 self.platform.can_select_mixed_files_and_dirs()
2066 }
2067
2068 /// Removes an image from the sprite atlas on all windows.
2069 ///
2070 /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2071 /// This is a no-op if the image is not in the sprite atlas.
2072 pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2073 // remove the texture from all other windows
2074 for window in self.windows.values_mut().flatten() {
2075 _ = window.drop_image(image.clone());
2076 }
2077
2078 // remove the texture from the current window
2079 if let Some(window) = current_window {
2080 _ = window.drop_image(image);
2081 }
2082 }
2083
2084 /// Sets the renderer for the inspector.
2085 #[cfg(any(feature = "inspector", debug_assertions))]
2086 pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2087 self.inspector_renderer = Some(f);
2088 }
2089
2090 /// Registers a renderer specific to an inspector state.
2091 #[cfg(any(feature = "inspector", debug_assertions))]
2092 pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2093 &mut self,
2094 f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2095 ) {
2096 self.inspector_element_registry.register(f);
2097 }
2098
2099 /// Initializes gpui's default colors for the application.
2100 ///
2101 /// These colors can be accessed through `cx.default_colors()`.
2102 pub fn init_colors(&mut self) {
2103 self.set_global(GlobalColors(Arc::new(Colors::default())));
2104 }
2105}
2106
2107impl AppContext for App {
2108 type Result<T> = T;
2109
2110 /// Builds an entity that is owned by the application.
2111 ///
2112 /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2113 /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2114 fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2115 self.update(|cx| {
2116 let slot = cx.entities.reserve();
2117 let handle = slot.clone();
2118 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2119
2120 cx.push_effect(Effect::EntityCreated {
2121 entity: handle.clone().into_any(),
2122 tid: TypeId::of::<T>(),
2123 window: cx.window_update_stack.last().cloned(),
2124 });
2125
2126 cx.entities.insert(slot, entity);
2127 handle
2128 })
2129 }
2130
2131 fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
2132 Reservation(self.entities.reserve())
2133 }
2134
2135 fn insert_entity<T: 'static>(
2136 &mut self,
2137 reservation: Reservation<T>,
2138 build_entity: impl FnOnce(&mut Context<T>) -> T,
2139 ) -> Self::Result<Entity<T>> {
2140 self.update(|cx| {
2141 let slot = reservation.0;
2142 let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2143 cx.entities.insert(slot, entity)
2144 })
2145 }
2146
2147 /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2148 /// entity along with a `Context` for the entity.
2149 fn update_entity<T: 'static, R>(
2150 &mut self,
2151 handle: &Entity<T>,
2152 update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2153 ) -> R {
2154 self.update(|cx| {
2155 let mut entity = cx.entities.lease(handle);
2156 let result = update(
2157 &mut entity,
2158 &mut Context::new_context(cx, handle.downgrade()),
2159 );
2160 cx.entities.end_lease(entity);
2161 result
2162 })
2163 }
2164
2165 fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2166 where
2167 T: 'static,
2168 {
2169 GpuiBorrow::new(handle.clone(), self)
2170 }
2171
2172 fn read_entity<T, R>(
2173 &self,
2174 handle: &Entity<T>,
2175 read: impl FnOnce(&T, &App) -> R,
2176 ) -> Self::Result<R>
2177 where
2178 T: 'static,
2179 {
2180 let entity = self.entities.read(handle);
2181 read(entity, self)
2182 }
2183
2184 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2185 where
2186 F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2187 {
2188 self.update_window_id(handle.id, update)
2189 }
2190
2191 fn read_window<T, R>(
2192 &self,
2193 window: &WindowHandle<T>,
2194 read: impl FnOnce(Entity<T>, &App) -> R,
2195 ) -> Result<R>
2196 where
2197 T: 'static,
2198 {
2199 let window = self
2200 .windows
2201 .get(window.id)
2202 .context("window not found")?
2203 .as_ref()
2204 .expect("attempted to read a window that is already on the stack");
2205
2206 let root_view = window.root.clone().unwrap();
2207 let view = root_view
2208 .downcast::<T>()
2209 .map_err(|_| anyhow!("root view's type has changed"))?;
2210
2211 Ok(read(view, self))
2212 }
2213
2214 fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2215 where
2216 R: Send + 'static,
2217 {
2218 self.background_executor.spawn(future)
2219 }
2220
2221 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
2222 where
2223 G: Global,
2224 {
2225 let mut g = self.global::<G>();
2226 callback(g, self)
2227 }
2228}
2229
2230/// These effects are processed at the end of each application update cycle.
2231pub(crate) enum Effect {
2232 Notify {
2233 emitter: EntityId,
2234 },
2235 Emit {
2236 emitter: EntityId,
2237 event_type: TypeId,
2238 event: Box<dyn Any>,
2239 },
2240 RefreshWindows,
2241 NotifyGlobalObservers {
2242 global_type: TypeId,
2243 },
2244 Defer {
2245 callback: Box<dyn FnOnce(&mut App) + 'static>,
2246 },
2247 EntityCreated {
2248 entity: AnyEntity,
2249 tid: TypeId,
2250 window: Option<WindowId>,
2251 },
2252}
2253
2254impl std::fmt::Debug for Effect {
2255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2256 match self {
2257 Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2258 Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2259 Effect::RefreshWindows => write!(f, "RefreshWindows"),
2260 Effect::NotifyGlobalObservers { global_type } => {
2261 write!(f, "NotifyGlobalObservers({:?})", global_type)
2262 }
2263 Effect::Defer { .. } => write!(f, "Defer(..)"),
2264 Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2265 }
2266 }
2267}
2268
2269/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2270pub(crate) struct GlobalLease<G: Global> {
2271 global: Box<dyn Any>,
2272 global_type: PhantomData<G>,
2273}
2274
2275impl<G: Global> GlobalLease<G> {
2276 fn new(global: Box<dyn Any>) -> Self {
2277 GlobalLease {
2278 global,
2279 global_type: PhantomData,
2280 }
2281 }
2282}
2283
2284impl<G: Global> Deref for GlobalLease<G> {
2285 type Target = G;
2286
2287 fn deref(&self) -> &Self::Target {
2288 self.global.downcast_ref().unwrap()
2289 }
2290}
2291
2292impl<G: Global> DerefMut for GlobalLease<G> {
2293 fn deref_mut(&mut self) -> &mut Self::Target {
2294 self.global.downcast_mut().unwrap()
2295 }
2296}
2297
2298/// Contains state associated with an active drag operation, started by dragging an element
2299/// within the window or by dragging into the app from the underlying platform.
2300pub struct AnyDrag {
2301 /// The view used to render this drag
2302 pub view: AnyView,
2303
2304 /// The value of the dragged item, to be dropped
2305 pub value: Arc<dyn Any>,
2306
2307 /// This is used to render the dragged item in the same place
2308 /// on the original element that the drag was initiated
2309 pub cursor_offset: Point<Pixels>,
2310
2311 /// The cursor style to use while dragging
2312 pub cursor_style: Option<CursorStyle>,
2313}
2314
2315/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2316/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2317#[derive(Clone)]
2318pub struct AnyTooltip {
2319 /// The view used to display the tooltip
2320 pub view: AnyView,
2321
2322 /// The absolute position of the mouse when the tooltip was deployed.
2323 pub mouse_position: Point<Pixels>,
2324
2325 /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2326 /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2327 /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2328 pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2329}
2330
2331/// A keystroke event, and potentially the associated action
2332#[derive(Debug)]
2333pub struct KeystrokeEvent {
2334 /// The keystroke that occurred
2335 pub keystroke: Keystroke,
2336
2337 /// The action that was resolved for the keystroke, if any
2338 pub action: Option<Box<dyn Action>>,
2339
2340 /// The context stack at the time
2341 pub context_stack: Vec<KeyContext>,
2342}
2343
2344struct NullHttpClient;
2345
2346impl HttpClient for NullHttpClient {
2347 fn send(
2348 &self,
2349 _req: http_client::Request<http_client::AsyncBody>,
2350 ) -> futures::future::BoxFuture<
2351 'static,
2352 anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2353 > {
2354 async move {
2355 anyhow::bail!("No HttpClient available");
2356 }
2357 .boxed()
2358 }
2359
2360 fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2361 None
2362 }
2363
2364 fn proxy(&self) -> Option<&Url> {
2365 None
2366 }
2367
2368 fn type_name(&self) -> &'static str {
2369 type_name::<Self>()
2370 }
2371}
2372
2373/// A mutable reference to an entity owned by GPUI
2374pub struct GpuiBorrow<'a, T> {
2375 inner: Option<Lease<T>>,
2376 app: &'a mut App,
2377}
2378
2379impl<'a, T: 'static> GpuiBorrow<'a, T> {
2380 fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2381 app.start_update();
2382 let lease = app.entities.lease(&inner);
2383 Self {
2384 inner: Some(lease),
2385 app,
2386 }
2387 }
2388}
2389
2390impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2391 fn borrow(&self) -> &T {
2392 self.inner.as_ref().unwrap().borrow()
2393 }
2394}
2395
2396impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2397 fn borrow_mut(&mut self) -> &mut T {
2398 self.inner.as_mut().unwrap().borrow_mut()
2399 }
2400}
2401
2402impl<'a, T> Drop for GpuiBorrow<'a, T> {
2403 fn drop(&mut self) {
2404 let lease = self.inner.take().unwrap();
2405 self.app.notify(lease.id);
2406 self.app.entities.end_lease(lease);
2407 self.app.finish_update();
2408 }
2409}
2410
2411#[cfg(test)]
2412mod test {
2413 use std::{cell::RefCell, rc::Rc};
2414
2415 use crate::{AppContext, TestAppContext};
2416
2417 #[test]
2418 fn test_gpui_borrow() {
2419 let cx = TestAppContext::single();
2420 let observation_count = Rc::new(RefCell::new(0));
2421
2422 let state = cx.update(|cx| {
2423 let state = cx.new(|_| false);
2424 cx.observe(&state, {
2425 let observation_count = observation_count.clone();
2426 move |_, _| {
2427 let mut count = observation_count.borrow_mut();
2428 *count += 1;
2429 }
2430 })
2431 .detach();
2432
2433 state
2434 });
2435
2436 cx.update(|cx| {
2437 // Calling this like this so that we don't clobber the borrow_mut above
2438 *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2439 });
2440
2441 cx.update(|cx| {
2442 state.write(cx, false);
2443 });
2444
2445 assert_eq!(*observation_count.borrow(), 2);
2446 }
2447}