Skip to main content

gpui/
app.rs

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