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