Skip to main content

gpui/
app.rs

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