Skip to main content

gpui/
app.rs

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