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