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