app.rs

   1use std::{
   2    any::{type_name, TypeId},
   3    cell::{Ref, RefCell, RefMut},
   4    marker::PhantomData,
   5    ops::{Deref, DerefMut},
   6    path::{Path, PathBuf},
   7    rc::{Rc, Weak},
   8    sync::{atomic::Ordering::SeqCst, Arc},
   9    time::Duration,
  10};
  11
  12use anyhow::{anyhow, Result};
  13use derive_more::{Deref, DerefMut};
  14use futures::{
  15    channel::oneshot,
  16    future::{LocalBoxFuture, Shared},
  17    Future, FutureExt,
  18};
  19use slotmap::SlotMap;
  20
  21pub use async_context::*;
  22use collections::{FxHashMap, FxHashSet, VecDeque};
  23pub use entity_map::*;
  24use http_client::HttpClient;
  25pub use model_context::*;
  26#[cfg(any(test, feature = "test-support"))]
  27pub use test_context::*;
  28use util::ResultExt;
  29
  30use crate::{
  31    current_platform, hash, init_app_menus, Action, ActionRegistry, Any, AnyView, AnyWindowHandle,
  32    Asset, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,
  33    Entity, EventEmitter, ForegroundExecutor, Global, KeyBinding, Keymap, Keystroke, LayoutId,
  34    Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point,
  35    PromptBuilder, PromptHandle, PromptLevel, Render, RenderablePromptHandle, Reservation,
  36    SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextSystem, View, ViewContext,
  37    Window, WindowAppearance, WindowContext, WindowHandle, WindowId,
  38};
  39
  40mod async_context;
  41mod entity_map;
  42mod model_context;
  43#[cfg(any(test, feature = "test-support"))]
  44mod test_context;
  45
  46/// The duration for which futures returned from [AppContext::on_app_context] or [ModelContext::on_app_quit] can run before the application fully quits.
  47pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
  48
  49/// Temporary(?) wrapper around [`RefCell<AppContext>`] to help us debug any double borrows.
  50/// Strongly consider removing after stabilization.
  51#[doc(hidden)]
  52pub struct AppCell {
  53    app: RefCell<AppContext>,
  54}
  55
  56impl AppCell {
  57    #[doc(hidden)]
  58    #[track_caller]
  59    pub fn borrow(&self) -> AppRef {
  60        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  61            let thread_id = std::thread::current().id();
  62            eprintln!("borrowed {thread_id:?}");
  63        }
  64        AppRef(self.app.borrow())
  65    }
  66
  67    #[doc(hidden)]
  68    #[track_caller]
  69    pub fn borrow_mut(&self) -> AppRefMut {
  70        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  71            let thread_id = std::thread::current().id();
  72            eprintln!("borrowed {thread_id:?}");
  73        }
  74        AppRefMut(self.app.borrow_mut())
  75    }
  76}
  77
  78#[doc(hidden)]
  79#[derive(Deref, DerefMut)]
  80pub struct AppRef<'a>(Ref<'a, AppContext>);
  81
  82impl<'a> Drop for AppRef<'a> {
  83    fn drop(&mut self) {
  84        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  85            let thread_id = std::thread::current().id();
  86            eprintln!("dropped borrow from {thread_id:?}");
  87        }
  88    }
  89}
  90
  91#[doc(hidden)]
  92#[derive(Deref, DerefMut)]
  93pub struct AppRefMut<'a>(RefMut<'a, AppContext>);
  94
  95impl<'a> Drop for AppRefMut<'a> {
  96    fn drop(&mut self) {
  97        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  98            let thread_id = std::thread::current().id();
  99            eprintln!("dropped {thread_id:?}");
 100        }
 101    }
 102}
 103
 104/// A reference to a GPUI application, typically constructed in the `main` function of your app.
 105/// You won't interact with this type much outside of initial configuration and startup.
 106pub struct App(Rc<AppCell>);
 107
 108/// Represents an application before it is fully launched. Once your app is
 109/// configured, you'll start the app with `App::run`.
 110impl App {
 111    /// Builds an app with the given asset source.
 112    #[allow(clippy::new_without_default)]
 113    pub fn new() -> Self {
 114        #[cfg(any(test, feature = "test-support"))]
 115        log::info!("GPUI was compiled in test mode");
 116
 117        Self(AppContext::new(
 118            current_platform(false),
 119            Arc::new(()),
 120            Arc::new(NullHttpClient),
 121        ))
 122    }
 123
 124    /// Build an app in headless mode. This prevents opening windows,
 125    /// but makes it possible to run an application in an context like
 126    /// SSH, where GUI applications are not allowed.
 127    pub fn headless() -> Self {
 128        Self(AppContext::new(
 129            current_platform(true),
 130            Arc::new(()),
 131            Arc::new(NullHttpClient),
 132        ))
 133    }
 134
 135    /// Assign
 136    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
 137        let mut context_lock = self.0.borrow_mut();
 138        let asset_source = Arc::new(asset_source);
 139        context_lock.asset_source = asset_source.clone();
 140        context_lock.svg_renderer = SvgRenderer::new(asset_source);
 141        drop(context_lock);
 142        self
 143    }
 144
 145    /// Set the http client for the application
 146    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
 147        let mut context_lock = self.0.borrow_mut();
 148        context_lock.http_client = http_client;
 149        drop(context_lock);
 150        self
 151    }
 152
 153    /// Start the application. The provided callback will be called once the
 154    /// app is fully launched.
 155    pub fn run<F>(self, on_finish_launching: F)
 156    where
 157        F: 'static + FnOnce(&mut AppContext),
 158    {
 159        let this = self.0.clone();
 160        let platform = self.0.borrow().platform.clone();
 161        platform.run(Box::new(move || {
 162            let cx = &mut *this.borrow_mut();
 163            on_finish_launching(cx);
 164        }));
 165    }
 166
 167    /// Register a handler to be invoked when the platform instructs the application
 168    /// to open one or more URLs.
 169    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 170    where
 171        F: 'static + FnMut(Vec<String>),
 172    {
 173        self.0.borrow().platform.on_open_urls(Box::new(callback));
 174        self
 175    }
 176
 177    /// Invokes a handler when an already-running application is launched.
 178    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
 179    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 180    where
 181        F: 'static + FnMut(&mut AppContext),
 182    {
 183        let this = Rc::downgrade(&self.0);
 184        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 185            if let Some(app) = this.upgrade() {
 186                callback(&mut app.borrow_mut());
 187            }
 188        }));
 189        self
 190    }
 191
 192    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
 193    pub fn background_executor(&self) -> BackgroundExecutor {
 194        self.0.borrow().background_executor.clone()
 195    }
 196
 197    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
 198    pub fn foreground_executor(&self) -> ForegroundExecutor {
 199        self.0.borrow().foreground_executor.clone()
 200    }
 201
 202    /// Returns a reference to the [`TextSystem`] associated with this app.
 203    pub fn text_system(&self) -> Arc<TextSystem> {
 204        self.0.borrow().text_system.clone()
 205    }
 206
 207    /// Returns the file URL of the executable with the specified name in the application bundle
 208    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 209        self.0.borrow().path_for_auxiliary_executable(name)
 210    }
 211}
 212
 213type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
 214type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
 215pub(crate) type KeystrokeObserver =
 216    Box<dyn FnMut(&KeystrokeEvent, &mut WindowContext) -> bool + 'static>;
 217type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
 218type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
 219type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
 220
 221/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
 222/// Other contexts such as [ModelContext], [WindowContext], and [ViewContext] deref to this type, making it the most general context type.
 223/// You need a reference to an `AppContext` to access the state of a [Model].
 224pub struct AppContext {
 225    pub(crate) this: Weak<AppCell>,
 226    pub(crate) platform: Rc<dyn Platform>,
 227    text_system: Arc<TextSystem>,
 228    flushing_effects: bool,
 229    pending_updates: usize,
 230    pub(crate) actions: Rc<ActionRegistry>,
 231    pub(crate) active_drag: Option<AnyDrag>,
 232    pub(crate) background_executor: BackgroundExecutor,
 233    pub(crate) foreground_executor: ForegroundExecutor,
 234    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
 235    asset_source: Arc<dyn AssetSource>,
 236    pub(crate) svg_renderer: SvgRenderer,
 237    http_client: Arc<dyn HttpClient>,
 238    pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
 239    pub(crate) entities: EntityMap,
 240    pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
 241    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
 242    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
 243    pub(crate) keymap: Rc<RefCell<Keymap>>,
 244    pub(crate) global_action_listeners:
 245        FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
 246    pending_effects: VecDeque<Effect>,
 247    pub(crate) pending_notifications: FxHashSet<EntityId>,
 248    pub(crate) pending_global_notifications: FxHashSet<TypeId>,
 249    pub(crate) observers: SubscriberSet<EntityId, Handler>,
 250    // TypeId is the type of the event that the listener callback expects
 251    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
 252    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
 253    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
 254    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
 255    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
 256    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
 257    pub(crate) propagate_event: bool,
 258    pub(crate) prompt_builder: Option<PromptBuilder>,
 259}
 260
 261impl AppContext {
 262    #[allow(clippy::new_ret_no_self)]
 263    pub(crate) fn new(
 264        platform: Rc<dyn Platform>,
 265        asset_source: Arc<dyn AssetSource>,
 266        http_client: Arc<dyn HttpClient>,
 267    ) -> Rc<AppCell> {
 268        let executor = platform.background_executor();
 269        let foreground_executor = platform.foreground_executor();
 270        assert!(
 271            executor.is_main_thread(),
 272            "must construct App on main thread"
 273        );
 274
 275        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 276        let entities = EntityMap::new();
 277
 278        let app = Rc::new_cyclic(|this| AppCell {
 279            app: RefCell::new(AppContext {
 280                this: this.clone(),
 281                platform: platform.clone(),
 282                text_system,
 283                actions: Rc::new(ActionRegistry::default()),
 284                flushing_effects: false,
 285                pending_updates: 0,
 286                active_drag: None,
 287                background_executor: executor,
 288                foreground_executor,
 289                svg_renderer: SvgRenderer::new(asset_source.clone()),
 290                loading_assets: Default::default(),
 291                asset_source,
 292                http_client,
 293                globals_by_type: FxHashMap::default(),
 294                entities,
 295                new_view_observers: SubscriberSet::new(),
 296                window_handles: FxHashMap::default(),
 297                windows: SlotMap::with_key(),
 298                keymap: Rc::new(RefCell::new(Keymap::default())),
 299                global_action_listeners: FxHashMap::default(),
 300                pending_effects: VecDeque::new(),
 301                pending_notifications: FxHashSet::default(),
 302                pending_global_notifications: FxHashSet::default(),
 303                observers: SubscriberSet::new(),
 304                event_listeners: SubscriberSet::new(),
 305                release_listeners: SubscriberSet::new(),
 306                keystroke_observers: SubscriberSet::new(),
 307                global_observers: SubscriberSet::new(),
 308                quit_observers: SubscriberSet::new(),
 309                layout_id_buffer: Default::default(),
 310                propagate_event: true,
 311                prompt_builder: Some(PromptBuilder::Default),
 312            }),
 313        });
 314
 315        init_app_menus(platform.as_ref(), &mut app.borrow_mut());
 316
 317        platform.on_quit(Box::new({
 318            let cx = app.clone();
 319            move || {
 320                cx.borrow_mut().shutdown();
 321            }
 322        }));
 323
 324        app
 325    }
 326
 327    /// Quit the application gracefully. Handlers registered with [`ModelContext::on_app_quit`]
 328    /// will be given 100ms to complete before exiting.
 329    pub fn shutdown(&mut self) {
 330        let mut futures = Vec::new();
 331
 332        for observer in self.quit_observers.remove(&()) {
 333            futures.push(observer(self));
 334        }
 335
 336        self.windows.clear();
 337        self.window_handles.clear();
 338        self.flush_effects();
 339
 340        let futures = futures::future::join_all(futures);
 341        if self
 342            .background_executor
 343            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
 344            .is_err()
 345        {
 346            log::error!("timed out waiting on app_will_quit");
 347        }
 348    }
 349
 350    /// Gracefully quit the application via the platform's standard routine.
 351    pub fn quit(&mut self) {
 352        self.platform.quit();
 353    }
 354
 355    /// Schedules all windows in the application to be redrawn. This can be called
 356    /// multiple times in an update cycle and still result in a single redraw.
 357    pub fn refresh(&mut self) {
 358        self.pending_effects.push_back(Effect::Refresh);
 359    }
 360
 361    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
 362        self.pending_updates += 1;
 363        let result = update(self);
 364        if !self.flushing_effects && self.pending_updates == 1 {
 365            self.flushing_effects = true;
 366            self.flush_effects();
 367            self.flushing_effects = false;
 368        }
 369        self.pending_updates -= 1;
 370        result
 371    }
 372
 373    /// Arrange a callback to be invoked when the given model or view calls `notify` on its respective context.
 374    pub fn observe<W, E>(
 375        &mut self,
 376        entity: &E,
 377        mut on_notify: impl FnMut(E, &mut AppContext) + 'static,
 378    ) -> Subscription
 379    where
 380        W: 'static,
 381        E: Entity<W>,
 382    {
 383        self.observe_internal(entity, move |e, cx| {
 384            on_notify(e, cx);
 385            true
 386        })
 387    }
 388
 389    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
 390        let (subscription, activate) = self.observers.insert(key, value);
 391        self.defer(move |_| activate());
 392        subscription
 393    }
 394    pub(crate) fn observe_internal<W, E>(
 395        &mut self,
 396        entity: &E,
 397        mut on_notify: impl FnMut(E, &mut AppContext) -> bool + 'static,
 398    ) -> Subscription
 399    where
 400        W: 'static,
 401        E: Entity<W>,
 402    {
 403        let entity_id = entity.entity_id();
 404        let handle = entity.downgrade();
 405        self.new_observer(
 406            entity_id,
 407            Box::new(move |cx| {
 408                if let Some(handle) = E::upgrade_from(&handle) {
 409                    on_notify(handle, cx)
 410                } else {
 411                    false
 412                }
 413            }),
 414        )
 415    }
 416
 417    /// Arrange for the given callback to be invoked whenever the given model or view emits an event of a given type.
 418    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
 419    pub fn subscribe<T, E, Event>(
 420        &mut self,
 421        entity: &E,
 422        mut on_event: impl FnMut(E, &Event, &mut AppContext) + 'static,
 423    ) -> Subscription
 424    where
 425        T: 'static + EventEmitter<Event>,
 426        E: Entity<T>,
 427        Event: 'static,
 428    {
 429        self.subscribe_internal(entity, move |entity, event, cx| {
 430            on_event(entity, event, cx);
 431            true
 432        })
 433    }
 434
 435    pub(crate) fn new_subscription(
 436        &mut self,
 437        key: EntityId,
 438        value: (TypeId, Listener),
 439    ) -> Subscription {
 440        let (subscription, activate) = self.event_listeners.insert(key, value);
 441        self.defer(move |_| activate());
 442        subscription
 443    }
 444    pub(crate) fn subscribe_internal<T, E, Evt>(
 445        &mut self,
 446        entity: &E,
 447        mut on_event: impl FnMut(E, &Evt, &mut AppContext) -> bool + 'static,
 448    ) -> Subscription
 449    where
 450        T: 'static + EventEmitter<Evt>,
 451        E: Entity<T>,
 452        Evt: 'static,
 453    {
 454        let entity_id = entity.entity_id();
 455        let entity = entity.downgrade();
 456        self.new_subscription(
 457            entity_id,
 458            (
 459                TypeId::of::<Evt>(),
 460                Box::new(move |event, cx| {
 461                    let event: &Evt = event.downcast_ref().expect("invalid event type");
 462                    if let Some(handle) = E::upgrade_from(&entity) {
 463                        on_event(handle, event, cx)
 464                    } else {
 465                        false
 466                    }
 467                }),
 468            ),
 469        )
 470    }
 471
 472    /// Returns handles to all open windows in the application.
 473    /// Each handle could be downcast to a handle typed for the root view of that window.
 474    /// To find all windows of a given type, you could filter on
 475    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 476        self.windows
 477            .keys()
 478            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
 479            .collect()
 480    }
 481
 482    /// Returns the window handles ordered by their appearance on screen, front to back.
 483    ///
 484    /// The first window in the returned list is the active/topmost window of the application.
 485    ///
 486    /// This method returns None if the platform doesn't implement the method yet.
 487    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 488        self.platform.window_stack()
 489    }
 490
 491    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
 492    pub fn active_window(&self) -> Option<AnyWindowHandle> {
 493        self.platform.active_window()
 494    }
 495
 496    /// Opens a new window with the given option and the root view returned by the given function.
 497    /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
 498    /// functionality.
 499    pub fn open_window<V: 'static + Render>(
 500        &mut self,
 501        options: crate::WindowOptions,
 502        build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
 503    ) -> anyhow::Result<WindowHandle<V>> {
 504        self.update(|cx| {
 505            let id = cx.windows.insert(None);
 506            let handle = WindowHandle::new(id);
 507            match Window::new(handle.into(), options, cx) {
 508                Ok(mut window) => {
 509                    let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
 510                    window.root_view.replace(root_view.into());
 511                    WindowContext::new(cx, &mut window).defer(|cx| cx.appearance_changed());
 512                    cx.window_handles.insert(id, window.handle);
 513                    cx.windows.get_mut(id).unwrap().replace(window);
 514                    Ok(handle)
 515                }
 516                Err(e) => {
 517                    cx.windows.remove(id);
 518                    Err(e)
 519                }
 520            }
 521        })
 522    }
 523
 524    /// Instructs the platform to activate the application by bringing it to the foreground.
 525    pub fn activate(&self, ignoring_other_apps: bool) {
 526        self.platform.activate(ignoring_other_apps);
 527    }
 528
 529    /// Hide the application at the platform level.
 530    pub fn hide(&self) {
 531        self.platform.hide();
 532    }
 533
 534    /// Hide other applications at the platform level.
 535    pub fn hide_other_apps(&self) {
 536        self.platform.hide_other_apps();
 537    }
 538
 539    /// Unhide other applications at the platform level.
 540    pub fn unhide_other_apps(&self) {
 541        self.platform.unhide_other_apps();
 542    }
 543
 544    /// Returns the list of currently active displays.
 545    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 546        self.platform.displays()
 547    }
 548
 549    /// Returns the primary display that will be used for new windows.
 550    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 551        self.platform.primary_display()
 552    }
 553
 554    /// Returns the display with the given ID, if one exists.
 555    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 556        self.displays()
 557            .iter()
 558            .find(|display| display.id() == id)
 559            .cloned()
 560    }
 561
 562    /// Returns the appearance of the application's windows.
 563    pub fn window_appearance(&self) -> WindowAppearance {
 564        self.platform.window_appearance()
 565    }
 566
 567    /// Writes data to the primary selection buffer.
 568    /// Only available on Linux.
 569    #[cfg(target_os = "linux")]
 570    pub fn write_to_primary(&self, item: ClipboardItem) {
 571        self.platform.write_to_primary(item)
 572    }
 573
 574    /// Writes data to the platform clipboard.
 575    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 576        self.platform.write_to_clipboard(item)
 577    }
 578
 579    /// Reads data from the primary selection buffer.
 580    /// Only available on Linux.
 581    #[cfg(target_os = "linux")]
 582    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
 583        self.platform.read_from_primary()
 584    }
 585
 586    /// Reads data from the platform clipboard.
 587    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 588        self.platform.read_from_clipboard()
 589    }
 590
 591    /// Writes credentials to the platform keychain.
 592    pub fn write_credentials(
 593        &self,
 594        url: &str,
 595        username: &str,
 596        password: &[u8],
 597    ) -> Task<Result<()>> {
 598        self.platform.write_credentials(url, username, password)
 599    }
 600
 601    /// Reads credentials from the platform keychain.
 602    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 603        self.platform.read_credentials(url)
 604    }
 605
 606    /// Deletes credentials from the platform keychain.
 607    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 608        self.platform.delete_credentials(url)
 609    }
 610
 611    /// Directs the platform's default browser to open the given URL.
 612    pub fn open_url(&self, url: &str) {
 613        self.platform.open_url(url);
 614    }
 615
 616    /// register_url_scheme requests that the given scheme (e.g. `zed` for `zed://` urls)
 617    /// is opened by the current app.
 618    /// On some platforms (e.g. macOS) you may be able to register URL schemes as part of app
 619    /// distribution, but this method exists to let you register schemes at runtime.
 620    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
 621        self.platform.register_url_scheme(scheme)
 622    }
 623
 624    /// Returns the full pathname of the current app bundle.
 625    /// If the app is not being run from a bundle, returns an error.
 626    pub fn app_path(&self) -> Result<PathBuf> {
 627        self.platform.app_path()
 628    }
 629
 630    /// On Linux, returns the name of the compositor in use.
 631    /// Is blank on other platforms.
 632    pub fn compositor_name(&self) -> &'static str {
 633        self.platform.compositor_name()
 634    }
 635
 636    /// Returns the file URL of the executable with the specified name in the application bundle
 637    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 638        self.platform.path_for_auxiliary_executable(name)
 639    }
 640
 641    /// Displays a platform modal for selecting paths.
 642    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
 643    /// If cancelled, a `None` will be relayed instead.
 644    /// May return an error on Linux if the file picker couldn't be opened.
 645    pub fn prompt_for_paths(
 646        &self,
 647        options: PathPromptOptions,
 648    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 649        self.platform.prompt_for_paths(options)
 650    }
 651
 652    /// Displays a platform modal for selecting a new path where a file can be saved.
 653    /// The provided directory will be used to set the initial location.
 654    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
 655    /// If cancelled, a `None` will be relayed instead.
 656    /// May return an error on Linux if the file picker couldn't be opened.
 657    pub fn prompt_for_new_path(
 658        &self,
 659        directory: &Path,
 660    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 661        self.platform.prompt_for_new_path(directory)
 662    }
 663
 664    /// Reveals the specified path at the platform level, such as in Finder on macOS.
 665    pub fn reveal_path(&self, path: &Path) {
 666        self.platform.reveal_path(path)
 667    }
 668
 669    /// Opens the specified path with the system's default application.
 670    pub fn open_with_system(&self, path: &Path) {
 671        self.platform.open_with_system(path)
 672    }
 673
 674    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
 675    pub fn should_auto_hide_scrollbars(&self) -> bool {
 676        self.platform.should_auto_hide_scrollbars()
 677    }
 678
 679    /// Restart the application.
 680    pub fn restart(&self, binary_path: Option<PathBuf>) {
 681        self.platform.restart(binary_path)
 682    }
 683
 684    /// Updates the http client assigned to GPUI
 685    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
 686        self.http_client = new_client;
 687    }
 688
 689    /// Returns the http client assigned to GPUI
 690    pub fn http_client(&self) -> Arc<dyn HttpClient> {
 691        self.http_client.clone()
 692    }
 693
 694    /// Returns the SVG renderer GPUI uses
 695    pub(crate) fn svg_renderer(&self) -> SvgRenderer {
 696        self.svg_renderer.clone()
 697    }
 698
 699    pub(crate) fn push_effect(&mut self, effect: Effect) {
 700        match &effect {
 701            Effect::Notify { emitter } => {
 702                if !self.pending_notifications.insert(*emitter) {
 703                    return;
 704                }
 705            }
 706            Effect::NotifyGlobalObservers { global_type } => {
 707                if !self.pending_global_notifications.insert(*global_type) {
 708                    return;
 709                }
 710            }
 711            _ => {}
 712        };
 713
 714        self.pending_effects.push_back(effect);
 715    }
 716
 717    /// Called at the end of [`AppContext::update`] to complete any side effects
 718    /// such as notifying observers, emitting events, etc. Effects can themselves
 719    /// cause effects, so we continue looping until all effects are processed.
 720    fn flush_effects(&mut self) {
 721        loop {
 722            self.release_dropped_entities();
 723            self.release_dropped_focus_handles();
 724
 725            if let Some(effect) = self.pending_effects.pop_front() {
 726                match effect {
 727                    Effect::Notify { emitter } => {
 728                        self.apply_notify_effect(emitter);
 729                    }
 730
 731                    Effect::Emit {
 732                        emitter,
 733                        event_type,
 734                        event,
 735                    } => self.apply_emit_effect(emitter, event_type, event),
 736
 737                    Effect::Refresh => {
 738                        self.apply_refresh_effect();
 739                    }
 740
 741                    Effect::NotifyGlobalObservers { global_type } => {
 742                        self.apply_notify_global_observers_effect(global_type);
 743                    }
 744
 745                    Effect::Defer { callback } => {
 746                        self.apply_defer_effect(callback);
 747                    }
 748                }
 749            } else {
 750                #[cfg(any(test, feature = "test-support"))]
 751                for window in self
 752                    .windows
 753                    .values()
 754                    .filter_map(|window| {
 755                        let window = window.as_ref()?;
 756                        window.dirty.get().then_some(window.handle)
 757                    })
 758                    .collect::<Vec<_>>()
 759                {
 760                    self.update_window(window, |_, cx| cx.draw()).unwrap();
 761                }
 762
 763                if self.pending_effects.is_empty() {
 764                    break;
 765                }
 766            }
 767        }
 768    }
 769
 770    /// Repeatedly called during `flush_effects` to release any entities whose
 771    /// reference count has become zero. We invoke any release observers before dropping
 772    /// each entity.
 773    fn release_dropped_entities(&mut self) {
 774        loop {
 775            let dropped = self.entities.take_dropped();
 776            if dropped.is_empty() {
 777                break;
 778            }
 779
 780            for (entity_id, mut entity) in dropped {
 781                self.observers.remove(&entity_id);
 782                self.event_listeners.remove(&entity_id);
 783                for release_callback in self.release_listeners.remove(&entity_id) {
 784                    release_callback(entity.as_mut(), self);
 785                }
 786            }
 787        }
 788    }
 789
 790    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 791    fn release_dropped_focus_handles(&mut self) {
 792        for window_handle in self.windows() {
 793            window_handle
 794                .update(self, |_, cx| {
 795                    let mut blur_window = false;
 796                    let focus = cx.window.focus;
 797                    cx.window.focus_handles.write().retain(|handle_id, count| {
 798                        if count.load(SeqCst) == 0 {
 799                            if focus == Some(handle_id) {
 800                                blur_window = true;
 801                            }
 802                            false
 803                        } else {
 804                            true
 805                        }
 806                    });
 807
 808                    if blur_window {
 809                        cx.blur();
 810                    }
 811                })
 812                .unwrap();
 813        }
 814    }
 815
 816    fn apply_notify_effect(&mut self, emitter: EntityId) {
 817        self.pending_notifications.remove(&emitter);
 818
 819        self.observers
 820            .clone()
 821            .retain(&emitter, |handler| handler(self));
 822    }
 823
 824    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 825        self.event_listeners
 826            .clone()
 827            .retain(&emitter, |(stored_type, handler)| {
 828                if *stored_type == event_type {
 829                    handler(event.as_ref(), self)
 830                } else {
 831                    true
 832                }
 833            });
 834    }
 835
 836    fn apply_refresh_effect(&mut self) {
 837        for window in self.windows.values_mut() {
 838            if let Some(window) = window.as_mut() {
 839                window.dirty.set(true);
 840            }
 841        }
 842    }
 843
 844    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
 845        self.pending_global_notifications.remove(&type_id);
 846        self.global_observers
 847            .clone()
 848            .retain(&type_id, |observer| observer(self));
 849    }
 850
 851    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
 852        callback(self);
 853    }
 854
 855    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
 856    /// so it can be held across `await` points.
 857    pub fn to_async(&self) -> AsyncAppContext {
 858        AsyncAppContext {
 859            app: self.this.clone(),
 860            background_executor: self.background_executor.clone(),
 861            foreground_executor: self.foreground_executor.clone(),
 862        }
 863    }
 864
 865    /// Obtains a reference to the executor, which can be used to spawn futures.
 866    pub fn background_executor(&self) -> &BackgroundExecutor {
 867        &self.background_executor
 868    }
 869
 870    /// Obtains a reference to the executor, which can be used to spawn futures.
 871    pub fn foreground_executor(&self) -> &ForegroundExecutor {
 872        &self.foreground_executor
 873    }
 874
 875    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
 876    /// with [AsyncAppContext], which allows the application state to be accessed across await points.
 877    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
 878    where
 879        Fut: Future<Output = R> + 'static,
 880        R: 'static,
 881    {
 882        self.foreground_executor.spawn(f(self.to_async()))
 883    }
 884
 885    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 886    /// that are currently on the stack to be returned to the app.
 887    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
 888        self.push_effect(Effect::Defer {
 889            callback: Box::new(f),
 890        });
 891    }
 892
 893    /// Accessor for the application's asset source, which is provided when constructing the `App`.
 894    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
 895        &self.asset_source
 896    }
 897
 898    /// Accessor for the text system.
 899    pub fn text_system(&self) -> &Arc<TextSystem> {
 900        &self.text_system
 901    }
 902
 903    /// Check whether a global of the given type has been assigned.
 904    pub fn has_global<G: Global>(&self) -> bool {
 905        self.globals_by_type.contains_key(&TypeId::of::<G>())
 906    }
 907
 908    /// Access the global of the given type. Panics if a global for that type has not been assigned.
 909    #[track_caller]
 910    pub fn global<G: Global>(&self) -> &G {
 911        self.globals_by_type
 912            .get(&TypeId::of::<G>())
 913            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 914            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 915            .unwrap()
 916    }
 917
 918    /// Access the global of the given type if a value has been assigned.
 919    pub fn try_global<G: Global>(&self) -> Option<&G> {
 920        self.globals_by_type
 921            .get(&TypeId::of::<G>())
 922            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 923    }
 924
 925    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
 926    #[track_caller]
 927    pub fn global_mut<G: Global>(&mut self) -> &mut G {
 928        let global_type = TypeId::of::<G>();
 929        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 930        self.globals_by_type
 931            .get_mut(&global_type)
 932            .and_then(|any_state| any_state.downcast_mut::<G>())
 933            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 934            .unwrap()
 935    }
 936
 937    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
 938    /// yet been assigned.
 939    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
 940        let global_type = TypeId::of::<G>();
 941        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 942        self.globals_by_type
 943            .entry(global_type)
 944            .or_insert_with(|| Box::<G>::default())
 945            .downcast_mut::<G>()
 946            .unwrap()
 947    }
 948
 949    /// Sets the value of the global of the given type.
 950    pub fn set_global<G: Global>(&mut self, global: G) {
 951        let global_type = TypeId::of::<G>();
 952        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 953        self.globals_by_type.insert(global_type, Box::new(global));
 954    }
 955
 956    /// Clear all stored globals. Does not notify global observers.
 957    #[cfg(any(test, feature = "test-support"))]
 958    pub fn clear_globals(&mut self) {
 959        self.globals_by_type.drain();
 960    }
 961
 962    /// Remove the global of the given type from the app context. Does not notify global observers.
 963    pub fn remove_global<G: Global>(&mut self) -> G {
 964        let global_type = TypeId::of::<G>();
 965        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 966        *self
 967            .globals_by_type
 968            .remove(&global_type)
 969            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
 970            .downcast()
 971            .unwrap()
 972    }
 973
 974    /// Register a callback to be invoked when a global of the given type is updated.
 975    pub fn observe_global<G: Global>(
 976        &mut self,
 977        mut f: impl FnMut(&mut Self) + 'static,
 978    ) -> Subscription {
 979        let (subscription, activate) = self.global_observers.insert(
 980            TypeId::of::<G>(),
 981            Box::new(move |cx| {
 982                f(cx);
 983                true
 984            }),
 985        );
 986        self.defer(move |_| activate());
 987        subscription
 988    }
 989
 990    /// Move the global of the given type to the stack.
 991    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
 992        GlobalLease::new(
 993            self.globals_by_type
 994                .remove(&TypeId::of::<G>())
 995                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
 996                .unwrap(),
 997        )
 998    }
 999
