Skip to main content

gpui/
app.rs

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