Skip to main content

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