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