Skip to main content

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