app.rs

   1use std::{
   2    any::{TypeId, type_name},
   3    cell::{BorrowMutError, Ref, RefCell, RefMut},
   4    marker::PhantomData,
   5    mem,
   6    ops::{Deref, DerefMut},
   7    path::{Path, PathBuf},
   8    rc::{Rc, Weak},
   9    sync::{Arc, atomic::Ordering::SeqCst},
  10    time::Duration,
  11};
  12
  13use anyhow::{Context as _, Result, anyhow};
  14use derive_more::{Deref, DerefMut};
  15use futures::{
  16    Future, FutureExt,
  17    channel::oneshot,
  18    future::{LocalBoxFuture, Shared},
  19};
  20use parking_lot::RwLock;
  21use slotmap::SlotMap;
  22
  23pub use async_context::*;
  24use collections::{FxHashMap, FxHashSet, HashMap, VecDeque};
  25pub use context::*;
  26pub use entity_map::*;
  27use http_client::{HttpClient, Url};
  28use smallvec::SmallVec;
  29#[cfg(any(test, feature = "test-support"))]
  30pub use test_context::*;
  31use util::{ResultExt, debug_panic};
  32
  33#[cfg(any(feature = "inspector", debug_assertions))]
  34use crate::InspectorElementRegistry;
  35use crate::{
  36    Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Asset,
  37    AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DispatchPhase, DisplayId,
  38    EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext,
  39    Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform,
  40    PlatformDisplay, PlatformKeyboardLayout, Point, PromptBuilder, PromptButton, PromptHandle,
  41    PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource,
  42    SubscriberSet, Subscription, SvgRenderer, Task, TextSystem, Window, WindowAppearance,
  43    WindowHandle, WindowId, WindowInvalidator,
  44    colors::{Colors, GlobalColors},
  45    current_platform, hash, init_app_menus,
  46};
  47
  48mod async_context;
  49mod context;
  50mod entity_map;
  51#[cfg(any(test, feature = "test-support"))]
  52mod test_context;
  53
  54/// The duration for which futures returned from [Context::on_app_quit] can run before the application fully quits.
  55pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
  56
  57/// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows.
  58/// Strongly consider removing after stabilization.
  59#[doc(hidden)]
  60pub struct AppCell {
  61    app: RefCell<App>,
  62}
  63
  64impl AppCell {
  65    #[doc(hidden)]
  66    #[track_caller]
  67    pub fn borrow(&self) -> AppRef<'_> {
  68        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  69            let thread_id = std::thread::current().id();
  70            eprintln!("borrowed {thread_id:?}");
  71        }
  72        AppRef(self.app.borrow())
  73    }
  74
  75    #[doc(hidden)]
  76    #[track_caller]
  77    pub fn borrow_mut(&self) -> AppRefMut<'_> {
  78        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  79            let thread_id = std::thread::current().id();
  80            eprintln!("borrowed {thread_id:?}");
  81        }
  82        AppRefMut(self.app.borrow_mut())
  83    }
  84
  85    #[doc(hidden)]
  86    #[track_caller]
  87    pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
  88        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  89            let thread_id = std::thread::current().id();
  90            eprintln!("borrowed {thread_id:?}");
  91        }
  92        Ok(AppRefMut(self.app.try_borrow_mut()?))
  93    }
  94}
  95
  96#[doc(hidden)]
  97#[derive(Deref, DerefMut)]
  98pub struct AppRef<'a>(Ref<'a, App>);
  99
 100impl Drop for AppRef<'_> {
 101    fn drop(&mut self) {
 102        if option_env!("TRACK_THREAD_BORROWS").is_some() {
 103            let thread_id = std::thread::current().id();
 104            eprintln!("dropped borrow from {thread_id:?}");
 105        }
 106    }
 107}
 108
 109#[doc(hidden)]
 110#[derive(Deref, DerefMut)]
 111pub struct AppRefMut<'a>(RefMut<'a, App>);
 112
 113impl Drop for AppRefMut<'_> {
 114    fn drop(&mut self) {
 115        if option_env!("TRACK_THREAD_BORROWS").is_some() {
 116            let thread_id = std::thread::current().id();
 117            eprintln!("dropped {thread_id:?}");
 118        }
 119    }
 120}
 121
 122/// A reference to a GPUI application, typically constructed in the `main` function of your app.
 123/// You won't interact with this type much outside of initial configuration and startup.
 124pub struct Application(Rc<AppCell>);
 125
 126/// Represents an application before it is fully launched. Once your app is
 127/// configured, you'll start the app with `App::run`.
 128impl Application {
 129    /// Builds an app with the given asset source.
 130    #[allow(clippy::new_without_default)]
 131    pub fn new() -> Self {
 132        #[cfg(any(test, feature = "test-support"))]
 133        log::info!("GPUI was compiled in test mode");
 134
 135        Self(App::new_app(
 136            current_platform(false),
 137            Arc::new(()),
 138            Arc::new(NullHttpClient),
 139        ))
 140    }
 141
 142    /// Build an app in headless mode. This prevents opening windows,
 143    /// but makes it possible to run an application in an context like
 144    /// SSH, where GUI applications are not allowed.
 145    pub fn headless() -> Self {
 146        Self(App::new_app(
 147            current_platform(true),
 148            Arc::new(()),
 149            Arc::new(NullHttpClient),
 150        ))
 151    }
 152
 153    /// Assign
 154    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
 155        let mut context_lock = self.0.borrow_mut();
 156        let asset_source = Arc::new(asset_source);
 157        context_lock.asset_source = asset_source.clone();
 158        context_lock.svg_renderer = SvgRenderer::new(asset_source);
 159        drop(context_lock);
 160        self
 161    }
 162
 163    /// Sets the HTTP client for the application.
 164    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
 165        let mut context_lock = self.0.borrow_mut();
 166        context_lock.http_client = http_client;
 167        drop(context_lock);
 168        self
 169    }
 170
 171    /// Start the application. The provided callback will be called once the
 172    /// app is fully launched.
 173    pub fn run<F>(self, on_finish_launching: F)
 174    where
 175        F: 'static + FnOnce(&mut App),
 176    {
 177        let this = self.0.clone();
 178        let platform = self.0.borrow().platform.clone();
 179        platform.run(Box::new(move || {
 180            let cx = &mut *this.borrow_mut();
 181            on_finish_launching(cx);
 182        }));
 183    }
 184
 185    /// Register a handler to be invoked when the platform instructs the application
 186    /// to open one or more URLs.
 187    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 188    where
 189        F: 'static + FnMut(Vec<String>),
 190    {
 191        self.0.borrow().platform.on_open_urls(Box::new(callback));
 192        self
 193    }
 194
 195    /// Invokes a handler when an already-running application is launched.
 196    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
 197    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 198    where
 199        F: 'static + FnMut(&mut App),
 200    {
 201        let this = Rc::downgrade(&self.0);
 202        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 203            if let Some(app) = this.upgrade() {
 204                callback(&mut app.borrow_mut());
 205            }
 206        }));
 207        self
 208    }
 209
 210    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
 211    pub fn background_executor(&self) -> BackgroundExecutor {
 212        self.0.borrow().background_executor.clone()
 213    }
 214
 215    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
 216    pub fn foreground_executor(&self) -> ForegroundExecutor {
 217        self.0.borrow().foreground_executor.clone()
 218    }
 219
 220    /// Returns a reference to the [`TextSystem`] associated with this app.
 221    pub fn text_system(&self) -> Arc<TextSystem> {
 222        self.0.borrow().text_system.clone()
 223    }
 224
 225    /// Returns the file URL of the executable with the specified name in the application bundle
 226    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 227        self.0.borrow().path_for_auxiliary_executable(name)
 228    }
 229}
 230
 231type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
 232type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
 233pub(crate) type KeystrokeObserver =
 234    Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
 235type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
 236type WindowClosedHandler = Box<dyn FnMut(&mut App)>;
 237type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
 238type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
 239
 240/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
 241/// Other [Context] derefs to this type.
 242/// You need a reference to an `App` to access the state of a [Entity].
 243pub struct App {
 244    pub(crate) this: Weak<AppCell>,
 245    pub(crate) platform: Rc<dyn Platform>,
 246    text_system: Arc<TextSystem>,
 247    flushing_effects: bool,
 248    pending_updates: usize,
 249    pub(crate) actions: Rc<ActionRegistry>,
 250    pub(crate) active_drag: Option<AnyDrag>,
 251    pub(crate) background_executor: BackgroundExecutor,
 252    pub(crate) foreground_executor: ForegroundExecutor,
 253    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
 254    asset_source: Arc<dyn AssetSource>,
 255    pub(crate) svg_renderer: SvgRenderer,
 256    http_client: Arc<dyn HttpClient>,
 257    pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
 258    pub(crate) entities: EntityMap,
 259    pub(crate) window_update_stack: Vec<WindowId>,
 260    pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
 261    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
 262    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
 263    pub(crate) focus_handles: Arc<FocusMap>,
 264    pub(crate) keymap: Rc<RefCell<Keymap>>,
 265    pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
 266    pub(crate) global_action_listeners:
 267        FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
 268    pending_effects: VecDeque<Effect>,
 269    pub(crate) pending_notifications: FxHashSet<EntityId>,
 270    pub(crate) pending_global_notifications: FxHashSet<TypeId>,
 271    pub(crate) observers: SubscriberSet<EntityId, Handler>,
 272    // TypeId is the type of the event that the listener callback expects
 273    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
 274    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
 275    pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
 276    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
 277    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
 278    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
 279    pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
 280    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
 281    pub(crate) propagate_event: bool,
 282    pub(crate) prompt_builder: Option<PromptBuilder>,
 283    pub(crate) window_invalidators_by_entity:
 284        FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
 285    pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
 286    #[cfg(any(feature = "inspector", debug_assertions))]
 287    pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
 288    #[cfg(any(feature = "inspector", debug_assertions))]
 289    pub(crate) inspector_element_registry: InspectorElementRegistry,
 290    #[cfg(any(test, feature = "test-support", debug_assertions))]
 291    pub(crate) name: Option<&'static str>,
 292    quitting: bool,
 293}
 294
 295impl App {
 296    #[allow(clippy::new_ret_no_self)]
 297    pub(crate) fn new_app(
 298        platform: Rc<dyn Platform>,
 299        asset_source: Arc<dyn AssetSource>,
 300        http_client: Arc<dyn HttpClient>,
 301    ) -> Rc<AppCell> {
 302        let executor = platform.background_executor();
 303        let foreground_executor = platform.foreground_executor();
 304        assert!(
 305            executor.is_main_thread(),
 306            "must construct App on main thread"
 307        );
 308
 309        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 310        let entities = EntityMap::new();
 311        let keyboard_layout = platform.keyboard_layout();
 312
 313        let app = Rc::new_cyclic(|this| AppCell {
 314            app: RefCell::new(App {
 315                this: this.clone(),
 316                platform: platform.clone(),
 317                text_system,
 318                actions: Rc::new(ActionRegistry::default()),
 319                flushing_effects: false,
 320                pending_updates: 0,
 321                active_drag: None,
 322                background_executor: executor,
 323                foreground_executor,
 324                svg_renderer: SvgRenderer::new(asset_source.clone()),
 325                loading_assets: Default::default(),
 326                asset_source,
 327                http_client,
 328                globals_by_type: FxHashMap::default(),
 329                entities,
 330                new_entity_observers: SubscriberSet::new(),
 331                windows: SlotMap::with_key(),
 332                window_update_stack: Vec::new(),
 333                window_handles: FxHashMap::default(),
 334                focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 335                keymap: Rc::new(RefCell::new(Keymap::default())),
 336                keyboard_layout,
 337                global_action_listeners: FxHashMap::default(),
 338                pending_effects: VecDeque::new(),
 339                pending_notifications: FxHashSet::default(),
 340                pending_global_notifications: FxHashSet::default(),
 341                observers: SubscriberSet::new(),
 342                tracked_entities: FxHashMap::default(),
 343                window_invalidators_by_entity: FxHashMap::default(),
 344                event_listeners: SubscriberSet::new(),
 345                release_listeners: SubscriberSet::new(),
 346                keystroke_observers: SubscriberSet::new(),
 347                keyboard_layout_observers: SubscriberSet::new(),
 348                global_observers: SubscriberSet::new(),
 349                quit_observers: SubscriberSet::new(),
 350                window_closed_observers: SubscriberSet::new(),
 351                layout_id_buffer: Default::default(),
 352                propagate_event: true,
 353                prompt_builder: Some(PromptBuilder::Default),
 354                #[cfg(any(feature = "inspector", debug_assertions))]
 355                inspector_renderer: None,
 356                #[cfg(any(feature = "inspector", debug_assertions))]
 357                inspector_element_registry: InspectorElementRegistry::default(),
 358                quitting: false,
 359
 360                #[cfg(any(test, feature = "test-support", debug_assertions))]
 361                name: None,
 362            }),
 363        });
 364
 365        init_app_menus(platform.as_ref(), &mut app.borrow_mut());
 366
 367        platform.on_keyboard_layout_change(Box::new({
 368            let app = Rc::downgrade(&app);
 369            move || {
 370                if let Some(app) = app.upgrade() {
 371                    let cx = &mut app.borrow_mut();
 372                    cx.keyboard_layout = cx.platform.keyboard_layout();
 373                    cx.keyboard_layout_observers
 374                        .clone()
 375                        .retain(&(), move |callback| (callback)(cx));
 376                }
 377            }
 378        }));
 379
 380        platform.on_quit(Box::new({
 381            let cx = app.clone();
 382            move || {
 383                cx.borrow_mut().shutdown();
 384            }
 385        }));
 386
 387        app
 388    }
 389
 390    /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`]
 391    /// will be given 100ms to complete before exiting.
 392    pub fn shutdown(&mut self) {
 393        let mut futures = Vec::new();
 394
 395        for observer in self.quit_observers.remove(&()) {
 396            futures.push(observer(self));
 397        }
 398
 399        self.windows.clear();
 400        self.window_handles.clear();
 401        self.flush_effects();
 402        self.quitting = true;
 403
 404        let futures = futures::future::join_all(futures);
 405        if self
 406            .background_executor
 407            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
 408            .is_err()
 409        {
 410            log::error!("timed out waiting on app_will_quit");
 411        }
 412
 413        self.quitting = false;
 414    }
 415
 416    /// Get the id of the current keyboard layout
 417    pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
 418        self.keyboard_layout.as_ref()
 419    }
 420
 421    /// Invokes a handler when the current keyboard layout changes
 422    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
 423    where
 424        F: 'static + FnMut(&mut App),
 425    {
 426        let (subscription, activate) = self.keyboard_layout_observers.insert(
 427            (),
 428            Box::new(move |cx| {
 429                callback(cx);
 430                true
 431            }),
 432        );
 433        activate();
 434        subscription
 435    }
 436
 437    /// Gracefully quit the application via the platform's standard routine.
 438    pub fn quit(&self) {
 439        self.platform.quit();
 440    }
 441
 442    /// Schedules all windows in the application to be redrawn. This can be called
 443    /// multiple times in an update cycle and still result in a single redraw.
 444    pub fn refresh_windows(&mut self) {
 445        self.pending_effects.push_back(Effect::RefreshWindows);
 446    }
 447
 448    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
 449        self.pending_updates += 1;
 450        let result = update(self);
 451        if !self.flushing_effects && self.pending_updates == 1 {
 452            self.flushing_effects = true;
 453            self.flush_effects();
 454            self.flushing_effects = false;
 455        }
 456        self.pending_updates -= 1;
 457        result
 458    }
 459
 460    /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
 461    pub fn observe<W>(
 462        &mut self,
 463        entity: &Entity<W>,
 464        mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
 465    ) -> Subscription
 466    where
 467        W: 'static,
 468    {
 469        self.observe_internal(entity, move |e, cx| {
 470            on_notify(e, cx);
 471            true
 472        })
 473    }
 474
 475    pub(crate) fn detect_accessed_entities<R>(
 476        &mut self,
 477        callback: impl FnOnce(&mut App) -> R,
 478    ) -> (R, FxHashSet<EntityId>) {
 479        let accessed_entities_start = self.entities.accessed_entities.borrow().clone();
 480        let result = callback(self);
 481        let accessed_entities_end = self.entities.accessed_entities.borrow().clone();
 482        let entities_accessed_in_callback = accessed_entities_end
 483            .difference(&accessed_entities_start)
 484            .copied()
 485            .collect::<FxHashSet<EntityId>>();
 486        (result, entities_accessed_in_callback)
 487    }
 488
 489    pub(crate) fn record_entities_accessed(
 490        &mut self,
 491        window_handle: AnyWindowHandle,
 492        invalidator: WindowInvalidator,
 493        entities: &FxHashSet<EntityId>,
 494    ) {
 495        let mut tracked_entities =
 496            std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
 497        for entity in tracked_entities.iter() {
 498            self.window_invalidators_by_entity
 499                .entry(*entity)
 500                .and_modify(|windows| {
 501                    windows.remove(&window_handle.id);
 502                });
 503        }
 504        for entity in entities.iter() {
 505            self.window_invalidators_by_entity
 506                .entry(*entity)
 507                .or_default()
 508                .insert(window_handle.id, invalidator.clone());
 509        }
 510        tracked_entities.clear();
 511        tracked_entities.extend(entities.iter().copied());
 512        self.tracked_entities
 513            .insert(window_handle.id, tracked_entities);
 514    }
 515
 516    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
 517        let (subscription, activate) = self.observers.insert(key, value);
 518        self.defer(move |_| activate());
 519        subscription
 520    }
 521
 522    pub(crate) fn observe_internal<W>(
 523        &mut self,
 524        entity: &Entity<W>,
 525        mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
 526    ) -> Subscription
 527    where
 528        W: 'static,
 529    {
 530        let entity_id = entity.entity_id();
 531        let handle = entity.downgrade();
 532        self.new_observer(
 533            entity_id,
 534            Box::new(move |cx| {
 535                if let Some(entity) = handle.upgrade() {
 536                    on_notify(entity, cx)
 537                } else {
 538                    false
 539                }
 540            }),
 541        )
 542    }
 543
 544    /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
 545    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
 546    pub fn subscribe<T, Event>(
 547        &mut self,
 548        entity: &Entity<T>,
 549        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
 550    ) -> Subscription
 551    where
 552        T: 'static + EventEmitter<Event>,
 553        Event: 'static,
 554    {
 555        self.subscribe_internal(entity, move |entity, event, cx| {
 556            on_event(entity, event, cx);
 557            true
 558        })
 559    }
 560
 561    pub(crate) fn new_subscription(
 562        &mut self,
 563        key: EntityId,
 564        value: (TypeId, Listener),
 565    ) -> Subscription {
 566        let (subscription, activate) = self.event_listeners.insert(key, value);
 567        self.defer(move |_| activate());
 568        subscription
 569    }
 570    pub(crate) fn subscribe_internal<T, Evt>(
 571        &mut self,
 572        entity: &Entity<T>,
 573        mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
 574    ) -> Subscription
 575    where
 576        T: 'static + EventEmitter<Evt>,
 577        Evt: 'static,
 578    {
 579        let entity_id = entity.entity_id();
 580        let handle = entity.downgrade();
 581        self.new_subscription(
 582            entity_id,
 583            (
 584                TypeId::of::<Evt>(),
 585                Box::new(move |event, cx| {
 586                    let event: &Evt = event.downcast_ref().expect("invalid event type");
 587                    if let Some(entity) = handle.upgrade() {
 588                        on_event(entity, event, cx)
 589                    } else {
 590                        false
 591                    }
 592                }),
 593            ),
 594        )
 595    }
 596
 597    /// Returns handles to all open windows in the application.
 598    /// Each handle could be downcast to a handle typed for the root view of that window.
 599    /// To find all windows of a given type, you could filter on
 600    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 601        self.windows
 602            .keys()
 603            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
 604            .collect()
 605    }
 606
 607    /// Returns the window handles ordered by their appearance on screen, front to back.
 608    ///
 609    /// The first window in the returned list is the active/topmost window of the application.
 610    ///
 611    /// This method returns None if the platform doesn't implement the method yet.
 612    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 613        self.platform.window_stack()
 614    }
 615
 616    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
 617    pub fn active_window(&self) -> Option<AnyWindowHandle> {
 618        self.platform.active_window()
 619    }
 620
 621    /// Opens a new window with the given option and the root view returned by the given function.
 622    /// The function is invoked with a `Window`, which can be used to interact with window-specific
 623    /// functionality.
 624    pub fn open_window<V: 'static + Render>(
 625        &mut self,
 626        options: crate::WindowOptions,
 627        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
 628    ) -> anyhow::Result<WindowHandle<V>> {
 629        self.update(|cx| {
 630            let id = cx.windows.insert(None);
 631            let handle = WindowHandle::new(id);
 632            match Window::new(handle.into(), options, cx) {
 633                Ok(mut window) => {
 634                    cx.window_update_stack.push(id);
 635                    let root_view = build_root_view(&mut window, cx);
 636                    cx.window_update_stack.pop();
 637                    window.root.replace(root_view.into());
 638                    window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
 639                    cx.window_handles.insert(id, window.handle);
 640                    cx.windows.get_mut(id).unwrap().replace(window);
 641                    Ok(handle)
 642                }
 643                Err(e) => {
 644                    cx.windows.remove(id);
 645                    Err(e)
 646                }
 647            }
 648        })
 649    }
 650
 651    /// Instructs the platform to activate the application by bringing it to the foreground.
 652    pub fn activate(&self, ignoring_other_apps: bool) {
 653        self.platform.activate(ignoring_other_apps);
 654    }
 655
 656    /// Hide the application at the platform level.
 657    pub fn hide(&self) {
 658        self.platform.hide();
 659    }
 660
 661    /// Hide other applications at the platform level.
 662    pub fn hide_other_apps(&self) {
 663        self.platform.hide_other_apps();
 664    }
 665
 666    /// Unhide other applications at the platform level.
 667    pub fn unhide_other_apps(&self) {
 668        self.platform.unhide_other_apps();
 669    }
 670
 671    /// Returns the list of currently active displays.
 672    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 673        self.platform.displays()
 674    }
 675
 676    /// Returns the primary display that will be used for new windows.
 677    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 678        self.platform.primary_display()
 679    }
 680
 681    /// Returns whether `screen_capture_sources` may work.
 682    pub fn is_screen_capture_supported(&self) -> bool {
 683        self.platform.is_screen_capture_supported()
 684    }
 685
 686    /// Returns a list of available screen capture sources.
 687    pub fn screen_capture_sources(
 688        &self,
 689    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
 690        self.platform.screen_capture_sources()
 691    }
 692
 693    /// Returns the display with the given ID, if one exists.
 694    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 695        self.displays()
 696            .iter()
 697            .find(|display| display.id() == id)
 698            .cloned()
 699    }
 700
 701    /// Returns the appearance of the application's windows.
 702    pub fn window_appearance(&self) -> WindowAppearance {
 703        self.platform.window_appearance()
 704    }
 705
 706    /// Writes data to the primary selection buffer.
 707    /// Only available on Linux.
 708    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 709    pub fn write_to_primary(&self, item: ClipboardItem) {
 710        self.platform.write_to_primary(item)
 711    }
 712
 713    /// Writes data to the platform clipboard.
 714    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 715        self.platform.write_to_clipboard(item)
 716    }
 717
 718    /// Reads data from the primary selection buffer.
 719    /// Only available on Linux.
 720    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 721    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
 722        self.platform.read_from_primary()
 723    }
 724
 725    /// Reads data from the platform clipboard.
 726    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 727        self.platform.read_from_clipboard()
 728    }
 729
 730    /// Writes credentials to the platform keychain.
 731    pub fn write_credentials(
 732        &self,
 733        url: &str,
 734        username: &str,
 735        password: &[u8],
 736    ) -> Task<Result<()>> {
 737        self.platform.write_credentials(url, username, password)
 738    }
 739
 740    /// Reads credentials from the platform keychain.
 741    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 742        self.platform.read_credentials(url)
 743    }
 744
 745    /// Deletes credentials from the platform keychain.
 746    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 747        self.platform.delete_credentials(url)
 748    }
 749
 750    /// Directs the platform's default browser to open the given URL.
 751    pub fn open_url(&self, url: &str) {
 752        self.platform.open_url(url);
 753    }
 754
 755    /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
 756    /// opened by the current app.
 757    ///
 758    /// On some platforms (e.g. macOS) you may be able to register URL schemes
 759    /// as part of app distribution, but this method exists to let you register
 760    /// schemes at runtime.
 761    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
 762        self.platform.register_url_scheme(scheme)
 763    }
 764
 765    /// Returns the full pathname of the current app bundle.
 766    ///
 767    /// Returns an error if the app is not being run from a bundle.
 768    pub fn app_path(&self) -> Result<PathBuf> {
 769        self.platform.app_path()
 770    }
 771
 772    /// On Linux, returns the name of the compositor in use.
 773    ///
 774    /// Returns an empty string on other platforms.
 775    pub fn compositor_name(&self) -> &'static str {
 776        self.platform.compositor_name()
 777    }
 778
 779    /// Returns the file URL of the executable with the specified name in the application bundle
 780    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 781        self.platform.path_for_auxiliary_executable(name)
 782    }
 783
 784    /// Displays a platform modal for selecting paths.
 785    ///
 786    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
 787    /// If cancelled, a `None` will be relayed instead.
 788    /// May return an error on Linux if the file picker couldn't be opened.
 789    pub fn prompt_for_paths(
 790        &self,
 791        options: PathPromptOptions,
 792    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 793        self.platform.prompt_for_paths(options)
 794    }
 795
 796    /// Displays a platform modal for selecting a new path where a file can be saved.
 797    ///
 798    /// The provided directory will be used to set the initial location.
 799    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
 800    /// If cancelled, a `None` will be relayed instead.
 801    /// May return an error on Linux if the file picker couldn't be opened.
 802    pub fn prompt_for_new_path(
 803        &self,
 804        directory: &Path,
 805    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 806        self.platform.prompt_for_new_path(directory)
 807    }
 808
 809    /// Reveals the specified path at the platform level, such as in Finder on macOS.
 810    pub fn reveal_path(&self, path: &Path) {
 811        self.platform.reveal_path(path)
 812    }
 813
 814    /// Opens the specified path with the system's default application.
 815    pub fn open_with_system(&self, path: &Path) {
 816        self.platform.open_with_system(path)
 817    }
 818
 819    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
 820    pub fn should_auto_hide_scrollbars(&self) -> bool {
 821        self.platform.should_auto_hide_scrollbars()
 822    }
 823
 824    /// Restarts the application.
 825    pub fn restart(&self, binary_path: Option<PathBuf>) {
 826        self.platform.restart(binary_path)
 827    }
 828
 829    /// Returns the HTTP client for the application.
 830    pub fn http_client(&self) -> Arc<dyn HttpClient> {
 831        self.http_client.clone()
 832    }
 833
 834    /// Sets the HTTP client for the application.
 835    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
 836        self.http_client = new_client;
 837    }
 838
 839    /// Returns the SVG renderer used by the application.
 840    pub fn svg_renderer(&self) -> SvgRenderer {
 841        self.svg_renderer.clone()
 842    }
 843
 844    pub(crate) fn push_effect(&mut self, effect: Effect) {
 845        match &effect {
 846            Effect::Notify { emitter } => {
 847                if !self.pending_notifications.insert(*emitter) {
 848                    return;
 849                }
 850            }
 851            Effect::NotifyGlobalObservers { global_type } => {
 852                if !self.pending_global_notifications.insert(*global_type) {
 853                    return;
 854                }
 855            }
 856            _ => {}
 857        };
 858
 859        self.pending_effects.push_back(effect);
 860    }
 861
 862    /// Called at the end of [`App::update`] to complete any side effects
 863    /// such as notifying observers, emitting events, etc. Effects can themselves
 864    /// cause effects, so we continue looping until all effects are processed.
 865    fn flush_effects(&mut self) {
 866        loop {
 867            self.release_dropped_entities();
 868            self.release_dropped_focus_handles();
 869
 870            if let Some(effect) = self.pending_effects.pop_front() {
 871                match effect {
 872                    Effect::Notify { emitter } => {
 873                        self.apply_notify_effect(emitter);
 874                    }
 875
 876                    Effect::Emit {
 877                        emitter,
 878                        event_type,
 879                        event,
 880                    } => self.apply_emit_effect(emitter, event_type, event),
 881
 882                    Effect::RefreshWindows => {
 883                        self.apply_refresh_effect();
 884                    }
 885
 886                    Effect::NotifyGlobalObservers { global_type } => {
 887                        self.apply_notify_global_observers_effect(global_type);
 888                    }
 889
 890                    Effect::Defer { callback } => {
 891                        self.apply_defer_effect(callback);
 892                    }
 893                    Effect::EntityCreated {
 894                        entity,
 895                        tid,
 896                        window,
 897                    } => {
 898                        self.apply_entity_created_effect(entity, tid, window);
 899                    }
 900                }
 901            } else {
 902                #[cfg(any(test, feature = "test-support"))]
 903                for window in self
 904                    .windows
 905                    .values()
 906                    .filter_map(|window| {
 907                        let window = window.as_ref()?;
 908                        window.invalidator.is_dirty().then_some(window.handle)
 909                    })
 910                    .collect::<Vec<_>>()
 911                {
 912                    self.update_window(window, |_, window, cx| window.draw(cx).clear())
 913                        .unwrap();
 914                }
 915
 916                if self.pending_effects.is_empty() {
 917                    break;
 918                }
 919            }
 920        }
 921    }
 922
 923    /// Repeatedly called during `flush_effects` to release any entities whose
 924    /// reference count has become zero. We invoke any release observers before dropping
 925    /// each entity.
 926    fn release_dropped_entities(&mut self) {
 927        loop {
 928            let dropped = self.entities.take_dropped();
 929            if dropped.is_empty() {
 930                break;
 931            }
 932
 933            for (entity_id, mut entity) in dropped {
 934                self.observers.remove(&entity_id);
 935                self.event_listeners.remove(&entity_id);
 936                for release_callback in self.release_listeners.remove(&entity_id) {
 937                    release_callback(entity.as_mut(), self);
 938                }
 939            }
 940        }
 941    }
 942
 943    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 944    fn release_dropped_focus_handles(&mut self) {
 945        self.focus_handles
 946            .clone()
 947            .write()
 948            .retain(|handle_id, count| {
 949                if count.load(SeqCst) == 0 {
 950                    for window_handle in self.windows() {
 951                        window_handle
 952                            .update(self, |_, window, _| {
 953                                if window.focus == Some(handle_id) {
 954                                    window.blur();
 955                                }
 956                            })
 957                            .unwrap();
 958                    }
 959                    false
 960                } else {
 961                    true
 962                }
 963            });
 964    }
 965
 966    fn apply_notify_effect(&mut self, emitter: EntityId) {
 967        self.pending_notifications.remove(&emitter);
 968
 969        self.observers
 970            .clone()
 971            .retain(&emitter, |handler| handler(self));
 972    }
 973
 974    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 975        self.event_listeners
 976            .clone()
 977            .retain(&emitter, |(stored_type, handler)| {
 978                if *stored_type == event_type {
 979                    handler(event.as_ref(), self)
 980                } else {
 981                    true
 982                }
 983            });
 984    }
 985
 986    fn apply_refresh_effect(&mut self) {
 987        for window in self.windows.values_mut() {
 988            if let Some(window) = window.as_mut() {
 989                window.refreshing = true;
 990                window.invalidator.set_dirty(true);
 991            }
 992        }
 993    }
 994
 995    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
 996        self.pending_global_notifications.remove(&type_id);
 997        self.global_observers
 998            .clone()
 999            .retain(&type_id, |observer| observer(self));
1000    }
1001
1002    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1003        callback(self);
1004    }
1005
1006    fn apply_entity_created_effect(
1007        &mut self,
1008        entity: AnyEntity,
1009        tid: TypeId,
1010        window: Option<WindowId>,
1011    ) {
1012        self.new_entity_observers.clone().retain(&tid, |observer| {
1013            if let Some(id) = window {
1014                self.update_window_id(id, {
1015                    let entity = entity.clone();
1016                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
1017                })
1018                .expect("All windows should be off the stack when flushing effects");
1019            } else {
1020                (observer)(entity.clone(), &mut None, self)
1021            }
1022            true
1023        });
1024    }
1025
1026    fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1027    where
1028        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1029    {
1030        self.update(|cx| {
1031            let mut window = cx
1032                .windows
1033                .get_mut(id)
1034                .context("window not found")?
1035                .take()
1036                .context("window not found")?;
1037
1038            let root_view = window.root.clone().unwrap();
1039
1040            cx.window_update_stack.push(window.handle.id);
1041            let result = update(root_view, &mut window, cx);
1042            cx.window_update_stack.pop();
1043
1044            if window.removed {
1045                cx.window_handles.remove(&id);
1046                cx.windows.remove(id);
1047
1048                cx.window_closed_observers.clone().retain(&(), |callback| {
1049                    callback(cx);
1050                    true
1051                });
1052            } else {
1053                cx.windows
1054                    .get_mut(id)
1055                    .context("window not found")?
1056                    .replace(window);
1057            }
1058
1059            Ok(result)
1060        })
1061    }
1062    /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1063    /// so it can be held across `await` points.
1064    pub fn to_async(&self) -> AsyncApp {
1065        AsyncApp {
1066            app: self.this.clone(),
1067            background_executor: self.background_executor.clone(),
1068            foreground_executor: self.foreground_executor.clone(),
1069        }
1070    }
1071
1072    /// Obtains a reference to the executor, which can be used to spawn futures.
1073    pub fn background_executor(&self) -> &BackgroundExecutor {
1074        &self.background_executor
1075    }
1076
1077    /// Obtains a reference to the executor, which can be used to spawn futures.
1078    pub fn foreground_executor(&self) -> &ForegroundExecutor {
1079        if self.quitting {
1080            panic!("Can't spawn on main thread after on_app_quit")
1081        };
1082        &self.foreground_executor
1083    }
1084
1085    /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1086    /// with [AsyncApp], which allows the application state to be accessed across await points.
1087    #[track_caller]
1088    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1089    where
1090        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1091        R: 'static,
1092    {
1093        if self.quitting {
1094            debug_panic!("Can't spawn on main thread after on_app_quit")
1095        };
1096
1097        let mut cx = self.to_async();
1098
1099        self.foreground_executor
1100            .spawn(async move { f(&mut cx).await })
1101    }
1102
1103    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1104    /// that are currently on the stack to be returned to the app.
1105    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1106        self.push_effect(Effect::Defer {
1107            callback: Box::new(f),
1108        });
1109    }
1110
1111    /// Accessor for the application's asset source, which is provided when constructing the `App`.
1112    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1113        &self.asset_source
1114    }
1115
1116    /// Accessor for the text system.
1117    pub fn text_system(&self) -> &Arc<TextSystem> {
1118        &self.text_system
1119    }
1120
1121    /// Check whether a global of the given type has been assigned.
1122    pub fn has_global<G: Global>(&self) -> bool {
1123        self.globals_by_type.contains_key(&TypeId::of::<G>())
1124    }
1125
1126    /// Access the global of the given type. Panics if a global for that type has not been assigned.
1127    #[track_caller]
1128    pub fn global<G: Global>(&self) -> &G {
1129        self.globals_by_type
1130            .get(&TypeId::of::<G>())
1131            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1132            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1133            .unwrap()
1134    }
1135
1136    /// Access the global of the given type if a value has been assigned.
1137    pub fn try_global<G: Global>(&self) -> Option<&G> {
1138        self.globals_by_type
1139            .get(&TypeId::of::<G>())
1140            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1141    }
1142
1143    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1144    #[track_caller]
1145    pub fn global_mut<G: Global>(&mut self) -> &mut G {
1146        let global_type = TypeId::of::<G>();
1147        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1148        self.globals_by_type
1149            .get_mut(&global_type)
1150            .and_then(|any_state| any_state.downcast_mut::<G>())
1151            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1152            .unwrap()
1153    }
1154
1155    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1156    /// yet been assigned.
1157    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1158        let global_type = TypeId::of::<G>();
1159        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1160        self.globals_by_type
1161            .entry(global_type)
1162            .or_insert_with(|| Box::<G>::default())
1163            .downcast_mut::<G>()
1164            .unwrap()
1165    }
1166
1167    /// Sets the value of the global of the given type.
1168    pub fn set_global<G: Global>(&mut self, global: G) {
1169        let global_type = TypeId::of::<G>();
1170        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1171        self.globals_by_type.insert(global_type, Box::new(global));
1172    }
1173
1174    /// Clear all stored globals. Does not notify global observers.
1175    #[cfg(any(test, feature = "test-support"))]
1176    pub fn clear_globals(&mut self) {
1177        self.globals_by_type.drain();
1178    }
1179
1180    /// Remove the global of the given type from the app context. Does not notify global observers.
1181    pub fn remove_global<G: Global>(&mut self) -> G {
1182        let global_type = TypeId::of::<G>();
1183        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1184        *self
1185            .globals_by_type
1186            .remove(&global_type)
1187            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1188            .downcast()
1189            .unwrap()
1190    }
1191
1192    /// Register a callback to be invoked when a global of the given type is updated.
1193    pub fn observe_global<G: Global>(
1194        &mut self,
1195        mut f: impl FnMut(&mut Self) + 'static,
1196    ) -> Subscription {
1197        let (subscription, activate) = self.global_observers.insert(
1198            TypeId::of::<G>(),
1199            Box::new(move |cx| {
1200                f(cx);
1201                true
1202            }),
1203        );
1204        self.defer(move |_| activate());
1205        subscription
1206    }
1207
1208    /// Move the global of the given type to the stack.
1209    #[track_caller]
1210    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1211        GlobalLease::new(
1212            self.globals_by_type
1213                .remove(&TypeId::of::<G>())
1214                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1215                .unwrap(),
1216        )
1217    }
1218
1219    /// Restore the global of the given type after it is moved to the stack.
1220    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1221        let global_type = TypeId::of::<G>();
1222
1223        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1224        self.globals_by_type.insert(global_type, lease.global);
1225    }
1226
1227    pub(crate) fn new_entity_observer(
1228        &self,
1229        key: TypeId,
1230        value: NewEntityListener,
1231    ) -> Subscription {
1232        let (subscription, activate) = self.new_entity_observers.insert(key, value);
1233        activate();
1234        subscription
1235    }
1236
1237    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1238    /// The function will be passed a mutable reference to the view along with an appropriate context.
1239    pub fn observe_new<T: 'static>(
1240        &self,
1241        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1242    ) -> Subscription {
1243        self.new_entity_observer(
1244            TypeId::of::<T>(),
1245            Box::new(
1246                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1247                    any_entity
1248                        .downcast::<T>()
1249                        .unwrap()
1250                        .update(cx, |entity_state, cx| {
1251                            if let Some(window) = window {
1252                                on_new(entity_state, Some(window), cx);
1253                            } else {
1254                                on_new(entity_state, None, cx);
1255                            }
1256                        })
1257                },
1258            ),
1259        )
1260    }
1261
1262    /// Observe the release of a entity. The callback is invoked after the entity
1263    /// has no more strong references but before it has been dropped.
1264    pub fn observe_release<T>(
1265        &self,
1266        handle: &Entity<T>,
1267        on_release: impl FnOnce(&mut T, &mut App) + 'static,
1268    ) -> Subscription
1269    where
1270        T: 'static,
1271    {
1272        let (subscription, activate) = self.release_listeners.insert(
1273            handle.entity_id(),
1274            Box::new(move |entity, cx| {
1275                let entity = entity.downcast_mut().expect("invalid entity type");
1276                on_release(entity, cx)
1277            }),
1278        );
1279        activate();
1280        subscription
1281    }
1282
1283    /// Observe the release of a entity. The callback is invoked after the entity
1284    /// has no more strong references but before it has been dropped.
1285    pub fn observe_release_in<T>(
1286        &self,
1287        handle: &Entity<T>,
1288        window: &Window,
1289        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1290    ) -> Subscription
1291    where
1292        T: 'static,
1293    {
1294        let window_handle = window.handle;
1295        self.observe_release(&handle, move |entity, cx| {
1296            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1297        })
1298    }
1299
1300    /// Register a callback to be invoked when a keystroke is received by the application
1301    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1302    /// and that this API will not be invoked if the event's propagation is stopped.
1303    pub fn observe_keystrokes(
1304        &mut self,
1305        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1306    ) -> Subscription {
1307        fn inner(
1308            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1309            handler: KeystrokeObserver,
1310        ) -> Subscription {
1311            let (subscription, activate) = keystroke_observers.insert((), handler);
1312            activate();
1313            subscription
1314        }
1315
1316        inner(
1317            &mut self.keystroke_observers,
1318            Box::new(move |event, window, cx| {
1319                f(event, window, cx);
1320                true
1321            }),
1322        )
1323    }
1324
1325    /// Register key bindings.
1326    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1327        self.keymap.borrow_mut().add_bindings(bindings);
1328        self.pending_effects.push_back(Effect::RefreshWindows);
1329    }
1330
1331    /// Clear all key bindings in the app.
1332    pub fn clear_key_bindings(&mut self) {
1333        self.keymap.borrow_mut().clear();
1334        self.pending_effects.push_back(Effect::RefreshWindows);
1335    }
1336
1337    /// Get all key bindings in the app.
1338    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1339        self.keymap.clone()
1340    }
1341
1342    /// Register a global listener for actions invoked via the keyboard.
1343    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1344        self.global_action_listeners
1345            .entry(TypeId::of::<A>())
1346            .or_default()
1347            .push(Rc::new(move |action, phase, cx| {
1348                if phase == DispatchPhase::Bubble {
1349                    let action = action.downcast_ref().unwrap();
1350                    listener(action, cx)
1351                }
1352            }));
1353    }
1354
1355    /// Event handlers propagate events by default. Call this method to stop dispatching to
1356    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1357    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1358    /// calling this method before effects are flushed.
1359    pub fn stop_propagation(&mut self) {
1360        self.propagate_event = false;
1361    }
1362
1363    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1364    /// dispatching to action handlers higher in the element tree. This is the opposite of
1365    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1366    /// this method before effects are flushed.
1367    pub fn propagate(&mut self) {
1368        self.propagate_event = true;
1369    }
1370
1371    /// Build an action from some arbitrary data, typically a keymap entry.
1372    pub fn build_action(
1373        &self,
1374        name: &str,
1375        data: Option<serde_json::Value>,
1376    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1377        self.actions.build_action(name, data)
1378    }
1379
1380    /// Get all action names that have been registered. Note that registration only allows for
1381    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1382    pub fn all_action_names(&self) -> &[&'static str] {
1383        self.actions.all_action_names()
1384    }
1385
1386    /// Returns key bindings that invoke the given action on the currently focused element, without
1387    /// checking context. Bindings are returned in the order they were added. For display, the last
1388    /// binding should take precedence.
1389    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1390        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1391    }
1392
1393    /// Get all non-internal actions that have been registered, along with their schemas.
1394    pub fn action_schemas(
1395        &self,
1396        generator: &mut schemars::SchemaGenerator,
1397    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1398        self.actions.action_schemas(generator)
1399    }
1400
1401    /// Get a map from a deprecated action name to the canonical name.
1402    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1403        self.actions.deprecated_aliases()
1404    }
1405
1406    /// Get a list of all action deprecation messages.
1407    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1408        self.actions.deprecation_messages()
1409    }
1410
1411    /// Register a callback to be invoked when the application is about to quit.
1412    /// It is not possible to cancel the quit event at this point.
1413    pub fn on_app_quit<Fut>(
1414        &self,
1415        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1416    ) -> Subscription
1417    where
1418        Fut: 'static + Future<Output = ()>,
1419    {
1420        let (subscription, activate) = self.quit_observers.insert(
1421            (),
1422            Box::new(move |cx| {
1423                let future = on_quit(cx);
1424                future.boxed_local()
1425            }),
1426        );
1427        activate();
1428        subscription
1429    }
1430
1431    /// Register a callback to be invoked when a window is closed
1432    /// The window is no longer accessible at the point this callback is invoked.
1433    pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1434        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1435        activate();
1436        subscription
1437    }
1438
1439    pub(crate) fn clear_pending_keystrokes(&mut self) {
1440        for window in self.windows() {
1441            window
1442                .update(self, |_, window, _| {
1443                    window.clear_pending_keystrokes();
1444                })
1445                .ok();
1446        }
1447    }
1448
1449    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1450    /// the bindings in the element tree, and any global action listeners.
1451    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1452        let mut action_available = false;
1453        if let Some(window) = self.active_window() {
1454            if let Ok(window_action_available) =
1455                window.update(self, |_, window, cx| window.is_action_available(action, cx))
1456            {
1457                action_available = window_action_available;
1458            }
1459        }
1460
1461        action_available
1462            || self
1463                .global_action_listeners
1464                .contains_key(&action.as_any().type_id())
1465    }
1466
1467    /// Sets the menu bar for this application. This will replace any existing menu bar.
1468    pub fn set_menus(&self, menus: Vec<Menu>) {
1469        self.platform.set_menus(menus, &self.keymap.borrow());
1470    }
1471
1472    /// Gets the menu bar for this application.
1473    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1474        self.platform.get_menus()
1475    }
1476
1477    /// Sets the right click menu for the app icon in the dock
1478    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1479        self.platform.set_dock_menu(menus, &self.keymap.borrow())
1480    }
1481
1482    /// Performs the action associated with the given dock menu item, only used on Windows for now.
1483    pub fn perform_dock_menu_action(&self, action: usize) {
1484        self.platform.perform_dock_menu_action(action);
1485    }
1486
1487    /// Adds given path to the bottom of the list of recent paths for the application.
1488    /// The list is usually shown on the application icon's context menu in the dock,
1489    /// and allows to open the recent files via that context menu.
1490    /// If the path is already in the list, it will be moved to the bottom of the list.
1491    pub fn add_recent_document(&self, path: &Path) {
1492        self.platform.add_recent_document(path);
1493    }
1494
1495    /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
1496    /// Note that this also sets the dock menu on Windows.
1497    pub fn update_jump_list(
1498        &self,
1499        menus: Vec<MenuItem>,
1500        entries: Vec<SmallVec<[PathBuf; 2]>>,
1501    ) -> Vec<SmallVec<[PathBuf; 2]>> {
1502        self.platform.update_jump_list(menus, entries)
1503    }
1504
1505    /// Dispatch an action to the currently active window or global action handler
1506    /// See [`crate::Action`] for more information on how actions work
1507    pub fn dispatch_action(&mut self, action: &dyn Action) {
1508        if let Some(active_window) = self.active_window() {
1509            active_window
1510                .update(self, |_, window, cx| {
1511                    window.dispatch_action(action.boxed_clone(), cx)
1512                })
1513                .log_err();
1514        } else {
1515            self.dispatch_global_action(action);
1516        }
1517    }
1518
1519    fn dispatch_global_action(&mut self, action: &dyn Action) {
1520        self.propagate_event = true;
1521
1522        if let Some(mut global_listeners) = self
1523            .global_action_listeners
1524            .remove(&action.as_any().type_id())
1525        {
1526            for listener in &global_listeners {
1527                listener(action.as_any(), DispatchPhase::Capture, self);
1528                if !self.propagate_event {
1529                    break;
1530                }
1531            }
1532
1533            global_listeners.extend(
1534                self.global_action_listeners
1535                    .remove(&action.as_any().type_id())
1536                    .unwrap_or_default(),
1537            );
1538
1539            self.global_action_listeners
1540                .insert(action.as_any().type_id(), global_listeners);
1541        }
1542
1543        if self.propagate_event {
1544            if let Some(mut global_listeners) = self
1545                .global_action_listeners
1546                .remove(&action.as_any().type_id())
1547            {
1548                for listener in global_listeners.iter().rev() {
1549                    listener(action.as_any(), DispatchPhase::Bubble, self);
1550                    if !self.propagate_event {
1551                        break;
1552                    }
1553                }
1554
1555                global_listeners.extend(
1556                    self.global_action_listeners
1557                        .remove(&action.as_any().type_id())
1558                        .unwrap_or_default(),
1559                );
1560
1561                self.global_action_listeners
1562                    .insert(action.as_any().type_id(), global_listeners);
1563            }
1564        }
1565    }
1566
1567    /// Is there currently something being dragged?
1568    pub fn has_active_drag(&self) -> bool {
1569        self.active_drag.is_some()
1570    }
1571
1572    /// Gets the cursor style of the currently active drag operation.
1573    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
1574        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
1575    }
1576
1577    /// Stops active drag and clears any related effects.
1578    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
1579        if self.active_drag.is_some() {
1580            self.active_drag = None;
1581            window.refresh();
1582            true
1583        } else {
1584            false
1585        }
1586    }
1587
1588    /// Sets the cursor style for the currently active drag operation.
1589    pub fn set_active_drag_cursor_style(
1590        &mut self,
1591        cursor_style: CursorStyle,
1592        window: &mut Window,
1593    ) -> bool {
1594        if let Some(ref mut drag) = self.active_drag {
1595            drag.cursor_style = Some(cursor_style);
1596            window.refresh();
1597            true
1598        } else {
1599            false
1600        }
1601    }
1602
1603    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1604    /// prompts with this custom implementation.
1605    pub fn set_prompt_builder(
1606        &mut self,
1607        renderer: impl Fn(
1608            PromptLevel,
1609            &str,
1610            Option<&str>,
1611            &[PromptButton],
1612            PromptHandle,
1613            &mut Window,
1614            &mut App,
1615        ) -> RenderablePromptHandle
1616        + 'static,
1617    ) {
1618        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
1619    }
1620
1621    /// Reset the prompt builder to the default implementation.
1622    pub fn reset_prompt_builder(&mut self) {
1623        self.prompt_builder = Some(PromptBuilder::Default);
1624    }
1625
1626    /// Remove an asset from GPUI's cache
1627    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
1628        let asset_id = (TypeId::of::<A>(), hash(source));
1629        self.loading_assets.remove(&asset_id);
1630    }
1631
1632    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1633    ///
1634    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1635    /// time, and the results of this call will be cached
1636    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
1637        let asset_id = (TypeId::of::<A>(), hash(source));
1638        let mut is_first = false;
1639        let task = self
1640            .loading_assets
1641            .remove(&asset_id)
1642            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1643            .unwrap_or_else(|| {
1644                is_first = true;
1645                let future = A::load(source.clone(), self);
1646                let task = self.background_executor().spawn(future).shared();
1647                task
1648            });
1649
1650        self.loading_assets.insert(asset_id, Box::new(task.clone()));
1651
1652        (task, is_first)
1653    }
1654
1655    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
1656    /// for elements rendered within this window.
1657    #[track_caller]
1658    pub fn focus_handle(&self) -> FocusHandle {
1659        FocusHandle::new(&self.focus_handles)
1660    }
1661
1662    /// Tell GPUI that an entity has changed and observers of it should be notified.
1663    pub fn notify(&mut self, entity_id: EntityId) {
1664        let window_invalidators = mem::take(
1665            self.window_invalidators_by_entity
1666                .entry(entity_id)
1667                .or_default(),
1668        );
1669
1670        if window_invalidators.is_empty() {
1671            if self.pending_notifications.insert(entity_id) {
1672                self.pending_effects
1673                    .push_back(Effect::Notify { emitter: entity_id });
1674            }
1675        } else {
1676            for invalidator in window_invalidators.values() {
1677                invalidator.invalidate_view(entity_id, self);
1678            }
1679        }
1680
1681        self.window_invalidators_by_entity
1682            .insert(entity_id, window_invalidators);
1683    }
1684
1685    /// Returns the name for this [`App`].
1686    #[cfg(any(test, feature = "test-support", debug_assertions))]
1687    pub fn get_name(&self) -> Option<&'static str> {
1688        self.name
1689    }
1690
1691    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
1692    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
1693        self.platform.can_select_mixed_files_and_dirs()
1694    }
1695
1696    /// Removes an image from the sprite atlas on all windows.
1697    ///
1698    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
1699    /// This is a no-op if the image is not in the sprite atlas.
1700    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
1701        // remove the texture from all other windows
1702        for window in self.windows.values_mut().flatten() {
1703            _ = window.drop_image(image.clone());
1704        }
1705
1706        // remove the texture from the current window
1707        if let Some(window) = current_window {
1708            _ = window.drop_image(image);
1709        }
1710    }
1711
1712    /// Sets the renderer for the inspector.
1713    #[cfg(any(feature = "inspector", debug_assertions))]
1714    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
1715        self.inspector_renderer = Some(f);
1716    }
1717
1718    /// Registers a renderer specific to an inspector state.
1719    #[cfg(any(feature = "inspector", debug_assertions))]
1720    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
1721        &mut self,
1722        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
1723    ) {
1724        self.inspector_element_registry.register(f);
1725    }
1726
1727    /// Initializes gpui's default colors for the application.
1728    ///
1729    /// These colors can be accessed through `cx.default_colors()`.
1730    pub fn init_colors(&mut self) {
1731        self.set_global(GlobalColors(Arc::new(Colors::default())));
1732    }
1733}
1734
1735impl AppContext for App {
1736    type Result<T> = T;
1737
1738    /// Builds an entity that is owned by the application.
1739    ///
1740    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
1741    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
1742    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
1743        self.update(|cx| {
1744            let slot = cx.entities.reserve();
1745            let handle = slot.clone();
1746            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1747
1748            cx.push_effect(Effect::EntityCreated {
1749                entity: handle.clone().into_any(),
1750                tid: TypeId::of::<T>(),
1751                window: cx.window_update_stack.last().cloned(),
1752            });
1753
1754            cx.entities.insert(slot, entity);
1755            handle
1756        })
1757    }
1758
1759    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1760        Reservation(self.entities.reserve())
1761    }
1762
1763    fn insert_entity<T: 'static>(
1764        &mut self,
1765        reservation: Reservation<T>,
1766        build_entity: impl FnOnce(&mut Context<T>) -> T,
1767    ) -> Self::Result<Entity<T>> {
1768        self.update(|cx| {
1769            let slot = reservation.0;
1770            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1771            cx.entities.insert(slot, entity)
1772        })
1773    }
1774
1775    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
1776    /// entity along with a `Context` for the entity.
1777    fn update_entity<T: 'static, R>(
1778        &mut self,
1779        handle: &Entity<T>,
1780        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
1781    ) -> R {
1782        self.update(|cx| {
1783            let mut entity = cx.entities.lease(handle);
1784            let result = update(
1785                &mut entity,
1786                &mut Context::new_context(cx, handle.downgrade()),
1787            );
1788            cx.entities.end_lease(entity);
1789            result
1790        })
1791    }
1792
1793    fn read_entity<T, R>(
1794        &self,
1795        handle: &Entity<T>,
1796        read: impl FnOnce(&T, &App) -> R,
1797    ) -> Self::Result<R>
1798    where
1799        T: 'static,
1800    {
1801        let entity = self.entities.read(handle);
1802        read(entity, self)
1803    }
1804
1805    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1806    where
1807        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1808    {
1809        self.update_window_id(handle.id, update)
1810    }
1811
1812    fn read_window<T, R>(
1813        &self,
1814        window: &WindowHandle<T>,
1815        read: impl FnOnce(Entity<T>, &App) -> R,
1816    ) -> Result<R>
1817    where
1818        T: 'static,
1819    {
1820        let window = self
1821            .windows
1822            .get(window.id)
1823            .context("window not found")?
1824            .as_ref()
1825            .expect("attempted to read a window that is already on the stack");
1826
1827        let root_view = window.root.clone().unwrap();
1828        let view = root_view
1829            .downcast::<T>()
1830            .map_err(|_| anyhow!("root view's type has changed"))?;
1831
1832        Ok(read(view, self))
1833    }
1834
1835    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
1836    where
1837        R: Send + 'static,
1838    {
1839        self.background_executor.spawn(future)
1840    }
1841
1842    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
1843    where
1844        G: Global,
1845    {
1846        let mut g = self.global::<G>();
1847        callback(&g, self)
1848    }
1849}
1850
1851/// These effects are processed at the end of each application update cycle.
1852pub(crate) enum Effect {
1853    Notify {
1854        emitter: EntityId,
1855    },
1856    Emit {
1857        emitter: EntityId,
1858        event_type: TypeId,
1859        event: Box<dyn Any>,
1860    },
1861    RefreshWindows,
1862    NotifyGlobalObservers {
1863        global_type: TypeId,
1864    },
1865    Defer {
1866        callback: Box<dyn FnOnce(&mut App) + 'static>,
1867    },
1868    EntityCreated {
1869        entity: AnyEntity,
1870        tid: TypeId,
1871        window: Option<WindowId>,
1872    },
1873}
1874
1875impl std::fmt::Debug for Effect {
1876    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1877        match self {
1878            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
1879            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
1880            Effect::RefreshWindows => write!(f, "RefreshWindows"),
1881            Effect::NotifyGlobalObservers { global_type } => {
1882                write!(f, "NotifyGlobalObservers({:?})", global_type)
1883            }
1884            Effect::Defer { .. } => write!(f, "Defer(..)"),
1885            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
1886        }
1887    }
1888}
1889
1890/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1891pub(crate) struct GlobalLease<G: Global> {
1892    global: Box<dyn Any>,
1893    global_type: PhantomData<G>,
1894}
1895
1896impl<G: Global> GlobalLease<G> {
1897    fn new(global: Box<dyn Any>) -> Self {
1898        GlobalLease {
1899            global,
1900            global_type: PhantomData,
1901        }
1902    }
1903}
1904
1905impl<G: Global> Deref for GlobalLease<G> {
1906    type Target = G;
1907
1908    fn deref(&self) -> &Self::Target {
1909        self.global.downcast_ref().unwrap()
1910    }
1911}
1912
1913impl<G: Global> DerefMut for GlobalLease<G> {
1914    fn deref_mut(&mut self) -> &mut Self::Target {
1915        self.global.downcast_mut().unwrap()
1916    }
1917}
1918
1919/// Contains state associated with an active drag operation, started by dragging an element
1920/// within the window or by dragging into the app from the underlying platform.
1921pub struct AnyDrag {
1922    /// The view used to render this drag
1923    pub view: AnyView,
1924
1925    /// The value of the dragged item, to be dropped
1926    pub value: Arc<dyn Any>,
1927
1928    /// This is used to render the dragged item in the same place
1929    /// on the original element that the drag was initiated
1930    pub cursor_offset: Point<Pixels>,
1931
1932    /// The cursor style to use while dragging
1933    pub cursor_style: Option<CursorStyle>,
1934}
1935
1936/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1937/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1938#[derive(Clone)]
1939pub struct AnyTooltip {
1940    /// The view used to display the tooltip
1941    pub view: AnyView,
1942
1943    /// The absolute position of the mouse when the tooltip was deployed.
1944    pub mouse_position: Point<Pixels>,
1945
1946    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
1947    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
1948    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
1949    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
1950}
1951
1952/// A keystroke event, and potentially the associated action
1953#[derive(Debug)]
1954pub struct KeystrokeEvent {
1955    /// The keystroke that occurred
1956    pub keystroke: Keystroke,
1957
1958    /// The action that was resolved for the keystroke, if any
1959    pub action: Option<Box<dyn Action>>,
1960
1961    /// The context stack at the time
1962    pub context_stack: Vec<KeyContext>,
1963}
1964
1965struct NullHttpClient;
1966
1967impl HttpClient for NullHttpClient {
1968    fn send(
1969        &self,
1970        _req: http_client::Request<http_client::AsyncBody>,
1971    ) -> futures::future::BoxFuture<
1972        'static,
1973        anyhow::Result<http_client::Response<http_client::AsyncBody>>,
1974    > {
1975        async move {
1976            anyhow::bail!("No HttpClient available");
1977        }
1978        .boxed()
1979    }
1980
1981    fn proxy(&self) -> Option<&Url> {
1982        None
1983    }
1984
1985    fn type_name(&self) -> &'static str {
1986        type_name::<Self>()
1987    }
1988}