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