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