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