Skip to main content

gpui/
app.rs

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