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