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