app.rs

   1use std::{
   2    any::{TypeId, type_name},
   3    cell::{BorrowMutError, Ref, RefCell, RefMut},
   4    marker::PhantomData,
   5    mem,
   6    ops::{Deref, DerefMut},
   7    path::{Path, PathBuf},
   8    rc::{Rc, Weak},
   9    sync::{Arc, atomic::Ordering::SeqCst},
  10    time::Duration,
  11};
  12
  13use anyhow::{Context as _, Result, anyhow};
  14use derive_more::{Deref, DerefMut};
  15use futures::{
  16    Future, FutureExt,
  17    channel::oneshot,
  18    future::{LocalBoxFuture, Shared},
  19};
  20use parking_lot::RwLock;
  21use slotmap::SlotMap;
  22
  23pub use async_context::*;
  24use collections::{FxHashMap, FxHashSet, HashMap, VecDeque};
  25pub use context::*;
  26pub use entity_map::*;
  27use http_client::{HttpClient, Url};
  28use smallvec::SmallVec;
  29#[cfg(any(test, feature = "test-support"))]
  30pub use test_context::*;
  31use util::{ResultExt, debug_panic};
  32
  33#[cfg(any(feature = "inspector", debug_assertions))]
  34use crate::InspectorElementRegistry;
  35use crate::{
  36    Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Asset,
  37    AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DispatchPhase, DisplayId,
  38    EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext,
  39    Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform,
  40    PlatformDisplay, PlatformKeyboardLayout, Point, PromptBuilder, PromptButton, PromptHandle,
  41    PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource,
  42    SubscriberSet, Subscription, SvgRenderer, Task, TextSystem, Window, WindowAppearance,
  43    WindowHandle, WindowId, WindowInvalidator,
  44    colors::{Colors, GlobalColors},
  45    current_platform, hash, init_app_menus,
  46};
  47
  48mod async_context;
  49mod context;
  50mod entity_map;
  51#[cfg(any(test, feature = "test-support"))]
  52mod test_context;
  53
  54/// The duration for which futures returned from [Context::on_app_quit] can run before the application fully quits.
  55pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
  56
  57/// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows.
  58/// Strongly consider removing after stabilization.
  59#[doc(hidden)]
  60pub struct AppCell {
  61    app: RefCell<App>,
  62}
  63
  64impl AppCell {
  65    #[doc(hidden)]
  66    #[track_caller]
  67    pub fn borrow(&self) -> AppRef<'_> {
  68        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  69            let thread_id = std::thread::current().id();
  70            eprintln!("borrowed {thread_id:?}");
  71        }
  72        AppRef(self.app.borrow())
  73    }
  74
  75    #[doc(hidden)]
  76    #[track_caller]
  77    pub fn borrow_mut(&self) -> AppRefMut<'_> {
  78        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  79            let thread_id = std::thread::current().id();
  80            eprintln!("borrowed {thread_id:?}");
  81        }
  82        AppRefMut(self.app.borrow_mut())
  83    }
  84
  85    #[doc(hidden)]
  86    #[track_caller]
  87    pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
  88        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  89            let thread_id = std::thread::current().id();
  90            eprintln!("borrowed {thread_id:?}");
  91        }
  92        Ok(AppRefMut(self.app.try_borrow_mut()?))
  93    }
  94}
  95
  96#[doc(hidden)]
  97#[derive(Deref, DerefMut)]
  98pub struct AppRef<'a>(Ref<'a, App>);
  99
 100impl Drop for AppRef<'_> {
 101    fn drop(&mut self) {
 102        if option_env!("TRACK_THREAD_BORROWS").is_some() {
 103            let thread_id = std::thread::current().id();
 104            eprintln!("dropped borrow from {thread_id:?}");
 105        }
 106    }
 107}
 108
 109#[doc(hidden)]
 110#[derive(Deref, DerefMut)]
 111pub struct AppRefMut<'a>(RefMut<'a, App>);
 112
 113impl Drop for AppRefMut<'_> {
 114    fn drop(&mut self) {
 115        if option_env!("TRACK_THREAD_BORROWS").is_some() {
 116            let thread_id = std::thread::current().id();
 117            eprintln!("dropped {thread_id:?}");
 118        }
 119    }
 120}
 121
 122/// A reference to a GPUI application, typically constructed in the `main` function of your app.
 123/// You won't interact with this type much outside of initial configuration and startup.
 124pub struct Application(Rc<AppCell>);
 125
 126/// Represents an application before it is fully launched. Once your app is
 127/// configured, you'll start the app with `App::run`.
 128impl Application {
 129    /// Builds an app with the given asset source.
 130    #[allow(clippy::new_without_default)]
 131    pub fn new() -> Self {
 132        #[cfg(any(test, feature = "test-support"))]
 133        log::info!("GPUI was compiled in test mode");
 134
 135        Self(App::new_app(
 136            current_platform(false),
 137            Arc::new(()),
 138            Arc::new(NullHttpClient),
 139        ))
 140    }
 141
 142    /// Build an app in headless mode. This prevents opening windows,
 143    /// but makes it possible to run an application in an context like
 144    /// SSH, where GUI applications are not allowed.
 145    pub fn headless() -> Self {
 146        Self(App::new_app(
 147            current_platform(true),
 148            Arc::new(()),
 149            Arc::new(NullHttpClient),
 150        ))
 151    }
 152
 153    /// Assign
 154    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
 155        let mut context_lock = self.0.borrow_mut();
 156        let asset_source = Arc::new(asset_source);
 157        context_lock.asset_source = asset_source.clone();
 158        context_lock.svg_renderer = SvgRenderer::new(asset_source);
 159        drop(context_lock);
 160        self
 161    }
 162
 163    /// Sets the HTTP client for the application.
 164    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
 165        let mut context_lock = self.0.borrow_mut();
 166        context_lock.http_client = http_client;
 167        drop(context_lock);
 168        self
 169    }
 170
 171    /// Start the application. The provided callback will be called once the
 172    /// app is fully launched.
 173    pub fn run<F>(self, on_finish_launching: F)
 174    where
 175        F: 'static + FnOnce(&mut App),
 176    {
 177        let this = self.0.clone();
 178        let platform = self.0.borrow().platform.clone();
 179        platform.run(Box::new(move || {
 180            let cx = &mut *this.borrow_mut();
 181            on_finish_launching(cx);
 182        }));
 183    }
 184
 185    /// Register a handler to be invoked when the platform instructs the application
 186    /// to open one or more URLs.
 187    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 188    where
 189        F: 'static + FnMut(Vec<String>),
 190    {
 191        self.0.borrow().platform.on_open_urls(Box::new(callback));
 192        self
 193    }
 194
 195    /// Invokes a handler when an already-running application is launched.
 196    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
 197    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 198    where
 199        F: 'static + FnMut(&mut App),
 200    {
 201        let this = Rc::downgrade(&self.0);
 202        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 203            if let Some(app) = this.upgrade() {
 204                callback(&mut app.borrow_mut());
 205            }
 206        }));
 207        self
 208    }
 209
 210    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
 211    pub fn background_executor(&self) -> BackgroundExecutor {
 212        self.0.borrow().background_executor.clone()
 213    }
 214
 215    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
 216    pub fn foreground_executor(&self) -> ForegroundExecutor {
 217        self.0.borrow().foreground_executor.clone()
 218    }
 219
 220    /// Returns a reference to the [`TextSystem`] associated with this app.
 221    pub fn text_system(&self) -> Arc<TextSystem> {
 222        self.0.borrow().text_system.clone()
 223    }
 224
 225    /// Returns the file URL of the executable with the specified name in the application bundle
 226    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 227        self.0.borrow().path_for_auxiliary_executable(name)
 228    }
 229}
 230
 231type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
 232type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
 233pub(crate) type KeystrokeObserver =
 234    Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
 235type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
 236type WindowClosedHandler = Box<dyn FnMut(&mut App)>;
 237type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
 238type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
 239
 240/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
 241/// Other [Context] derefs to this type.
 242/// You need a reference to an `App` to access the state of a [Entity].
 243pub struct App {
 244    pub(crate) this: Weak<AppCell>,
 245    pub(crate) platform: Rc<dyn Platform>,
 246    text_system: Arc<TextSystem>,
 247    flushing_effects: bool,
 248    pending_updates: usize,
 249    pub(crate) actions: Rc<ActionRegistry>,
 250    pub(crate) active_drag: Option<AnyDrag>,
 251    pub(crate) background_executor: BackgroundExecutor,
 252    pub(crate) foreground_executor: ForegroundExecutor,
 253    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
 254    asset_source: Arc<dyn AssetSource>,
 255    pub(crate) svg_renderer: SvgRenderer,
 256    http_client: Arc<dyn HttpClient>,
 257    pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
 258    pub(crate) entities: EntityMap,
 259    pub(crate) window_update_stack: Vec<WindowId>,
 260    pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
 261    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
 262    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
 263    pub(crate) focus_handles: Arc<FocusMap>,
 264    pub(crate) keymap: Rc<RefCell<Keymap>>,
 265    pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
 266    pub(crate) global_action_listeners:
 267        FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
 268    pending_effects: VecDeque<Effect>,
 269    pub(crate) pending_notifications: FxHashSet<EntityId>,
 270    pub(crate) pending_global_notifications: FxHashSet<TypeId>,
 271    pub(crate) observers: SubscriberSet<EntityId, Handler>,
 272    // TypeId is the type of the event that the listener callback expects
 273    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
 274    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
 275    pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
 276    pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
 277    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
 278    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
 279    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
 280    pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
 281    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
 282    pub(crate) propagate_event: bool,
 283    pub(crate) prompt_builder: Option<PromptBuilder>,
 284    pub(crate) window_invalidators_by_entity:
 285        FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
 286    pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
 287    #[cfg(any(feature = "inspector", debug_assertions))]
 288    pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
 289    #[cfg(any(feature = "inspector", debug_assertions))]
 290    pub(crate) inspector_element_registry: InspectorElementRegistry,
 291    #[cfg(any(test, feature = "test-support", debug_assertions))]
 292    pub(crate) name: Option<&'static str>,
 293    quitting: bool,
 294}
 295
 296impl App {
 297    #[allow(clippy::new_ret_no_self)]
 298    pub(crate) fn new_app(
 299        platform: Rc<dyn Platform>,
 300        asset_source: Arc<dyn AssetSource>,
 301        http_client: Arc<dyn HttpClient>,
 302    ) -> Rc<AppCell> {
 303        let executor = platform.background_executor();
 304        let foreground_executor = platform.foreground_executor();
 305        assert!(
 306            executor.is_main_thread(),
 307            "must construct App on main thread"
 308        );
 309
 310        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 311        let entities = EntityMap::new();
 312        let keyboard_layout = platform.keyboard_layout();
 313
 314        let app = Rc::new_cyclic(|this| AppCell {
 315            app: RefCell::new(App {
 316                this: this.clone(),
 317                platform: platform.clone(),
 318                text_system,
 319                actions: Rc::new(ActionRegistry::default()),
 320                flushing_effects: false,
 321                pending_updates: 0,
 322                active_drag: None,
 323                background_executor: executor,
 324                foreground_executor,
 325                svg_renderer: SvgRenderer::new(asset_source.clone()),
 326                loading_assets: Default::default(),
 327                asset_source,
 328                http_client,
 329                globals_by_type: FxHashMap::default(),
 330                entities,
 331                new_entity_observers: SubscriberSet::new(),
 332                windows: SlotMap::with_key(),
 333                window_update_stack: Vec::new(),
 334                window_handles: FxHashMap::default(),
 335                focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 336                keymap: Rc::new(RefCell::new(Keymap::default())),
 337                keyboard_layout,
 338                global_action_listeners: FxHashMap::default(),
 339                pending_effects: VecDeque::new(),
 340                pending_notifications: FxHashSet::default(),
 341                pending_global_notifications: FxHashSet::default(),
 342                observers: SubscriberSet::new(),
 343                tracked_entities: FxHashMap::default(),
 344                window_invalidators_by_entity: FxHashMap::default(),
 345                event_listeners: SubscriberSet::new(),
 346                release_listeners: SubscriberSet::new(),
 347                keystroke_observers: SubscriberSet::new(),
 348                keystroke_interceptors: SubscriberSet::new(),
 349                keyboard_layout_observers: SubscriberSet::new(),
 350                global_observers: SubscriberSet::new(),
 351                quit_observers: SubscriberSet::new(),
 352                window_closed_observers: SubscriberSet::new(),
 353                layout_id_buffer: Default::default(),
 354                propagate_event: true,
 355                prompt_builder: Some(PromptBuilder::Default),
 356                #[cfg(any(feature = "inspector", debug_assertions))]
 357                inspector_renderer: None,
 358                #[cfg(any(feature = "inspector", debug_assertions))]
 359                inspector_element_registry: InspectorElementRegistry::default(),
 360                quitting: false,
 361
 362                #[cfg(any(test, feature = "test-support", debug_assertions))]
 363                name: None,
 364            }),
 365        });
 366
 367        init_app_menus(platform.as_ref(), &mut app.borrow_mut());
 368
 369        platform.on_keyboard_layout_change(Box::new({
 370            let app = Rc::downgrade(&app);
 371            move || {
 372                if let Some(app) = app.upgrade() {
 373                    let cx = &mut app.borrow_mut();
 374                    cx.keyboard_layout = cx.platform.keyboard_layout();
 375                    cx.keyboard_layout_observers
 376                        .clone()
 377                        .retain(&(), move |callback| (callback)(cx));
 378                }
 379            }
 380        }));
 381
 382        platform.on_quit(Box::new({
 383            let cx = app.clone();
 384            move || {
 385                cx.borrow_mut().shutdown();
 386            }
 387        }));
 388
 389        app
 390    }
 391
 392    /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`]
 393    /// will be given 100ms to complete before exiting.
 394    pub fn shutdown(&mut self) {
 395        let mut futures = Vec::new();
 396
 397        for observer in self.quit_observers.remove(&()) {
 398            futures.push(observer(self));
 399        }
 400
 401        self.windows.clear();
 402        self.window_handles.clear();
 403        self.flush_effects();
 404        self.quitting = true;
 405
 406        let futures = futures::future::join_all(futures);
 407        if self
 408            .background_executor
 409            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
 410            .is_err()
 411        {
 412            log::error!("timed out waiting on app_will_quit");
 413        }
 414
 415        self.quitting = false;
 416    }
 417
 418    /// Get the id of the current keyboard layout
 419    pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
 420        self.keyboard_layout.as_ref()
 421    }
 422
 423    /// Invokes a handler when the current keyboard layout changes
 424    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
 425    where
 426        F: 'static + FnMut(&mut App),
 427    {
 428        let (subscription, activate) = self.keyboard_layout_observers.insert(
 429            (),
 430            Box::new(move |cx| {
 431                callback(cx);
 432                true
 433            }),
 434        );
 435        activate();
 436        subscription
 437    }
 438
 439    /// Gracefully quit the application via the platform's standard routine.
 440    pub fn quit(&self) {
 441        self.platform.quit();
 442    }
 443
 444    /// Schedules all windows in the application to be redrawn. This can be called
 445    /// multiple times in an update cycle and still result in a single redraw.
 446    pub fn refresh_windows(&mut self) {
 447        self.pending_effects.push_back(Effect::RefreshWindows);
 448    }
 449
 450    /// Clears cache of rasterized glyphs.
 451    pub fn clear_glyph_atlases(&mut self) {
 452        if let Some(window) = self.windows.values().find_map(|window| window.as_ref()) {
 453            let atlas = window.platform_window.sprite_atlas();
 454            atlas.clear_glyphs();
 455        }
 456    }
 457
 458    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
 459        self.start_update();
 460        let result = update(self);
 461        self.finish_update();
 462        result
 463    }
 464
 465    pub(crate) fn start_update(&mut self) {
 466        self.pending_updates += 1;
 467    }
 468
 469    pub(crate) fn finish_update(&mut self) {
 470        if !self.flushing_effects && self.pending_updates == 1 {
 471            self.flushing_effects = true;
 472            self.flush_effects();
 473            self.flushing_effects = false;
 474        }
 475        self.pending_updates -= 1;
 476    }
 477
 478    /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
 479    pub fn observe<W>(
 480        &mut self,
 481        entity: &Entity<W>,
 482        mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
 483    ) -> Subscription
 484    where
 485        W: 'static,
 486    {
 487        self.observe_internal(entity, move |e, cx| {
 488            on_notify(e, cx);
 489            true
 490        })
 491    }
 492
 493    pub(crate) fn detect_accessed_entities<R>(
 494        &mut self,
 495        callback: impl FnOnce(&mut App) -> R,
 496    ) -> (R, FxHashSet<EntityId>) {
 497        let accessed_entities_start = self.entities.accessed_entities.borrow().clone();
 498        let result = callback(self);
 499        let accessed_entities_end = self.entities.accessed_entities.borrow().clone();
 500        let entities_accessed_in_callback = accessed_entities_end
 501            .difference(&accessed_entities_start)
 502            .copied()
 503            .collect::<FxHashSet<EntityId>>();
 504        (result, entities_accessed_in_callback)
 505    }
 506
 507    pub(crate) fn record_entities_accessed(
 508        &mut self,
 509        window_handle: AnyWindowHandle,
 510        invalidator: WindowInvalidator,
 511        entities: &FxHashSet<EntityId>,
 512    ) {
 513        let mut tracked_entities =
 514            std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
 515        for entity in tracked_entities.iter() {
 516            self.window_invalidators_by_entity
 517                .entry(*entity)
 518                .and_modify(|windows| {
 519                    windows.remove(&window_handle.id);
 520                });
 521        }
 522        for entity in entities.iter() {
 523            self.window_invalidators_by_entity
 524                .entry(*entity)
 525                .or_default()
 526                .insert(window_handle.id, invalidator.clone());
 527        }
 528        tracked_entities.clear();
 529        tracked_entities.extend(entities.iter().copied());
 530        self.tracked_entities
 531            .insert(window_handle.id, tracked_entities);
 532    }
 533
 534    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
 535        let (subscription, activate) = self.observers.insert(key, value);
 536        self.defer(move |_| activate());
 537        subscription
 538    }
 539
 540    pub(crate) fn observe_internal<W>(
 541        &mut self,
 542        entity: &Entity<W>,
 543        mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
 544    ) -> Subscription
 545    where
 546        W: 'static,
 547    {
 548        let entity_id = entity.entity_id();
 549        let handle = entity.downgrade();
 550        self.new_observer(
 551            entity_id,
 552            Box::new(move |cx| {
 553                if let Some(entity) = handle.upgrade() {
 554                    on_notify(entity, cx)
 555                } else {
 556                    false
 557                }
 558            }),
 559        )
 560    }
 561
 562    /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
 563    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
 564    pub fn subscribe<T, Event>(
 565        &mut self,
 566        entity: &Entity<T>,
 567        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
 568    ) -> Subscription
 569    where
 570        T: 'static + EventEmitter<Event>,
 571        Event: 'static,
 572    {
 573        self.subscribe_internal(entity, move |entity, event, cx| {
 574            on_event(entity, event, cx);
 575            true
 576        })
 577    }
 578
 579    pub(crate) fn new_subscription(
 580        &mut self,
 581        key: EntityId,
 582        value: (TypeId, Listener),
 583    ) -> Subscription {
 584        let (subscription, activate) = self.event_listeners.insert(key, value);
 585        self.defer(move |_| activate());
 586        subscription
 587    }
 588    pub(crate) fn subscribe_internal<T, Evt>(
 589        &mut self,
 590        entity: &Entity<T>,
 591        mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
 592    ) -> Subscription
 593    where
 594        T: 'static + EventEmitter<Evt>,
 595        Evt: 'static,
 596    {
 597        let entity_id = entity.entity_id();
 598        let handle = entity.downgrade();
 599        self.new_subscription(
 600            entity_id,
 601            (
 602                TypeId::of::<Evt>(),
 603                Box::new(move |event, cx| {
 604                    let event: &Evt = event.downcast_ref().expect("invalid event type");
 605                    if let Some(entity) = handle.upgrade() {
 606                        on_event(entity, event, cx)
 607                    } else {
 608                        false
 609                    }
 610                }),
 611            ),
 612        )
 613    }
 614
 615    /// Returns handles to all open windows in the application.
 616    /// Each handle could be downcast to a handle typed for the root view of that window.
 617    /// To find all windows of a given type, you could filter on
 618    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 619        self.windows
 620            .keys()
 621            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
 622            .collect()
 623    }
 624
 625    /// Returns the window handles ordered by their appearance on screen, front to back.
 626    ///
 627    /// The first window in the returned list is the active/topmost window of the application.
 628    ///
 629    /// This method returns None if the platform doesn't implement the method yet.
 630    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 631        self.platform.window_stack()
 632    }
 633
 634    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
 635    pub fn active_window(&self) -> Option<AnyWindowHandle> {
 636        self.platform.active_window()
 637    }
 638
 639    /// Opens a new window with the given option and the root view returned by the given function.
 640    /// The function is invoked with a `Window`, which can be used to interact with window-specific
 641    /// functionality.
 642    pub fn open_window<V: 'static + Render>(
 643        &mut self,
 644        options: crate::WindowOptions,
 645        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
 646    ) -> anyhow::Result<WindowHandle<V>> {
 647        self.update(|cx| {
 648            let id = cx.windows.insert(None);
 649            let handle = WindowHandle::new(id);
 650            match Window::new(handle.into(), options, cx) {
 651                Ok(mut window) => {
 652                    cx.window_update_stack.push(id);
 653                    let root_view = build_root_view(&mut window, cx);
 654                    cx.window_update_stack.pop();
 655                    window.root.replace(root_view.into());
 656                    window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
 657                    cx.window_handles.insert(id, window.handle);
 658                    cx.windows.get_mut(id).unwrap().replace(window);
 659                    Ok(handle)
 660                }
 661                Err(e) => {
 662                    cx.windows.remove(id);
 663                    Err(e)
 664                }
 665            }
 666        })
 667    }
 668
 669    /// Instructs the platform to activate the application by bringing it to the foreground.
 670    pub fn activate(&self, ignoring_other_apps: bool) {
 671        self.platform.activate(ignoring_other_apps);
 672    }
 673
 674    /// Hide the application at the platform level.
 675    pub fn hide(&self) {
 676        self.platform.hide();
 677    }
 678
 679    /// Hide other applications at the platform level.
 680    pub fn hide_other_apps(&self) {
 681        self.platform.hide_other_apps();
 682    }
 683
 684    /// Unhide other applications at the platform level.
 685    pub fn unhide_other_apps(&self) {
 686        self.platform.unhide_other_apps();
 687    }
 688
 689    /// Returns the list of currently active displays.
 690    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 691        self.platform.displays()
 692    }
 693
 694    /// Returns the primary display that will be used for new windows.
 695    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 696        self.platform.primary_display()
 697    }
 698
 699    /// Returns whether `screen_capture_sources` may work.
 700    pub fn is_screen_capture_supported(&self) -> bool {
 701        self.platform.is_screen_capture_supported()
 702    }
 703
 704    /// Returns a list of available screen capture sources.
 705    pub fn screen_capture_sources(
 706        &self,
 707    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
 708        self.platform.screen_capture_sources()
 709    }
 710
 711    /// Returns the display with the given ID, if one exists.
 712    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 713        self.displays()
 714            .iter()
 715            .find(|display| display.id() == id)
 716            .cloned()
 717    }
 718
 719    /// Returns the appearance of the application's windows.
 720    pub fn window_appearance(&self) -> WindowAppearance {
 721        self.platform.window_appearance()
 722    }
 723
 724    /// Writes data to the primary selection buffer.
 725    /// Only available on Linux.
 726    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 727    pub fn write_to_primary(&self, item: ClipboardItem) {
 728        self.platform.write_to_primary(item)
 729    }
 730
 731    /// Writes data to the platform clipboard.
 732    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 733        self.platform.write_to_clipboard(item)
 734    }
 735
 736    /// Reads data from the primary selection buffer.
 737    /// Only available on Linux.
 738    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 739    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
 740        self.platform.read_from_primary()
 741    }
 742
 743    /// Reads data from the platform clipboard.
 744    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 745        self.platform.read_from_clipboard()
 746    }
 747
 748    /// Writes credentials to the platform keychain.
 749    pub fn write_credentials(
 750        &self,
 751        url: &str,
 752        username: &str,
 753        password: &[u8],
 754    ) -> Task<Result<()>> {
 755        self.platform.write_credentials(url, username, password)
 756    }
 757
 758    /// Reads credentials from the platform keychain.
 759    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 760        self.platform.read_credentials(url)
 761    }
 762
 763    /// Deletes credentials from the platform keychain.
 764    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 765        self.platform.delete_credentials(url)
 766    }
 767
 768    /// Directs the platform's default browser to open the given URL.
 769    pub fn open_url(&self, url: &str) {
 770        self.platform.open_url(url);
 771    }
 772
 773    /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
 774    /// opened by the current app.
 775    ///
 776    /// On some platforms (e.g. macOS) you may be able to register URL schemes
 777    /// as part of app distribution, but this method exists to let you register
 778    /// schemes at runtime.
 779    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
 780        self.platform.register_url_scheme(scheme)
 781    }
 782
 783    /// Returns the full pathname of the current app bundle.
 784    ///
 785    /// Returns an error if the app is not being run from a bundle.
 786    pub fn app_path(&self) -> Result<PathBuf> {
 787        self.platform.app_path()
 788    }
 789
 790    /// On Linux, returns the name of the compositor in use.
 791    ///
 792    /// Returns an empty string on other platforms.
 793    pub fn compositor_name(&self) -> &'static str {
 794        self.platform.compositor_name()
 795    }
 796
 797    /// Returns the file URL of the executable with the specified name in the application bundle
 798    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 799        self.platform.path_for_auxiliary_executable(name)
 800    }
 801
 802    /// Displays a platform modal for selecting paths.
 803    ///
 804    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
 805    /// If cancelled, a `None` will be relayed instead.
 806    /// May return an error on Linux if the file picker couldn't be opened.
 807    pub fn prompt_for_paths(
 808        &self,
 809        options: PathPromptOptions,
 810    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 811        self.platform.prompt_for_paths(options)
 812    }
 813
 814    /// Displays a platform modal for selecting a new path where a file can be saved.
 815    ///
 816    /// The provided directory will be used to set the initial location.
 817    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
 818    /// If cancelled, a `None` will be relayed instead.
 819    /// May return an error on Linux if the file picker couldn't be opened.
 820    pub fn prompt_for_new_path(
 821        &self,
 822        directory: &Path,
 823    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 824        self.platform.prompt_for_new_path(directory)
 825    }
 826
 827    /// Reveals the specified path at the platform level, such as in Finder on macOS.
 828    pub fn reveal_path(&self, path: &Path) {
 829        self.platform.reveal_path(path)
 830    }
 831
 832    /// Opens the specified path with the system's default application.
 833    pub fn open_with_system(&self, path: &Path) {
 834        self.platform.open_with_system(path)
 835    }
 836
 837    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
 838    pub fn should_auto_hide_scrollbars(&self) -> bool {
 839        self.platform.should_auto_hide_scrollbars()
 840    }
 841
 842    /// Restarts the application.
 843    pub fn restart(&self, binary_path: Option<PathBuf>) {
 844        self.platform.restart(binary_path)
 845    }
 846
 847    /// Returns the HTTP client for the application.
 848    pub fn http_client(&self) -> Arc<dyn HttpClient> {
 849        self.http_client.clone()
 850    }
 851
 852    /// Sets the HTTP client for the application.
 853    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
 854        self.http_client = new_client;
 855    }
 856
 857    /// Returns the SVG renderer used by the application.
 858    pub fn svg_renderer(&self) -> SvgRenderer {
 859        self.svg_renderer.clone()
 860    }
 861
 862    pub(crate) fn push_effect(&mut self, effect: Effect) {
 863        match &effect {
 864            Effect::Notify { emitter } => {
 865                if !self.pending_notifications.insert(*emitter) {
 866                    return;
 867                }
 868            }
 869            Effect::NotifyGlobalObservers { global_type } => {
 870                if !self.pending_global_notifications.insert(*global_type) {
 871                    return;
 872                }
 873            }
 874            _ => {}
 875        };
 876
 877        self.pending_effects.push_back(effect);
 878    }
 879
 880    /// Called at the end of [`App::update`] to complete any side effects
 881    /// such as notifying observers, emitting events, etc. Effects can themselves
 882    /// cause effects, so we continue looping until all effects are processed.
 883    fn flush_effects(&mut self) {
 884        loop {
 885            self.release_dropped_entities();
 886            self.release_dropped_focus_handles();
 887            if let Some(effect) = self.pending_effects.pop_front() {
 888                match effect {
 889                    Effect::Notify { emitter } => {
 890                        self.apply_notify_effect(emitter);
 891                    }
 892
 893                    Effect::Emit {
 894                        emitter,
 895                        event_type,
 896                        event,
 897                    } => self.apply_emit_effect(emitter, event_type, event),
 898
 899                    Effect::RefreshWindows => {
 900                        self.apply_refresh_effect();
 901                    }
 902
 903                    Effect::NotifyGlobalObservers { global_type } => {
 904                        self.apply_notify_global_observers_effect(global_type);
 905                    }
 906
 907                    Effect::Defer { callback } => {
 908                        self.apply_defer_effect(callback);
 909                    }
 910                    Effect::EntityCreated {
 911                        entity,
 912                        tid,
 913                        window,
 914                    } => {
 915                        self.apply_entity_created_effect(entity, tid, window);
 916                    }
 917                }
 918            } else {
 919                #[cfg(any(test, feature = "test-support"))]
 920                for window in self
 921                    .windows
 922                    .values()
 923                    .filter_map(|window| {
 924                        let window = window.as_ref()?;
 925                        window.invalidator.is_dirty().then_some(window.handle)
 926                    })
 927                    .collect::<Vec<_>>()
 928                {
 929                    self.update_window(window, |_, window, cx| window.draw(cx).clear())
 930                        .unwrap();
 931                }
 932
 933                if self.pending_effects.is_empty() {
 934                    break;
 935                }
 936            }
 937        }
 938    }
 939
 940    /// Repeatedly called during `flush_effects` to release any entities whose
 941    /// reference count has become zero. We invoke any release observers before dropping
 942    /// each entity.
 943    fn release_dropped_entities(&mut self) {
 944        loop {
 945            let dropped = self.entities.take_dropped();
 946            if dropped.is_empty() {
 947                break;
 948            }
 949
 950            for (entity_id, mut entity) in dropped {
 951                self.observers.remove(&entity_id);
 952                self.event_listeners.remove(&entity_id);
 953                for release_callback in self.release_listeners.remove(&entity_id) {
 954                    release_callback(entity.as_mut(), self);
 955                }
 956            }
 957        }
 958    }
 959
 960    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 961    fn release_dropped_focus_handles(&mut self) {
 962        self.focus_handles
 963            .clone()
 964            .write()
 965            .retain(|handle_id, focus| {
 966                if focus.ref_count.load(SeqCst) == 0 {
 967                    for window_handle in self.windows() {
 968                        window_handle
 969                            .update(self, |_, window, _| {
 970                                if window.focus == Some(handle_id) {
 971                                    window.blur();
 972                                }
 973                            })
 974                            .unwrap();
 975                    }
 976                    false
 977                } else {
 978                    true
 979                }
 980            });
 981    }
 982
 983    fn apply_notify_effect(&mut self, emitter: EntityId) {
 984        self.pending_notifications.remove(&emitter);
 985
 986        self.observers
 987            .clone()
 988            .retain(&emitter, |handler| handler(self));
 989    }
 990
 991    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 992        self.event_listeners
 993            .clone()
 994            .retain(&emitter, |(stored_type, handler)| {
 995                if *stored_type == event_type {
 996                    handler(event.as_ref(), self)
 997                } else {
 998                    true
 999                }
1000            });
1001    }
1002
1003    fn apply_refresh_effect(&mut self) {
1004        for window in self.windows.values_mut() {
1005            if let Some(window) = window.as_mut() {
1006                window.refreshing = true;
1007                window.invalidator.set_dirty(true);
1008            }
1009        }
1010    }
1011
1012    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1013        self.pending_global_notifications.remove(&type_id);
1014        self.global_observers
1015            .clone()
1016            .retain(&type_id, |observer| observer(self));
1017    }
1018
1019    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1020        callback(self);
1021    }
1022
1023    fn apply_entity_created_effect(
1024        &mut self,
1025        entity: AnyEntity,
1026        tid: TypeId,
1027        window: Option<WindowId>,
1028    ) {
1029        self.new_entity_observers.clone().retain(&tid, |observer| {
1030            if let Some(id) = window {
1031                self.update_window_id(id, {
1032                    let entity = entity.clone();
1033                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
1034                })
1035                .expect("All windows should be off the stack when flushing effects");
1036            } else {
1037                (observer)(entity.clone(), &mut None, self)
1038            }
1039            true
1040        });
1041    }
1042
1043    fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1044    where
1045        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1046    {
1047        self.update(|cx| {
1048            let mut window = cx
1049                .windows
1050                .get_mut(id)
1051                .context("window not found")?
1052                .take()
1053                .context("window not found")?;
1054
1055            let root_view = window.root.clone().unwrap();
1056
1057            cx.window_update_stack.push(window.handle.id);
1058            let result = update(root_view, &mut window, cx);
1059            cx.window_update_stack.pop();
1060
1061            if window.removed {
1062                cx.window_handles.remove(&id);
1063                cx.windows.remove(id);
1064
1065                cx.window_closed_observers.clone().retain(&(), |callback| {
1066                    callback(cx);
1067                    true
1068                });
1069            } else {
1070                cx.windows
1071                    .get_mut(id)
1072                    .context("window not found")?
1073                    .replace(window);
1074            }
1075
1076            Ok(result)
1077        })
1078    }
1079    /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1080    /// so it can be held across `await` points.
1081    pub fn to_async(&self) -> AsyncApp {
1082        AsyncApp {
1083            app: self.this.clone(),
1084            background_executor: self.background_executor.clone(),
1085            foreground_executor: self.foreground_executor.clone(),
1086        }
1087    }
1088
1089    /// Obtains a reference to the executor, which can be used to spawn futures.
1090    pub fn background_executor(&self) -> &BackgroundExecutor {
1091        &self.background_executor
1092    }
1093
1094    /// Obtains a reference to the executor, which can be used to spawn futures.
1095    pub fn foreground_executor(&self) -> &ForegroundExecutor {
1096        if self.quitting {
1097            panic!("Can't spawn on main thread after on_app_quit")
1098        };
1099        &self.foreground_executor
1100    }
1101
1102    /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1103    /// with [AsyncApp], which allows the application state to be accessed across await points.
1104    #[track_caller]
1105    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1106    where
1107        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1108        R: 'static,
1109    {
1110        if self.quitting {
1111            debug_panic!("Can't spawn on main thread after on_app_quit")
1112        };
1113
1114        let mut cx = self.to_async();
1115
1116        self.foreground_executor
1117            .spawn(async move { f(&mut cx).await })
1118    }
1119
1120    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1121    /// that are currently on the stack to be returned to the app.
1122    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1123        self.push_effect(Effect::Defer {
1124            callback: Box::new(f),
1125        });
1126    }
1127
1128    /// Accessor for the application's asset source, which is provided when constructing the `App`.
1129    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1130        &self.asset_source
1131    }
1132
1133    /// Accessor for the text system.
1134    pub fn text_system(&self) -> &Arc<TextSystem> {
1135        &self.text_system
1136    }
1137
1138    /// Check whether a global of the given type has been assigned.
1139    pub fn has_global<G: Global>(&self) -> bool {
1140        self.globals_by_type.contains_key(&TypeId::of::<G>())
1141    }
1142
1143    /// Access the global of the given type. Panics if a global for that type has not been assigned.
1144    #[track_caller]
1145    pub fn global<G: Global>(&self) -> &G {
1146        self.globals_by_type
1147            .get(&TypeId::of::<G>())
1148            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1149            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1150            .unwrap()
1151    }
1152
1153    /// Access the global of the given type if a value has been assigned.
1154    pub fn try_global<G: Global>(&self) -> Option<&G> {
1155        self.globals_by_type
1156            .get(&TypeId::of::<G>())
1157            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1158    }
1159
1160    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1161    #[track_caller]
1162    pub fn global_mut<G: Global>(&mut self) -> &mut G {
1163        let global_type = TypeId::of::<G>();
1164        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1165        self.globals_by_type
1166            .get_mut(&global_type)
1167            .and_then(|any_state| any_state.downcast_mut::<G>())
1168            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1169            .unwrap()
1170    }
1171
1172    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1173    /// yet been assigned.
1174    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1175        let global_type = TypeId::of::<G>();
1176        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1177        self.globals_by_type
1178            .entry(global_type)
1179            .or_insert_with(|| Box::<G>::default())
1180            .downcast_mut::<G>()
1181            .unwrap()
1182    }
1183
1184    /// Sets the value of the global of the given type.
1185    pub fn set_global<G: Global>(&mut self, global: G) {
1186        let global_type = TypeId::of::<G>();
1187        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1188        self.globals_by_type.insert(global_type, Box::new(global));
1189    }
1190
1191    /// Clear all stored globals. Does not notify global observers.
1192    #[cfg(any(test, feature = "test-support"))]
1193    pub fn clear_globals(&mut self) {
1194        self.globals_by_type.drain();
1195    }
1196
1197    /// Remove the global of the given type from the app context. Does not notify global observers.
1198    pub fn remove_global<G: Global>(&mut self) -> G {
1199        let global_type = TypeId::of::<G>();
1200        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1201        *self
1202            .globals_by_type
1203            .remove(&global_type)
1204            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1205            .downcast()
1206            .unwrap()
1207    }
1208
1209    /// Register a callback to be invoked when a global of the given type is updated.
1210    pub fn observe_global<G: Global>(
1211        &mut self,
1212        mut f: impl FnMut(&mut Self) + 'static,
1213    ) -> Subscription {
1214        let (subscription, activate) = self.global_observers.insert(
1215            TypeId::of::<G>(),
1216            Box::new(move |cx| {
1217                f(cx);
1218                true
1219            }),
1220        );
1221        self.defer(move |_| activate());
1222        subscription
1223    }
1224
1225    /// Move the global of the given type to the stack.
1226    #[track_caller]
1227    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1228        GlobalLease::new(
1229            self.globals_by_type
1230                .remove(&TypeId::of::<G>())
1231                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1232                .unwrap(),
1233        )
1234    }
1235
1236    /// Restore the global of the given type after it is moved to the stack.
1237    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1238        let global_type = TypeId::of::<G>();
1239
1240        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1241        self.globals_by_type.insert(global_type, lease.global);
1242    }
1243
1244    pub(crate) fn new_entity_observer(
1245        &self,
1246        key: TypeId,
1247        value: NewEntityListener,
1248    ) -> Subscription {
1249        let (subscription, activate) = self.new_entity_observers.insert(key, value);
1250        activate();
1251        subscription
1252    }
1253
1254    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1255    /// The function will be passed a mutable reference to the view along with an appropriate context.
1256    pub fn observe_new<T: 'static>(
1257        &self,
1258        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1259    ) -> Subscription {
1260        self.new_entity_observer(
1261            TypeId::of::<T>(),
1262            Box::new(
1263                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1264                    any_entity
1265                        .downcast::<T>()
1266                        .unwrap()
1267                        .update(cx, |entity_state, cx| {
1268                            on_new(entity_state, window.as_deref_mut(), cx)
1269                        })
1270                },
1271            ),
1272        )
1273    }
1274
1275    /// Observe the release of a entity. The callback is invoked after the entity
1276    /// has no more strong references but before it has been dropped.
1277    pub fn observe_release<T>(
1278        &self,
1279        handle: &Entity<T>,
1280        on_release: impl FnOnce(&mut T, &mut App) + 'static,
1281    ) -> Subscription
1282    where
1283        T: 'static,
1284    {
1285        let (subscription, activate) = self.release_listeners.insert(
1286            handle.entity_id(),
1287            Box::new(move |entity, cx| {
1288                let entity = entity.downcast_mut().expect("invalid entity type");
1289                on_release(entity, cx)
1290            }),
1291        );
1292        activate();
1293        subscription
1294    }
1295
1296    /// Observe the release of a entity. The callback is invoked after the entity
1297    /// has no more strong references but before it has been dropped.
1298    pub fn observe_release_in<T>(
1299        &self,
1300        handle: &Entity<T>,
1301        window: &Window,
1302        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1303    ) -> Subscription
1304    where
1305        T: 'static,
1306    {
1307        let window_handle = window.handle;
1308        self.observe_release(&handle, move |entity, cx| {
1309            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1310        })
1311    }
1312
1313    /// Register a callback to be invoked when a keystroke is received by the application
1314    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1315    /// and that this API will not be invoked if the event's propagation is stopped.
1316    pub fn observe_keystrokes(
1317        &mut self,
1318        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1319    ) -> Subscription {
1320        fn inner(
1321            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1322            handler: KeystrokeObserver,
1323        ) -> Subscription {
1324            let (subscription, activate) = keystroke_observers.insert((), handler);
1325            activate();
1326            subscription
1327        }
1328
1329        inner(
1330            &mut self.keystroke_observers,
1331            Box::new(move |event, window, cx| {
1332                f(event, window, cx);
1333                true
1334            }),
1335        )
1336    }
1337
1338    /// Register a callback to be invoked when a keystroke is received by the application
1339    /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1340    /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1341    /// within interceptors will prevent action dispatch
1342    pub fn intercept_keystrokes(
1343        &mut self,
1344        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1345    ) -> Subscription {
1346        fn inner(
1347            keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1348            handler: KeystrokeObserver,
1349        ) -> Subscription {
1350            let (subscription, activate) = keystroke_interceptors.insert((), handler);
1351            activate();
1352            subscription
1353        }
1354
1355        inner(
1356            &mut self.keystroke_interceptors,
1357            Box::new(move |event, window, cx| {
1358                f(event, window, cx);
1359                true
1360            }),
1361        )
1362    }
1363
1364    /// Register key bindings.
1365    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1366        self.keymap.borrow_mut().add_bindings(bindings);
1367        self.pending_effects.push_back(Effect::RefreshWindows);
1368    }
1369
1370    /// Clear all key bindings in the app.
1371    pub fn clear_key_bindings(&mut self) {
1372        self.keymap.borrow_mut().clear();
1373        self.pending_effects.push_back(Effect::RefreshWindows);
1374    }
1375
1376    /// Get all key bindings in the app.
1377    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1378        self.keymap.clone()
1379    }
1380
1381    /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1382    /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1383    /// handlers or if they called `cx.propagate()`.
1384    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1385        self.global_action_listeners
1386            .entry(TypeId::of::<A>())
1387            .or_default()
1388            .push(Rc::new(move |action, phase, cx| {
1389                if phase == DispatchPhase::Bubble {
1390                    let action = action.downcast_ref().unwrap();
1391                    listener(action, cx)
1392                }
1393            }));
1394    }
1395
1396    /// Event handlers propagate events by default. Call this method to stop dispatching to
1397    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1398    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1399    /// calling this method before effects are flushed.
1400    pub fn stop_propagation(&mut self) {
1401        self.propagate_event = false;
1402    }
1403
1404    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1405    /// dispatching to action handlers higher in the element tree. This is the opposite of
1406    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1407    /// this method before effects are flushed.
1408    pub fn propagate(&mut self) {
1409        self.propagate_event = true;
1410    }
1411
1412    /// Build an action from some arbitrary data, typically a keymap entry.
1413    pub fn build_action(
1414        &self,
1415        name: &str,
1416        data: Option<serde_json::Value>,
1417    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1418        self.actions.build_action(name, data)
1419    }
1420
1421    /// Get all action names that have been registered. Note that registration only allows for
1422    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1423    pub fn all_action_names(&self) -> &[&'static str] {
1424        self.actions.all_action_names()
1425    }
1426
1427    /// Returns key bindings that invoke the given action on the currently focused element, without
1428    /// checking context. Bindings are returned in the order they were added. For display, the last
1429    /// binding should take precedence.
1430    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1431        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1432    }
1433
1434    /// Get all non-internal actions that have been registered, along with their schemas.
1435    pub fn action_schemas(
1436        &self,
1437        generator: &mut schemars::SchemaGenerator,
1438    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1439        self.actions.action_schemas(generator)
1440    }
1441
1442    /// Get a map from a deprecated action name to the canonical name.
1443    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1444        self.actions.deprecated_aliases()
1445    }
1446
1447    /// Get a map from an action name to the deprecation messages.
1448    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1449        self.actions.deprecation_messages()
1450    }
1451
1452    /// Get a map from an action name to the documentation.
1453    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
1454        self.actions.documentation()
1455    }
1456
1457    /// Register a callback to be invoked when the application is about to quit.
1458    /// It is not possible to cancel the quit event at this point.
1459    pub fn on_app_quit<Fut>(
1460        &self,
1461        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1462    ) -> Subscription
1463    where
1464        Fut: 'static + Future<Output = ()>,
1465    {
1466        let (subscription, activate) = self.quit_observers.insert(
1467            (),
1468            Box::new(move |cx| {
1469                let future = on_quit(cx);
1470                future.boxed_local()
1471            }),
1472        );
1473        activate();
1474        subscription
1475    }
1476
1477    /// Register a callback to be invoked when a window is closed
1478    /// The window is no longer accessible at the point this callback is invoked.
1479    pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1480        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1481        activate();
1482        subscription
1483    }
1484
1485    pub(crate) fn clear_pending_keystrokes(&mut self) {
1486        for window in self.windows() {
1487            window
1488                .update(self, |_, window, _| {
1489                    window.clear_pending_keystrokes();
1490                })
1491                .ok();
1492        }
1493    }
1494
1495    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1496    /// the bindings in the element tree, and any global action listeners.
1497    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1498        let mut action_available = false;
1499        if let Some(window) = self.active_window() {
1500            if let Ok(window_action_available) =
1501                window.update(self, |_, window, cx| window.is_action_available(action, cx))
1502            {
1503                action_available = window_action_available;
1504            }
1505        }
1506
1507        action_available
1508            || self
1509                .global_action_listeners
1510                .contains_key(&action.as_any().type_id())
1511    }
1512
1513    /// Sets the menu bar for this application. This will replace any existing menu bar.
1514    pub fn set_menus(&self, menus: Vec<Menu>) {
1515        self.platform.set_menus(menus, &self.keymap.borrow());
1516    }
1517
1518    /// Gets the menu bar for this application.
1519    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1520        self.platform.get_menus()
1521    }
1522
1523    /// Sets the right click menu for the app icon in the dock
1524    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1525        self.platform.set_dock_menu(menus, &self.keymap.borrow())
1526    }
1527
1528    /// Performs the action associated with the given dock menu item, only used on Windows for now.
1529    pub fn perform_dock_menu_action(&self, action: usize) {
1530        self.platform.perform_dock_menu_action(action);
1531    }
1532
1533    /// Adds given path to the bottom of the list of recent paths for the application.
1534    /// The list is usually shown on the application icon's context menu in the dock,
1535    /// and allows to open the recent files via that context menu.
1536    /// If the path is already in the list, it will be moved to the bottom of the list.
1537    pub fn add_recent_document(&self, path: &Path) {
1538        self.platform.add_recent_document(path);
1539    }
1540
1541    /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
1542    /// Note that this also sets the dock menu on Windows.
1543    pub fn update_jump_list(
1544        &self,
1545        menus: Vec<MenuItem>,
1546        entries: Vec<SmallVec<[PathBuf; 2]>>,
1547    ) -> Vec<SmallVec<[PathBuf; 2]>> {
1548        self.platform.update_jump_list(menus, entries)
1549    }
1550
1551    /// Dispatch an action to the currently active window or global action handler
1552    /// See [`crate::Action`] for more information on how actions work
1553    pub fn dispatch_action(&mut self, action: &dyn Action) {
1554        if let Some(active_window) = self.active_window() {
1555            active_window
1556                .update(self, |_, window, cx| {
1557                    window.dispatch_action(action.boxed_clone(), cx)
1558                })
1559                .log_err();
1560        } else {
1561            self.dispatch_global_action(action);
1562        }
1563    }
1564
1565    fn dispatch_global_action(&mut self, action: &dyn Action) {
1566        self.propagate_event = true;
1567
1568        if let Some(mut global_listeners) = self
1569            .global_action_listeners
1570            .remove(&action.as_any().type_id())
1571        {
1572            for listener in &global_listeners {
1573                listener(action.as_any(), DispatchPhase::Capture, self);
1574                if !self.propagate_event {
1575                    break;
1576                }
1577            }
1578
1579            global_listeners.extend(
1580                self.global_action_listeners
1581                    .remove(&action.as_any().type_id())
1582                    .unwrap_or_default(),
1583            );
1584
1585            self.global_action_listeners
1586                .insert(action.as_any().type_id(), global_listeners);
1587        }
1588
1589        if self.propagate_event {
1590            if let Some(mut global_listeners) = self
1591                .global_action_listeners
1592                .remove(&action.as_any().type_id())
1593            {
1594                for listener in global_listeners.iter().rev() {
1595                    listener(action.as_any(), DispatchPhase::Bubble, self);
1596                    if !self.propagate_event {
1597                        break;
1598                    }
1599                }
1600
1601                global_listeners.extend(
1602                    self.global_action_listeners
1603                        .remove(&action.as_any().type_id())
1604                        .unwrap_or_default(),
1605                );
1606
1607                self.global_action_listeners
1608                    .insert(action.as_any().type_id(), global_listeners);
1609            }
1610        }
1611    }
1612
1613    /// Is there currently something being dragged?
1614    pub fn has_active_drag(&self) -> bool {
1615        self.active_drag.is_some()
1616    }
1617
1618    /// Gets the cursor style of the currently active drag operation.
1619    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
1620        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
1621    }
1622
1623    /// Stops active drag and clears any related effects.
1624    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
1625        if self.active_drag.is_some() {
1626            self.active_drag = None;
1627            window.refresh();
1628            true
1629        } else {
1630            false
1631        }
1632    }
1633
1634    /// Sets the cursor style for the currently active drag operation.
1635    pub fn set_active_drag_cursor_style(
1636        &mut self,
1637        cursor_style: CursorStyle,
1638        window: &mut Window,
1639    ) -> bool {
1640        if let Some(ref mut drag) = self.active_drag {
1641            drag.cursor_style = Some(cursor_style);
1642            window.refresh();
1643            true
1644        } else {
1645            false
1646        }
1647    }
1648
1649    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1650    /// prompts with this custom implementation.
1651    pub fn set_prompt_builder(
1652        &mut self,
1653        renderer: impl Fn(
1654            PromptLevel,
1655            &str,
1656            Option<&str>,
1657            &[PromptButton],
1658            PromptHandle,
1659            &mut Window,
1660            &mut App,
1661        ) -> RenderablePromptHandle
1662        + 'static,
1663    ) {
1664        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
1665    }
1666
1667    /// Reset the prompt builder to the default implementation.
1668    pub fn reset_prompt_builder(&mut self) {
1669        self.prompt_builder = Some(PromptBuilder::Default);
1670    }
1671
1672    /// Remove an asset from GPUI's cache
1673    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
1674        let asset_id = (TypeId::of::<A>(), hash(source));
1675        self.loading_assets.remove(&asset_id);
1676    }
1677
1678    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1679    ///
1680    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1681    /// time, and the results of this call will be cached
1682    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
1683        let asset_id = (TypeId::of::<A>(), hash(source));
1684        let mut is_first = false;
1685        let task = self
1686            .loading_assets
1687            .remove(&asset_id)
1688            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1689            .unwrap_or_else(|| {
1690                is_first = true;
1691                let future = A::load(source.clone(), self);
1692                let task = self.background_executor().spawn(future).shared();
1693                task
1694            });
1695
1696        self.loading_assets.insert(asset_id, Box::new(task.clone()));
1697
1698        (task, is_first)
1699    }
1700
1701    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
1702    /// for elements rendered within this window.
1703    #[track_caller]
1704    pub fn focus_handle(&self) -> FocusHandle {
1705        FocusHandle::new(&self.focus_handles)
1706    }
1707
1708    /// Tell GPUI that an entity has changed and observers of it should be notified.
1709    pub fn notify(&mut self, entity_id: EntityId) {
1710        let window_invalidators = mem::take(
1711            self.window_invalidators_by_entity
1712                .entry(entity_id)
1713                .or_default(),
1714        );
1715
1716        if window_invalidators.is_empty() {
1717            if self.pending_notifications.insert(entity_id) {
1718                self.pending_effects
1719                    .push_back(Effect::Notify { emitter: entity_id });
1720            }
1721        } else {
1722            for invalidator in window_invalidators.values() {
1723                invalidator.invalidate_view(entity_id, self);
1724            }
1725        }
1726
1727        self.window_invalidators_by_entity
1728            .insert(entity_id, window_invalidators);
1729    }
1730
1731    /// Returns the name for this [`App`].
1732    #[cfg(any(test, feature = "test-support", debug_assertions))]
1733    pub fn get_name(&self) -> Option<&'static str> {
1734        self.name
1735    }
1736
1737    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
1738    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
1739        self.platform.can_select_mixed_files_and_dirs()
1740    }
1741
1742    /// Removes an image from the sprite atlas on all windows.
1743    ///
1744    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
1745    /// This is a no-op if the image is not in the sprite atlas.
1746    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
1747        // remove the texture from all other windows
1748        for window in self.windows.values_mut().flatten() {
1749            _ = window.drop_image(image.clone());
1750        }
1751
1752        // remove the texture from the current window
1753        if let Some(window) = current_window {
1754            _ = window.drop_image(image);
1755        }
1756    }
1757
1758    /// Sets the renderer for the inspector.
1759    #[cfg(any(feature = "inspector", debug_assertions))]
1760    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
1761        self.inspector_renderer = Some(f);
1762    }
1763
1764    /// Registers a renderer specific to an inspector state.
1765    #[cfg(any(feature = "inspector", debug_assertions))]
1766    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
1767        &mut self,
1768        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
1769    ) {
1770        self.inspector_element_registry.register(f);
1771    }
1772
1773    /// Initializes gpui's default colors for the application.
1774    ///
1775    /// These colors can be accessed through `cx.default_colors()`.
1776    pub fn init_colors(&mut self) {
1777        self.set_global(GlobalColors(Arc::new(Colors::default())));
1778    }
1779}
1780
1781impl AppContext for App {
1782    type Result<T> = T;
1783
1784    /// Builds an entity that is owned by the application.
1785    ///
1786    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
1787    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
1788    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
1789        self.update(|cx| {
1790            let slot = cx.entities.reserve();
1791            let handle = slot.clone();
1792            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1793
1794            cx.push_effect(Effect::EntityCreated {
1795                entity: handle.clone().into_any(),
1796                tid: TypeId::of::<T>(),
1797                window: cx.window_update_stack.last().cloned(),
1798            });
1799
1800            cx.entities.insert(slot, entity);
1801            handle
1802        })
1803    }
1804
1805    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1806        Reservation(self.entities.reserve())
1807    }
1808
1809    fn insert_entity<T: 'static>(
1810        &mut self,
1811        reservation: Reservation<T>,
1812        build_entity: impl FnOnce(&mut Context<T>) -> T,
1813    ) -> Self::Result<Entity<T>> {
1814        self.update(|cx| {
1815            let slot = reservation.0;
1816            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1817            cx.entities.insert(slot, entity)
1818        })
1819    }
1820
1821    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
1822    /// entity along with a `Context` for the entity.
1823    fn update_entity<T: 'static, R>(
1824        &mut self,
1825        handle: &Entity<T>,
1826        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
1827    ) -> R {
1828        self.update(|cx| {
1829            let mut entity = cx.entities.lease(handle);
1830            let result = update(
1831                &mut entity,
1832                &mut Context::new_context(cx, handle.downgrade()),
1833            );
1834            cx.entities.end_lease(entity);
1835            result
1836        })
1837    }
1838
1839    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
1840    where
1841        T: 'static,
1842    {
1843        GpuiBorrow::new(handle.clone(), self)
1844    }
1845
1846    fn read_entity<T, R>(
1847        &self,
1848        handle: &Entity<T>,
1849        read: impl FnOnce(&T, &App) -> R,
1850    ) -> Self::Result<R>
1851    where
1852        T: 'static,
1853    {
1854        let entity = self.entities.read(handle);
1855        read(entity, self)
1856    }
1857
1858    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1859    where
1860        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1861    {
1862        self.update_window_id(handle.id, update)
1863    }
1864
1865    fn read_window<T, R>(
1866        &self,
1867        window: &WindowHandle<T>,
1868        read: impl FnOnce(Entity<T>, &App) -> R,
1869    ) -> Result<R>
1870    where
1871        T: 'static,
1872    {
1873        let window = self
1874            .windows
1875            .get(window.id)
1876            .context("window not found")?
1877            .as_ref()
1878            .expect("attempted to read a window that is already on the stack");
1879
1880        let root_view = window.root.clone().unwrap();
1881        let view = root_view
1882            .downcast::<T>()
1883            .map_err(|_| anyhow!("root view's type has changed"))?;
1884
1885        Ok(read(view, self))
1886    }
1887
1888    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
1889    where
1890        R: Send + 'static,
1891    {
1892        self.background_executor.spawn(future)
1893    }
1894
1895    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
1896    where
1897        G: Global,
1898    {
1899        let mut g = self.global::<G>();
1900        callback(&g, self)
1901    }
1902}
1903
1904/// These effects are processed at the end of each application update cycle.
1905pub(crate) enum Effect {
1906    Notify {
1907        emitter: EntityId,
1908    },
1909    Emit {
1910        emitter: EntityId,
1911        event_type: TypeId,
1912        event: Box<dyn Any>,
1913    },
1914    RefreshWindows,
1915    NotifyGlobalObservers {
1916        global_type: TypeId,
1917    },
1918    Defer {
1919        callback: Box<dyn FnOnce(&mut App) + 'static>,
1920    },
1921    EntityCreated {
1922        entity: AnyEntity,
1923        tid: TypeId,
1924        window: Option<WindowId>,
1925    },
1926}
1927
1928impl std::fmt::Debug for Effect {
1929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1930        match self {
1931            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
1932            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
1933            Effect::RefreshWindows => write!(f, "RefreshWindows"),
1934            Effect::NotifyGlobalObservers { global_type } => {
1935                write!(f, "NotifyGlobalObservers({:?})", global_type)
1936            }
1937            Effect::Defer { .. } => write!(f, "Defer(..)"),
1938            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
1939        }
1940    }
1941}
1942
1943/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1944pub(crate) struct GlobalLease<G: Global> {
1945    global: Box<dyn Any>,
1946    global_type: PhantomData<G>,
1947}
1948
1949impl<G: Global> GlobalLease<G> {
1950    fn new(global: Box<dyn Any>) -> Self {
1951        GlobalLease {
1952            global,
1953            global_type: PhantomData,
1954        }
1955    }
1956}
1957
1958impl<G: Global> Deref for GlobalLease<G> {
1959    type Target = G;
1960
1961    fn deref(&self) -> &Self::Target {
1962        self.global.downcast_ref().unwrap()
1963    }
1964}
1965
1966impl<G: Global> DerefMut for GlobalLease<G> {
1967    fn deref_mut(&mut self) -> &mut Self::Target {
1968        self.global.downcast_mut().unwrap()
1969    }
1970}
1971
1972/// Contains state associated with an active drag operation, started by dragging an element
1973/// within the window or by dragging into the app from the underlying platform.
1974pub struct AnyDrag {
1975    /// The view used to render this drag
1976    pub view: AnyView,
1977
1978    /// The value of the dragged item, to be dropped
1979    pub value: Arc<dyn Any>,
1980
1981    /// This is used to render the dragged item in the same place
1982    /// on the original element that the drag was initiated
1983    pub cursor_offset: Point<Pixels>,
1984
1985    /// The cursor style to use while dragging
1986    pub cursor_style: Option<CursorStyle>,
1987}
1988
1989/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1990/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1991#[derive(Clone)]
1992pub struct AnyTooltip {
1993    /// The view used to display the tooltip
1994    pub view: AnyView,
1995
1996    /// The absolute position of the mouse when the tooltip was deployed.
1997    pub mouse_position: Point<Pixels>,
1998
1999    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2000    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2001    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2002    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2003}
2004
2005/// A keystroke event, and potentially the associated action
2006#[derive(Debug)]
2007pub struct KeystrokeEvent {
2008    /// The keystroke that occurred
2009    pub keystroke: Keystroke,
2010
2011    /// The action that was resolved for the keystroke, if any
2012    pub action: Option<Box<dyn Action>>,
2013
2014    /// The context stack at the time
2015    pub context_stack: Vec<KeyContext>,
2016}
2017
2018struct NullHttpClient;
2019
2020impl HttpClient for NullHttpClient {
2021    fn send(
2022        &self,
2023        _req: http_client::Request<http_client::AsyncBody>,
2024    ) -> futures::future::BoxFuture<
2025        'static,
2026        anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2027    > {
2028        async move {
2029            anyhow::bail!("No HttpClient available");
2030        }
2031        .boxed()
2032    }
2033
2034    fn proxy(&self) -> Option<&Url> {
2035        None
2036    }
2037
2038    fn type_name(&self) -> &'static str {
2039        type_name::<Self>()
2040    }
2041}
2042
2043/// A mutable reference to an entity owned by GPUI
2044pub struct GpuiBorrow<'a, T> {
2045    inner: Option<Lease<T>>,
2046    app: &'a mut App,
2047}
2048
2049impl<'a, T: 'static> GpuiBorrow<'a, T> {
2050    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2051        app.start_update();
2052        let lease = app.entities.lease(&inner);
2053        Self {
2054            inner: Some(lease),
2055            app,
2056        }
2057    }
2058}
2059
2060impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2061    fn borrow(&self) -> &T {
2062        self.inner.as_ref().unwrap().borrow()
2063    }
2064}
2065
2066impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2067    fn borrow_mut(&mut self) -> &mut T {
2068        self.inner.as_mut().unwrap().borrow_mut()
2069    }
2070}
2071
2072impl<'a, T> Drop for GpuiBorrow<'a, T> {
2073    fn drop(&mut self) {
2074        let lease = self.inner.take().unwrap();
2075        self.app.notify(lease.id);
2076        self.app.entities.end_lease(lease);
2077        self.app.finish_update();
2078    }
2079}
2080
2081#[cfg(test)]
2082mod test {
2083    use std::{cell::RefCell, rc::Rc};
2084
2085    use crate::{AppContext, TestAppContext};
2086
2087    #[test]
2088    fn test_gpui_borrow() {
2089        let cx = TestAppContext::single();
2090        let observation_count = Rc::new(RefCell::new(0));
2091
2092        let state = cx.update(|cx| {
2093            let state = cx.new(|_| false);
2094            cx.observe(&state, {
2095                let observation_count = observation_count.clone();
2096                move |_, _| {
2097                    let mut count = observation_count.borrow_mut();
2098                    *count += 1;
2099                }
2100            })
2101            .detach();
2102
2103            state
2104        });
2105
2106        cx.update(|cx| {
2107            // Calling this like this so that we don't clobber the borrow_mut above
2108            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2109        });
2110
2111        cx.update(|cx| {
2112            state.write(cx, false);
2113        });
2114
2115        assert_eq!(*observation_count.borrow(), 2);
2116    }
2117}