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(&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(&self, key: TypeId, value: NewViewListener) -> Subscription {
1008        let (subscription, activate) = self.new_view_observers.insert(key, value);
1009        activate();
1010        subscription
1011    }
1012    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1013    /// The function will be passed a mutable reference to the view along with an appropriate context.
1014    pub fn observe_new_views<V: 'static>(
1015        &self,
1016        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
1017    ) -> Subscription {
1018        self.new_view_observer(
1019            TypeId::of::<V>(),
1020            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
1021                any_view
1022                    .downcast::<V>()
1023                    .unwrap()
1024                    .update(cx, |view_state, cx| {
1025                        on_new(view_state, cx);
1026                    })
1027            }),
1028        )
1029    }
1030
1031    /// Observe the release of a model or view. The callback is invoked after the model or view
1032    /// has no more strong references but before it has been dropped.
1033    pub fn observe_release<E, T>(
1034        &self,
1035        handle: &E,
1036        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
1037    ) -> Subscription
1038    where
1039        E: Entity<T>,
1040        T: 'static,
1041    {
1042        let (subscription, activate) = self.release_listeners.insert(
1043            handle.entity_id(),
1044            Box::new(move |entity, cx| {
1045                let entity = entity.downcast_mut().expect("invalid entity type");
1046                on_release(entity, cx)
1047            }),
1048        );
1049        activate();
1050        subscription
1051    }
1052
1053    /// Register a callback to be invoked when a keystroke is received by the application
1054    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1055    /// and that this API will not be invoked if the event's propagation is stopped.
1056    pub fn observe_keystrokes(
1057        &mut self,
1058        mut f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
1059    ) -> Subscription {
1060        fn inner(
1061            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1062            handler: KeystrokeObserver,
1063        ) -> Subscription {
1064            let (subscription, activate) = keystroke_observers.insert((), handler);
1065            activate();
1066            subscription
1067        }
1068
1069        inner(
1070            &mut self.keystroke_observers,
1071            Box::new(move |event, cx| {
1072                f(event, cx);
1073                true
1074            }),
1075        )
1076    }
1077
1078    /// Register key bindings.
1079    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1080        self.keymap.borrow_mut().add_bindings(bindings);
1081        self.pending_effects.push_back(Effect::Refresh);
1082    }
1083
1084    /// Clear all key bindings in the app.
1085    pub fn clear_key_bindings(&mut self) {
1086        self.keymap.borrow_mut().clear();
1087        self.pending_effects.push_back(Effect::Refresh);
1088    }
1089
1090    /// Register a global listener for actions invoked via the keyboard.
1091    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1092        self.global_action_listeners
1093            .entry(TypeId::of::<A>())
1094            .or_default()
1095            .push(Rc::new(move |action, phase, cx| {
1096                if phase == DispatchPhase::Bubble {
1097                    let action = action.downcast_ref().unwrap();
1098                    listener(action, cx)
1099                }
1100            }));
1101    }
1102
1103    /// Event handlers propagate events by default. Call this method to stop dispatching to
1104    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1105    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1106    /// calling this method before effects are flushed.
1107    pub fn stop_propagation(&mut self) {
1108        self.propagate_event = false;
1109    }
1110
1111    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1112    /// dispatching to action handlers higher in the element tree. This is the opposite of
1113    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1114    /// this method before effects are flushed.
1115    pub fn propagate(&mut self) {
1116        self.propagate_event = true;
1117    }
1118
1119    /// Build an action from some arbitrary data, typically a keymap entry.
1120    pub fn build_action(
1121        &self,
1122        name: &str,
1123        data: Option<serde_json::Value>,
1124    ) -> Result<Box<dyn Action>> {
1125        self.actions.build_action(name, data)
1126    }
1127
1128    /// Get a list of all action names that have been registered.
1129    /// in the application. Note that registration only allows for
1130    /// actions to be built dynamically, and is unrelated to binding
1131    /// actions in the element tree.
1132    pub fn all_action_names(&self) -> &[SharedString] {
1133        self.actions.all_action_names()
1134    }
1135
1136    /// Register a callback to be invoked when the application is about to quit.
1137    /// It is not possible to cancel the quit event at this point.
1138    pub fn on_app_quit<Fut>(
1139        &self,
1140        mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1141    ) -> Subscription
1142    where
1143        Fut: 'static + Future<Output = ()>,
1144    {
1145        let (subscription, activate) = self.quit_observers.insert(
1146            (),
1147            Box::new(move |cx| {
1148                let future = on_quit(cx);
1149                future.boxed_local()
1150            }),
1151        );
1152        activate();
1153        subscription
1154    }
1155
1156    pub(crate) fn clear_pending_keystrokes(&mut self) {
1157        for window in self.windows() {
1158            window
1159                .update(self, |_, cx| {
1160                    cx.clear_pending_keystrokes();
1161                })
1162                .ok();
1163        }
1164    }
1165
1166    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1167    /// the bindings in the element tree, and any global action listeners.
1168    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1169        let mut action_available = false;
1170        if let Some(window) = self.active_window() {
1171            if let Ok(window_action_available) =
1172                window.update(self, |_, cx| cx.is_action_available(action))
1173            {
1174                action_available = window_action_available;
1175            }
1176        }
1177
1178        action_available
1179            || self
1180                .global_action_listeners
1181                .contains_key(&action.as_any().type_id())
1182    }
1183
1184    /// Sets the menu bar for this application. This will replace any existing menu bar.
1185    pub fn set_menus(&self, menus: Vec<Menu>) {
1186        self.platform.set_menus(menus, &self.keymap.borrow());
1187    }
1188
1189    /// Gets the menu bar for this application.
1190    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1191        self.platform.get_menus()
1192    }
1193
1194    /// Sets the right click menu for the app icon in the dock
1195    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1196        self.platform.set_dock_menu(menus, &self.keymap.borrow());
1197    }
1198
1199    /// Adds given path to the bottom of the list of recent paths for the application.
1200    /// The list is usually shown on the application icon's context menu in the dock,
1201    /// and allows to open the recent files via that context menu.
1202    /// If the path is already in the list, it will be moved to the bottom of the list.
1203    pub fn add_recent_document(&self, path: &Path) {
1204        self.platform.add_recent_document(path);
1205    }
1206
1207    /// Dispatch an action to the currently active window or global action handler
1208    /// See [action::Action] for more information on how actions work
1209    pub fn dispatch_action(&mut self, action: &dyn Action) {
1210        if let Some(active_window) = self.active_window() {
1211            active_window
1212                .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1213                .log_err();
1214        } else {
1215            self.dispatch_global_action(action);
1216        }
1217    }
1218
1219    fn dispatch_global_action(&mut self, action: &dyn Action) {
1220        self.propagate_event = true;
1221
1222        if let Some(mut global_listeners) = self
1223            .global_action_listeners
1224            .remove(&action.as_any().type_id())
1225        {
1226            for listener in &global_listeners {
1227                listener(action.as_any(), DispatchPhase::Capture, self);
1228                if !self.propagate_event {
1229                    break;
1230                }
1231            }
1232
1233            global_listeners.extend(
1234                self.global_action_listeners
1235                    .remove(&action.as_any().type_id())
1236                    .unwrap_or_default(),
1237            );
1238
1239            self.global_action_listeners
1240                .insert(action.as_any().type_id(), global_listeners);
1241        }
1242
1243        if self.propagate_event {
1244            if let Some(mut global_listeners) = self
1245                .global_action_listeners
1246                .remove(&action.as_any().type_id())
1247            {
1248                for listener in global_listeners.iter().rev() {
1249                    listener(action.as_any(), DispatchPhase::Bubble, self);
1250                    if !self.propagate_event {
1251                        break;
1252                    }
1253                }
1254
1255                global_listeners.extend(
1256                    self.global_action_listeners
1257                        .remove(&action.as_any().type_id())
1258                        .unwrap_or_default(),
1259                );
1260
1261                self.global_action_listeners
1262                    .insert(action.as_any().type_id(), global_listeners);
1263            }
1264        }
1265    }
1266
1267    /// Is there currently something being dragged?
1268    pub fn has_active_drag(&self) -> bool {
1269        self.active_drag.is_some()
1270    }
1271
1272    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1273    /// prompts with this custom implementation.
1274    pub fn set_prompt_builder(
1275        &mut self,
1276        renderer: impl Fn(
1277                PromptLevel,
1278                &str,
1279                Option<&str>,
1280                &[&str],
1281                PromptHandle,
1282                &mut WindowContext,
1283            ) -> RenderablePromptHandle
1284            + 'static,
1285    ) {
1286        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1287    }
1288
1289    /// Remove an asset from GPUI's cache
1290    pub fn remove_cached_asset<A: Asset + 'static>(&mut self, source: &A::Source) {
1291        let asset_id = (TypeId::of::<A>(), hash(source));
1292        self.loading_assets.remove(&asset_id);
1293    }
1294
1295    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1296    ///
1297    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1298    /// time, and the results of this call will be cached
1299    ///
1300    /// This asset will not be cached by default, see [Self::use_cached_asset]
1301    pub fn fetch_asset<A: Asset + 'static>(
1302        &mut self,
1303        source: &A::Source,
1304    ) -> (Shared<Task<A::Output>>, bool) {
1305        let asset_id = (TypeId::of::<A>(), hash(source));
1306        let mut is_first = false;
1307        let task = self
1308            .loading_assets
1309            .remove(&asset_id)
1310            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1311            .unwrap_or_else(|| {
1312                is_first = true;
1313                let future = A::load(source.clone(), self);
1314                let task = self.background_executor().spawn(future).shared();
1315                task
1316            });
1317
1318        self.loading_assets.insert(asset_id, Box::new(task.clone()));
1319
1320        (task, is_first)
1321    }
1322}
1323
1324impl Context for AppContext {
1325    type Result<T> = T;
1326
1327    /// Build an entity that is owned by the application. The given function will be invoked with
1328    /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1329    /// which can be used to access the entity in a context.
1330    fn new_model<T: 'static>(
1331        &mut self,
1332        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1333    ) -> Model<T> {
1334        self.update(|cx| {
1335            let slot = cx.entities.reserve();
1336            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1337            cx.entities.insert(slot, entity)
1338        })
1339    }
1340
1341    fn reserve_model<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1342        Reservation(self.entities.reserve())
1343    }
1344
1345    fn insert_model<T: 'static>(
1346        &mut self,
1347        reservation: Reservation<T>,
1348        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1349    ) -> Self::Result<Model<T>> {
1350        self.update(|cx| {
1351            let slot = reservation.0;
1352            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1353            cx.entities.insert(slot, entity)
1354        })
1355    }
1356
1357    /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1358    /// entity along with a `ModelContext` for the entity.
1359    fn update_model<T: 'static, R>(
1360        &mut self,
1361        model: &Model<T>,
1362        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1363    ) -> R {
1364        self.update(|cx| {
1365            let mut entity = cx.entities.lease(model);
1366            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1367            cx.entities.end_lease(entity);
1368            result
1369        })
1370    }
1371
1372    fn read_model<T, R>(
1373        &self,
1374        handle: &Model<T>,
1375        read: impl FnOnce(&T, &AppContext) -> R,
1376    ) -> Self::Result<R>
1377    where
1378        T: 'static,
1379    {
1380        let entity = self.entities.read(handle);
1381        read(entity, self)
1382    }
1383
1384    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1385    where
1386        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1387    {
1388        self.update(|cx| {
1389            let mut window = cx
1390                .windows
1391                .get_mut(handle.id)
1392                .ok_or_else(|| anyhow!("window not found"))?
1393                .take()
1394                .ok_or_else(|| anyhow!("window not found"))?;
1395
1396            let root_view = window.root_view.clone().unwrap();
1397            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1398
1399            if window.removed {
1400                cx.window_handles.remove(&handle.id);
1401                cx.windows.remove(handle.id);
1402            } else {
1403                cx.windows
1404                    .get_mut(handle.id)
1405                    .ok_or_else(|| anyhow!("window not found"))?
1406                    .replace(window);
1407            }
1408
1409            Ok(result)
1410        })
1411    }
1412
1413    fn read_window<T, R>(
1414        &self,
1415        window: &WindowHandle<T>,
1416        read: impl FnOnce(View<T>, &AppContext) -> R,
1417    ) -> Result<R>
1418    where
1419        T: 'static,
1420    {
1421        let window = self
1422            .windows
1423            .get(window.id)
1424            .ok_or_else(|| anyhow!("window not found"))?
1425            .as_ref()
1426            .unwrap();
1427
1428        let root_view = window.root_view.clone().unwrap();
1429        let view = root_view
1430            .downcast::<T>()
1431            .map_err(|_| anyhow!("root view's type has changed"))?;
1432
1433        Ok(read(view, self))
1434    }
1435}
1436
1437/// These effects are processed at the end of each application update cycle.
1438pub(crate) enum Effect {
1439    Notify {
1440        emitter: EntityId,
1441    },
1442    Emit {
1443        emitter: EntityId,
1444        event_type: TypeId,
1445        event: Box<dyn Any>,
1446    },
1447    Refresh,
1448    NotifyGlobalObservers {
1449        global_type: TypeId,
1450    },
1451    Defer {
1452        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1453    },
1454}
1455
1456/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1457pub(crate) struct GlobalLease<G: Global> {
1458    global: Box<dyn Any>,
1459    global_type: PhantomData<G>,
1460}
1461
1462impl<G: Global> GlobalLease<G> {
1463    fn new(global: Box<dyn Any>) -> Self {
1464        GlobalLease {
1465            global,
1466            global_type: PhantomData,
1467        }
1468    }
1469}
1470
1471impl<G: Global> Deref for GlobalLease<G> {
1472    type Target = G;
1473
1474    fn deref(&self) -> &Self::Target {
1475        self.global.downcast_ref().unwrap()
1476    }
1477}
1478
1479impl<G: Global> DerefMut for GlobalLease<G> {
1480    fn deref_mut(&mut self) -> &mut Self::Target {
1481        self.global.downcast_mut().unwrap()
1482    }
1483}
1484
1485/// Contains state associated with an active drag operation, started by dragging an element
1486/// within the window or by dragging into the app from the underlying platform.
1487pub struct AnyDrag {
1488    /// The view used to render this drag
1489    pub view: AnyView,
1490
1491    /// The value of the dragged item, to be dropped
1492    pub value: Box<dyn Any>,
1493
1494    /// This is used to render the dragged item in the same place
1495    /// on the original element that the drag was initiated
1496    pub cursor_offset: Point<Pixels>,
1497}
1498
1499/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1500/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1501#[derive(Clone)]
1502pub struct AnyTooltip {
1503    /// The view used to display the tooltip
1504    pub view: AnyView,
1505
1506    /// The absolute position of the mouse when the tooltip was deployed.
1507    pub mouse_position: Point<Pixels>,
1508}
1509
1510/// A keystroke event, and potentially the associated action
1511#[derive(Debug)]
1512pub struct KeystrokeEvent {
1513    /// The keystroke that occurred
1514    pub keystroke: Keystroke,
1515
1516    /// The action that was resolved for the keystroke, if any
1517    pub action: Option<Box<dyn Action>>,
1518}
1519
1520struct NullHttpClient;
1521
1522impl HttpClient for NullHttpClient {
1523    fn send(
1524        &self,
1525        _req: http_client::Request<http_client::AsyncBody>,
1526    ) -> futures::future::BoxFuture<
1527        'static,
1528        Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>,
1529    > {
1530        async move { Err(anyhow!("No HttpClient available")) }.boxed()
1531    }
1532
1533    fn proxy(&self) -> Option<&http_client::Uri> {
1534        None
1535    }
1536}