Skip to main content

gpui/
app.rs

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