Skip to main content

gpui/
app.rs

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