1000    /// Restore the global of the given type after it is moved to the stack.
1001    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1002        let global_type = TypeId::of::<G>();
1003        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1004        self.globals_by_type.insert(global_type, lease.global);
1005    }
1006
1007    pub(crate) fn new_view_observer(
1008        &mut self,
1009        key: TypeId,
1010        value: NewViewListener,
1011    ) -> Subscription {
1012        let (subscription, activate) = self.new_view_observers.insert(key, value);
1013        activate();
1014        subscription
1015    }
1016    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1017    /// The function will be passed a mutable reference to the view along with an appropriate context.
1018    pub fn observe_new_views<V: 'static>(
1019        &mut self,
1020        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
1021    ) -> Subscription {
1022        self.new_view_observer(
1023            TypeId::of::<V>(),
1024            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
1025                any_view
1026                    .downcast::<V>()
1027                    .unwrap()
1028                    .update(cx, |view_state, cx| {
1029                        on_new(view_state, cx);
1030                    })
1031            }),
1032        )
1033    }
1034
1035    /// Observe the release of a model or view. The callback is invoked after the model or view
1036    /// has no more strong references but before it has been dropped.
1037    pub fn observe_release<E, T>(
1038        &mut self,
1039        handle: &E,
1040        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
1041    ) -> Subscription
1042    where
1043        E: Entity<T>,
1044        T: 'static,
1045    {
1046        let (subscription, activate) = self.release_listeners.insert(
1047            handle.entity_id(),
1048            Box::new(move |entity, cx| {
1049                let entity = entity.downcast_mut().expect("invalid entity type");
1050                on_release(entity, cx)
1051            }),
1052        );
1053        activate();
1054        subscription
1055    }
1056
1057    /// Register a callback to be invoked when a keystroke is received by the application
1058    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1059    /// and that this API will not be invoked if the event's propagation is stopped.
1060    pub fn observe_keystrokes(
1061        &mut self,
1062        mut f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
1063    ) -> Subscription {
1064        fn inner(
1065            keystroke_observers: &mut SubscriberSet<(), KeystrokeObserver>,
1066            handler: KeystrokeObserver,
1067        ) -> Subscription {
1068            let (subscription, activate) = keystroke_observers.insert((), handler);
1069            activate();
1070            subscription
1071        }
1072
1073        inner(
1074            &mut self.keystroke_observers,
1075            Box::new(move |event, cx| {
1076                f(event, cx);
1077                true
1078            }),
1079        )
1080    }
1081
1082    /// Register key bindings.
1083    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1084        self.keymap.borrow_mut().add_bindings(bindings);
1085        self.pending_effects.push_back(Effect::Refresh);
1086    }
1087
1088    /// Clear all key bindings in the app.
1089    pub fn clear_key_bindings(&mut self) {
1090        self.keymap.borrow_mut().clear();
1091        self.pending_effects.push_back(Effect::Refresh);
1092    }
1093
1094    /// Register a global listener for actions invoked via the keyboard.
1095    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1096        self.global_action_listeners
1097            .entry(TypeId::of::<A>())
1098            .or_default()
1099            .push(Rc::new(move |action, phase, cx| {
1100                if phase == DispatchPhase::Bubble {
1101                    let action = action.downcast_ref().unwrap();
1102                    listener(action, cx)
1103                }
1104            }));
1105    }
1106
1107    /// Event handlers propagate events by default. Call this method to stop dispatching to
1108    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1109    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1110    /// calling this method before effects are flushed.
1111    pub fn stop_propagation(&mut self) {
1112        self.propagate_event = false;
1113    }
1114
1115    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1116    /// dispatching to action handlers higher in the element tree. This is the opposite of
1117    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1118    /// this method before effects are flushed.
1119    pub fn propagate(&mut self) {
1120        self.propagate_event = true;
1121    }
1122
1123    /// Build an action from some arbitrary data, typically a keymap entry.
1124    pub fn build_action(
1125        &self,
1126        name: &str,
1127        data: Option<serde_json::Value>,
1128    ) -> Result<Box<dyn Action>> {
1129        self.actions.build_action(name, data)
1130    }
1131
1132    /// Get a list of all action names that have been registered.
1133    /// in the application. Note that registration only allows for
1134    /// actions to be built dynamically, and is unrelated to binding
1135    /// actions in the element tree.
1136    pub fn all_action_names(&self) -> &[SharedString] {
1137        self.actions.all_action_names()
1138    }
1139
1140    /// Register a callback to be invoked when the application is about to quit.
1141    /// It is not possible to cancel the quit event at this point.
1142    pub fn on_app_quit<Fut>(
1143        &mut self,
1144        mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1145    ) -> Subscription
1146    where
1147        Fut: 'static + Future<Output = ()>,
1148    {
1149        let (subscription, activate) = self.quit_observers.insert(
1150            (),
1151            Box::new(move |cx| {
1152                let future = on_quit(cx);
1153                future.boxed_local()
1154            }),
1155        );
1156        activate();
1157        subscription
1158    }
1159
1160    pub(crate) fn clear_pending_keystrokes(&mut self) {
1161        for window in self.windows() {
1162            window
1163                .update(self, |_, cx| {
1164                    cx.clear_pending_keystrokes();
1165                })
1166                .ok();
1167        }
1168    }
1169
1170    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1171    /// the bindings in the element tree, and any global action listeners.
1172    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1173        let mut action_available = false;
1174        if let Some(window) = self.active_window() {
1175            if let Ok(window_action_available) =
1176                window.update(self, |_, cx| cx.is_action_available(action))
1177            {
1178                action_available = window_action_available;
1179            }
1180        }
1181
1182        action_available
1183            || self
1184                .global_action_listeners
1185                .contains_key(&action.as_any().type_id())
1186    }
1187
1188    /// Sets the menu bar for this application. This will replace any existing menu bar.
1189    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1190        self.platform.set_menus(menus, &self.keymap.borrow());
1191    }
1192
1193    /// Gets the menu bar for this application.
1194    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1195        self.platform.get_menus()
1196    }
1197
1198    /// Sets the right click menu for the app icon in the dock
1199    pub fn set_dock_menu(&mut self, menus: Vec<MenuItem>) {
1200        self.platform.set_dock_menu(menus, &self.keymap.borrow());
1201    }
1202
1203    /// Adds given path to the bottom of the list of recent paths for the application.
1204    /// The list is usually shown on the application icon's context menu in the dock,
1205    /// and allows to open the recent files via that context menu.
1206    /// If the path is already in the list, it will be moved to the bottom of the list.
1207    pub fn add_recent_document(&mut self, path: &Path) {
1208        self.platform.add_recent_document(path);
1209    }
1210
1211    /// Dispatch an action to the currently active window or global action handler
1212    /// See [action::Action] for more information on how actions work
1213    pub fn dispatch_action(&mut self, action: &dyn Action) {
1214        if let Some(active_window) = self.active_window() {
1215            active_window
1216                .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1217                .log_err();
1218        } else {
1219            self.dispatch_global_action(action);
1220        }
1221    }
1222
1223    fn dispatch_global_action(&mut self, action: &dyn Action) {
1224        self.propagate_event = true;
1225
1226        if let Some(mut global_listeners) = self
1227            .global_action_listeners
1228            .remove(&action.as_any().type_id())
1229        {
1230            for listener in &global_listeners {
1231                listener(action.as_any(), DispatchPhase::Capture, self);
1232                if !self.propagate_event {
1233                    break;
1234                }
1235            }
1236
1237            global_listeners.extend(
1238                self.global_action_listeners
1239                    .remove(&action.as_any().type_id())
1240                    .unwrap_or_default(),
1241            );
1242
1243            self.global_action_listeners
1244                .insert(action.as_any().type_id(), global_listeners);
1245        }
1246
1247        if self.propagate_event {
1248            if let Some(mut global_listeners) = self
1249                .global_action_listeners
1250                .remove(&action.as_any().type_id())
1251            {
1252                for listener in global_listeners.iter().rev() {
1253                    listener(action.as_any(), DispatchPhase::Bubble, self);
1254                    if !self.propagate_event {
1255                        break;
1256                    }
1257                }
1258
1259                global_listeners.extend(
1260                    self.global_action_listeners
1261                        .remove(&action.as_any().type_id())
1262                        .unwrap_or_default(),
1263                );
1264
1265                self.global_action_listeners
1266                    .insert(action.as_any().type_id(), global_listeners);
1267            }
1268        }
1269    }
1270
1271    /// Is there currently something being dragged?
1272    pub fn has_active_drag(&self) -> bool {
1273        self.active_drag.is_some()
1274    }
1275
1276    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1277    /// prompts with this custom implementation.
1278    pub fn set_prompt_builder(
1279        &mut self,
1280        renderer: impl Fn(
1281                PromptLevel,
1282                &str,
1283                Option<&str>,
1284                &[&str],
1285                PromptHandle,
1286                &mut WindowContext,
1287            ) -> RenderablePromptHandle
1288            + 'static,
1289    ) {
1290        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1291    }
1292
1293    /// Remove an asset from GPUI's cache
1294    pub fn remove_cached_asset<A: Asset + 'static>(&mut self, source: &A::Source) {
1295        let asset_id = (TypeId::of::<A>(), hash(source));
1296        self.loading_assets.remove(&asset_id);
1297    }
1298
1299    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1300    ///
1301    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1302    /// time, and the results of this call will be cached
1303    ///
1304    /// This asset will not be cached by default, see [Self::use_cached_asset]
1305    pub fn fetch_asset<A: Asset + 'static>(
1306        &mut self,
1307        source: &A::Source,
1308    ) -> (Shared<Task<A::Output>>, bool) {
1309        let asset_id = (TypeId::of::<A>(), hash(source));
1310        let mut is_first = false;
1311        let task = self
1312            .loading_assets
1313            .remove(&asset_id)
1314            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1315            .unwrap_or_else(|| {
1316                is_first = true;
1317                let future = A::load(source.clone(), self);
1318                let task = self.background_executor().spawn(future).shared();
1319                task
1320            });
1321
1322        self.loading_assets.insert(asset_id, Box::new(task.clone()));
1323
1324        (task, is_first)
1325    }
1326}
1327
1328impl Context for AppContext {
1329    type Result<T> = T;
1330
1331    /// Build an entity that is owned by the application. The given function will be invoked with
1332    /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1333    /// which can be used to access the entity in a context.
1334    fn new_model<T: 'static>(
1335        &mut self,
1336        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1337    ) -> Model<T> {
1338        self.update(|cx| {
1339            let slot = cx.entities.reserve();
1340            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1341            cx.entities.insert(slot, entity)
1342        })
1343    }
1344
1345    fn reserve_model<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1346        Reservation(self.entities.reserve())
1347    }
1348
1349    fn insert_model<T: 'static>(
1350        &mut self,
1351        reservation: Reservation<T>,
1352        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1353    ) -> Self::Result<Model<T>> {
1354        self.update(|cx| {
1355            let slot = reservation.0;
1356            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1357            cx.entities.insert(slot, entity)
1358        })
1359    }
1360
1361    /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1362    /// entity along with a `ModelContext` for the entity.
1363    fn update_model<T: 'static, R>(
1364        &mut self,
1365        model: &Model<T>,
1366        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1367    ) -> R {
1368        self.update(|cx| {
1369            let mut entity = cx.entities.lease(model);
1370            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1371            cx.entities.end_lease(entity);
1372            result
1373        })
1374    }
1375
1376    fn read_model<T, R>(
1377        &self,
1378        handle: &Model<T>,
1379        read: impl FnOnce(&T, &AppContext) -> R,
1380    ) -> Self::Result<R>
1381    where
1382        T: 'static,
1383    {
1384        let entity = self.entities.read(handle);
1385        read(entity, self)
1386    }
1387
1388    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1389    where
1390        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1391    {
1392        self.update(|cx| {
1393            let mut window = cx
1394                .windows
1395                .get_mut(handle.id)
1396                .ok_or_else(|| anyhow!("window not found"))?
1397                .take()
1398                .ok_or_else(|| anyhow!("window not found"))?;
1399
1400            let root_view = window.root_view.clone().unwrap();
1401            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1402
1403            if window.removed {
1404                cx.window_handles.remove(&handle.id);
1405                cx.windows.remove(handle.id);
1406            } else {
1407                cx.windows
1408                    .get_mut(handle.id)
1409                    .ok_or_else(|| anyhow!("window not found"))?
1410                    .replace(window);
1411            }
1412
1413            Ok(result)
1414        })
1415    }
1416
1417    fn read_window<T, R>(
1418        &self,
1419        window: &WindowHandle<T>,
1420        read: impl FnOnce(View<T>, &AppContext) -> R,
1421    ) -> Result<R>
1422    where
1423        T: 'static,
1424    {
1425        let window = self
1426            .windows
1427            .get(window.id)
1428            .ok_or_else(|| anyhow!("window not found"))?
1429            .as_ref()
1430            .unwrap();
1431
1432        let root_view = window.root_view.clone().unwrap();
1433        let view = root_view
1434            .downcast::<T>()
1435            .map_err(|_| anyhow!("root view's type has changed"))?;
1436
1437        Ok(read(view, self))
1438    }
1439}
1440
1441/// These effects are processed at the end of each application update cycle.
1442pub(crate) enum Effect {
1443    Notify {
1444        emitter: EntityId,
1445    },
1446    Emit {
1447        emitter: EntityId,
1448        event_type: TypeId,
1449        event: Box<dyn Any>,
1450    },
1451    Refresh,
1452    NotifyGlobalObservers {
1453        global_type: TypeId,
1454    },
1455    Defer {
1456        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1457    },
1458}
1459
1460/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1461pub(crate) struct GlobalLease<G: Global> {
1462    global: Box<dyn Any>,
1463    global_type: PhantomData<G>,
1464}
1465
1466impl<G: Global> GlobalLease<G> {
1467    fn new(global: Box<dyn Any>) -> Self {
1468        GlobalLease {
1469            global,
1470            global_type: PhantomData,
1471        }
1472    }
1473}
1474
1475impl<G: Global> Deref for GlobalLease<G> {
1476    type Target = G;
1477
1478    fn deref(&self) -> &Self::Target {
1479        self.global.downcast_ref().unwrap()
1480    }
1481}
1482
1483impl<G: Global> DerefMut for GlobalLease<G> {
1484    fn deref_mut(&mut self) -> &mut Self::Target {
1485        self.global.downcast_mut().unwrap()
1486    }
1487}
1488
1489/// Contains state associated with an active drag operation, started by dragging an element
1490/// within the window or by dragging into the app from the underlying platform.
1491pub struct AnyDrag {
1492    /// The view used to render this drag
1493    pub view: AnyView,
1494
1495    /// The value of the dragged item, to be dropped
1496    pub value: Box<dyn Any>,
1497
1498    /// This is used to render the dragged item in the same place
1499    /// on the original element that the drag was initiated
1500    pub cursor_offset: Point<Pixels>,
1501}
1502
1503/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1504/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1505#[derive(Clone)]
1506pub struct AnyTooltip {
1507    /// The view used to display the tooltip
1508    pub view: AnyView,
1509
1510    /// The absolute position of the mouse when the tooltip was deployed.
1511    pub mouse_position: Point<Pixels>,
1512}
1513
1514/// A keystroke event, and potentially the associated action
1515#[derive(Debug)]
1516pub struct KeystrokeEvent {
1517    /// The keystroke that occurred
1518    pub keystroke: Keystroke,
1519
1520    /// The action that was resolved for the keystroke, if any
1521    pub action: Option<Box<dyn Action>>,
1522}
1523
1524struct NullHttpClient;
1525
1526impl HttpClient for NullHttpClient {
1527    fn send(
1528        &self,
1529        _req: http_client::Request<http_client::AsyncBody>,
1530    ) -> futures::future::BoxFuture<
1531        'static,
1532        Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>,
1533    > {
1534        async move { Err(anyhow!("No HttpClient available")) }.boxed()
1535    }
1536
1537    fn proxy(&self) -> Option<&http_client::Uri> {
1538        None
1539    }
1540}