Skip to main content

gpui/
app.rs

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