Skip to main content

gpui/
app.rs

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