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        platform.on_system_sleep(Box::new({
1148            let app = Rc::downgrade(&app);
1149            move || {
1150                if let Some(app) = app.upgrade() {
1151                    let cx = &mut app.borrow_mut();
1152                    cx.system_sleep_observers
1153                        .clone()
1154                        .retain(move |callback| (callback)(cx));
1155                }
1156            }
1157        }));
1158
1159        platform.on_system_wake(Box::new({
1160            let app = Rc::downgrade(&app);
1161            move || {
1162                if let Some(app) = app.upgrade() {
1163                    let cx = &mut app.borrow_mut();
1164                    cx.system_wake_observers
1165                        .clone()
1166                        .retain(move |callback| (callback)(cx));
1167                }
1168            }
1169        }));
1170
1171        platform.on_app_lifecycle(Box::new({
1172            let app = Rc::downgrade(&app);
1173            move |phase| {
1174                if let Some(app) = app.upgrade() {
1175                    app.borrow_mut().update(|cx| {
1176                        cx.app_lifecycle_observers
1177                            .clone()
1178                            .retain(|callback| callback(phase, cx));
1179                    });
1180                }
1181            }
1182        }));
1183
1184        platform.on_memory_warning(Box::new({
1185            let app = Rc::downgrade(&app);
1186            move || {
1187                if let Some(app) = app.upgrade() {
1188                    app.borrow_mut().update(|cx| {
1189                        cx.memory_warning_observers
1190                            .clone()
1191                            .retain(|callback| callback(cx));
1192                    });
1193                }
1194            }
1195        }));
1196
1197        platform.on_power_mode_change(Box::new({
1198            let app = Rc::downgrade(&app);
1199            move || {
1200                if let Some(app) = app.upgrade() {
1201                    let power_mode = app.borrow().platform.power_mode();
1202                    app.borrow_mut().power_mode = power_mode;
1203                }
1204            }
1205        }));
1206
1207        platform.on_quit(Box::new({
1208            let cx = Rc::downgrade(&app);
1209            move || {
1210                let Some(cx) = cx.upgrade() else {
1211                    return true;
1212                };
1213                match cx.try_borrow_mut() {
1214                    Ok(mut cx) => {
1215                        cx.shutdown();
1216                        true
1217                    }
1218                    Err(_) => {
1219                        // Quit was requested while the AppCell was borrowed, so we can't shut down synchronously.
1220                        // The platform decides how to proceed.
1221                        false
1222                    }
1223                }
1224            }
1225        }));
1226
1227        app
1228    }
1229
1230    #[doc(hidden)]
1231    pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1232        self.entities.ref_counts_drop_handle()
1233    }
1234
1235    /// Captures a snapshot of all entities that currently have alive handles.
1236    ///
1237    /// The returned [`LeakDetectorSnapshot`] can later be passed to
1238    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
1239    /// entities created after the snapshot are still alive.
1240    #[cfg(any(test, gpui_leak_detection))]
1241    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1242        self.entities.leak_detector_snapshot()
1243    }
1244
1245    /// Asserts that no entities created after `snapshot` still have alive handles.
1246    ///
1247    /// Entities that were already tracked at the time of the snapshot are ignored,
1248    /// even if they still have handles. Only *new* entities (those whose
1249    /// `EntityId` was not present in the snapshot) are considered leaks.
1250    ///
1251    /// # Panics
1252    ///
1253    /// Panics if any new entity handles exist. The panic message lists every
1254    /// leaked entity with its type name, and includes allocation-site backtraces
1255    /// when `LEAK_BACKTRACE` is set.
1256    #[cfg(any(test, gpui_leak_detection))]
1257    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1258        self.entities.assert_no_new_leaks(snapshot)
1259    }
1260
1261    /// Without leak detection compiled in, this records nothing.
1262    #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1263    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1264        LeakDetectorSnapshot::default()
1265    }
1266
1267    /// Without leak detection compiled in, this checks nothing. Set
1268    /// `GPUI_LEAK_DETECTION` when building to enable it.
1269    #[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
1270    pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
1271
1272    /// Quit the application gracefully.
1273    ///
1274    /// Native applications give handlers registered with [`Context::on_app_quit`]
1275    /// [`SHUTDOWN_TIMEOUT`] to complete. WebAssembly runs them asynchronously as best-effort cleanup
1276    /// because its event-loop thread cannot block.
1277    pub fn shutdown(&mut self) {
1278        // Requested first so the final hang poll overlaps with the quit
1279        // handlers. It's awaited alongside them, within `SHUTDOWN_TIMEOUT`.
1280        #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1281        let hang_monitor_flush = self
1282            .hang_monitor
1283            .as_ref()
1284            .and_then(|hang_monitor| hang_monitor.request_flush());
1285
1286        let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
1287
1288        for observer in self.quit_observers.remove() {
1289            futures.push(observer(self));
1290        }
1291
1292        #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
1293        if let Some(flushed) = hang_monitor_flush {
1294            futures.push(
1295                async move {
1296                    if flushed.await.is_err() {
1297                        log::warn!("hang monitor exited before flushing");
1298                    }
1299                }
1300                .boxed_local(),
1301            );
1302        }
1303
1304        self.windows.clear();
1305        self.window_handles.clear();
1306        self.flush_effects();
1307        self.quitting = true;
1308
1309        let futures = futures::future::join_all(futures);
1310        #[cfg(not(target_family = "wasm"))]
1311        if self
1312            .foreground_executor
1313            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1314            .is_err()
1315        {
1316            log::error!("timed out waiting on app_will_quit");
1317        }
1318        #[cfg(target_family = "wasm")]
1319        self.foreground_executor.spawn(futures).detach();
1320
1321        self.quitting = false;
1322    }
1323
1324    /// Get the id of the current keyboard layout
1325    pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1326        self.keyboard_layout.as_ref()
1327    }
1328
1329    /// Get the current keyboard mapper.
1330    pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1331        &self.keyboard_mapper
1332    }
1333
1334    /// Invokes a handler when the current keyboard layout changes
1335    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1336    where
1337        F: 'static + FnMut(&mut App),
1338    {
1339        self.keyboard_layout_observers.insert(Box::new(move |cx| {
1340            callback(cx);
1341            true
1342        }))
1343    }
1344
1345    /// Gracefully quit the application via the platform's standard routine.
1346    pub fn quit(&self) {
1347        self.platform.quit();
1348    }
1349
1350    /// Switches the platform between headless and windowed modes.
1351    ///
1352    /// On Linux, headless means no display server: windows opened afterwards lay out and handle
1353    /// input but draw nothing. Windowed, the platform connects to the display server the
1354    /// environment names. On macOS, the modes set the [`ActivationPolicy`]: headless is
1355    /// `Accessory` (no Dock icon or menu bar) and windowed is `Regular`. Switching to windowed
1356    /// doesn't activate the app: call [`App::activate`] for that.
1357    ///
1358    /// The returned task resolves once the switch has been applied. It fails if the platform is
1359    /// already in the requested mode (switching to another display server means going headless
1360    /// first), if the platform doesn't allow the mode or can't switch at all, if any window is
1361    /// open (a window belongs to the display server that opened it), or if the display server
1362    /// can't be reached.
1363    pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
1364        if !self.windows.is_empty() {
1365            return Task::ready(Err(anyhow::anyhow!(
1366                "cannot switch windowing modes while windows are open"
1367            )));
1368        }
1369        self.platform.request_windowing(request)
1370    }
1371
1372    /// The environment of the display server the platform is connected to, or `None` while
1373    /// headless. Its activation token is always unset, since the connection has used it.
1374    ///
1375    /// Programs an app launches inherit this process's environment, which may name another
1376    /// graphical session, or none if the app started headless. Pass them this one with
1377    /// [`GraphicalEnvironment::apply_to`](crate::GraphicalEnvironment::apply_to).
1378    ///
1379    /// On macOS, the environment carries nothing, and this is `None` while the activation
1380    /// policy is `Accessory`. Always `None` on platforms that can't switch windowing modes.
1381    pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
1382        self.platform.graphical_environment()
1383    }
1384
1385    /// Returns the current policy for hiding the cursor in response to
1386    /// keyboard input.
1387    pub fn cursor_hide_mode(&self) -> CursorHideMode {
1388        self.cursor_hide_mode
1389    }
1390
1391    /// Sets the policy controlling when GPUI hides the cursor in response
1392    /// to keyboard input.
1393    pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1394        self.cursor_hide_mode = mode;
1395    }
1396
1397    /// Returns whether the cursor is currently visible according to the
1398    /// platform. This will report `false` after a keyboard input has hidden
1399    /// the cursor and the user has not yet moved the mouse to restore it.
1400    ///
1401    /// See [`App::set_cursor_hide_mode`].
1402    pub fn is_cursor_visible(&self) -> bool {
1403        self.platform.is_cursor_visible()
1404    }
1405
1406    /// Returns whether non-essential animations (e.g. loading spinners) should
1407    /// be rendered in a static state instead of animating.
1408    pub fn reduce_motion(&self) -> bool {
1409        self.reduce_motion
1410    }
1411
1412    /// Sets whether non-essential animations (e.g. loading spinners) should be
1413    /// rendered in a static state instead of animating.
1414    pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1415        if self.reduce_motion != reduce_motion {
1416            self.reduce_motion = reduce_motion;
1417            self.refresh_windows();
1418        }
1419    }
1420
1421    /// Schedules all windows in the application to be redrawn. This can be called
1422    /// multiple times in an update cycle and still result in a single redraw.
1423    pub fn refresh_windows(&mut self) {
1424        self.pending_effects.push_back(Effect::RefreshWindows);
1425    }
1426
1427    #[inline(always)]
1428    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1429        self.start_update();
1430        let result = update(self);
1431        self.finish_update();
1432        result
1433    }
1434
1435    pub(crate) fn start_update(&mut self) {
1436        self.pending_updates += 1;
1437    }
1438
1439    #[inline(never)]
1440    pub(crate) fn finish_update(&mut self) {
1441        if self.pending_updates == 1 {
1442            self.flush_effects();
1443        }
1444        self.pending_updates -= 1;
1445    }
1446
1447    /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
1448    pub fn observe<W>(
1449        &mut self,
1450        entity: &Entity<W>,
1451        mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1452    ) -> Subscription
1453    where
1454        W: 'static,
1455    {
1456        self.observe_internal(entity, move |e, cx| {
1457            on_notify(e, cx);
1458            true
1459        })
1460    }
1461
1462    pub(crate) fn detect_accessed_entities<R>(
1463        &mut self,
1464        callback: impl FnOnce(&mut App) -> R,
1465    ) -> (R, FxHashSet<EntityId>) {
1466        self.entities.push_access_scope();
1467        let result = callback(self);
1468        (result, self.entities.pop_access_scope())
1469    }
1470
1471    pub(crate) fn record_entities_accessed(
1472        &mut self,
1473        window_handle: AnyWindowHandle,
1474        invalidator: WindowInvalidator,
1475        entities: &FxHashSet<EntityId>,
1476    ) {
1477        let mut tracked_entities =
1478            std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1479        for entity in tracked_entities.iter() {
1480            self.window_invalidators_by_entity
1481                .entry(*entity)
1482                .and_modify(|windows| {
1483                    windows.remove(&window_handle.id);
1484                });
1485        }
1486        for entity in entities.iter() {
1487            self.window_invalidators_by_entity
1488                .entry(*entity)
1489                .or_default()
1490                .insert(window_handle.id, invalidator.clone());
1491            self.current_window_by_entity
1492                .insert(*entity, window_handle.id);
1493        }
1494        tracked_entities.clear();
1495        tracked_entities.extend(entities.iter().copied());
1496        self.tracked_entities
1497            .insert(window_handle.id, tracked_entities);
1498    }
1499
1500    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1501        let (subscription, activate) = self.observers.insert_pending(key, value);
1502        self.defer(move |_| activate());
1503        subscription
1504    }
1505
1506    pub(crate) fn observe_internal<W>(
1507        &mut self,
1508        entity: &Entity<W>,
1509        mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1510    ) -> Subscription
1511    where
1512        W: 'static,
1513    {
1514        let entity_id = entity.entity_id();
1515        let handle = entity.downgrade();
1516        self.new_observer(
1517            entity_id,
1518            Box::new(move |cx| {
1519                if let Some(entity) = handle.upgrade() {
1520                    on_notify(entity, cx)
1521                } else {
1522                    false
1523                }
1524            }),
1525        )
1526    }
1527
1528    /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
1529    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
1530    pub fn subscribe<T, Event>(
1531        &mut self,
1532        entity: &Entity<T>,
1533        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1534    ) -> Subscription
1535    where
1536        T: 'static + EventEmitter<Event>,
1537        Event: 'static,
1538    {
1539        self.subscribe_internal(entity, move |entity, event, cx| {
1540            on_event(entity, event, cx);
1541            true
1542        })
1543    }
1544
1545    pub(crate) fn new_subscription(
1546        &mut self,
1547        key: EntityId,
1548        value: (TypeId, Listener),
1549    ) -> Subscription {
1550        let (subscription, activate) = self.event_listeners.insert_pending(key, value);
1551        self.defer(move |_| activate());
1552        subscription
1553    }
1554    pub(crate) fn subscribe_internal<T, Evt>(
1555        &mut self,
1556        entity: &Entity<T>,
1557        mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1558    ) -> Subscription
1559    where
1560        T: 'static + EventEmitter<Evt>,
1561        Evt: 'static,
1562    {
1563        let entity_id = entity.entity_id();
1564        let handle = entity.downgrade();
1565        self.new_subscription(
1566            entity_id,
1567            (
1568                TypeId::of::<Evt>(),
1569                Box::new(move |event, cx| {
1570                    let event: &Evt = event.downcast_ref().expect("invalid event type");
1571                    if let Some(entity) = handle.upgrade() {
1572                        on_event(entity, event, cx)
1573                    } else {
1574                        false
1575                    }
1576                }),
1577            ),
1578        )
1579    }
1580
1581    /// Returns handles to all open windows in the application.
1582    /// Each handle could be downcast to a handle typed for the root view of that window.
1583    /// To find all windows of a given type, you could filter on
1584    pub fn windows(&self) -> Vec<AnyWindowHandle> {
1585        self.windows
1586            .keys()
1587            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1588            .collect()
1589    }
1590
1591    /// Returns the window handles ordered by their appearance on screen, front to back.
1592    ///
1593    /// The first window in the returned list is the active/topmost window of the application.
1594    ///
1595    /// This method returns None if the platform doesn't implement the method yet.
1596    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1597        self.platform.window_stack()
1598    }
1599
1600    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
1601    pub fn active_window(&self) -> Option<AnyWindowHandle> {
1602        self.platform.active_window()
1603    }
1604
1605    /// Opens a new window with the given option and the root view returned by the given function.
1606    /// The function is invoked with a `Window`, which can be used to interact with window-specific
1607    /// functionality.
1608    pub fn open_window<V: 'static + Render>(
1609        &mut self,
1610        options: crate::WindowOptions,
1611        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1612    ) -> anyhow::Result<WindowHandle<V>> {
1613        self.update(|cx| {
1614            let id = cx.windows.insert(None);
1615            let handle = WindowHandle::new(id);
1616            match Window::new(handle.into(), options, cx) {
1617                Ok(mut window) => {
1618                    cx.window_update_stack.push(id);
1619                    let root_view = build_root_view(&mut window, cx);
1620                    cx.window_update_stack.pop();
1621                    window.root.replace(root_view.into());
1622                    window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1623
1624                    // allow a window to draw at least once before returning
1625                    // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
1626                    // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
1627                    // where DispatchTree::root_node_id asserts on empty nodes
1628                    let clear = window.draw(cx);
1629                    clear.clear(cx);
1630
1631                    cx.window_handles.insert(id, window.handle);
1632                    cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1633                    Ok(handle)
1634                }
1635                Err(e) => {
1636                    cx.windows.remove(id);
1637                    Err(e)
1638                }
1639            }
1640        })
1641    }
1642
1643    /// Instructs the platform to activate the application by bringing it to the foreground.
1644    pub fn activate(&self, ignoring_other_apps: bool) {
1645        self.platform.activate(ignoring_other_apps);
1646    }
1647
1648    /// Hide the application at the platform level.
1649    pub fn hide(&self) {
1650        self.platform.hide();
1651    }
1652
1653    /// Hide other applications at the platform level.
1654    pub fn hide_other_apps(&self) {
1655        self.platform.hide_other_apps();
1656    }
1657
1658    /// Unhide other applications at the platform level.
1659    pub fn unhide_other_apps(&self) {
1660        self.platform.unhide_other_apps();
1661    }
1662
1663    /// Returns the list of currently active displays.
1664    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1665        self.platform.displays()
1666    }
1667
1668    /// Returns the primary display that will be used for new windows.
1669    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1670        self.platform.primary_display()
1671    }
1672
1673    /// Returns whether `screen_capture_sources` may work.
1674    pub fn is_screen_capture_supported(&self) -> bool {
1675        self.platform.is_screen_capture_supported()
1676    }
1677
1678    /// Returns a list of available screen capture sources.
1679    pub fn screen_capture_sources(
1680        &self,
1681    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1682        self.platform.screen_capture_sources()
1683    }
1684
1685    /// Returns the display with the given ID, if one exists.
1686    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1687        self.displays()
1688            .iter()
1689            .find(|display| display.id() == id)
1690            .cloned()
1691    }
1692
1693    /// Returns the current thermal state of the system.
1694    pub fn thermal_state(&self) -> ThermalState {
1695        self.platform.thermal_state()
1696    }
1697
1698    /// Prevents idle sleep while the returned guard is held.
1699    pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
1700        self.platform.prevent_idle_sleep(reason)
1701    }
1702
1703    /// Invokes a handler when the thermal state changes
1704    pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1705    where
1706        F: 'static + FnMut(&mut App),
1707    {
1708        self.thermal_state_observers.insert(Box::new(move |cx| {
1709            callback(cx);
1710            true
1711        }))
1712    }
1713
1714    /// Invokes a handler when the system is about to sleep.
1715    ///
1716    /// The platform gives the process only a short time before suspending, so
1717    /// handlers should record state or cancel work rather than start it.
1718    pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
1719    where
1720        F: 'static + FnMut(&mut App),
1721    {
1722        self.system_sleep_observers.insert(Box::new(move |cx| {
1723            callback(cx);
1724            true
1725        }))
1726    }
1727
1728    pub(crate) fn displays_changed(&mut self) {
1729        let current = read_displays(self.platform.as_ref());
1730        let events = display_events(&self.displays, &current);
1731        self.displays = current;
1732        for event in &events {
1733            let DisplayEvent::Changed { id, .. } = *event else {
1734                continue;
1735            };
1736            for handle in self.windows() {
1737                self.update_window(handle, |_, window, cx| {
1738                    if window.display_id == Some(id) {
1739                        window.notify_display_observers(cx);
1740                    }
1741                })
1742                .log_err();
1743            }
1744        }
1745        for event in events {
1746            self.display_observers
1747                .clone()
1748                .retain(|callback| (callback)(event, self));
1749        }
1750    }
1751
1752    pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
1753        self.displays.contains_key(&id)
1754    }
1755
1756    /// The refresh interval of a connected display, as of the platform's last
1757    /// display change notification.
1758    pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
1759        self.displays.get(&id)?.refresh_interval
1760    }
1761
1762    /// Invokes a handler when a display is connected, disconnected, or its
1763    /// properties change.
1764    pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
1765    where
1766        F: 'static + FnMut(DisplayEvent, &mut App),
1767    {
1768        self.display_observers.insert(Box::new(move |event, cx| {
1769            callback(event, cx);
1770            true
1771        }))
1772    }
1773
1774    /// Invokes a handler when the system wakes from sleep.
1775    pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
1776    where
1777        F: 'static + FnMut(&mut App),
1778    {
1779        self.system_wake_observers.insert(Box::new(move |cx| {
1780            callback(cx);
1781            true
1782        }))
1783    }
1784
1785    /// Observes mobile application lifecycle changes. Desktop platforms do not
1786    /// emit these events. On iOS these currently describe the single connected
1787    /// scene, not individual windows.
1788    ///
1789    /// Save important changes incrementally: neither disconnection nor quit is
1790    /// guaranteed before the system terminates a backgrounded application.
1791    /// Dropping the returned subscription removes the observer.
1792    pub fn on_app_lifecycle(
1793        &self,
1794        mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
1795    ) -> Subscription {
1796        self.app_lifecycle_observers
1797            .insert(Box::new(move |phase, cx| {
1798                callback(phase, cx);
1799                true
1800            }))
1801    }
1802
1803    /// Observes mobile memory-pressure warnings so applications can release
1804    /// expendable caches. Dropping the subscription removes the observer.
1805    pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
1806        self.memory_warning_observers.insert(Box::new(move |cx| {
1807            callback(cx);
1808            true
1809        }))
1810    }
1811
1812    /// Returns the appearance of the application's windows.
1813    pub fn window_appearance(&self) -> WindowAppearance {
1814        self.platform.window_appearance()
1815    }
1816
1817    /// Overrides the appearance (light/dark) applied to the app's windows, independent of
1818    /// the OS-wide setting. Pass `None` to clear the override and follow the system again.
1819    /// The current value is reported by [`App::window_appearance`].
1820    ///
1821    /// On macOS this sets the underlying `NSApplication.appearance`, which controls the
1822    /// native window chrome (the window border and titlebar) of every window. Use this
1823    /// when the app uses a dark theme while the system is in light mode (or vice versa)
1824    /// so the window edges render to match the theme. While an appearance is forced,
1825    /// windows stop tracking system light/dark changes; pass `None` to resume following
1826    /// the system. On other platforms this is a no-op.
1827    pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
1828        self.platform.set_window_appearance(appearance);
1829    }
1830
1831    /// Returns the window button layout configuration when supported.
1832    pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1833        self.platform.button_layout()
1834    }
1835
1836    /// Reads data from the platform clipboard.
1837    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1838        self.platform.read_from_clipboard()
1839    }
1840
1841    /// Reads data from the platform clipboard, resolving once the contents
1842    /// are available.
1843    ///
1844    /// Prefer this over [`App::read_from_clipboard`] in code that can await:
1845    /// on platforms where clipboard access is asynchronous and
1846    /// permission-gated (e.g. web), the synchronous read always returns
1847    /// `None` while this method performs a real read.
1848    pub fn read_from_clipboard_async(
1849        &self,
1850    ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
1851        self.platform.read_from_clipboard_async()
1852    }
1853
1854    /// Sets the text rendering mode for the application.
1855    pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1856        self.text_rendering_mode.set(mode);
1857    }
1858
1859    /// Returns the current text rendering mode for the application.
1860    pub fn text_rendering_mode(&self) -> TextRenderingMode {
1861        self.text_rendering_mode.get()
1862    }
1863
1864    /// Returns the operating system's power mode, or [`PowerMode::Unknown`]
1865    /// when the platform cannot determine it.
1866    pub fn power_mode(&self) -> PowerMode {
1867        self.power_mode
1868    }
1869
1870    /// Writes data to the platform clipboard.
1871    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1872        self.platform.write_to_clipboard(item)
1873    }
1874
1875    /// Reads data from the primary selection buffer.
1876    /// Only available on Linux.
1877    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1878    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1879        self.platform.read_from_primary()
1880    }
1881
1882    /// Writes data to the primary selection buffer.
1883    /// Only available on Linux.
1884    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1885    pub fn write_to_primary(&self, item: ClipboardItem) {
1886        self.platform.write_to_primary(item)
1887    }
1888
1889    /// Reads data from macOS's "Find" pasteboard.
1890    ///
1891    /// Used to share the current search string between apps.
1892    ///
1893    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1894    #[cfg(target_os = "macos")]
1895    pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1896        self.platform.read_from_find_pasteboard()
1897    }
1898
1899    /// Writes data to macOS's "Find" pasteboard.
1900    ///
1901    /// Used to share the current search string between apps.
1902    ///
1903    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1904    #[cfg(target_os = "macos")]
1905    pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1906        self.platform.write_to_find_pasteboard(item)
1907    }
1908
1909    /// Writes credentials to the platform keychain.
1910    pub fn write_credentials(
1911        &self,
1912        url: &str,
1913        username: &str,
1914        password: &[u8],
1915    ) -> Task<Result<()>> {
1916        self.platform.write_credentials(url, username, password)
1917    }
1918
1919    /// Atomically writes credentials unless an item with this URL and username exists.
1920    ///
1921    /// Returns `true` if written, or `false` if the existing item was left unchanged.
1922    ///
1923    /// # Errors
1924    ///
1925    /// Returns an error if Keychain access fails or the platform lacks support.
1926    #[cfg(target_os = "macos")]
1927    pub fn write_credentials_if_not_exists(
1928        &self,
1929        url: &str,
1930        username: &str,
1931        password: &[u8],
1932    ) -> Task<Result<bool>> {
1933        self.platform
1934            .write_credentials_if_not_exists(url, username, password)
1935    }
1936
1937    /// Reads credentials from the platform keychain.
1938    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1939        self.platform.read_credentials(url)
1940    }
1941
1942    /// Deletes credentials from the platform keychain.
1943    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1944        self.platform.delete_credentials(url)
1945    }
1946
1947    /// Directs the platform's default browser to open the given URL.
1948    pub fn open_url(&self, url: &str) {
1949        self.platform.open_url(url);
1950    }
1951
1952    /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
1953    /// opened by the current app.
1954    ///
1955    /// On some platforms (e.g. macOS) you may be able to register URL schemes
1956    /// as part of app distribution, but this method exists to let you register
1957    /// schemes at runtime.
1958    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1959        self.platform.register_url_scheme(scheme)
1960    }
1961
1962    /// Sets the application's process-wide identity and user-visible name.
1963    ///
1964    /// The identifier is used for platform identity mechanisms such as the
1965    /// Windows AppUserModelID. The name is used wherever the operating system
1966    /// presents the application to the user. Call this once, early in startup,
1967    /// before opening windows or posting notifications.
1968    pub fn set_app_identity(&self, identifier: &str, name: &str) {
1969        self.platform.set_app_identity(identifier, name);
1970    }
1971
1972    /// Posts a notification to the operating system's notification center.
1973    ///
1974    /// Posting a notification whose [`SystemNotification::tag`] matches an
1975    /// earlier one replaces that notification where the platform supports it.
1976    /// No-op on platforms without notification support, or when delivery is
1977    /// unavailable (e.g. authorization was denied).
1978    pub fn show_system_notification(&self, notification: SystemNotification) {
1979        self.platform.show_system_notification(notification);
1980    }
1981
1982    /// Removes the delivered or pending notification with this tag.
1983    ///
1984    /// Best-effort: some platforms cannot retract a notification once shown,
1985    /// in which case it ages out of the notification center on its own.
1986    pub fn dismiss_system_notification(&self, tag: &str) {
1987        self.platform.dismiss_system_notification(tag);
1988    }
1989
1990    /// Registers the handler invoked when the user activates a system
1991    /// notification, either by clicking its body or one of its action
1992    /// buttons. Subsequent registrations replace the handler.
1993    pub fn on_system_notification_response<F>(&self, mut callback: F)
1994    where
1995        F: 'static + FnMut(SystemNotificationResponse, &mut App),
1996    {
1997        let this = self.this.clone();
1998        self.platform
1999            .on_system_notification_response(Box::new(move |response| {
2000                if let Some(app) = this.upgrade() {
2001                    callback(response, &mut app.borrow_mut());
2002                }
2003            }));
2004    }
2005
2006    /// Returns the full pathname of the current app bundle.
2007    ///
2008    /// Returns an error if the app is not being run from a bundle.
2009    pub fn app_path(&self) -> Result<PathBuf> {
2010        self.platform.app_path()
2011    }
2012
2013    /// On Linux, returns the name of the compositor in use.
2014    ///
2015    /// Returns an empty string on other platforms.
2016    pub fn compositor_name(&self) -> &'static str {
2017        self.platform.compositor_name()
2018    }
2019
2020    /// Returns the host OS and application target reported by the backend.
2021    pub fn platform_info(&self) -> crate::PlatformInfo {
2022        self.platform.platform_info()
2023    }
2024
2025    /// Returns the file URL of the executable with the specified name in the application bundle
2026    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
2027        self.platform.path_for_auxiliary_executable(name)
2028    }
2029
2030    /// Displays a platform modal for selecting paths.
2031    ///
2032    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
2033    /// If cancelled, a `None` will be relayed instead.
2034    /// May return an error on Linux if the file picker couldn't be opened.
2035    pub fn prompt_for_paths(
2036        &self,
2037        options: PathPromptOptions,
2038    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
2039        self.platform.prompt_for_paths(options)
2040    }
2041
2042    /// Displays a platform modal for selecting a new path where a file can be saved.
2043    ///
2044    /// The provided directory will be used to set the initial location.
2045    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
2046    /// If cancelled, a `None` will be relayed instead.
2047    /// May return an error on Linux if the file picker couldn't be opened.
2048    pub fn prompt_for_new_path(
2049        &self,
2050        directory: &Path,
2051        suggested_name: Option<&str>,
2052    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
2053        self.platform.prompt_for_new_path(directory, suggested_name)
2054    }
2055
2056    /// Reveals the specified path at the platform level, such as in Finder on macOS.
2057    pub fn reveal_path(&self, path: &Path) {
2058        self.platform.reveal_path(path)
2059    }
2060
2061    /// Opens the specified path with the system's default application.
2062    pub fn open_with_system(&self, path: &Path) {
2063        self.platform.open_with_system(path)
2064    }
2065
2066    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
2067    pub fn should_auto_hide_scrollbars(&self) -> bool {
2068        self.platform.should_auto_hide_scrollbars()
2069    }
2070
2071    /// Restarts the application.
2072    pub fn restart(&mut self) {
2073        self.restart_observers
2074            .clone()
2075            .retain(|observer| observer(self));
2076        self.platform.restart(
2077            self.restart_path.take(),
2078            std::mem::take(&mut self.restart_arguments),
2079        )
2080    }
2081
2082    /// Sets the path to use when restarting the application.
2083    pub fn set_restart_path(&mut self, path: PathBuf) {
2084        self.restart_path = Some(path);
2085    }
2086
2087    /// Returns the HTTP client for the application.
2088    pub fn http_client(&self) -> Arc<dyn HttpClient> {
2089        self.http_client.clone()
2090    }
2091
2092    /// Sets the HTTP client for the application.
2093    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
2094        self.http_client = new_client;
2095    }
2096
2097    /// Configures when the application should automatically quit.
2098    /// By default, [`QuitMode::Default`] is used.
2099    pub fn set_quit_mode(&mut self, mode: QuitMode) {
2100        self.quit_mode = mode;
2101    }
2102
2103    /// Sets whether the application participates in the system's foreground UI.
2104    ///
2105    /// Only has an effect on macOS, where [`Self::request_windowing`] normally sets it. Use this
2106    /// for an accessory app that shows windows, such as a menu bar utility. It overrides the
2107    /// policy until the next [`Self::request_windowing`], and the app counts as headless while
2108    /// `Accessory`. After switching to [`ActivationPolicy::Regular`], activate the app yourself
2109    /// with [`Self::activate`]; otherwise its menu bar may not appear until the app is
2110    /// reactivated.
2111    pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
2112        self.platform.set_activation_policy(policy);
2113    }
2114
2115    /// Returns the SVG renderer used by the application.
2116    pub fn svg_renderer(&self) -> SvgRenderer {
2117        self.svg_renderer.clone()
2118    }
2119
2120    pub(crate) fn push_effect(&mut self, effect: Effect) {
2121        match &effect {
2122            Effect::Notify { emitter } => {
2123                if !self.pending_notifications.insert(*emitter) {
2124                    return;
2125                }
2126            }
2127            Effect::NotifyGlobalObservers { global_type } => {
2128                crate::fast::dependencies::global_changed(self, *global_type);
2129                if !self.pending_global_notifications.insert(*global_type) {
2130                    return;
2131                }
2132            }
2133            _ => {}
2134        };
2135
2136        self.pending_effects.push_back(effect);
2137    }
2138
2139    /// Called at the end of [`App::update`] to complete any side effects
2140    /// such as notifying observers, emitting events, etc. Effects can themselves
2141    /// cause effects, so we continue looping until all effects are processed.
2142    fn flush_effects(&mut self) {
2143        loop {
2144            self.release_dropped_entities();
2145            self.release_dropped_focus_handles();
2146            if let Some(effect) = self.pending_effects.pop_front() {
2147                match effect {
2148                    Effect::Notify { emitter } => {
2149                        self.apply_notify_effect(emitter);
2150                    }
2151
2152                    Effect::Emit {
2153                        emitter,
2154                        event_type,
2155                        event,
2156                    } => self.apply_emit_effect(emitter, event_type, &*event),
2157
2158                    Effect::RefreshWindows => {
2159                        self.apply_refresh_effect();
2160                    }
2161
2162                    Effect::NotifyGlobalObservers { global_type } => {
2163                        self.apply_notify_global_observers_effect(global_type);
2164                    }
2165
2166                    Effect::Defer { callback } => {
2167                        self.apply_defer_effect(callback);
2168                    }
2169                    Effect::EntityCreated {
2170                        entity,
2171                        tid,
2172                        window,
2173                    } => {
2174                        self.apply_entity_created_effect(entity, tid, window);
2175                    }
2176                }
2177            } else {
2178                #[cfg(any(test, feature = "test-support"))]
2179                if matches!(self.mode, GpuiMode::Test { .. }) {
2180                    for window in self
2181                        .windows
2182                        .values()
2183                        .filter_map(|window| {
2184                            let window = window.as_deref()?;
2185                            window.invalidator.is_dirty().then_some(window.handle)
2186                        })
2187                        .collect::<Vec<_>>()
2188                    {
2189                        self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
2190                            .unwrap();
2191                    }
2192                }
2193
2194                if self.pending_effects.is_empty() {
2195                    for window in self.windows.values().filter_map(|window| window.as_deref()) {
2196                        if window.invalidator.is_dirty()
2197                            || window.needs_present.get()
2198                            || !window.next_frame_callbacks.borrow().is_empty()
2199                        {
2200                            window.platform_window.schedule_frame();
2201                        }
2202                    }
2203
2204                    self.event_arena.clear();
2205                    break;
2206                }
2207            }
2208        }
2209    }
2210
2211    /// Repeatedly called during `flush_effects` to release any entities whose
2212    /// reference count has become zero. We invoke any release observers before dropping
2213    /// each entity.
2214    fn release_dropped_entities(&mut self) {
2215        loop {
2216            let dropped = self.entities.take_dropped();
2217            if dropped.is_empty() {
2218                break;
2219            }
2220
2221            for (entity_id, mut entity) in dropped {
2222                self.observers.remove(&entity_id);
2223                self.event_listeners.remove(&entity_id);
2224                self.window_invalidators_by_entity.remove(&entity_id);
2225                self.current_window_by_entity.remove(&entity_id);
2226                for release_callback in self.release_listeners.remove(&entity_id) {
2227                    release_callback(entity.as_mut(), self);
2228                }
2229            }
2230        }
2231    }
2232
2233    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
2234    fn release_dropped_focus_handles(&mut self) {
2235        let focus_handles = self.focus_handles.clone();
2236        let mut focus_handles = focus_handles.write();
2237        let FocusMap {
2238            handles,
2239            dropped_handles,
2240        } = &mut *focus_handles;
2241        if dropped_handles.is_empty() {
2242            return;
2243        }
2244
2245        let windows = self
2246            .windows
2247            .values()
2248            .filter_map(|window| {
2249                let window = window.as_ref()?;
2250                dropped_handles
2251                    .contains(&window.focus?)
2252                    .then_some(window.handle)
2253            })
2254            .collect::<SmallVec<[_; 1]>>();
2255        for handle_id in dropped_handles.drain(..) {
2256            handles.remove(handle_id);
2257        }
2258        drop(focus_handles);
2259
2260        for window_handle in windows {
2261            window_handle
2262                .update(self, |_, window, cx| window.blur(cx))
2263                .ok();
2264        }
2265    }
2266
2267    fn apply_notify_effect(&mut self, emitter: EntityId) {
2268        self.pending_notifications.remove(&emitter);
2269
2270        self.observers
2271            .clone()
2272            .retain(&emitter, |handler| handler(self));
2273    }
2274
2275    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
2276        self.event_listeners
2277            .clone()
2278            .retain(&emitter, |(stored_type, handler)| {
2279                if *stored_type == event_type {
2280                    handler(event, self)
2281                } else {
2282                    true
2283                }
2284            });
2285    }
2286
2287    fn apply_refresh_effect(&mut self) {
2288        for window in self.windows.values_mut() {
2289            if let Some(window) = window.as_deref_mut() {
2290                window.refreshing = true;
2291                window.invalidator.set_dirty(true);
2292            }
2293        }
2294    }
2295
2296    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
2297        self.pending_global_notifications.remove(&type_id);
2298        self.global_observers
2299            .clone()
2300            .retain(&type_id, |observer| observer(self));
2301    }
2302
2303    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
2304        callback(self);
2305    }
2306
2307    fn apply_entity_created_effect(
2308        &mut self,
2309        entity: AnyEntity,
2310        tid: TypeId,
2311        window: Option<WindowId>,
2312    ) {
2313        // Seed the entity's current window from its creation context so
2314        // `with_window` resolves correctly before the entity has ever been
2315        // rendered.
2316        if let Some(id) = window {
2317            self.current_window_by_entity.insert(entity.entity_id(), id);
2318        }
2319
2320        self.new_entity_observers.clone().retain(&tid, |observer| {
2321            if let Some(id) = window {
2322                self.update_window_id(id, {
2323                    let entity = entity.clone();
2324                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
2325                })
2326                .expect("All windows should be off the stack when flushing effects");
2327            } else {
2328                (observer)(entity.clone(), &mut None, self)
2329            }
2330            true
2331        });
2332    }
2333
2334    /// Run `f` against the entity's *current* window — the most recently
2335    /// rendered window that referenced the entity, or its creation window if
2336    /// it has yet to be rendered. Returns `None` if the entity has no
2337    /// current window, or if that window has been closed, or if it is
2338    /// already on the update stack.
2339    #[inline(always)]
2340    pub fn with_window<R>(
2341        &mut self,
2342        entity_id: EntityId,
2343        f: impl FnOnce(&mut Window, &mut App) -> R,
2344    ) -> Option<R> {
2345        let window_id = *self.current_window_by_entity.get(&entity_id)?;
2346        self.update_window_id(window_id, |_, window, cx| f(window, cx))
2347            .ok()
2348    }
2349
2350    fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
2351        self.current_window_by_entity
2352            .entry(entity_id)
2353            .or_insert(window);
2354    }
2355
2356    #[inline(always)]
2357    pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
2358    where
2359        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2360    {
2361        let mut update = Some(update);
2362        let mut result = None;
2363        self.update_window_erased(id, &mut |arguments| {
2364            if let Some((root_view, window, cx)) = arguments {
2365                result = Some(update.take().unwrap()(root_view, window, cx));
2366            } else {
2367                drop(update.take());
2368                drop(result.take());
2369            }
2370        });
2371        result.context("window not found")
2372    }
2373
2374    /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
2375    /// so it can be held across `await` points.
2376    pub fn to_async(&self) -> AsyncApp {
2377        AsyncApp {
2378            app: self.this.clone(),
2379            background_executor: self.background_executor.clone(),
2380            foreground_executor: self.foreground_executor.clone(),
2381        }
2382    }
2383
2384    /// Obtains a reference to the executor, which can be used to spawn futures.
2385    pub fn background_executor(&self) -> &BackgroundExecutor {
2386        &self.background_executor
2387    }
2388
2389    /// Whether this app runs on the deterministic test scheduler. See
2390    /// [`BackgroundExecutor::is_test`].
2391    pub fn is_test(&self) -> bool {
2392        self.background_executor.is_test()
2393    }
2394
2395    /// Obtains a reference to the executor, which can be used to spawn futures.
2396    pub fn foreground_executor(&self) -> &ForegroundExecutor {
2397        if self.quitting {
2398            panic!("Can't spawn on main thread after on_app_quit")
2399        };
2400        &self.foreground_executor
2401    }
2402
2403    /// Returns the foreground work journal for this app's foreground thread.
2404    /// Apps constructed on the same thread share the stream.
2405    #[cfg(feature = "profiler")]
2406    pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
2407        self.foreground_journal.clone()
2408    }
2409
2410    /// Starts detecting foreground hangs on a dedicated thread.
2411    ///
2412    /// Nothing is spawned unless the app calls this. The thread polls a
2413    /// detector over this app's foreground journal every `config.interval`
2414    /// and passes each poll's incidents, including empty polls, to `on_poll`
2415    /// on that thread. When the app quits, a final poll with
2416    /// [`HangMonitorPollReason::Flush`] runs during shutdown, concurrently
2417    /// with quit handlers and within [`SHUTDOWN_TIMEOUT`], so `on_poll` can
2418    /// deliver batched results.
2419    ///
2420    /// # Errors
2421    ///
2422    /// Fails if the monitor was already started or its thread can't be
2423    /// spawned.
2424    ///
2425    /// [`HangMonitorPollReason::Flush`]: crate::profiler::hang::HangMonitorPollReason::Flush
2426    #[cfg(all(feature = "profiler", not(target_family = "wasm")))]
2427    pub fn start_hang_monitor(
2428        &mut self,
2429        config: crate::profiler::hang::HangMonitorConfig,
2430        on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
2431    ) -> Result<(), crate::profiler::hang::HangMonitorError> {
2432        use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
2433
2434        if self.hang_monitor.is_some() {
2435            debug_assert!(false, "the hang monitor was started twice");
2436            return Err(HangMonitorError::AlreadyStarted);
2437        }
2438        let detector = HangDetector::new(
2439            self.foreground_journal(),
2440            config.threshold,
2441            config.frame_budget,
2442        );
2443        let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
2444            .map_err(HangMonitorError::Spawn)?;
2445        self.hang_monitor = Some(monitor);
2446        Ok(())
2447    }
2448
2449    /// Spawns the future returned by the given function on the main thread. The closure will be invoked
2450    /// with [AsyncApp], which allows the application state to be accessed across await points.
2451    #[track_caller]
2452    #[inline(always)]
2453    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2454    where
2455        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2456        R: 'static,
2457    {
2458        let mut cx = self.prepare_spawn();
2459
2460        self.foreground_executor
2461            .spawn(async move { f(&mut cx).await }.boxed_local())
2462    }
2463
2464    /// Spawns the future returned by the given function on the main thread with
2465    /// the given priority. The closure will be invoked with [AsyncApp], which
2466    /// allows the application state to be accessed across await points.
2467    pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2468    where
2469        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2470        R: 'static,
2471    {
2472        if self.quitting {
2473            debug_panic!("Can't spawn on main thread after on_app_quit")
2474        };
2475
2476        let mut cx = self.to_async();
2477
2478        self.foreground_executor
2479            .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2480    }
2481
2482    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2483    /// that are currently on the stack to be returned to the app.
2484    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2485        self.push_effect(Effect::Defer {
2486            callback: Box::new(f),
2487        });
2488    }
2489
2490    /// Accessor for the application's asset source, which is provided when constructing the `App`.
2491    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2492        &self.asset_source
2493    }
2494
2495    /// Accessor for the text system.
2496    pub fn text_system(&self) -> &Arc<TextSystem> {
2497        &self.text_system
2498    }
2499
2500    /// Invokes a callback with grapheme clusters that exhausted font fallback.
2501    ///
2502    /// Registering a callback replaces the previous callback and enables missing-glyph
2503    /// detection. The callback runs on the foreground executor after shaping has
2504    /// released its internal locks. Dropping its subscription disables detection until
2505    /// another callback is registered.
2506    ///
2507    /// Reports are queued without blocking shaping, then deduplicated before delivery.
2508    /// The bounded queue can drop reports on overflow. Dropped reports may be reported
2509    /// again when the text is reshaped; no retry is scheduled automatically.
2510    pub fn on_missing_glyphs(
2511        &self,
2512        callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
2513    ) -> Subscription {
2514        let registration = self.missing_glyph_callback.replace(Box::new(callback));
2515
2516        if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
2517            let callback = self.missing_glyph_callback.clone();
2518            self.spawn(async move |cx| {
2519                while let Ok(missing_glyphs) = receiver.recv().await {
2520                    cx.update(|cx| callback.invoke(&missing_glyphs, cx));
2521                }
2522            })
2523            .detach();
2524        }
2525        self.text_system.enable_missing_glyph_reporting();
2526
2527        let callback = self.missing_glyph_callback.clone();
2528        let text_system = self.text_system.clone();
2529        Subscription::new(move || {
2530            if callback.remove(&registration) {
2531                text_system.disable_missing_glyph_reporting();
2532            }
2533        })
2534    }
2535
2536    /// Check whether a global of the given type has been assigned.
2537    pub fn has_global<G: Global>(&self) -> bool {
2538        crate::fast::dependencies::note_global_presence_read::<G>(self);
2539        self.globals_by_type.contains_key(&TypeId::of::<G>())
2540    }
2541
2542    /// Access the global of the given type. Panics if a global for that type has not been assigned.
2543    #[track_caller]
2544    pub fn global<G: Global>(&self) -> &G {
2545        crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2546        self.globals_by_type
2547            .get(&TypeId::of::<G>())
2548            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2549            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2550    }
2551
2552    /// Access the global of the given type if a value has been assigned.
2553    pub fn try_global<G: Global>(&self) -> Option<&G> {
2554        crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
2555        self.globals_by_type
2556            .get(&TypeId::of::<G>())
2557            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
2558    }
2559
2560    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
2561    #[track_caller]
2562    pub fn global_mut<G: Global>(&mut self) -> &mut G {
2563        let global_type = TypeId::of::<G>();
2564        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2565        self.globals_by_type
2566            .get_mut(&global_type)
2567            .and_then(|any_state| any_state.downcast_mut::<G>())
2568            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2569    }
2570
2571    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
2572    /// yet been assigned.
2573    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2574        let global_type = TypeId::of::<G>();
2575        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2576        crate::fast::dependencies::note_global_inserted::<G>(self);
2577        self.globals_by_type
2578            .entry(global_type)
2579            .or_insert_with(|| Box::<G>::default())
2580            .downcast_mut::<G>()
2581            .unwrap()
2582    }
2583
2584    /// Sets the value of the global of the given type.
2585    pub fn set_global<G: Global>(&mut self, global: G) {
2586        let global_type = TypeId::of::<G>();
2587        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2588        crate::fast::dependencies::note_global_inserted::<G>(self);
2589        self.globals_by_type.insert(global_type, Box::new(global));
2590    }
2591
2592    /// Clear all stored globals. Does not notify global observers.
2593    #[cfg(any(test, feature = "test-support"))]
2594    pub fn clear_globals(&mut self) {
2595        self.globals_by_type.drain();
2596    }
2597
2598    /// Remove the global of the given type from the app context. Does not notify global observers.
2599    pub fn remove_global<G: Global>(&mut self) -> G {
2600        crate::fast::dependencies::note_global_removed::<G>(self);
2601        let global_type = TypeId::of::<G>();
2602        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2603        *self
2604            .globals_by_type
2605            .remove(&global_type)
2606            .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2607            .downcast()
2608            .unwrap()
2609    }
2610
2611    /// Register a callback to be invoked when a global of the given type is updated.
2612    pub fn observe_global<G: Global>(
2613        &mut self,
2614        mut f: impl FnMut(&mut Self) + 'static,
2615    ) -> Subscription {
2616        let (subscription, activate) = self.global_observers.insert_pending(
2617            TypeId::of::<G>(),
2618            Box::new(move |cx| {
2619                f(cx);
2620                true
2621            }),
2622        );
2623        self.defer(move |_| activate());
2624        subscription
2625    }
2626
2627    /// Move the global of the given type to the stack.
2628    #[track_caller]
2629    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2630        GlobalLease::new(
2631            self.globals_by_type
2632                .remove(&TypeId::of::<G>())
2633                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
2634                .unwrap(),
2635        )
2636    }
2637
2638    /// Restore the global of the given type after it is moved to the stack.
2639    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2640        let global_type = TypeId::of::<G>();
2641
2642        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2643        self.globals_by_type.insert(global_type, lease.global);
2644    }
2645
2646    pub(crate) fn new_entity_observer(
2647        &self,
2648        key: TypeId,
2649        value: NewEntityListener,
2650    ) -> Subscription {
2651        self.new_entity_observers.insert(key, value)
2652    }
2653
2654    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
2655    /// The function will be passed a mutable reference to the view along with an appropriate context.
2656    pub fn observe_new<T: 'static>(
2657        &self,
2658        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2659    ) -> Subscription {
2660        self.new_entity_observer(
2661            TypeId::of::<T>(),
2662            Box::new(
2663                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2664                    any_entity
2665                        .downcast::<T>()
2666                        .unwrap()
2667                        .update(cx, |entity_state, cx| {
2668                            on_new(entity_state, window.as_deref_mut(), cx)
2669                        })
2670                },
2671            ),
2672        )
2673    }
2674
2675    /// Observe the release of a entity. The callback is invoked after the entity
2676    /// has no more strong references but before it has been dropped.
2677    pub fn observe_release<T>(
2678        &self,
2679        handle: &Entity<T>,
2680        on_release: impl FnOnce(&mut T, &mut App) + 'static,
2681    ) -> Subscription
2682    where
2683        T: 'static,
2684    {
2685        self.release_listeners.insert(
2686            handle.entity_id(),
2687            Box::new(move |entity, cx| {
2688                let entity = entity.downcast_mut().expect("invalid entity type");
2689                on_release(entity, cx)
2690            }),
2691        )
2692    }
2693
2694    /// Observe the release of a entity. The callback is invoked after the entity
2695    /// has no more strong references but before it has been dropped.
2696    pub fn observe_release_in<T>(
2697        &self,
2698        handle: &Entity<T>,
2699        window: &Window,
2700        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2701    ) -> Subscription
2702    where
2703        T: 'static,
2704    {
2705        let window_handle = window.handle;
2706        self.observe_release(handle, move |entity, cx| {
2707            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2708        })
2709    }
2710
2711    /// Register a callback to be invoked after a keystroke is resolved in any window,
2712    /// including the action that handled it, if any. Keystrokes consumed by an
2713    /// interceptor or raw keyboard event handler are not observed.
2714    /// Standalone modifiers are observed on release.
2715    pub fn observe_keystrokes(
2716        &mut self,
2717        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2718    ) -> Subscription {
2719        self.keystroke_observers
2720            .insert(Box::new(move |event, window, cx| {
2721                f(event, window, cx);
2722                true
2723            }))
2724    }
2725
2726    /// Register a callback to be invoked when a keystroke is received by the application
2727    /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
2728    /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
2729    /// within interceptors will prevent action dispatch
2730    pub fn intercept_keystrokes(
2731        &mut self,
2732        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2733    ) -> Subscription {
2734        self.keystroke_interceptors
2735            .insert(Box::new(move |event, window, cx| {
2736                f(event, window, cx);
2737                true
2738            }))
2739    }
2740
2741    /// Register key bindings.
2742    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2743        self.keymap.borrow_mut().add_bindings(bindings);
2744        self.pending_effects.push_back(Effect::RefreshWindows);
2745    }
2746
2747    /// Clear all key bindings in the app.
2748    pub fn clear_key_bindings(&mut self) {
2749        self.keymap.borrow_mut().clear();
2750        self.pending_effects.push_back(Effect::RefreshWindows);
2751    }
2752
2753    /// Get all key bindings in the app.
2754    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2755        self.keymap.clone()
2756    }
2757
2758    /// Register a global handler for actions invoked via the keyboard. These handlers are run at
2759    /// the end of the bubble phase for actions, and so will only be invoked if there are no other
2760    /// handlers or if they called `cx.propagate()`.
2761    pub fn on_action<A: Action>(
2762        &mut self,
2763        listener: impl Fn(&A, &mut Self) + 'static,
2764    ) -> &mut Self {
2765        self.global_action_listeners
2766            .entry(TypeId::of::<A>())
2767            .or_default()
2768            .push(Rc::new(move |action, phase, cx| {
2769                if phase == DispatchPhase::Bubble {
2770                    let action = action.downcast_ref().unwrap();
2771                    listener(action, cx)
2772                }
2773            }));
2774        self
2775    }
2776
2777    /// Event handlers propagate events by default. Call this method to stop dispatching to
2778    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
2779    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
2780    /// calling this method before effects are flushed.
2781    pub fn stop_propagation(&mut self) {
2782        self.propagate_event = false;
2783    }
2784
2785    /// Action handlers stop propagation by default during the bubble phase of action dispatch
2786    /// dispatching to action handlers higher in the element tree. This is the opposite of
2787    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
2788    /// this method before effects are flushed.
2789    pub fn propagate(&mut self) {
2790        self.propagate_event = true;
2791    }
2792
2793    /// Build an action from some arbitrary data, typically a keymap entry.
2794    pub fn build_action(
2795        &self,
2796        name: &str,
2797        data: Option<serde_json::Value>,
2798    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2799        self.actions.build_action(name, data)
2800    }
2801
2802    /// Get all action names that have been registered. Note that registration only allows for
2803    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
2804    pub fn all_action_names(&self) -> &[&'static str] {
2805        self.actions.all_action_names()
2806    }
2807
2808    /// Returns key bindings that invoke the given action on the currently focused element, without
2809    /// checking context. Bindings are returned in the order they were added. For display, the last
2810    /// binding should take precedence.
2811    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2812        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2813    }
2814
2815    /// Get all non-internal actions that have been registered, along with their schemas.
2816    pub fn action_schemas(
2817        &self,
2818        generator: &mut schemars::SchemaGenerator,
2819    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2820        self.actions.action_schemas(generator)
2821    }
2822
2823    /// Get the schema for a specific action by name.
2824    /// Returns `None` if the action is not found.
2825    /// Returns `Some(None)` if the action exists but has no schema.
2826    /// Returns `Some(Some(schema))` if the action exists and has a schema.
2827    pub fn action_schema_by_name(
2828        &self,
2829        name: &str,
2830        generator: &mut schemars::SchemaGenerator,
2831    ) -> Option<Option<schemars::Schema>> {
2832        self.actions.action_schema_by_name(name, generator)
2833    }
2834
2835    /// Get a map from a deprecated action name to the canonical name.
2836    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2837        self.actions.deprecated_aliases()
2838    }
2839
2840    /// Get a map from an action name to the deprecation messages.
2841    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2842        self.actions.deprecation_messages()
2843    }
2844
2845    /// Get a map from an action name to the documentation.
2846    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2847        self.actions.documentation()
2848    }
2849
2850    /// Register a callback to be invoked when the application is about to quit.
2851    /// It is not possible to cancel the quit event at this point.
2852    pub fn on_app_quit<Fut>(
2853        &self,
2854        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2855    ) -> Subscription
2856    where
2857        Fut: 'static + Future<Output = ()>,
2858    {
2859        self.quit_observers.insert(Box::new(move |cx| {
2860            let future = on_quit(cx);
2861            future.boxed_local()
2862        }))
2863    }
2864
2865    /// Register a callback to be invoked when the application is about to restart.
2866    ///
2867    /// These callbacks are called before any `on_app_quit` callbacks.
2868    pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2869        self.restart_observers.insert(Box::new(move |cx| {
2870            on_restart(cx);
2871            true
2872        }))
2873    }
2874
2875    /// Register a callback to be invoked when a window is closed
2876    /// The window is no longer accessible at the point this callback is invoked.
2877    pub fn on_window_closed(
2878        &self,
2879        on_closed: impl FnMut(&mut App, WindowId) + 'static,
2880    ) -> Subscription {
2881        self.window_closed_observers.insert(Box::new(on_closed))
2882    }
2883
2884    pub(crate) fn clear_pending_keystrokes(&mut self) {
2885        for window in self.windows() {
2886            window
2887                .update(self, |_, window, cx| {
2888                    window.clear_pending_keystrokes(cx);
2889                })
2890                .ok();
2891        }
2892    }
2893
2894    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
2895    /// the bindings in the element tree, and any global action listeners.
2896    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2897        let mut action_available = false;
2898        if let Some(window) = self.active_window()
2899            && let Ok(window_action_available) =
2900                window.update(self, |_, window, cx| window.is_action_available(action, cx))
2901        {
2902            action_available = window_action_available;
2903        }
2904
2905        action_available
2906            || self
2907                .global_action_listeners
2908                .contains_key(&action.as_any().type_id())
2909    }
2910
2911    /// Sets the menu bar for this application. This will replace any existing menu bar.
2912    pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2913        let menus: Vec<Menu> = menus.into_iter().collect();
2914        self.platform.set_menus(menus, &self.keymap.borrow());
2915    }
2916
2917    /// Gets the menu bar for this application.
2918    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2919        self.platform.get_menus()
2920    }
2921
2922    /// Sets the right click menu for the app icon in the dock
2923    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2924        self.platform.set_dock_menu(menus, &self.keymap.borrow())
2925    }
2926
2927    /// Performs the action associated with the given dock menu item, only used on Windows for now.
2928    pub fn perform_dock_menu_action(&self, action: usize) {
2929        self.platform.perform_dock_menu_action(action);
2930    }
2931
2932    /// Adds given path to the bottom of the list of recent paths for the application.
2933    /// The list is usually shown on the application icon's context menu in the dock,
2934    /// and allows to open the recent files via that context menu.
2935    /// If the path is already in the list, it will be moved to the bottom of the list.
2936    pub fn add_recent_document(&self, path: &Path) {
2937        self.platform.add_recent_document(path);
2938    }
2939
2940    /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
2941    /// Note that this also sets the dock menu on Windows.
2942    pub fn update_jump_list(
2943        &self,
2944        menus: Vec<MenuItem>,
2945        entries: Vec<SmallVec<[PathBuf; 2]>>,
2946    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2947        self.platform.update_jump_list(menus, entries)
2948    }
2949
2950    /// Dispatch an action to the currently active window or global action handler
2951    /// See [`crate::Action`] for more information on how actions work
2952    pub fn dispatch_action(&mut self, action: &dyn Action) {
2953        if let Some(active_window) = self.active_window() {
2954            active_window
2955                .update(self, |_, window, cx| {
2956                    window.dispatch_action(action.boxed_clone(), cx)
2957                })
2958                .log_err();
2959        } else {
2960            self.dispatch_global_action(action);
2961        }
2962    }
2963
2964    fn dispatch_global_action(&mut self, action: &dyn Action) {
2965        self.propagate_event = true;
2966
2967        if let Some(mut global_listeners) = self
2968            .global_action_listeners
2969            .remove(&action.as_any().type_id())
2970        {
2971            for listener in &global_listeners {
2972                listener(action.as_any(), DispatchPhase::Capture, self);
2973                if !self.propagate_event {
2974                    break;
2975                }
2976            }
2977
2978            global_listeners.extend(
2979                self.global_action_listeners
2980                    .remove(&action.as_any().type_id())
2981                    .unwrap_or_default(),
2982            );
2983
2984            self.global_action_listeners
2985                .insert(action.as_any().type_id(), global_listeners);
2986        }
2987
2988        if self.propagate_event
2989            && let Some(mut global_listeners) = self
2990                .global_action_listeners
2991                .remove(&action.as_any().type_id())
2992        {
2993            for listener in global_listeners.iter().rev() {
2994                listener(action.as_any(), DispatchPhase::Bubble, self);
2995                if !self.propagate_event {
2996                    break;
2997                }
2998            }
2999
3000            global_listeners.extend(
3001                self.global_action_listeners
3002                    .remove(&action.as_any().type_id())
3003                    .unwrap_or_default(),
3004            );
3005
3006            self.global_action_listeners
3007                .insert(action.as_any().type_id(), global_listeners);
3008        }
3009    }
3010
3011    /// Is there currently something being dragged?
3012    pub fn has_active_drag(&self) -> bool {
3013        self.active_drag.is_some()
3014    }
3015
3016    /// Gets the cursor style of the currently active drag operation.
3017    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3018        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3019    }
3020
3021    /// Stops active drag and clears any related effects.
3022    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3023        if self.active_drag.is_some() {
3024            self.active_drag = None;
3025            if self.platform_owned_drag.as_ref().is_some_and(|drag| {
3026                drag.source_window == window.window_handle().window_id()
3027                    && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3028            }) {
3029                self.platform_owned_drag = None;
3030            }
3031            window.refresh();
3032            true
3033        } else {
3034            false
3035        }
3036    }
3037
3038    pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3039        let Some(drag) = self.active_drag.take() else {
3040            return false;
3041        };
3042        self.platform_owned_drag = Some(PlatformOwnedDrag {
3043            source_window,
3044            state: PlatformOwnedDragState::Suspended(drag),
3045        });
3046        true
3047    }
3048
3049    pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
3050        let Some(platform_drag) = self
3051            .platform_owned_drag
3052            .as_mut()
3053            .filter(|drag| drag.source_window == source_window)
3054        else {
3055            return false;
3056        };
3057        let state = std::mem::replace(
3058            &mut platform_drag.state,
3059            PlatformOwnedDragState::RestoredInSourceWindow,
3060        );
3061        let PlatformOwnedDragState::Suspended(drag) = state else {
3062            return false;
3063        };
3064        self.active_drag = Some(drag);
3065        true
3066    }
3067
3068    pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
3069        let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
3070            drag.source_window == source_window
3071                && matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
3072        }) else {
3073            return false;
3074        };
3075        let Some(drag) = self.active_drag.take() else {
3076            return false;
3077        };
3078        platform_drag.state = PlatformOwnedDragState::Suspended(drag);
3079        true
3080    }
3081
3082    pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
3083        if !self
3084            .platform_owned_drag
3085            .as_ref()
3086            .is_some_and(|drag| drag.source_window == source_window)
3087        {
3088            return false;
3089        }
3090        self.platform_owned_drag = None;
3091        self.active_drag = None;
3092        true
3093    }
3094
3095    /// Sets the cursor style for the currently active drag operation.
3096    pub fn set_active_drag_cursor_style(
3097        &mut self,
3098        cursor_style: CursorStyle,
3099        window: &mut Window,
3100    ) -> bool {
3101        if let Some(ref mut drag) = self.active_drag {
3102            drag.cursor_style = Some(cursor_style);
3103            window.refresh();
3104            true
3105        } else {
3106            false
3107        }
3108    }
3109
3110    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
3111    /// prompts with this custom implementation.
3112    pub fn set_prompt_builder(
3113        &mut self,
3114        renderer: impl Fn(
3115            PromptLevel,
3116            &str,
3117            Option<&str>,
3118            &[PromptButton],
3119            PromptHandle,
3120            &mut Window,
3121            &mut App,
3122        ) -> RenderablePromptHandle
3123        + 'static,
3124    ) {
3125        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3126    }
3127
3128    /// Reset the prompt builder to the default implementation.
3129    pub fn reset_prompt_builder(&mut self) {
3130        self.prompt_builder = Some(PromptBuilder::Default);
3131    }
3132
3133    /// Remove an asset from GPUI's cache
3134    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3135        let asset_id = (TypeId::of::<A>(), hash(source));
3136        self.loading_assets.remove(&asset_id);
3137    }
3138
3139    /// Check whether an asset is present in GPUI's cache (loading or loaded),
3140    /// without fetching it.
3141    #[cfg(any(test, feature = "test-support"))]
3142    pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
3143        let asset_id = (TypeId::of::<A>(), hash(source));
3144        self.loading_assets.contains_key(&asset_id)
3145    }
3146
3147    /// Starts loading an uncached asset and returns its result once available.
3148    ///
3149    /// Pending loads and completed results are cached until [`Self::remove_asset`].
3150    /// This method does not subscribe a view to completion notifications.
3151    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
3152        self.asset_entry::<A>(source).get()
3153    }
3154
3155    pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
3156        let asset_id = (TypeId::of::<A>(), hash(source));
3157        if !self.loading_assets.contains_key(&asset_id) {
3158            let future = A::load(source.clone(), self);
3159            let entry = CachedLoad::new(future, self);
3160            self.loading_assets.insert(asset_id, Box::new(entry));
3161        }
3162        self.loading_assets
3163            .get(&asset_id)
3164            .and_then(|entry| entry.downcast_ref())
3165            .expect("asset cache entries are keyed by their asset type")
3166    }
3167
3168    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
3169    /// for elements rendered within this window.
3170    #[track_caller]
3171    pub fn focus_handle(&self) -> FocusHandle {
3172        FocusHandle::new(&self.focus_handles)
3173    }
3174
3175    /// Tell GPUI that an entity has changed and observers of it should be notified.
3176    pub fn notify(&mut self, entity_id: EntityId) {
3177        crate::fast::dependencies::note_notify(&mut self.entities, entity_id);
3178        let window_invalidators = mem::take(
3179            self.window_invalidators_by_entity
3180                .entry(entity_id)
3181                .or_default(),
3182        );
3183
3184        // `window_invalidators_by_entity` is monotonic, so an entry alone
3185        // doesn't mean the window is currently rendering the entity. Filter
3186        // through `tracked_entities` to keep invalidation tight to windows
3187        // that actually display this entity right now.
3188        let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3189            .iter()
3190            .filter(|(window_id, _)| {
3191                self.tracked_entities
3192                    .get(window_id)
3193                    .is_some_and(|set| set.contains(&entity_id))
3194            })
3195            .map(|(_, invalidator)| invalidator.clone())
3196            .collect();
3197
3198        if live_invalidators.is_empty() {
3199            if self.pending_notifications.insert(entity_id) {
3200                self.pending_effects
3201                    .push_back(Effect::Notify { emitter: entity_id });
3202            }
3203        } else {
3204            for invalidator in &live_invalidators {
3205                invalidator.invalidate_view(entity_id, self);
3206            }
3207        }
3208
3209        self.window_invalidators_by_entity
3210            .insert(entity_id, window_invalidators);
3211    }
3212
3213    /// Returns the name for this [`App`].
3214    #[cfg(any(test, feature = "test-support", debug_assertions))]
3215    pub fn get_name(&self) -> Option<&'static str> {
3216        self.name
3217    }
3218
3219    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
3220    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3221        self.platform.can_select_mixed_files_and_dirs()
3222    }
3223
3224    /// Removes an image from the sprite atlas on all windows.
3225    ///
3226    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
3227    /// This is a no-op if the image is not in the sprite atlas.
3228    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3229        // remove the texture from all other windows
3230        for window in self.windows.values_mut().flatten() {
3231            _ = window.drop_image(image.clone());
3232        }
3233
3234        // remove the texture from the current window
3235        if let Some(window) = current_window {
3236            _ = window.drop_image(image);
3237        }
3238    }
3239
3240    /// Sets the renderer for the inspector.
3241    #[cfg(any(feature = "inspector", debug_assertions))]
3242    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3243        self.inspector_renderer = Some(f);
3244    }
3245
3246    /// Registers a renderer specific to an inspector state.
3247    #[cfg(any(feature = "inspector", debug_assertions))]
3248    pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
3249        &mut self,
3250        factory: impl 'static + Fn(&mut Window, &mut App) -> F,
3251    ) where
3252        F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3253    {
3254        self.inspector_element_registry.register(factory);
3255    }
3256
3257    /// Initializes gpui's default colors for the application.
3258    ///
3259    /// These colors can be accessed through `cx.default_colors()`.
3260    pub fn init_colors(&mut self) {
3261        self.set_global(GlobalColors(Arc::new(Colors::default())));
3262    }
3263
3264    #[inline(never)]
3265    fn update_window_erased(
3266        &mut self,
3267        window_id: WindowId,
3268        update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
3269    ) {
3270        self.update(|cx| {
3271            let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
3272                update(None);
3273                return;
3274            };
3275
3276            let root_view = window.root.clone().unwrap();
3277
3278            cx.window_update_stack.push(window.handle.id);
3279            update(Some((root_view, &mut window, cx)));
3280            fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
3281                cx.window_update_stack.pop();
3282
3283                if window.removed {
3284                    cx.end_platform_drag(window_id);
3285                    cx.window_handles.remove(&window_id);
3286                    cx.windows.remove(window_id);
3287                    if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
3288                        for entity_id in tracked {
3289                            if let Some(windows) =
3290                                cx.window_invalidators_by_entity.get_mut(&entity_id)
3291                            {
3292                                windows.remove(&window_id);
3293                            }
3294                            if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
3295                                cx.current_window_by_entity.remove(&entity_id);
3296                            }
3297                        }
3298                    }
3299
3300                    cx.window_closed_observers.clone().retain(|callback| {
3301                        callback(cx, window_id);
3302                        true
3303                    });
3304
3305                    let quit_on_empty = match cx.quit_mode {
3306                        QuitMode::Explicit => false,
3307                        QuitMode::LastWindowClosed => true,
3308                        QuitMode::Default => cfg!(not(target_os = "macos")),
3309                    };
3310
3311                    if quit_on_empty && cx.windows.is_empty() {
3312                        cx.quit();
3313                    }
3314                } else {
3315                    cx.windows.get_mut(window_id)?.replace(window);
3316                }
3317                Some(())
3318            }
3319            if trail(window_id, window, cx).is_none() {
3320                update(None);
3321            }
3322        });
3323    }
3324
3325    #[inline(never)]
3326    fn update_entity_erased(
3327        &mut self,
3328        handle: &AnyEntity,
3329        entity_type: &str,
3330        update: &mut dyn FnMut(&mut dyn Any, &mut App),
3331    ) {
3332        self.update(|cx| {
3333            let mut lease = cx.entities.lease_erased(handle, entity_type);
3334            update(lease.entity.as_deref_mut().unwrap(), cx);
3335            cx.entities.end_lease_erased(handle.entity_id, lease);
3336        });
3337    }
3338
3339    #[inline(never)]
3340    #[track_caller]
3341    fn prepare_spawn(&self) -> AsyncApp {
3342        if self.quitting {
3343            debug_panic!("Can't spawn on main thread after on_app_quit")
3344        };
3345        self.to_async()
3346    }
3347}
3348
3349impl AppContext for App {
3350    /// Builds an entity that is owned by the application.
3351    ///
3352    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
3353    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
3354    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3355        self.update(|cx| {
3356            let slot = cx.entities.reserve();
3357            let handle = slot.clone();
3358            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3359
3360            cx.push_effect(Effect::EntityCreated {
3361                entity: handle.into_any(),
3362                tid: TypeId::of::<T>(),
3363                window: cx.window_update_stack.last().cloned(),
3364            });
3365
3366            cx.entities.insert(slot, entity)
3367        })
3368    }
3369
3370    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3371        Reservation(self.entities.reserve())
3372    }
3373
3374    fn insert_entity<T: 'static>(
3375        &mut self,
3376        reservation: Reservation<T>,
3377        build_entity: impl FnOnce(&mut Context<T>) -> T,
3378    ) -> Entity<T> {
3379        self.update(|cx| {
3380            let slot = reservation.0;
3381            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3382            cx.entities.insert(slot, entity)
3383        })
3384    }
3385
3386    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
3387    /// entity along with a `Context` for the entity.
3388    #[inline(always)]
3389    fn update_entity<T: 'static, R>(
3390        &mut self,
3391        handle: &Entity<T>,
3392        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3393    ) -> R {
3394        let mut update = Some(update);
3395        let mut result = None;
3396        self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
3397            let value = update.take().unwrap()(
3398                entity.downcast_mut::<T>().unwrap(),
3399                &mut Context::new_context(cx, handle.downgrade()),
3400            );
3401            result = Some(value);
3402        });
3403        result.unwrap()
3404    }
3405
3406    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3407    where
3408        T: 'static,
3409    {
3410        GpuiBorrow::new(handle.clone(), self)
3411    }
3412
3413    #[inline(always)]
3414    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3415    where
3416        T: 'static,
3417    {
3418        let entity = self.entities.read(handle);
3419        read(entity, self)
3420    }
3421
3422    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3423    where
3424        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3425    {
3426        self.update_window_id(handle.id, update)
3427    }
3428
3429    fn with_window<R>(
3430        &mut self,
3431        entity_id: EntityId,
3432        f: impl FnOnce(&mut Window, &mut App) -> R,
3433    ) -> Option<R> {
3434        App::with_window(self, entity_id, f)
3435    }
3436
3437    fn read_window<T, R>(
3438        &self,
3439        window: &WindowHandle<T>,
3440        read: impl FnOnce(Entity<T>, &App) -> R,
3441    ) -> Result<R>
3442    where
3443        T: 'static,
3444    {
3445        let window = self
3446            .windows
3447            .get(window.id)
3448            .context("window not found")?
3449            .as_deref()
3450            .expect("attempted to read a window that is already on the stack");
3451
3452        let root_view = window.root.clone().unwrap();
3453        let view = root_view
3454            .downcast::<T>()
3455            .map_err(|_| anyhow!("root view's type has changed"))?;
3456
3457        Ok(read(view, self))
3458    }
3459
3460    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3461    where
3462        R: Send + 'static,
3463    {
3464        self.background_executor.spawn(future)
3465    }
3466
3467    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3468    where
3469        G: Global,
3470    {
3471        let g = self.global::<G>();
3472        callback(g, self)
3473    }
3474}
3475
3476/// These effects are processed at the end of each application update cycle.
3477pub(crate) enum Effect {
3478    Notify {
3479        emitter: EntityId,
3480    },
3481    Emit {
3482        emitter: EntityId,
3483        event_type: TypeId,
3484        event: ArenaBox<dyn Any>,
3485    },
3486    RefreshWindows,
3487    NotifyGlobalObservers {
3488        global_type: TypeId,
3489    },
3490    Defer {
3491        callback: Box<dyn FnOnce(&mut App) + 'static>,
3492    },
3493    EntityCreated {
3494        entity: AnyEntity,
3495        tid: TypeId,
3496        window: Option<WindowId>,
3497    },
3498}
3499
3500impl std::fmt::Debug for Effect {
3501    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3502        match self {
3503            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3504            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3505            Effect::RefreshWindows => write!(f, "RefreshWindows"),
3506            Effect::NotifyGlobalObservers { global_type } => {
3507                write!(f, "NotifyGlobalObservers({:?})", global_type)
3508            }
3509            Effect::Defer { .. } => write!(f, "Defer(..)"),
3510            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3511        }
3512    }
3513}
3514
3515/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
3516pub(crate) struct GlobalLease<G: Global> {
3517    global: Box<dyn Any>,
3518    global_type: PhantomData<G>,
3519}
3520
3521impl<G: Global> GlobalLease<G> {
3522    fn new(global: Box<dyn Any>) -> Self {
3523        GlobalLease {
3524            global,
3525            global_type: PhantomData,
3526        }
3527    }
3528}
3529
3530impl<G: Global> Deref for GlobalLease<G> {
3531    type Target = G;
3532
3533    fn deref(&self) -> &Self::Target {
3534        self.global.downcast_ref().unwrap()
3535    }
3536}
3537
3538impl<G: Global> DerefMut for GlobalLease<G> {
3539    fn deref_mut(&mut self) -> &mut Self::Target {
3540        self.global.downcast_mut().unwrap()
3541    }
3542}
3543
3544/// Contains state associated with an active drag operation, started by dragging an element
3545/// within the window or by dragging into the app from the underlying platform.
3546pub struct AnyDrag {
3547    /// The view used to render this drag
3548    pub view: AnyView,
3549
3550    /// The value of the dragged item, to be dropped
3551    pub value: Arc<dyn Any>,
3552
3553    /// This is used to render the dragged item in the same place
3554    /// on the original element that the drag was initiated
3555    pub cursor_offset: Point<Pixels>,
3556
3557    /// The cursor style to use while dragging
3558    pub cursor_style: Option<CursorStyle>,
3559
3560    /// Resolves the payload to offer the platform if the drag leaves the window.
3561    /// Invoked at most once per drag gesture, at promotion time.
3562    pub external_payload_source: Option<ExternalDragPayloadSource>,
3563}
3564
3565/// Lazily resolves the payload handed to the platform when an internal drag is
3566/// promoted to a native drag session.
3567pub type ExternalDragPayloadSource =
3568    Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
3569
3570/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
3571/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
3572#[derive(Clone)]
3573pub struct AnyTooltip {
3574    /// The view used to display the tooltip
3575    pub view: AnyView,
3576
3577    /// The absolute position of the mouse when the tooltip was deployed.
3578    pub mouse_position: Point<Pixels>,
3579
3580    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
3581    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
3582    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
3583    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3584}
3585
3586/// Whether a keystroke should prefer character input or key bindings.
3587#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3588pub enum InputPreference {
3589    /// Prefer typing text over triggering key bindings.
3590    CharacterInput,
3591    /// Dispatch key bindings normally, if any match.
3592    KeyBindings,
3593}
3594
3595/// A keystroke event, and potentially the associated action
3596#[derive(Debug)]
3597pub struct KeystrokeEvent {
3598    /// The keystroke that occurred
3599    pub keystroke: Keystroke,
3600
3601    /// Whether this keystroke should prefer character input or key bindings.
3602    /// This is [`InputPreference::CharacterInput`] when the platform prefers text for the key
3603    /// (e.g. AltGr on Windows) and the focused input accepts text. Interceptors still receive
3604    /// these keystrokes and can consume them.
3605    ///
3606    /// If the keystroke is part of a multi-stroke binding, it still waits as pending input
3607    /// even when this is [`InputPreference::CharacterInput`].
3608    pub input_preference: InputPreference,
3609
3610    /// The action that was resolved for the keystroke, if any
3611    pub action: Option<Box<dyn Action>>,
3612
3613    /// The context stack at the time
3614    pub context_stack: Vec<KeyContext>,
3615}
3616
3617struct NullHttpClient;
3618
3619impl HttpClient for NullHttpClient {
3620    fn send(
3621        &self,
3622        _req: http_client::Request<http_client::AsyncBody>,
3623    ) -> futures::future::BoxFuture<
3624        'static,
3625        anyhow::Result<http_client::Response<http_client::AsyncBody>>,
3626    > {
3627        async move {
3628            anyhow::bail!("No HttpClient available");
3629        }
3630        .boxed()
3631    }
3632
3633    fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
3634        None
3635    }
3636
3637    fn proxy(&self) -> Option<&Url> {
3638        None
3639    }
3640}
3641
3642/// A mutable reference to an entity owned by GPUI
3643pub struct GpuiBorrow<'a, T> {
3644    inner: Option<Lease<T>>,
3645    app: &'a mut App,
3646}
3647
3648impl<'a, T: 'static> GpuiBorrow<'a, T> {
3649    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3650        app.start_update();
3651        let lease = app.entities.lease(&inner);
3652        Self {
3653            inner: Some(lease),
3654            app,
3655        }
3656    }
3657}
3658
3659impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3660    fn borrow(&self) -> &T {
3661        self.inner.as_ref().unwrap().borrow()
3662    }
3663}
3664
3665impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3666    fn borrow_mut(&mut self) -> &mut T {
3667        self.inner.as_mut().unwrap().borrow_mut()
3668    }
3669}
3670
3671impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3672    type Target = T;
3673
3674    fn deref(&self) -> &Self::Target {
3675        self.inner.as_ref().unwrap()
3676    }
3677}
3678
3679impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3680    fn deref_mut(&mut self) -> &mut T {
3681        self.inner.as_mut().unwrap()
3682    }
3683}
3684
3685impl<'a, T> Drop for GpuiBorrow<'a, T> {
3686    fn drop(&mut self) {
3687        let lease = self.inner.take().unwrap();
3688        self.app.notify(lease.id);
3689        self.app.entities.end_lease(lease);
3690        self.app.finish_update();
3691    }
3692}
3693
3694#[cfg(test)]
3695mod test {
3696    use std::{
3697        cell::{Cell, RefCell},
3698        ffi::OsString,
3699        path::PathBuf,
3700        rc::Rc,
3701    };
3702
3703    #[cfg(unix)]
3704    use std::os::unix::ffi::OsStringExt;
3705
3706    use crate::{
3707        AppContext, Context, Empty, FallbackFontClass, IntoElement, MissingGlyph, Render,
3708        TestAppContext, Window,
3709    };
3710
3711    #[gpui::test]
3712    fn app_borrow_diagnostics(cx: &mut TestAppContext) {
3713        use std::panic::{AssertUnwindSafe, catch_unwind};
3714
3715        let app = cx.app.clone();
3716        let first_line = line!() + 1;
3717        let first = app.borrow();
3718        let second = app.borrow();
3719        drop(first);
3720        assert!(app.try_borrow_mut().is_err());
3721        let attempted_line = line!() + 1;
3722        let panic = catch_unwind(AssertUnwindSafe(|| drop(app.borrow_mut())));
3723        let message = *panic
3724            .expect_err("conflicting borrow")
3725            .downcast::<String>()
3726            .unwrap();
3727        assert!(message.contains(&format!(
3728            "mutable App borrow at {}:{attempted_line}:",
3729            file!()
3730        )));
3731        assert!(message.contains(&format!(
3732            "shared borrow group began at {}:{first_line}:",
3733            file!()
3734        )));
3735        drop(second);
3736
3737        let origin_line = line!() + 2;
3738        let panic = catch_unwind(AssertUnwindSafe(|| {
3739            let _borrow = app.try_borrow_mut().expect("initial borrow");
3740            drop(app.borrow());
3741        }));
3742        let message = *panic
3743            .expect_err("conflicting borrow")
3744            .downcast::<String>()
3745            .unwrap();
3746        assert!(message.contains("attempted shared App borrow"));
3747        assert!(message.contains(&format!(
3748            "mutable borrow group began at {}:{origin_line}:",
3749            file!()
3750        )));
3751
3752        let next_line = line!() + 1;
3753        let _borrow = app.borrow();
3754        assert_eq!(
3755            app.borrow_origin.get().expect("new origin").0.line(),
3756            next_line
3757        );
3758    }
3759
3760    struct RenderCounter(Rc<Cell<usize>>);
3761
3762    impl Render for RenderCounter {
3763        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3764            self.0.set(self.0.get() + 1);
3765            Empty
3766        }
3767    }
3768
3769    #[gpui::test]
3770    fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
3771        let render_count = Rc::new(Cell::new(0));
3772
3773        let _window = cx.add_window({
3774            let render_count = render_count.clone();
3775            move |_, _| RenderCounter(render_count)
3776        });
3777
3778        cx.run_until_parked();
3779        let render_count_before_refresh = render_count.get();
3780
3781        cx.to_async().refresh();
3782
3783        assert_eq!(render_count.get(), render_count_before_refresh + 1);
3784    }
3785
3786    #[gpui::test]
3787    fn missing_glyph_callbacks_follow_subscription_lifetime(cx: &mut TestAppContext) {
3788        let observed = Rc::new(RefCell::new(Vec::new()));
3789        let subscription = cx.update(|cx| {
3790            let observed = observed.clone();
3791            cx.on_missing_glyphs(move |missing_glyphs, _| {
3792                observed.borrow_mut().extend_from_slice(missing_glyphs);
3793            })
3794        });
3795        cx.update(|cx| {
3796            cx.text_system()
3797                .report_missing_glyphs_in_test(vec![missing_glyph("active")]);
3798        });
3799        cx.run_until_parked();
3800        assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3801
3802        let second_observed = Rc::new(RefCell::new(Vec::new()));
3803        let second_subscription = cx.update(|cx| {
3804            let second_observed = second_observed.clone();
3805            cx.on_missing_glyphs(move |missing_glyphs, _| {
3806                second_observed
3807                    .borrow_mut()
3808                    .extend_from_slice(missing_glyphs);
3809            })
3810        });
3811        cx.update(|cx| {
3812            cx.text_system()
3813                .report_missing_glyphs_in_test(vec![missing_glyph("replacement")]);
3814        });
3815        cx.run_until_parked();
3816        assert_eq!(observed.borrow().as_slice(), &[missing_glyph("active")]);
3817        assert_eq!(
3818            second_observed.borrow().as_slice(),
3819            &[missing_glyph("replacement")]
3820        );
3821
3822        drop(subscription);
3823        cx.update(|cx| {
3824            cx.text_system()
3825                .report_missing_glyphs_in_test(vec![missing_glyph("after old drop")]);
3826        });
3827        cx.run_until_parked();
3828        assert_eq!(
3829            second_observed.borrow().as_slice(),
3830            &[
3831                missing_glyph("replacement"),
3832                missing_glyph("after old drop")
3833            ]
3834        );
3835
3836        drop(second_subscription);
3837        cx.update(|cx| {
3838            cx.text_system()
3839                .report_missing_glyphs_in_test(vec![missing_glyph("inactive")]);
3840        });
3841        cx.run_until_parked();
3842        assert_eq!(second_observed.borrow().len(), 2);
3843    }
3844
3845    #[test]
3846    fn test_gpui_borrow() {
3847        let cx = TestAppContext::single();
3848        let observation_count = Rc::new(RefCell::new(0));
3849
3850        let state = cx.update(|cx| {
3851            let state = cx.new(|_| false);
3852            cx.observe(&state, {
3853                let observation_count = observation_count.clone();
3854                move |_, _| {
3855                    let mut count = observation_count.borrow_mut();
3856                    *count += 1;
3857                }
3858            })
3859            .detach();
3860
3861            state
3862        });
3863
3864        cx.update(|cx| {
3865            // Calling this like this so that we don't clobber the borrow_mut above
3866            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3867        });
3868
3869        cx.update(|cx| {
3870            state.write(cx, false);
3871        });
3872
3873        assert_eq!(*observation_count.borrow(), 2);
3874    }
3875
3876    #[gpui::test]
3877    async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
3878        #[cfg(unix)]
3879        let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
3880        #[cfg(not(unix))]
3881        let user_data_dir = OsString::from("C:\\zed data");
3882        let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
3883        let restart_path = PathBuf::from("updated-zed");
3884        let _application =
3885            super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
3886        let restart = cx.expect_restart();
3887
3888        cx.update(|cx| {
3889            cx.set_restart_path(restart_path.clone());
3890            cx.restart();
3891        });
3892
3893        let (path, restart_arguments) = restart.await.expect("restart was not requested");
3894        assert_eq!(path, Some(restart_path));
3895        assert_eq!(restart_arguments, arguments);
3896    }
3897
3898    fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
3899        MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
3900    }
3901}