Skip to main content

open_gpui/
app.rs

1use open_gpui_scheduler::Instant;
2use std::{
3    any::{TypeId, type_name},
4    cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
5    marker::PhantomData,
6    mem,
7    ops::{Deref, DerefMut},
8    path::{Path, PathBuf},
9    rc::{Rc, Weak},
10    sync::{Arc, atomic::Ordering::SeqCst},
11    time::Duration,
12};
13
14use anyhow::{Context as _, Result, anyhow};
15use derive_more::{Deref, DerefMut};
16use futures::{
17    Future, FutureExt,
18    channel::oneshot,
19    future::{LocalBoxFuture, Shared},
20};
21use itertools::Itertools;
22use parking_lot::RwLock;
23use slotmap::SlotMap;
24
25pub use async_context::*;
26#[cfg(any(test, feature = "test-support"))]
27pub use bench_context::{BenchAppContext, BenchWindowContext};
28pub use context::*;
29pub use entity_map::*;
30#[cfg(any(test, feature = "test-support"))]
31pub use headless_app_context::*;
32use open_gpui_collections::{
33    FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque,
34};
35use open_gpui_core_util::{ResultExt, debug_panic};
36use open_gpui_http_client::{HttpClient, Url};
37use smallvec::SmallVec;
38#[cfg(any(test, feature = "test-support"))]
39pub use test_app::*;
40#[cfg(any(test, feature = "test-support"))]
41pub use test_context::*;
42#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
43pub use visual_test_context::*;
44
45#[cfg(any(feature = "inspector", debug_assertions))]
46use crate::InspectorElementRegistry;
47use crate::{
48    Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
49    ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle,
50    DispatchPhase, DisplayId, EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global,
51    KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu,
52    PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
53    PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton, PromptHandle,
54    PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource,
55    SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextRenderingMode, TextSystem,
56    ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
57    WindowInvalidator,
58    colors::{Colors, GlobalColors},
59    hash, init_app_menus,
60};
61
62mod async_context;
63#[cfg(any(test, feature = "test-support"))]
64mod bench_context;
65mod context;
66mod entity_map;
67#[cfg(any(test, feature = "test-support"))]
68mod headless_app_context;
69#[cfg(any(test, feature = "test-support"))]
70mod test_app;
71#[cfg(any(test, feature = "test-support"))]
72mod test_context;
73#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
74mod visual_test_context;
75
76/// The duration for which futures returned from [Context::on_app_quit] can run before the application fully quits.
77pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
78
79/// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows.
80/// Strongly consider removing after stabilization.
81#[doc(hidden)]
82pub struct AppCell {
83    app: RefCell<App>,
84}
85
86impl AppCell {
87    #[doc(hidden)]
88    #[track_caller]
89    pub fn borrow(&self) -> AppRef<'_> {
90        if option_env!("TRACK_THREAD_BORROWS").is_some() {
91            let thread_id = std::thread::current().id();
92            eprintln!("borrowed {thread_id:?}");
93        }
94        AppRef(self.app.borrow())
95    }
96
97    #[doc(hidden)]
98    #[track_caller]
99    pub fn borrow_mut(&self) -> AppRefMut<'_> {
100        if option_env!("TRACK_THREAD_BORROWS").is_some() {
101            let thread_id = std::thread::current().id();
102            eprintln!("borrowed {thread_id:?}");
103        }
104        AppRefMut(self.app.borrow_mut())
105    }
106
107    #[doc(hidden)]
108    #[track_caller]
109    pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
110        if option_env!("TRACK_THREAD_BORROWS").is_some() {
111            let thread_id = std::thread::current().id();
112            eprintln!("borrowed {thread_id:?}");
113        }
114        Ok(AppRefMut(self.app.try_borrow_mut()?))
115    }
116}
117
118#[doc(hidden)]
119#[derive(Deref, DerefMut)]
120pub struct AppRef<'a>(Ref<'a, App>);
121
122impl Drop for AppRef<'_> {
123    fn drop(&mut self) {
124        if option_env!("TRACK_THREAD_BORROWS").is_some() {
125            let thread_id = std::thread::current().id();
126            eprintln!("dropped borrow from {thread_id:?}");
127        }
128    }
129}
130
131#[doc(hidden)]
132#[derive(Deref, DerefMut)]
133pub struct AppRefMut<'a>(RefMut<'a, App>);
134
135impl Drop for AppRefMut<'_> {
136    fn drop(&mut self) {
137        if option_env!("TRACK_THREAD_BORROWS").is_some() {
138            let thread_id = std::thread::current().id();
139            eprintln!("dropped {thread_id:?}");
140        }
141    }
142}
143
144/// A reference to a GPUI application, typically constructed in the `main` function of your app.
145/// You won't interact with this type much outside of initial configuration and startup.
146pub struct Application(Rc<AppCell>);
147
148/// Represents an application before it is fully launched. Once your app is
149/// configured, you'll start the app with `App::run`.
150impl Application {
151    /// Builds an app with a caller-provided platform implementation.
152    pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
153        Self(App::new_app(
154            platform,
155            Arc::new(()),
156            Arc::new(NullHttpClient),
157        ))
158    }
159
160    /// Builds an app with accessibility (AccessKit) integration forcibly
161    /// disabled.
162    ///
163    /// In this mode, accessibility APIs (e.g.
164    /// [`div().role()`][crate::StatefulInteractiveElement::role]) silently
165    /// no-op.
166    ///
167    /// See the [accessibility guide](crate::_accessibility) for an overview of
168    /// the features this disables.
169    pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
170        let this = Self::with_platform(platform);
171        this.0.borrow_mut().accessibility_force_disabled = true;
172        this
173    }
174
175    /// Assigns the source of assets for the application.
176    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
177        let mut context_lock = self.0.borrow_mut();
178        let asset_source = Arc::new(asset_source);
179        context_lock.asset_source = asset_source.clone();
180        context_lock.svg_renderer = SvgRenderer::new(asset_source);
181        drop(context_lock);
182        self
183    }
184
185    /// Sets the HTTP client for the application.
186    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
187        let mut context_lock = self.0.borrow_mut();
188        context_lock.http_client = http_client;
189        drop(context_lock);
190        self
191    }
192
193    /// Configures when the application should automatically quit.
194    /// By default, [`QuitMode::Default`] is used.
195    pub fn with_quit_mode(self, mode: QuitMode) -> Self {
196        self.0.borrow_mut().quit_mode = mode;
197        self
198    }
199
200    /// Start the application. The provided callback will be called once the
201    /// app is fully launched.
202    pub fn run<F>(self, on_finish_launching: F)
203    where
204        F: 'static + FnOnce(&mut App),
205    {
206        let this = self.0.clone();
207        let platform = self.0.borrow().platform.clone();
208        platform.run(Box::new(move || {
209            let cx = &mut *this.borrow_mut();
210            on_finish_launching(cx);
211        }));
212    }
213
214    /// Register a handler to be invoked when the platform instructs the application
215    /// to open one or more URLs.
216    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
217    where
218        F: 'static + FnMut(Vec<String>),
219    {
220        self.0.borrow().platform.on_open_urls(Box::new(callback));
221        self
222    }
223
224    /// Invokes a handler when an already-running application is launched.
225    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
226    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
227    where
228        F: 'static + FnMut(&mut App),
229    {
230        let this = Rc::downgrade(&self.0);
231        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
232            if let Some(app) = this.upgrade() {
233                callback(&mut app.borrow_mut());
234            }
235        }));
236        self
237    }
238
239    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
240    pub fn background_executor(&self) -> BackgroundExecutor {
241        self.0.borrow().background_executor.clone()
242    }
243
244    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
245    pub fn foreground_executor(&self) -> ForegroundExecutor {
246        self.0.borrow().foreground_executor.clone()
247    }
248
249    /// Returns a reference to the [`TextSystem`] associated with this app.
250    pub fn text_system(&self) -> Arc<TextSystem> {
251        self.0.borrow().text_system.clone()
252    }
253
254    /// Returns the file URL of the executable with the specified name in the application bundle
255    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
256        self.0.borrow().path_for_auxiliary_executable(name)
257    }
258}
259
260type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
261type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
262pub(crate) type KeystrokeObserver =
263    Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
264type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
265type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
266type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
267type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
268
269/// Defines when the application should automatically quit.
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
271pub enum QuitMode {
272    /// Use [`QuitMode::Explicit`] on macOS and [`QuitMode::LastWindowClosed`] on other platforms.
273    #[default]
274    Default,
275    /// Quit automatically when the last window is closed.
276    LastWindowClosed,
277    /// Quit only when requested via [`App::quit`].
278    Explicit,
279}
280
281/// Controls when GPUI hides the mouse cursor in response to keyboard input.
282///
283/// Restoration on mouse motion is handled by the platform layer; this enum
284/// only describes the policy for *triggering* a hide.
285#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
286pub enum CursorHideMode {
287    /// Never hide the cursor automatically.
288    Never,
289    /// Hide on character-producing key presses (typing).
290    OnTyping,
291    /// Hide on character-producing key presses, *and* when a key binding
292    /// resolves to an action that consumes the keystroke.
293    #[default]
294    OnTypingAndAction,
295}
296
297#[doc(hidden)]
298#[derive(Clone, PartialEq, Eq)]
299pub struct SystemWindowTab {
300    pub id: WindowId,
301    pub title: SharedString,
302    pub handle: AnyWindowHandle,
303    pub last_active_at: Instant,
304}
305
306impl SystemWindowTab {
307    /// Create a new instance of the window tab.
308    pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
309        Self {
310            id: handle.id,
311            title,
312            handle,
313            last_active_at: Instant::now(),
314        }
315    }
316}
317
318/// A controller for managing window tabs.
319#[derive(Default)]
320pub struct SystemWindowTabController {
321    visible: Option<bool>,
322    tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
323}
324
325impl Global for SystemWindowTabController {}
326
327impl SystemWindowTabController {
328    /// Create a new instance of the window tab controller.
329    pub fn new() -> Self {
330        Self {
331            visible: None,
332            tab_groups: FxHashMap::default(),
333        }
334    }
335
336    /// Initialize the global window tab controller.
337    pub fn init(cx: &mut App) {
338        cx.set_global(SystemWindowTabController::new());
339    }
340
341    /// Get all tab groups.
342    pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
343        &self.tab_groups
344    }
345
346    /// Get the next tab group window handle.
347    pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
348        let controller = cx.global::<SystemWindowTabController>();
349        let current_group = controller
350            .tab_groups
351            .iter()
352            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
353
354        let current_group = current_group?;
355        // TODO: `.keys()` returns arbitrary order, what does "next" mean?
356        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
357        let idx = group_ids.iter().position(|g| *g == current_group)?;
358        let next_idx = (idx + 1) % group_ids.len();
359
360        controller
361            .tab_groups
362            .get(group_ids[next_idx])
363            .and_then(|tabs| {
364                tabs.iter()
365                    .max_by_key(|tab| tab.last_active_at)
366                    .or_else(|| tabs.first())
367                    .map(|tab| &tab.handle)
368            })
369    }
370
371    /// Get the previous tab group window handle.
372    pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
373        let controller = cx.global::<SystemWindowTabController>();
374        let current_group = controller
375            .tab_groups
376            .iter()
377            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
378
379        let current_group = current_group?;
380        // TODO: `.keys()` returns arbitrary order, what does "previous" mean?
381        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
382        let idx = group_ids.iter().position(|g| *g == current_group)?;
383        let prev_idx = if idx == 0 {
384            group_ids.len() - 1
385        } else {
386            idx - 1
387        };
388
389        controller
390            .tab_groups
391            .get(group_ids[prev_idx])
392            .and_then(|tabs| {
393                tabs.iter()
394                    .max_by_key(|tab| tab.last_active_at)
395                    .or_else(|| tabs.first())
396                    .map(|tab| &tab.handle)
397            })
398    }
399
400    /// Get all tabs in the same window.
401    pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
402        self.tab_groups
403            .values()
404            .find(|tabs| tabs.iter().any(|tab| tab.id == id))
405    }
406
407    /// Initialize the visibility of the system window tab controller.
408    pub fn init_visible(cx: &mut App, visible: bool) {
409        let mut controller = cx.global_mut::<SystemWindowTabController>();
410        if controller.visible.is_none() {
411            controller.visible = Some(visible);
412        }
413    }
414
415    /// Get the visibility of the system window tab controller.
416    pub fn is_visible(&self) -> bool {
417        self.visible.unwrap_or(false)
418    }
419
420    /// Set the visibility of the system window tab controller.
421    pub fn set_visible(cx: &mut App, visible: bool) {
422        let mut controller = cx.global_mut::<SystemWindowTabController>();
423        controller.visible = Some(visible);
424    }
425
426    /// Update the last active of a window.
427    pub fn update_last_active(cx: &mut App, id: WindowId) {
428        let mut controller = cx.global_mut::<SystemWindowTabController>();
429        for windows in controller.tab_groups.values_mut() {
430            for tab in windows.iter_mut() {
431                if tab.id == id {
432                    tab.last_active_at = Instant::now();
433                }
434            }
435        }
436    }
437
438    /// Update the position of a tab within its group.
439    pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
440        let mut controller = cx.global_mut::<SystemWindowTabController>();
441        for (_, windows) in controller.tab_groups.iter_mut() {
442            if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
443                if ix < windows.len() && current_pos != ix {
444                    let window_tab = windows.remove(current_pos);
445                    windows.insert(ix, window_tab);
446                }
447                break;
448            }
449        }
450    }
451
452    /// Update the title of a tab.
453    pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
454        let controller = cx.global::<SystemWindowTabController>();
455        let tab = controller
456            .tab_groups
457            .values()
458            .flat_map(|windows| windows.iter())
459            .find(|tab| tab.id == id);
460
461        if tab.map_or(true, |t| t.title == title) {
462            return;
463        }
464
465        let mut controller = cx.global_mut::<SystemWindowTabController>();
466        for windows in controller.tab_groups.values_mut() {
467            for tab in windows.iter_mut() {
468                if tab.id == id {
469                    tab.title = title;
470                    return;
471                }
472            }
473        }
474    }
475
476    /// Insert a tab into a tab group.
477    pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
478        let mut controller = cx.global_mut::<SystemWindowTabController>();
479        let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
480            return;
481        };
482
483        let mut expected_tab_ids: Vec<_> = tabs
484            .iter()
485            .filter(|tab| tab.id != id)
486            .map(|tab| tab.id)
487            .sorted()
488            .collect();
489
490        let mut tab_group_id = None;
491        for (group_id, group_tabs) in &controller.tab_groups {
492            let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
493            if tab_ids == expected_tab_ids {
494                tab_group_id = Some(*group_id);
495                break;
496            }
497        }
498
499        if let Some(tab_group_id) = tab_group_id {
500            if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
501                tabs.push(tab);
502            }
503        } else {
504            let new_group_id = controller.tab_groups.len();
505            controller.tab_groups.insert(new_group_id, tabs);
506        }
507    }
508
509    /// Remove a tab from a tab group.
510    pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
511        let mut controller = cx.global_mut::<SystemWindowTabController>();
512        let mut removed_tab = None;
513
514        controller.tab_groups.retain(|_, tabs| {
515            if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
516                removed_tab = Some(tabs.remove(pos));
517            }
518            !tabs.is_empty()
519        });
520
521        removed_tab
522    }
523
524    /// Move a tab to a new tab group.
525    pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
526        let mut removed_tab = Self::remove_tab(cx, id);
527        let mut controller = cx.global_mut::<SystemWindowTabController>();
528
529        if let Some(tab) = removed_tab {
530            let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
531            controller.tab_groups.insert(new_group_id, vec![tab]);
532        }
533    }
534
535    /// Merge all tab groups into a single group.
536    pub fn merge_all_windows(cx: &mut App, id: WindowId) {
537        let mut controller = cx.global_mut::<SystemWindowTabController>();
538        let Some(initial_tabs) = controller.tabs(id) else {
539            return;
540        };
541
542        let initial_tabs_len = initial_tabs.len();
543        let mut all_tabs = initial_tabs.clone();
544
545        for (_, mut tabs) in controller.tab_groups.drain() {
546            tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
547            all_tabs.extend(tabs);
548        }
549
550        controller.tab_groups.insert(0, all_tabs);
551    }
552
553    /// Selects the next tab in the tab group in the trailing direction.
554    pub fn select_next_tab(cx: &mut App, id: WindowId) {
555        let mut controller = cx.global_mut::<SystemWindowTabController>();
556        let Some(tabs) = controller.tabs(id) else {
557            return;
558        };
559
560        let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
561        let next_index = (current_index + 1) % tabs.len();
562
563        let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
564            window.activate_window();
565        });
566    }
567
568    /// Selects the previous tab in the tab group in the leading direction.
569    pub fn select_previous_tab(cx: &mut App, id: WindowId) {
570        let mut controller = cx.global_mut::<SystemWindowTabController>();
571        let Some(tabs) = controller.tabs(id) else {
572            return;
573        };
574
575        let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
576        let previous_index = if current_index == 0 {
577            tabs.len() - 1
578        } else {
579            current_index - 1
580        };
581
582        let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
583            window.activate_window();
584        });
585    }
586}
587
588pub(crate) enum GpuiMode {
589    #[cfg(any(test, feature = "test-support"))]
590    Test {
591        skip_drawing: bool,
592    },
593    Production,
594}
595
596impl GpuiMode {
597    #[cfg(any(test, feature = "test-support"))]
598    pub fn test() -> Self {
599        GpuiMode::Test {
600            skip_drawing: false,
601        }
602    }
603
604    #[inline]
605    pub(crate) fn skip_drawing(&self) -> bool {
606        match self {
607            #[cfg(any(test, feature = "test-support"))]
608            GpuiMode::Test { skip_drawing } => *skip_drawing,
609            GpuiMode::Production => false,
610        }
611    }
612}
613
614/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
615/// Other [Context] derefs to this type.
616/// You need a reference to an `App` to access the state of a [Entity].
617pub struct App {
618    pub(crate) this: Weak<AppCell>,
619    pub(crate) platform: Rc<dyn Platform>,
620    text_system: Arc<TextSystem>,
621
622    pub(crate) actions: Rc<ActionRegistry>,
623    pub(crate) active_drag: Option<AnyDrag>,
624    pub(crate) background_executor: BackgroundExecutor,
625    pub(crate) foreground_executor: ForegroundExecutor,
626    pub(crate) entities: EntityMap,
627    pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
628    pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
629    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
630    pub(crate) focus_handles: Arc<FocusMap>,
631    pub(crate) keymap: Rc<RefCell<Keymap>>,
632    pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
633    pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
634    pub(crate) global_action_listeners:
635        TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
636    pending_effects: VecDeque<Effect>,
637
638    pub(crate) observers: SubscriberSet<EntityId, Handler>,
639    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
640    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
641    pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
642    pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
643    pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
644    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
645    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
646    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
647    pub(crate) restart_observers: SubscriberSet<(), Handler>,
648    pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
649
650    /// Per-App element arena. This isolates element allocations between different
651    /// App instances (important for tests where multiple Apps run concurrently).
652    pub(crate) element_arena: RefCell<Arena>,
653    /// Per-App event arena.
654    pub(crate) event_arena: Arena,
655
656    // Drop globals last. We need to ensure all tasks owned by entities and
657    // callbacks are marked cancelled at this point as this will also shutdown
658    // the tokio runtime. As any task attempting to spawn a blocking tokio task,
659    // might panic.
660    pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
661
662    // assets
663    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
664    asset_source: Arc<dyn AssetSource>,
665    pub(crate) svg_renderer: SvgRenderer,
666    http_client: Arc<dyn HttpClient>,
667
668    // below is plain data, the drop order is insignificant here
669    pub(crate) pending_notifications: FxHashSet<EntityId>,
670    pub(crate) pending_global_notifications: TypeIdHashSet,
671    pub(crate) restart_path: Option<PathBuf>,
672    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
673    pub(crate) propagate_event: bool,
674    pub(crate) prompt_builder: Option<PromptBuilder>,
675    pub(crate) window_invalidators_by_entity:
676        FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
677    pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
678    pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
679    #[cfg(any(feature = "inspector", debug_assertions))]
680    pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
681    #[cfg(any(feature = "inspector", debug_assertions))]
682    pub(crate) inspector_element_registry: InspectorElementRegistry,
683    #[cfg(any(test, feature = "test-support", debug_assertions))]
684    pub(crate) name: Option<&'static str>,
685    pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
686
687    pub(crate) window_update_stack: Vec<WindowId>,
688    pub(crate) mode: GpuiMode,
689    pub(crate) cursor_hide_mode: CursorHideMode,
690    /// Whether the app was created by [`Application::new_inaccessible`]. No
691    /// accesskit APIs will be called when this flag is set.
692    pub(crate) accessibility_force_disabled: bool,
693    flushing_effects: bool,
694    pending_updates: usize,
695    quit_mode: QuitMode,
696    quitting: bool,
697
698    // We need to ensure the leak detector drops last, after all tasks, callbacks and things have been dropped.
699    // Otherwise it may report false positives.
700    #[cfg(any(test, feature = "leak-detection"))]
701    _ref_counts: Arc<RwLock<EntityRefCounts>>,
702}
703
704impl App {
705    #[allow(clippy::new_ret_no_self)]
706    pub(crate) fn new_app(
707        platform: Rc<dyn Platform>,
708        asset_source: Arc<dyn AssetSource>,
709        http_client: Arc<dyn HttpClient>,
710    ) -> Rc<AppCell> {
711        let background_executor = platform.background_executor();
712        let foreground_executor = platform.foreground_executor();
713        assert!(
714            background_executor.is_main_thread(),
715            "must construct App on main thread"
716        );
717
718        let text_system = Arc::new(TextSystem::new(platform.text_system()));
719        let entities = EntityMap::new();
720        let keyboard_layout = platform.keyboard_layout();
721        let keyboard_mapper = platform.keyboard_mapper();
722
723        #[cfg(any(test, feature = "leak-detection"))]
724        let _ref_counts = entities.ref_counts_drop_handle();
725
726        let app = Rc::new_cyclic(|this| AppCell {
727            app: RefCell::new(App {
728                this: this.clone(),
729                platform: platform.clone(),
730                text_system,
731                text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
732                mode: GpuiMode::Production,
733                actions: Rc::new(ActionRegistry::default()),
734                flushing_effects: false,
735                pending_updates: 0,
736                active_drag: None,
737                background_executor,
738                foreground_executor,
739                svg_renderer: SvgRenderer::new(asset_source.clone()),
740                loading_assets: Default::default(),
741                asset_source,
742                http_client,
743                globals_by_type: Default::default(),
744                entities,
745                new_entity_observers: SubscriberSet::new(),
746                windows: SlotMap::with_key(),
747                window_update_stack: Vec::new(),
748                window_handles: FxHashMap::default(),
749                focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
750                keymap: Rc::new(RefCell::new(Keymap::default())),
751                keyboard_layout,
752                keyboard_mapper,
753                global_action_listeners: Default::default(),
754                pending_effects: VecDeque::new(),
755                pending_notifications: FxHashSet::default(),
756                pending_global_notifications: Default::default(),
757                observers: SubscriberSet::new(),
758                tracked_entities: FxHashMap::default(),
759                window_invalidators_by_entity: FxHashMap::default(),
760                current_window_by_entity: FxHashMap::default(),
761                event_listeners: SubscriberSet::new(),
762                release_listeners: SubscriberSet::new(),
763                keystroke_observers: SubscriberSet::new(),
764                keystroke_interceptors: SubscriberSet::new(),
765                keyboard_layout_observers: SubscriberSet::new(),
766                thermal_state_observers: SubscriberSet::new(),
767                global_observers: SubscriberSet::new(),
768                quit_observers: SubscriberSet::new(),
769                restart_observers: SubscriberSet::new(),
770                restart_path: None,
771                window_closed_observers: SubscriberSet::new(),
772                layout_id_buffer: Default::default(),
773                propagate_event: true,
774                prompt_builder: Some(PromptBuilder::Default),
775                #[cfg(any(feature = "inspector", debug_assertions))]
776                inspector_renderer: None,
777                #[cfg(any(feature = "inspector", debug_assertions))]
778                inspector_element_registry: InspectorElementRegistry::default(),
779                quit_mode: QuitMode::default(),
780                quitting: false,
781                cursor_hide_mode: CursorHideMode::default(),
782                accessibility_force_disabled: false,
783
784                #[cfg(any(test, feature = "test-support", debug_assertions))]
785                name: None,
786                element_arena: RefCell::new(Arena::new(1024 * 1024)),
787                event_arena: Arena::new(1024 * 1024),
788
789                #[cfg(any(test, feature = "leak-detection"))]
790                _ref_counts,
791            }),
792        });
793
794        init_app_menus(platform.as_ref(), &app.borrow());
795        SystemWindowTabController::init(&mut app.borrow_mut());
796
797        platform.on_keyboard_layout_change(Box::new({
798            let app = Rc::downgrade(&app);
799            move || {
800                if let Some(app) = app.upgrade() {
801                    let cx = &mut app.borrow_mut();
802                    cx.keyboard_layout = cx.platform.keyboard_layout();
803                    cx.keyboard_mapper = cx.platform.keyboard_mapper();
804                    cx.keyboard_layout_observers
805                        .clone()
806                        .retain(&(), move |callback| (callback)(cx));
807                }
808            }
809        }));
810
811        platform.on_thermal_state_change(Box::new({
812            let app = Rc::downgrade(&app);
813            move || {
814                if let Some(app) = app.upgrade() {
815                    let cx = &mut app.borrow_mut();
816                    cx.thermal_state_observers
817                        .clone()
818                        .retain(&(), move |callback| (callback)(cx));
819                }
820            }
821        }));
822
823        platform.on_quit(Box::new({
824            let cx = Rc::downgrade(&app);
825            move || {
826                if let Some(cx) = cx.upgrade() {
827                    cx.borrow_mut().shutdown();
828                }
829            }
830        }));
831
832        app
833    }
834
835    #[doc(hidden)]
836    pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
837        self.entities.ref_counts_drop_handle()
838    }
839
840    /// Captures a snapshot of all entities that currently have alive handles.
841    ///
842    /// The returned [`LeakDetectorSnapshot`] can later be passed to
843    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
844    /// entities created after the snapshot are still alive.
845    #[cfg(any(test, feature = "leak-detection"))]
846    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
847        self.entities.leak_detector_snapshot()
848    }
849
850    /// Asserts that no entities created after `snapshot` still have alive handles.
851    ///
852    /// Entities that were already tracked at the time of the snapshot are ignored,
853    /// even if they still have handles. Only *new* entities (those whose
854    /// `EntityId` was not present in the snapshot) are considered leaks.
855    ///
856    /// # Panics
857    ///
858    /// Panics if any new entity handles exist. The panic message lists every
859    /// leaked entity with its type name, and includes allocation-site backtraces
860    /// when `LEAK_BACKTRACE` is set.
861    #[cfg(any(test, feature = "leak-detection"))]
862    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
863        self.entities.assert_no_new_leaks(snapshot)
864    }
865
866    /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`]
867    /// will be given `SHUTDOWN_TIMEOUT` to complete before exiting.
868    pub fn shutdown(&mut self) {
869        let mut futures = Vec::new();
870
871        for observer in self.quit_observers.remove(&()) {
872            futures.push(observer(self));
873        }
874
875        self.windows.clear();
876        self.window_handles.clear();
877        self.flush_effects();
878        self.quitting = true;
879
880        let futures = futures::future::join_all(futures);
881        if self
882            .foreground_executor
883            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
884            .is_err()
885        {
886            log::error!("timed out waiting on app_will_quit");
887        }
888
889        self.quitting = false;
890    }
891
892    /// Get the id of the current keyboard layout
893    pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
894        self.keyboard_layout.as_ref()
895    }
896
897    /// Get the current keyboard mapper.
898    pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
899        &self.keyboard_mapper
900    }
901
902    /// Invokes a handler when the current keyboard layout changes
903    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
904    where
905        F: 'static + FnMut(&mut App),
906    {
907        let (subscription, activate) = self.keyboard_layout_observers.insert(
908            (),
909            Box::new(move |cx| {
910                callback(cx);
911                true
912            }),
913        );
914        activate();
915        subscription
916    }
917
918    /// Gracefully quit the application via the platform's standard routine.
919    pub fn quit(&self) {
920        self.platform.quit();
921    }
922
923    /// Returns the current policy for hiding the cursor in response to
924    /// keyboard input.
925    pub fn cursor_hide_mode(&self) -> CursorHideMode {
926        self.cursor_hide_mode
927    }
928
929    /// Sets the policy controlling when GPUI hides the cursor in response
930    /// to keyboard input.
931    pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
932        self.cursor_hide_mode = mode;
933    }
934
935    /// Returns whether the cursor is currently visible according to the
936    /// platform. This will report `false` after a keyboard input has hidden
937    /// the cursor and the user has not yet moved the mouse to restore it.
938    ///
939    /// See [`App::set_cursor_hide_mode`].
940    pub fn is_cursor_visible(&self) -> bool {
941        self.platform.is_cursor_visible()
942    }
943
944    /// Schedules all windows in the application to be redrawn. This can be called
945    /// multiple times in an update cycle and still result in a single redraw.
946    pub fn refresh_windows(&mut self) {
947        self.pending_effects.push_back(Effect::RefreshWindows);
948    }
949
950    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
951        self.start_update();
952        let result = update(self);
953        self.finish_update();
954        result
955    }
956
957    pub(crate) fn start_update(&mut self) {
958        self.pending_updates += 1;
959    }
960
961    pub(crate) fn finish_update(&mut self) {
962        if !self.flushing_effects && self.pending_updates == 1 {
963            self.flushing_effects = true;
964            self.flush_effects();
965            self.flushing_effects = false;
966        }
967        self.pending_updates -= 1;
968    }
969
970    /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
971    pub fn observe<W>(
972        &mut self,
973        entity: &Entity<W>,
974        mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
975    ) -> Subscription
976    where
977        W: 'static,
978    {
979        self.observe_internal(entity, move |e, cx| {
980            on_notify(e, cx);
981            true
982        })
983    }
984
985    pub(crate) fn detect_accessed_entities<R>(
986        &mut self,
987        callback: impl FnOnce(&mut App) -> R,
988    ) -> (R, FxHashSet<EntityId>) {
989        let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
990        let result = callback(self);
991        let entities_accessed_in_callback = self
992            .entities
993            .accessed_entities
994            .get_mut()
995            .difference(&accessed_entities_start)
996            .copied()
997            .collect::<FxHashSet<EntityId>>();
998        (result, entities_accessed_in_callback)
999    }
1000
1001    pub(crate) fn record_entities_accessed(
1002        &mut self,
1003        window_handle: AnyWindowHandle,
1004        invalidator: WindowInvalidator,
1005        entities: &FxHashSet<EntityId>,
1006    ) {
1007        let mut tracked_entities =
1008            std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1009        for entity in tracked_entities.iter() {
1010            self.window_invalidators_by_entity
1011                .entry(*entity)
1012                .and_modify(|windows| {
1013                    windows.remove(&window_handle.id);
1014                });
1015        }
1016        for entity in entities.iter() {
1017            self.window_invalidators_by_entity
1018                .entry(*entity)
1019                .or_default()
1020                .insert(window_handle.id, invalidator.clone());
1021            self.current_window_by_entity
1022                .insert(*entity, window_handle.id);
1023        }
1024        tracked_entities.clear();
1025        tracked_entities.extend(entities.iter().copied());
1026        self.tracked_entities
1027            .insert(window_handle.id, tracked_entities);
1028    }
1029
1030    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1031        let (subscription, activate) = self.observers.insert(key, value);
1032        self.defer(move |_| activate());
1033        subscription
1034    }
1035
1036    pub(crate) fn observe_internal<W>(
1037        &mut self,
1038        entity: &Entity<W>,
1039        mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1040    ) -> Subscription
1041    where
1042        W: 'static,
1043    {
1044        let entity_id = entity.entity_id();
1045        let handle = entity.downgrade();
1046        self.new_observer(
1047            entity_id,
1048            Box::new(move |cx| {
1049                if let Some(entity) = handle.upgrade() {
1050                    on_notify(entity, cx)
1051                } else {
1052                    false
1053                }
1054            }),
1055        )
1056    }
1057
1058    /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
1059    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
1060    pub fn subscribe<T, Event>(
1061        &mut self,
1062        entity: &Entity<T>,
1063        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1064    ) -> Subscription
1065    where
1066        T: 'static + EventEmitter<Event>,
1067        Event: 'static,
1068    {
1069        self.subscribe_internal(entity, move |entity, event, cx| {
1070            on_event(entity, event, cx);
1071            true
1072        })
1073    }
1074
1075    pub(crate) fn new_subscription(
1076        &mut self,
1077        key: EntityId,
1078        value: (TypeId, Listener),
1079    ) -> Subscription {
1080        let (subscription, activate) = self.event_listeners.insert(key, value);
1081        self.defer(move |_| activate());
1082        subscription
1083    }
1084    pub(crate) fn subscribe_internal<T, Evt>(
1085        &mut self,
1086        entity: &Entity<T>,
1087        mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1088    ) -> Subscription
1089    where
1090        T: 'static + EventEmitter<Evt>,
1091        Evt: 'static,
1092    {
1093        let entity_id = entity.entity_id();
1094        let handle = entity.downgrade();
1095        self.new_subscription(
1096            entity_id,
1097            (
1098                TypeId::of::<Evt>(),
1099                Box::new(move |event, cx| {
1100                    let event: &Evt = event.downcast_ref().expect("invalid event type");
1101                    if let Some(entity) = handle.upgrade() {
1102                        on_event(entity, event, cx)
1103                    } else {
1104                        false
1105                    }
1106                }),
1107            ),
1108        )
1109    }
1110
1111    /// Returns handles to all open windows in the application.
1112    /// Each handle could be downcast to a handle typed for the root view of that window.
1113    /// To find all windows of a given type, you could filter on
1114    pub fn windows(&self) -> Vec<AnyWindowHandle> {
1115        self.windows
1116            .keys()
1117            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1118            .collect()
1119    }
1120
1121    /// Returns the window handles ordered by their appearance on screen, front to back.
1122    ///
1123    /// The first window in the returned list is the active/topmost window of the application.
1124    ///
1125    /// This method returns None if the platform doesn't implement the method yet.
1126    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1127        self.platform.window_stack()
1128    }
1129
1130    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
1131    pub fn active_window(&self) -> Option<AnyWindowHandle> {
1132        self.platform.active_window()
1133    }
1134
1135    /// Opens a new window with the given option and the root view returned by the given function.
1136    /// The function is invoked with a `Window`, which can be used to interact with window-specific
1137    /// functionality.
1138    pub fn open_window<V: 'static + Render>(
1139        &mut self,
1140        options: crate::WindowOptions,
1141        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1142    ) -> anyhow::Result<WindowHandle<V>> {
1143        self.update(|cx| {
1144            let id = cx.windows.insert(None);
1145            let handle = WindowHandle::new(id);
1146            match Window::new(handle.into(), options, cx) {
1147                Ok(mut window) => {
1148                    cx.window_update_stack.push(id);
1149                    let root_view = build_root_view(&mut window, cx);
1150                    cx.window_update_stack.pop();
1151                    window.root.replace(root_view.into());
1152                    window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1153
1154                    // allow a window to draw at least once before returning
1155                    // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
1156                    // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
1157                    // where DispatchTree::root_node_id asserts on empty nodes
1158                    let clear = window.draw(cx);
1159                    clear.clear();
1160
1161                    cx.window_handles.insert(id, window.handle);
1162                    cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1163                    Ok(handle)
1164                }
1165                Err(e) => {
1166                    cx.windows.remove(id);
1167                    Err(e)
1168                }
1169            }
1170        })
1171    }
1172
1173    /// Instructs the platform to activate the application by bringing it to the foreground.
1174    pub fn activate(&self, ignoring_other_apps: bool) {
1175        self.platform.activate(ignoring_other_apps);
1176    }
1177
1178    /// Hide the application at the platform level.
1179    pub fn hide(&self) {
1180        self.platform.hide();
1181    }
1182
1183    /// Hide other applications at the platform level.
1184    pub fn hide_other_apps(&self) {
1185        self.platform.hide_other_apps();
1186    }
1187
1188    /// Unhide other applications at the platform level.
1189    pub fn unhide_other_apps(&self) {
1190        self.platform.unhide_other_apps();
1191    }
1192
1193    /// Returns the list of currently active displays.
1194    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1195        self.platform.displays()
1196    }
1197
1198    /// Returns the primary display that will be used for new windows.
1199    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1200        self.platform.primary_display()
1201    }
1202
1203    /// Returns whether `screen_capture_sources` may work.
1204    pub fn is_screen_capture_supported(&self) -> bool {
1205        self.platform.is_screen_capture_supported()
1206    }
1207
1208    /// Returns a list of available screen capture sources.
1209    pub fn screen_capture_sources(
1210        &self,
1211    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1212        self.platform.screen_capture_sources()
1213    }
1214
1215    /// Returns the display with the given ID, if one exists.
1216    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1217        self.displays()
1218            .iter()
1219            .find(|display| display.id() == id)
1220            .cloned()
1221    }
1222
1223    /// Returns the current thermal state of the system.
1224    pub fn thermal_state(&self) -> ThermalState {
1225        self.platform.thermal_state()
1226    }
1227
1228    /// Invokes a handler when the thermal state changes
1229    pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1230    where
1231        F: 'static + FnMut(&mut App),
1232    {
1233        let (subscription, activate) = self.thermal_state_observers.insert(
1234            (),
1235            Box::new(move |cx| {
1236                callback(cx);
1237                true
1238            }),
1239        );
1240        activate();
1241        subscription
1242    }
1243
1244    /// Returns the appearance of the application's windows.
1245    pub fn window_appearance(&self) -> WindowAppearance {
1246        self.platform.window_appearance()
1247    }
1248
1249    /// Returns the window button layout configuration when supported.
1250    pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1251        self.platform.button_layout()
1252    }
1253
1254    /// Reads data from the platform clipboard.
1255    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1256        self.platform.read_from_clipboard()
1257    }
1258
1259    /// Sets the text rendering mode for the application.
1260    pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1261        self.text_rendering_mode.set(mode);
1262    }
1263
1264    /// Returns the current text rendering mode for the application.
1265    pub fn text_rendering_mode(&self) -> TextRenderingMode {
1266        self.text_rendering_mode.get()
1267    }
1268
1269    /// Writes data to the platform clipboard.
1270    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1271        self.platform.write_to_clipboard(item)
1272    }
1273
1274    /// Reads data from the primary selection buffer.
1275    /// Only available on Linux.
1276    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1277    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1278        self.platform.read_from_primary()
1279    }
1280
1281    /// Writes data to the primary selection buffer.
1282    /// Only available on Linux.
1283    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1284    pub fn write_to_primary(&self, item: ClipboardItem) {
1285        self.platform.write_to_primary(item)
1286    }
1287
1288    /// Reads data from macOS's "Find" pasteboard.
1289    ///
1290    /// Used to share the current search string between apps.
1291    ///
1292    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1293    #[cfg(target_os = "macos")]
1294    pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1295        self.platform.read_from_find_pasteboard()
1296    }
1297
1298    /// Writes data to macOS's "Find" pasteboard.
1299    ///
1300    /// Used to share the current search string between apps.
1301    ///
1302    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1303    #[cfg(target_os = "macos")]
1304    pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1305        self.platform.write_to_find_pasteboard(item)
1306    }
1307
1308    /// Writes credentials to the platform keychain.
1309    pub fn write_credentials(
1310        &self,
1311        url: &str,
1312        username: &str,
1313        password: &[u8],
1314    ) -> Task<Result<()>> {
1315        self.platform.write_credentials(url, username, password)
1316    }
1317
1318    /// Reads credentials from the platform keychain.
1319    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1320        self.platform.read_credentials(url)
1321    }
1322
1323    /// Deletes credentials from the platform keychain.
1324    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1325        self.platform.delete_credentials(url)
1326    }
1327
1328    /// Directs the platform's default browser to open the given URL.
1329    pub fn open_url(&self, url: &str) {
1330        self.platform.open_url(url);
1331    }
1332
1333    /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
1334    /// opened by the current app.
1335    ///
1336    /// On some platforms (e.g. macOS) you may be able to register URL schemes
1337    /// as part of app distribution, but this method exists to let you register
1338    /// schemes at runtime.
1339    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1340        self.platform.register_url_scheme(scheme)
1341    }
1342
1343    /// Returns the full pathname of the current app bundle.
1344    ///
1345    /// Returns an error if the app is not being run from a bundle.
1346    pub fn app_path(&self) -> Result<PathBuf> {
1347        self.platform.app_path()
1348    }
1349
1350    /// On Linux, returns the name of the compositor in use.
1351    ///
1352    /// Returns an empty string on other platforms.
1353    pub fn compositor_name(&self) -> &'static str {
1354        self.platform.compositor_name()
1355    }
1356
1357    /// Returns the file URL of the executable with the specified name in the application bundle
1358    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1359        self.platform.path_for_auxiliary_executable(name)
1360    }
1361
1362    /// Displays a platform modal for selecting paths.
1363    ///
1364    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
1365    /// If cancelled, a `None` will be relayed instead.
1366    /// May return an error on Linux if the file picker couldn't be opened.
1367    pub fn prompt_for_paths(
1368        &self,
1369        options: PathPromptOptions,
1370    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1371        self.platform.prompt_for_paths(options)
1372    }
1373
1374    /// Displays a platform modal for selecting a new path where a file can be saved.
1375    ///
1376    /// The provided directory will be used to set the initial location.
1377    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
1378    /// If cancelled, a `None` will be relayed instead.
1379    /// May return an error on Linux if the file picker couldn't be opened.
1380    pub fn prompt_for_new_path(
1381        &self,
1382        directory: &Path,
1383        suggested_name: Option<&str>,
1384    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1385        self.platform.prompt_for_new_path(directory, suggested_name)
1386    }
1387
1388    /// Reveals the specified path at the platform level, such as in Finder on macOS.
1389    pub fn reveal_path(&self, path: &Path) {
1390        self.platform.reveal_path(path)
1391    }
1392
1393    /// Opens the specified path with the system's default application.
1394    pub fn open_with_system(&self, path: &Path) {
1395        self.platform.open_with_system(path)
1396    }
1397
1398    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
1399    pub fn should_auto_hide_scrollbars(&self) -> bool {
1400        self.platform.should_auto_hide_scrollbars()
1401    }
1402
1403    /// Restarts the application.
1404    pub fn restart(&mut self) {
1405        self.restart_observers
1406            .clone()
1407            .retain(&(), |observer| observer(self));
1408        self.platform.restart(self.restart_path.take())
1409    }
1410
1411    /// Sets the path to use when restarting the application.
1412    pub fn set_restart_path(&mut self, path: PathBuf) {
1413        self.restart_path = Some(path);
1414    }
1415
1416    /// Returns the HTTP client for the application.
1417    pub fn http_client(&self) -> Arc<dyn HttpClient> {
1418        self.http_client.clone()
1419    }
1420
1421    /// Sets the HTTP client for the application.
1422    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1423        self.http_client = new_client;
1424    }
1425
1426    /// Configures when the application should automatically quit.
1427    /// By default, [`QuitMode::Default`] is used.
1428    pub fn set_quit_mode(&mut self, mode: QuitMode) {
1429        self.quit_mode = mode;
1430    }
1431
1432    /// Returns the SVG renderer used by the application.
1433    pub fn svg_renderer(&self) -> SvgRenderer {
1434        self.svg_renderer.clone()
1435    }
1436
1437    pub(crate) fn push_effect(&mut self, effect: Effect) {
1438        match &effect {
1439            Effect::Notify { emitter } => {
1440                if !self.pending_notifications.insert(*emitter) {
1441                    return;
1442                }
1443            }
1444            Effect::NotifyGlobalObservers { global_type } => {
1445                if !self.pending_global_notifications.insert(*global_type) {
1446                    return;
1447                }
1448            }
1449            _ => {}
1450        };
1451
1452        self.pending_effects.push_back(effect);
1453    }
1454
1455    /// Called at the end of [`App::update`] to complete any side effects
1456    /// such as notifying observers, emitting events, etc. Effects can themselves
1457    /// cause effects, so we continue looping until all effects are processed.
1458    fn flush_effects(&mut self) {
1459        loop {
1460            self.release_dropped_entities();
1461            self.release_dropped_focus_handles();
1462            if let Some(effect) = self.pending_effects.pop_front() {
1463                match effect {
1464                    Effect::Notify { emitter } => {
1465                        self.apply_notify_effect(emitter);
1466                    }
1467
1468                    Effect::Emit {
1469                        emitter,
1470                        event_type,
1471                        event,
1472                    } => self.apply_emit_effect(emitter, event_type, &*event),
1473
1474                    Effect::RefreshWindows => {
1475                        self.apply_refresh_effect();
1476                    }
1477
1478                    Effect::NotifyGlobalObservers { global_type } => {
1479                        self.apply_notify_global_observers_effect(global_type);
1480                    }
1481
1482                    Effect::Defer { callback } => {
1483                        self.apply_defer_effect(callback);
1484                    }
1485                    Effect::EntityCreated {
1486                        entity,
1487                        tid,
1488                        window,
1489                    } => {
1490                        self.apply_entity_created_effect(entity, tid, window);
1491                    }
1492                }
1493            } else {
1494                #[cfg(any(test, feature = "test-support"))]
1495                for window in self
1496                    .windows
1497                    .values()
1498                    .filter_map(|window| {
1499                        let window = window.as_deref()?;
1500                        window.invalidator.is_dirty().then_some(window.handle)
1501                    })
1502                    .collect::<Vec<_>>()
1503                {
1504                    self.update_window(window, |_, window, cx| window.draw(cx).clear())
1505                        .unwrap();
1506                }
1507
1508                if self.pending_effects.is_empty() {
1509                    self.event_arena.clear();
1510                    break;
1511                }
1512            }
1513        }
1514    }
1515
1516    /// Repeatedly called during `flush_effects` to release any entities whose
1517    /// reference count has become zero. We invoke any release observers before dropping
1518    /// each entity.
1519    fn release_dropped_entities(&mut self) {
1520        loop {
1521            let dropped = self.entities.take_dropped();
1522            if dropped.is_empty() {
1523                break;
1524            }
1525
1526            for (entity_id, mut entity) in dropped {
1527                self.observers.remove(&entity_id);
1528                self.event_listeners.remove(&entity_id);
1529                self.window_invalidators_by_entity.remove(&entity_id);
1530                self.current_window_by_entity.remove(&entity_id);
1531                for release_callback in self.release_listeners.remove(&entity_id) {
1532                    release_callback(entity.as_mut(), self);
1533                }
1534            }
1535        }
1536    }
1537
1538    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
1539    fn release_dropped_focus_handles(&mut self) {
1540        self.focus_handles
1541            .clone()
1542            .write()
1543            .retain(|handle_id, focus| {
1544                if focus.ref_count.load(SeqCst) == 0 {
1545                    for window_handle in self.windows() {
1546                        window_handle
1547                            .update(self, |_, window, _| {
1548                                if window.focus == Some(handle_id) {
1549                                    window.blur();
1550                                }
1551                            })
1552                            .unwrap();
1553                    }
1554                    false
1555                } else {
1556                    true
1557                }
1558            });
1559    }
1560
1561    fn apply_notify_effect(&mut self, emitter: EntityId) {
1562        self.pending_notifications.remove(&emitter);
1563
1564        self.observers
1565            .clone()
1566            .retain(&emitter, |handler| handler(self));
1567    }
1568
1569    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1570        self.event_listeners
1571            .clone()
1572            .retain(&emitter, |(stored_type, handler)| {
1573                if *stored_type == event_type {
1574                    handler(event, self)
1575                } else {
1576                    true
1577                }
1578            });
1579    }
1580
1581    fn apply_refresh_effect(&mut self) {
1582        for window in self.windows.values_mut() {
1583            if let Some(window) = window.as_deref_mut() {
1584                window.refreshing = true;
1585                window.invalidator.set_dirty(true);
1586            }
1587        }
1588    }
1589
1590    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1591        self.pending_global_notifications.remove(&type_id);
1592        self.global_observers
1593            .clone()
1594            .retain(&type_id, |observer| observer(self));
1595    }
1596
1597    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1598        callback(self);
1599    }
1600
1601    fn apply_entity_created_effect(
1602        &mut self,
1603        entity: AnyEntity,
1604        tid: TypeId,
1605        window: Option<WindowId>,
1606    ) {
1607        // Seed the entity's current window from its creation context so
1608        // `with_window` resolves correctly before the entity has ever been
1609        // rendered.
1610        if let Some(id) = window {
1611            self.current_window_by_entity.insert(entity.entity_id(), id);
1612        }
1613
1614        self.new_entity_observers.clone().retain(&tid, |observer| {
1615            if let Some(id) = window {
1616                self.update_window_id(id, {
1617                    let entity = entity.clone();
1618                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
1619                })
1620                .expect("All windows should be off the stack when flushing effects");
1621            } else {
1622                (observer)(entity.clone(), &mut None, self)
1623            }
1624            true
1625        });
1626    }
1627
1628    /// Run `f` against the entity's *current* window — the most recently
1629    /// rendered window that referenced the entity, or its creation window if
1630    /// it has yet to be rendered. Returns `None` if the entity has no
1631    /// current window, or if that window has been closed, or if it is
1632    /// already on the update stack.
1633    pub fn with_window<R>(
1634        &mut self,
1635        entity_id: EntityId,
1636        f: impl FnOnce(&mut Window, &mut App) -> R,
1637    ) -> Option<R> {
1638        let window_id = *self.current_window_by_entity.get(&entity_id)?;
1639        self.update_window_id(window_id, |_, window, cx| f(window, cx))
1640            .ok()
1641    }
1642
1643    fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1644        self.current_window_by_entity
1645            .entry(entity_id)
1646            .or_insert(window);
1647    }
1648
1649    pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1650    where
1651        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1652    {
1653        self.update(|cx| {
1654            let mut window = cx.windows.get_mut(id)?.take()?;
1655
1656            let root_view = window.root.clone().unwrap();
1657
1658            cx.window_update_stack.push(window.handle.id);
1659            let result = update(root_view, &mut window, cx);
1660            fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1661                cx.window_update_stack.pop();
1662
1663                if window.removed {
1664                    cx.window_handles.remove(&id);
1665                    cx.windows.remove(id);
1666                    if let Some(tracked) = cx.tracked_entities.remove(&id) {
1667                        for entity_id in tracked {
1668                            if let Some(windows) =
1669                                cx.window_invalidators_by_entity.get_mut(&entity_id)
1670                            {
1671                                windows.remove(&id);
1672                            }
1673                            if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1674                                cx.current_window_by_entity.remove(&entity_id);
1675                            }
1676                        }
1677                    }
1678
1679                    cx.window_closed_observers.clone().retain(&(), |callback| {
1680                        callback(cx, id);
1681                        true
1682                    });
1683
1684                    let quit_on_empty = match cx.quit_mode {
1685                        QuitMode::Explicit => false,
1686                        QuitMode::LastWindowClosed => true,
1687                        QuitMode::Default => cfg!(not(target_os = "macos")),
1688                    };
1689
1690                    if quit_on_empty && cx.windows.is_empty() {
1691                        cx.quit();
1692                    }
1693                } else {
1694                    cx.windows.get_mut(id)?.replace(window);
1695                }
1696                Some(())
1697            }
1698            trail(id, window, cx)?;
1699
1700            Some(result)
1701        })
1702        .context("window not found")
1703    }
1704
1705    /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1706    /// so it can be held across `await` points.
1707    pub fn to_async(&self) -> AsyncApp {
1708        AsyncApp {
1709            app: self.this.clone(),
1710            background_executor: self.background_executor.clone(),
1711            foreground_executor: self.foreground_executor.clone(),
1712        }
1713    }
1714
1715    /// Obtains a reference to the executor, which can be used to spawn futures.
1716    pub fn background_executor(&self) -> &BackgroundExecutor {
1717        &self.background_executor
1718    }
1719
1720    /// Obtains a reference to the executor, which can be used to spawn futures.
1721    pub fn foreground_executor(&self) -> &ForegroundExecutor {
1722        if self.quitting {
1723            panic!("Can't spawn on main thread after on_app_quit")
1724        };
1725        &self.foreground_executor
1726    }
1727
1728    /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1729    /// with [AsyncApp], which allows the application state to be accessed across await points.
1730    #[track_caller]
1731    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1732    where
1733        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1734        R: 'static,
1735    {
1736        if self.quitting {
1737            debug_panic!("Can't spawn on main thread after on_app_quit")
1738        };
1739
1740        let mut cx = self.to_async();
1741
1742        self.foreground_executor
1743            .spawn(async move { f(&mut cx).await }.boxed_local())
1744    }
1745
1746    /// Spawns the future returned by the given function on the main thread with
1747    /// the given priority. The closure will be invoked with [AsyncApp], which
1748    /// allows the application state to be accessed across await points.
1749    pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1750    where
1751        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1752        R: 'static,
1753    {
1754        if self.quitting {
1755            debug_panic!("Can't spawn on main thread after on_app_quit")
1756        };
1757
1758        let mut cx = self.to_async();
1759
1760        self.foreground_executor
1761            .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
1762    }
1763
1764    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1765    /// that are currently on the stack to be returned to the app.
1766    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1767        self.push_effect(Effect::Defer {
1768            callback: Box::new(f),
1769        });
1770    }
1771
1772    /// Accessor for the application's asset source, which is provided when constructing the `App`.
1773    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1774        &self.asset_source
1775    }
1776
1777    /// Accessor for the text system.
1778    pub fn text_system(&self) -> &Arc<TextSystem> {
1779        &self.text_system
1780    }
1781
1782    /// Check whether a global of the given type has been assigned.
1783    pub fn has_global<G: Global>(&self) -> bool {
1784        self.globals_by_type.contains_key(&TypeId::of::<G>())
1785    }
1786
1787    /// Access the global of the given type. Panics if a global for that type has not been assigned.
1788    #[track_caller]
1789    pub fn global<G: Global>(&self) -> &G {
1790        self.globals_by_type
1791            .get(&TypeId::of::<G>())
1792            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1793            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1794    }
1795
1796    /// Access the global of the given type if a value has been assigned.
1797    pub fn try_global<G: Global>(&self) -> Option<&G> {
1798        self.globals_by_type
1799            .get(&TypeId::of::<G>())
1800            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1801    }
1802
1803    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1804    #[track_caller]
1805    pub fn global_mut<G: Global>(&mut self) -> &mut G {
1806        let global_type = TypeId::of::<G>();
1807        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1808        self.globals_by_type
1809            .get_mut(&global_type)
1810            .and_then(|any_state| any_state.downcast_mut::<G>())
1811            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1812    }
1813
1814    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1815    /// yet been assigned.
1816    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1817        let global_type = TypeId::of::<G>();
1818        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1819        self.globals_by_type
1820            .entry(global_type)
1821            .or_insert_with(|| Box::<G>::default())
1822            .downcast_mut::<G>()
1823            .unwrap()
1824    }
1825
1826    /// Sets the value of the global of the given type.
1827    pub fn set_global<G: Global>(&mut self, global: G) {
1828        let global_type = TypeId::of::<G>();
1829        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1830        self.globals_by_type.insert(global_type, Box::new(global));
1831    }
1832
1833    /// Clear all stored globals. Does not notify global observers.
1834    #[cfg(any(test, feature = "test-support"))]
1835    pub fn clear_globals(&mut self) {
1836        self.globals_by_type.drain();
1837    }
1838
1839    /// Remove the global of the given type from the app context. Does not notify global observers.
1840    pub fn remove_global<G: Global>(&mut self) -> G {
1841        let global_type = TypeId::of::<G>();
1842        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1843        *self
1844            .globals_by_type
1845            .remove(&global_type)
1846            .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
1847            .downcast()
1848            .unwrap()
1849    }
1850
1851    /// Register a callback to be invoked when a global of the given type is updated.
1852    pub fn observe_global<G: Global>(
1853        &mut self,
1854        mut f: impl FnMut(&mut Self) + 'static,
1855    ) -> Subscription {
1856        let (subscription, activate) = self.global_observers.insert(
1857            TypeId::of::<G>(),
1858            Box::new(move |cx| {
1859                f(cx);
1860                true
1861            }),
1862        );
1863        self.defer(move |_| activate());
1864        subscription
1865    }
1866
1867    /// Move the global of the given type to the stack.
1868    #[track_caller]
1869    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1870        GlobalLease::new(
1871            self.globals_by_type
1872                .remove(&TypeId::of::<G>())
1873                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1874                .unwrap(),
1875        )
1876    }
1877
1878    /// Restore the global of the given type after it is moved to the stack.
1879    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1880        let global_type = TypeId::of::<G>();
1881
1882        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1883        self.globals_by_type.insert(global_type, lease.global);
1884    }
1885
1886    pub(crate) fn new_entity_observer(
1887        &self,
1888        key: TypeId,
1889        value: NewEntityListener,
1890    ) -> Subscription {
1891        let (subscription, activate) = self.new_entity_observers.insert(key, value);
1892        activate();
1893        subscription
1894    }
1895
1896    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1897    /// The function will be passed a mutable reference to the view along with an appropriate context.
1898    pub fn observe_new<T: 'static>(
1899        &self,
1900        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1901    ) -> Subscription {
1902        self.new_entity_observer(
1903            TypeId::of::<T>(),
1904            Box::new(
1905                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1906                    any_entity
1907                        .downcast::<T>()
1908                        .unwrap()
1909                        .update(cx, |entity_state, cx| {
1910                            on_new(entity_state, window.as_deref_mut(), cx)
1911                        })
1912                },
1913            ),
1914        )
1915    }
1916
1917    /// Observe the release of a entity. The callback is invoked after the entity
1918    /// has no more strong references but before it has been dropped.
1919    pub fn observe_release<T>(
1920        &self,
1921        handle: &Entity<T>,
1922        on_release: impl FnOnce(&mut T, &mut App) + 'static,
1923    ) -> Subscription
1924    where
1925        T: 'static,
1926    {
1927        let (subscription, activate) = self.release_listeners.insert(
1928            handle.entity_id(),
1929            Box::new(move |entity, cx| {
1930                let entity = entity.downcast_mut().expect("invalid entity type");
1931                on_release(entity, cx)
1932            }),
1933        );
1934        activate();
1935        subscription
1936    }
1937
1938    /// Observe the release of a entity. The callback is invoked after the entity
1939    /// has no more strong references but before it has been dropped.
1940    pub fn observe_release_in<T>(
1941        &self,
1942        handle: &Entity<T>,
1943        window: &Window,
1944        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1945    ) -> Subscription
1946    where
1947        T: 'static,
1948    {
1949        let window_handle = window.handle;
1950        self.observe_release(handle, move |entity, cx| {
1951            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1952        })
1953    }
1954
1955    /// Register a callback to be invoked when a keystroke is received by the application
1956    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1957    /// and that this API will not be invoked if the event's propagation is stopped.
1958    pub fn observe_keystrokes(
1959        &mut self,
1960        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1961    ) -> Subscription {
1962        fn inner(
1963            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1964            handler: KeystrokeObserver,
1965        ) -> Subscription {
1966            let (subscription, activate) = keystroke_observers.insert((), handler);
1967            activate();
1968            subscription
1969        }
1970
1971        inner(
1972            &self.keystroke_observers,
1973            Box::new(move |event, window, cx| {
1974                f(event, window, cx);
1975                true
1976            }),
1977        )
1978    }
1979
1980    /// Register a callback to be invoked when a keystroke is received by the application
1981    /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1982    /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1983    /// within interceptors will prevent action dispatch
1984    pub fn intercept_keystrokes(
1985        &mut self,
1986        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1987    ) -> Subscription {
1988        fn inner(
1989            keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1990            handler: KeystrokeObserver,
1991        ) -> Subscription {
1992            let (subscription, activate) = keystroke_interceptors.insert((), handler);
1993            activate();
1994            subscription
1995        }
1996
1997        inner(
1998            &self.keystroke_interceptors,
1999            Box::new(move |event, window, cx| {
2000                f(event, window, cx);
2001                true
2002            }),
2003        )
2004    }
2005
2006    /// Register key bindings.
2007    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2008        self.keymap.borrow_mut().add_bindings(bindings);
2009        self.pending_effects.push_back(Effect::RefreshWindows);
2010    }
2011
2012    /// Clear all key bindings in the app.
2013    pub fn clear_key_bindings(&mut self) {
2014        self.keymap.borrow_mut().clear();
2015        self.pending_effects.push_back(Effect::RefreshWindows);
2016    }
2017
2018    /// Get all key bindings in the app.
2019    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2020        self.keymap.clone()
2021    }
2022
2023    /// Register a global handler for actions invoked via the keyboard. These handlers are run at
2024    /// the end of the bubble phase for actions, and so will only be invoked if there are no other
2025    /// handlers or if they called `cx.propagate()`.
2026    pub fn on_action<A: Action>(
2027        &mut self,
2028        listener: impl Fn(&A, &mut Self) + 'static,
2029    ) -> &mut Self {
2030        self.global_action_listeners
2031            .entry(TypeId::of::<A>())
2032            .or_default()
2033            .push(Rc::new(move |action, phase, cx| {
2034                if phase == DispatchPhase::Bubble {
2035                    let action = action.downcast_ref().unwrap();
2036                    listener(action, cx)
2037                }
2038            }));
2039        self
2040    }
2041
2042    /// Event handlers propagate events by default. Call this method to stop dispatching to
2043    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
2044    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
2045    /// calling this method before effects are flushed.
2046    pub fn stop_propagation(&mut self) {
2047        self.propagate_event = false;
2048    }
2049
2050    /// Action handlers stop propagation by default during the bubble phase of action dispatch
2051    /// dispatching to action handlers higher in the element tree. This is the opposite of
2052    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
2053    /// this method before effects are flushed.
2054    pub fn propagate(&mut self) {
2055        self.propagate_event = true;
2056    }
2057
2058    /// Build an action from some arbitrary data, typically a keymap entry.
2059    pub fn build_action(
2060        &self,
2061        name: &str,
2062        data: Option<serde_json::Value>,
2063    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2064        self.actions.build_action(name, data)
2065    }
2066
2067    /// Get all action names that have been registered. Note that registration only allows for
2068    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
2069    pub fn all_action_names(&self) -> &[&'static str] {
2070        self.actions.all_action_names()
2071    }
2072
2073    /// Returns key bindings that invoke the given action on the currently focused element, without
2074    /// checking context. Bindings are returned in the order they were added. For display, the last
2075    /// binding should take precedence.
2076    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2077        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2078    }
2079
2080    /// Get all non-internal actions that have been registered, along with their schemas.
2081    pub fn action_schemas(
2082        &self,
2083        generator: &mut schemars::SchemaGenerator,
2084    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2085        self.actions.action_schemas(generator)
2086    }
2087
2088    /// Get the schema for a specific action by name.
2089    /// Returns `None` if the action is not found.
2090    /// Returns `Some(None)` if the action exists but has no schema.
2091    /// Returns `Some(Some(schema))` if the action exists and has a schema.
2092    pub fn action_schema_by_name(
2093        &self,
2094        name: &str,
2095        generator: &mut schemars::SchemaGenerator,
2096    ) -> Option<Option<schemars::Schema>> {
2097        self.actions.action_schema_by_name(name, generator)
2098    }
2099
2100    /// Get a map from a deprecated action name to the canonical name.
2101    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2102        self.actions.deprecated_aliases()
2103    }
2104
2105    /// Get a map from an action name to the deprecation messages.
2106    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2107        self.actions.deprecation_messages()
2108    }
2109
2110    /// Get a map from an action name to the documentation.
2111    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2112        self.actions.documentation()
2113    }
2114
2115    /// Register a callback to be invoked when the application is about to quit.
2116    /// It is not possible to cancel the quit event at this point.
2117    pub fn on_app_quit<Fut>(
2118        &self,
2119        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2120    ) -> Subscription
2121    where
2122        Fut: 'static + Future<Output = ()>,
2123    {
2124        let (subscription, activate) = self.quit_observers.insert(
2125            (),
2126            Box::new(move |cx| {
2127                let future = on_quit(cx);
2128                future.boxed_local()
2129            }),
2130        );
2131        activate();
2132        subscription
2133    }
2134
2135    /// Register a callback to be invoked when the application is about to restart.
2136    ///
2137    /// These callbacks are called before any `on_app_quit` callbacks.
2138    pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2139        let (subscription, activate) = self.restart_observers.insert(
2140            (),
2141            Box::new(move |cx| {
2142                on_restart(cx);
2143                true
2144            }),
2145        );
2146        activate();
2147        subscription
2148    }
2149
2150    /// Register a callback to be invoked when a window is closed
2151    /// The window is no longer accessible at the point this callback is invoked.
2152    pub fn on_window_closed(
2153        &self,
2154        mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2155    ) -> Subscription {
2156        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2157        activate();
2158        subscription
2159    }
2160
2161    pub(crate) fn clear_pending_keystrokes(&mut self) {
2162        for window in self.windows() {
2163            window
2164                .update(self, |_, window, cx| {
2165                    if window.pending_input_keystrokes().is_some() {
2166                        window.clear_pending_keystrokes();
2167                        window.pending_input_changed(cx);
2168                    }
2169                })
2170                .ok();
2171        }
2172    }
2173
2174    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
2175    /// the bindings in the element tree, and any global action listeners.
2176    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2177        let mut action_available = false;
2178        if let Some(window) = self.active_window()
2179            && let Ok(window_action_available) =
2180                window.update(self, |_, window, cx| window.is_action_available(action, cx))
2181        {
2182            action_available = window_action_available;
2183        }
2184
2185        action_available
2186            || self
2187                .global_action_listeners
2188                .contains_key(&action.as_any().type_id())
2189    }
2190
2191    /// Sets the menu bar for this application. This will replace any existing menu bar.
2192    pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2193        let menus: Vec<Menu> = menus.into_iter().collect();
2194        self.platform.set_menus(menus, &self.keymap.borrow());
2195    }
2196
2197    /// Gets the menu bar for this application.
2198    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2199        self.platform.get_menus()
2200    }
2201
2202    /// Sets the right click menu for the app icon in the dock
2203    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2204        self.platform.set_dock_menu(menus, &self.keymap.borrow())
2205    }
2206
2207    /// Performs the action associated with the given dock menu item, only used on Windows for now.
2208    pub fn perform_dock_menu_action(&self, action: usize) {
2209        self.platform.perform_dock_menu_action(action);
2210    }
2211
2212    /// Adds given path to the bottom of the list of recent paths for the application.
2213    /// The list is usually shown on the application icon's context menu in the dock,
2214    /// and allows to open the recent files via that context menu.
2215    /// If the path is already in the list, it will be moved to the bottom of the list.
2216    pub fn add_recent_document(&self, path: &Path) {
2217        self.platform.add_recent_document(path);
2218    }
2219
2220    /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
2221    /// Note that this also sets the dock menu on Windows.
2222    pub fn update_jump_list(
2223        &self,
2224        menus: Vec<MenuItem>,
2225        entries: Vec<SmallVec<[PathBuf; 2]>>,
2226    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2227        self.platform.update_jump_list(menus, entries)
2228    }
2229
2230    /// Dispatch an action to the currently active window or global action handler
2231    /// See [`crate::Action`] for more information on how actions work
2232    pub fn dispatch_action(&mut self, action: &dyn Action) {
2233        if let Some(active_window) = self.active_window() {
2234            active_window
2235                .update(self, |_, window, cx| {
2236                    window.dispatch_action(action.boxed_clone(), cx)
2237                })
2238                .log_err();
2239        } else {
2240            self.dispatch_global_action(action);
2241        }
2242    }
2243
2244    fn dispatch_global_action(&mut self, action: &dyn Action) {
2245        self.propagate_event = true;
2246
2247        if let Some(mut global_listeners) = self
2248            .global_action_listeners
2249            .remove(&action.as_any().type_id())
2250        {
2251            for listener in &global_listeners {
2252                listener(action.as_any(), DispatchPhase::Capture, self);
2253                if !self.propagate_event {
2254                    break;
2255                }
2256            }
2257
2258            global_listeners.extend(
2259                self.global_action_listeners
2260                    .remove(&action.as_any().type_id())
2261                    .unwrap_or_default(),
2262            );
2263
2264            self.global_action_listeners
2265                .insert(action.as_any().type_id(), global_listeners);
2266        }
2267
2268        if self.propagate_event
2269            && let Some(mut global_listeners) = self
2270                .global_action_listeners
2271                .remove(&action.as_any().type_id())
2272        {
2273            for listener in global_listeners.iter().rev() {
2274                listener(action.as_any(), DispatchPhase::Bubble, self);
2275                if !self.propagate_event {
2276                    break;
2277                }
2278            }
2279
2280            global_listeners.extend(
2281                self.global_action_listeners
2282                    .remove(&action.as_any().type_id())
2283                    .unwrap_or_default(),
2284            );
2285
2286            self.global_action_listeners
2287                .insert(action.as_any().type_id(), global_listeners);
2288        }
2289    }
2290
2291    /// Is there currently something being dragged?
2292    pub fn has_active_drag(&self) -> bool {
2293        self.active_drag.is_some()
2294    }
2295
2296    /// Gets the cursor style of the currently active drag operation.
2297    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2298        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2299    }
2300
2301    /// Stops active drag and clears any related effects.
2302    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2303        if self.active_drag.is_some() {
2304            self.active_drag = None;
2305            window.refresh();
2306            true
2307        } else {
2308            false
2309        }
2310    }
2311
2312    /// Sets the cursor style for the currently active drag operation.
2313    pub fn set_active_drag_cursor_style(
2314        &mut self,
2315        cursor_style: CursorStyle,
2316        window: &mut Window,
2317    ) -> bool {
2318        if let Some(ref mut drag) = self.active_drag {
2319            drag.cursor_style = Some(cursor_style);
2320            window.refresh();
2321            true
2322        } else {
2323            false
2324        }
2325    }
2326
2327    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
2328    /// prompts with this custom implementation.
2329    pub fn set_prompt_builder(
2330        &mut self,
2331        renderer: impl Fn(
2332            PromptLevel,
2333            &str,
2334            Option<&str>,
2335            &[PromptButton],
2336            PromptHandle,
2337            &mut Window,
2338            &mut App,
2339        ) -> RenderablePromptHandle
2340        + 'static,
2341    ) {
2342        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2343    }
2344
2345    /// Reset the prompt builder to the default implementation.
2346    pub fn reset_prompt_builder(&mut self) {
2347        self.prompt_builder = Some(PromptBuilder::Default);
2348    }
2349
2350    /// Remove an asset from GPUI's cache
2351    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2352        let asset_id = (TypeId::of::<A>(), hash(source));
2353        self.loading_assets.remove(&asset_id);
2354    }
2355
2356    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2357    ///
2358    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2359    /// time, and the results of this call will be cached
2360    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2361        let asset_id = (TypeId::of::<A>(), hash(source));
2362        let mut is_first = false;
2363        let task = self
2364            .loading_assets
2365            .remove(&asset_id)
2366            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2367            .unwrap_or_else(|| {
2368                is_first = true;
2369                let future = A::load(source.clone(), self);
2370
2371                self.background_executor().spawn(future).shared()
2372            });
2373
2374        self.loading_assets.insert(asset_id, Box::new(task.clone()));
2375
2376        (task, is_first)
2377    }
2378
2379    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2380    /// for elements rendered within this window.
2381    #[track_caller]
2382    pub fn focus_handle(&self) -> FocusHandle {
2383        FocusHandle::new(&self.focus_handles)
2384    }
2385
2386    /// Tell GPUI that an entity has changed and observers of it should be notified.
2387    pub fn notify(&mut self, entity_id: EntityId) {
2388        let window_invalidators = mem::take(
2389            self.window_invalidators_by_entity
2390                .entry(entity_id)
2391                .or_default(),
2392        );
2393
2394        // `window_invalidators_by_entity` is monotonic, so an entry alone
2395        // doesn't mean the window is currently rendering the entity. Filter
2396        // through `tracked_entities` to keep invalidation tight to windows
2397        // that actually display this entity right now.
2398        let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
2399            .iter()
2400            .filter(|(window_id, _)| {
2401                self.tracked_entities
2402                    .get(window_id)
2403                    .is_some_and(|set| set.contains(&entity_id))
2404            })
2405            .map(|(_, invalidator)| invalidator.clone())
2406            .collect();
2407
2408        if live_invalidators.is_empty() {
2409            if self.pending_notifications.insert(entity_id) {
2410                self.pending_effects
2411                    .push_back(Effect::Notify { emitter: entity_id });
2412            }
2413        } else {
2414            for invalidator in &live_invalidators {
2415                invalidator.invalidate_view(entity_id, self);
2416            }
2417        }
2418
2419        self.window_invalidators_by_entity
2420            .insert(entity_id, window_invalidators);
2421    }
2422
2423    /// Returns the name for this [`App`].
2424    #[cfg(any(test, feature = "test-support", debug_assertions))]
2425    pub fn get_name(&self) -> Option<&'static str> {
2426        self.name
2427    }
2428
2429    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2430    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2431        self.platform.can_select_mixed_files_and_dirs()
2432    }
2433
2434    /// Removes an image from the sprite atlas on all windows.
2435    ///
2436    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2437    /// This is a no-op if the image is not in the sprite atlas.
2438    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2439        // remove the texture from all other windows
2440        for window in self.windows.values_mut().flatten() {
2441            _ = window.drop_image(image.clone());
2442        }
2443
2444        // remove the texture from the current window
2445        if let Some(window) = current_window {
2446            _ = window.drop_image(image);
2447        }
2448    }
2449
2450    /// Sets the renderer for the inspector.
2451    #[cfg(any(feature = "inspector", debug_assertions))]
2452    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2453        self.inspector_renderer = Some(f);
2454    }
2455
2456    /// Registers a renderer specific to an inspector state.
2457    #[cfg(any(feature = "inspector", debug_assertions))]
2458    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2459        &mut self,
2460        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2461    ) {
2462        self.inspector_element_registry.register(f);
2463    }
2464
2465    /// Initializes gpui's default colors for the application.
2466    ///
2467    /// These colors can be accessed through `cx.default_colors()`.
2468    pub fn init_colors(&mut self) {
2469        self.set_global(GlobalColors(Arc::new(Colors::default())));
2470    }
2471}
2472
2473impl AppContext for App {
2474    /// Builds an entity that is owned by the application.
2475    ///
2476    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2477    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2478    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2479        self.update(|cx| {
2480            let slot = cx.entities.reserve();
2481            let handle = slot.clone();
2482            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2483
2484            cx.push_effect(Effect::EntityCreated {
2485                entity: handle.into_any(),
2486                tid: TypeId::of::<T>(),
2487                window: cx.window_update_stack.last().cloned(),
2488            });
2489
2490            cx.entities.insert(slot, entity)
2491        })
2492    }
2493
2494    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
2495        Reservation(self.entities.reserve())
2496    }
2497
2498    fn insert_entity<T: 'static>(
2499        &mut self,
2500        reservation: Reservation<T>,
2501        build_entity: impl FnOnce(&mut Context<T>) -> T,
2502    ) -> Entity<T> {
2503        self.update(|cx| {
2504            let slot = reservation.0;
2505            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2506            cx.entities.insert(slot, entity)
2507        })
2508    }
2509
2510    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2511    /// entity along with a `Context` for the entity.
2512    fn update_entity<T: 'static, R>(
2513        &mut self,
2514        handle: &Entity<T>,
2515        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2516    ) -> R {
2517        self.update(|cx| {
2518            let mut entity = cx.entities.lease(handle);
2519            let result = update(
2520                &mut entity,
2521                &mut Context::new_context(cx, handle.downgrade()),
2522            );
2523            cx.entities.end_lease(entity);
2524            result
2525        })
2526    }
2527
2528    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2529    where
2530        T: 'static,
2531    {
2532        GpuiBorrow::new(handle.clone(), self)
2533    }
2534
2535    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
2536    where
2537        T: 'static,
2538    {
2539        let entity = self.entities.read(handle);
2540        read(entity, self)
2541    }
2542
2543    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2544    where
2545        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2546    {
2547        self.update_window_id(handle.id, update)
2548    }
2549
2550    fn with_window<R>(
2551        &mut self,
2552        entity_id: EntityId,
2553        f: impl FnOnce(&mut Window, &mut App) -> R,
2554    ) -> Option<R> {
2555        App::with_window(self, entity_id, f)
2556    }
2557
2558    fn read_window<T, R>(
2559        &self,
2560        window: &WindowHandle<T>,
2561        read: impl FnOnce(Entity<T>, &App) -> R,
2562    ) -> Result<R>
2563    where
2564        T: 'static,
2565    {
2566        let window = self
2567            .windows
2568            .get(window.id)
2569            .context("window not found")?
2570            .as_deref()
2571            .expect("attempted to read a window that is already on the stack");
2572
2573        let root_view = window.root.clone().unwrap();
2574        let view = root_view
2575            .downcast::<T>()
2576            .map_err(|_| anyhow!("root view's type has changed"))?;
2577
2578        Ok(read(view, self))
2579    }
2580
2581    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2582    where
2583        R: Send + 'static,
2584    {
2585        self.background_executor.spawn(future)
2586    }
2587
2588    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
2589    where
2590        G: Global,
2591    {
2592        let mut g = self.global::<G>();
2593        callback(g, self)
2594    }
2595}
2596
2597/// These effects are processed at the end of each application update cycle.
2598pub(crate) enum Effect {
2599    Notify {
2600        emitter: EntityId,
2601    },
2602    Emit {
2603        emitter: EntityId,
2604        event_type: TypeId,
2605        event: ArenaBox<dyn Any>,
2606    },
2607    RefreshWindows,
2608    NotifyGlobalObservers {
2609        global_type: TypeId,
2610    },
2611    Defer {
2612        callback: Box<dyn FnOnce(&mut App) + 'static>,
2613    },
2614    EntityCreated {
2615        entity: AnyEntity,
2616        tid: TypeId,
2617        window: Option<WindowId>,
2618    },
2619}
2620
2621impl std::fmt::Debug for Effect {
2622    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2623        match self {
2624            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2625            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2626            Effect::RefreshWindows => write!(f, "RefreshWindows"),
2627            Effect::NotifyGlobalObservers { global_type } => {
2628                write!(f, "NotifyGlobalObservers({:?})", global_type)
2629            }
2630            Effect::Defer { .. } => write!(f, "Defer(..)"),
2631            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2632        }
2633    }
2634}
2635
2636/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2637pub(crate) struct GlobalLease<G: Global> {
2638    global: Box<dyn Any>,
2639    global_type: PhantomData<G>,
2640}
2641
2642impl<G: Global> GlobalLease<G> {
2643    fn new(global: Box<dyn Any>) -> Self {
2644        GlobalLease {
2645            global,
2646            global_type: PhantomData,
2647        }
2648    }
2649}
2650
2651impl<G: Global> Deref for GlobalLease<G> {
2652    type Target = G;
2653
2654    fn deref(&self) -> &Self::Target {
2655        self.global.downcast_ref().unwrap()
2656    }
2657}
2658
2659impl<G: Global> DerefMut for GlobalLease<G> {
2660    fn deref_mut(&mut self) -> &mut Self::Target {
2661        self.global.downcast_mut().unwrap()
2662    }
2663}
2664
2665/// Contains state associated with an active drag operation, started by dragging an element
2666/// within the window or by dragging into the app from the underlying platform.
2667pub struct AnyDrag {
2668    /// The view used to render this drag
2669    pub view: AnyView,
2670
2671    /// The value of the dragged item, to be dropped
2672    pub value: Arc<dyn Any>,
2673
2674    /// This is used to render the dragged item in the same place
2675    /// on the original element that the drag was initiated
2676    pub cursor_offset: Point<Pixels>,
2677
2678    /// The cursor style to use while dragging
2679    pub cursor_style: Option<CursorStyle>,
2680}
2681
2682/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2683/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2684#[derive(Clone)]
2685pub struct AnyTooltip {
2686    /// The view used to display the tooltip
2687    pub view: AnyView,
2688
2689    /// The absolute position of the mouse when the tooltip was deployed.
2690    pub mouse_position: Point<Pixels>,
2691
2692    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2693    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2694    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2695    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2696}
2697
2698/// A keystroke event, and potentially the associated action
2699#[derive(Debug)]
2700pub struct KeystrokeEvent {
2701    /// The keystroke that occurred
2702    pub keystroke: Keystroke,
2703
2704    /// The action that was resolved for the keystroke, if any
2705    pub action: Option<Box<dyn Action>>,
2706
2707    /// The context stack at the time
2708    pub context_stack: Vec<KeyContext>,
2709}
2710
2711struct NullHttpClient;
2712
2713impl HttpClient for NullHttpClient {
2714    fn send(
2715        &self,
2716        _req: open_gpui_http_client::Request<open_gpui_http_client::AsyncBody>,
2717    ) -> futures::future::BoxFuture<
2718        'static,
2719        anyhow::Result<open_gpui_http_client::Response<open_gpui_http_client::AsyncBody>>,
2720    > {
2721        async move {
2722            anyhow::bail!("No HttpClient available");
2723        }
2724        .boxed()
2725    }
2726
2727    fn user_agent(&self) -> Option<&open_gpui_http_client::http::HeaderValue> {
2728        None
2729    }
2730
2731    fn proxy(&self) -> Option<&Url> {
2732        None
2733    }
2734}
2735
2736/// A mutable reference to an entity owned by GPUI
2737pub struct GpuiBorrow<'a, T> {
2738    inner: Option<Lease<T>>,
2739    app: &'a mut App,
2740}
2741
2742impl<'a, T: 'static> GpuiBorrow<'a, T> {
2743    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2744        app.start_update();
2745        let lease = app.entities.lease(&inner);
2746        Self {
2747            inner: Some(lease),
2748            app,
2749        }
2750    }
2751}
2752
2753impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2754    fn borrow(&self) -> &T {
2755        self.inner.as_ref().unwrap().borrow()
2756    }
2757}
2758
2759impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2760    fn borrow_mut(&mut self) -> &mut T {
2761        self.inner.as_mut().unwrap().borrow_mut()
2762    }
2763}
2764
2765impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
2766    type Target = T;
2767
2768    fn deref(&self) -> &Self::Target {
2769        self.inner.as_ref().unwrap()
2770    }
2771}
2772
2773impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
2774    fn deref_mut(&mut self) -> &mut T {
2775        self.inner.as_mut().unwrap()
2776    }
2777}
2778
2779impl<'a, T> Drop for GpuiBorrow<'a, T> {
2780    fn drop(&mut self) {
2781        let lease = self.inner.take().unwrap();
2782        self.app.notify(lease.id);
2783        self.app.entities.end_lease(lease);
2784        self.app.finish_update();
2785    }
2786}
2787
2788#[cfg(test)]
2789mod test {
2790    use std::{cell::RefCell, rc::Rc};
2791
2792    use crate::{AppContext, TestAppContext};
2793
2794    #[test]
2795    fn test_gpui_borrow() {
2796        let cx = TestAppContext::single();
2797        let observation_count = Rc::new(RefCell::new(0));
2798
2799        let state = cx.update(|cx| {
2800            let state = cx.new(|_| false);
2801            cx.observe(&state, {
2802                let observation_count = observation_count.clone();
2803                move |_, _| {
2804                    let mut count = observation_count.borrow_mut();
2805                    *count += 1;
2806                }
2807            })
2808            .detach();
2809
2810            state
2811        });
2812
2813        cx.update(|cx| {
2814            // Calling this like this so that we don't clobber the borrow_mut above
2815            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2816        });
2817
2818        cx.update(|cx| {
2819            state.write(cx, false);
2820        });
2821
2822        assert_eq!(*observation_count.borrow(), 2);
2823    }
2824}