Skip to main content

gpui/
app.rs

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