Skip to main content

gpui/
app.rs

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