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