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