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(), &mut app.borrow_mut());
 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    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 820        self.platform.prompt_for_new_path(directory)
 821    }
 822
 823    /// Reveals the specified path at the platform level, such as in Finder on macOS.
 824    pub fn reveal_path(&self, path: &Path) {
 825        self.platform.reveal_path(path)
 826    }
 827
 828    /// Opens the specified path with the system's default application.
 829    pub fn open_with_system(&self, path: &Path) {
 830        self.platform.open_with_system(path)
 831    }
 832
 833    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
 834    pub fn should_auto_hide_scrollbars(&self) -> bool {
 835        self.platform.should_auto_hide_scrollbars()
 836    }
 837
 838    /// Restarts the application.
 839    pub fn restart(&mut self) {
 840        self.restart_observers
 841            .clone()
 842            .retain(&(), |observer| observer(self));
 843        self.platform.restart(self.restart_path.take())
 844    }
 845
 846    /// Sets the path to use when restarting the application.
 847    pub fn set_restart_path(&mut self, path: PathBuf) {
 848        self.restart_path = Some(path);
 849    }
 850
 851    /// Returns the HTTP client for the application.
 852    pub fn http_client(&self) -> Arc<dyn HttpClient> {
 853        self.http_client.clone()
 854    }
 855
 856    /// Sets the HTTP client for the application.
 857    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
 858        self.http_client = new_client;
 859    }
 860
 861    /// Returns the SVG renderer used by the application.
 862    pub fn svg_renderer(&self) -> SvgRenderer {
 863        self.svg_renderer.clone()
 864    }
 865
 866    pub(crate) fn push_effect(&mut self, effect: Effect) {
 867        match &effect {
 868            Effect::Notify { emitter } => {
 869                if !self.pending_notifications.insert(*emitter) {
 870                    return;
 871                }
 872            }
 873            Effect::NotifyGlobalObservers { global_type } => {
 874                if !self.pending_global_notifications.insert(*global_type) {
 875                    return;
 876                }
 877            }
 878            _ => {}
 879        };
 880
 881        self.pending_effects.push_back(effect);
 882    }
 883
 884    /// Called at the end of [`App::update`] to complete any side effects
 885    /// such as notifying observers, emitting events, etc. Effects can themselves
 886    /// cause effects, so we continue looping until all effects are processed.
 887    fn flush_effects(&mut self) {
 888        loop {
 889            self.release_dropped_entities();
 890            self.release_dropped_focus_handles();
 891            if let Some(effect) = self.pending_effects.pop_front() {
 892                match effect {
 893                    Effect::Notify { emitter } => {
 894                        self.apply_notify_effect(emitter);
 895                    }
 896
 897                    Effect::Emit {
 898                        emitter,
 899                        event_type,
 900                        event,
 901                    } => self.apply_emit_effect(emitter, event_type, event),
 902
 903                    Effect::RefreshWindows => {
 904                        self.apply_refresh_effect();
 905                    }
 906
 907                    Effect::NotifyGlobalObservers { global_type } => {
 908                        self.apply_notify_global_observers_effect(global_type);
 909                    }
 910
 911                    Effect::Defer { callback } => {
 912                        self.apply_defer_effect(callback);
 913                    }
 914                    Effect::EntityCreated {
 915                        entity,
 916                        tid,
 917                        window,
 918                    } => {
 919                        self.apply_entity_created_effect(entity, tid, window);
 920                    }
 921                }
 922            } else {
 923                #[cfg(any(test, feature = "test-support"))]
 924                for window in self
 925                    .windows
 926                    .values()
 927                    .filter_map(|window| {
 928                        let window = window.as_ref()?;
 929                        window.invalidator.is_dirty().then_some(window.handle)
 930                    })
 931                    .collect::<Vec<_>>()
 932                {
 933                    self.update_window(window, |_, window, cx| window.draw(cx).clear())
 934                        .unwrap();
 935                }
 936
 937                if self.pending_effects.is_empty() {
 938                    break;
 939                }
 940            }
 941        }
 942    }
 943
 944    /// Repeatedly called during `flush_effects` to release any entities whose
 945    /// reference count has become zero. We invoke any release observers before dropping
 946    /// each entity.
 947    fn release_dropped_entities(&mut self) {
 948        loop {
 949            let dropped = self.entities.take_dropped();
 950            if dropped.is_empty() {
 951                break;
 952            }
 953
 954            for (entity_id, mut entity) in dropped {
 955                self.observers.remove(&entity_id);
 956                self.event_listeners.remove(&entity_id);
 957                for release_callback in self.release_listeners.remove(&entity_id) {
 958                    release_callback(entity.as_mut(), self);
 959                }
 960            }
 961        }
 962    }
 963
 964    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 965    fn release_dropped_focus_handles(&mut self) {
 966        self.focus_handles
 967            .clone()
 968            .write()
 969            .retain(|handle_id, focus| {
 970                if focus.ref_count.load(SeqCst) == 0 {
 971                    for window_handle in self.windows() {
 972                        window_handle
 973                            .update(self, |_, window, _| {
 974                                if window.focus == Some(handle_id) {
 975                                    window.blur();
 976                                }
 977                            })
 978                            .unwrap();
 979                    }
 980                    false
 981                } else {
 982                    true
 983                }
 984            });
 985    }
 986
 987    fn apply_notify_effect(&mut self, emitter: EntityId) {
 988        self.pending_notifications.remove(&emitter);
 989
 990        self.observers
 991            .clone()
 992            .retain(&emitter, |handler| handler(self));
 993    }
 994
 995    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 996        self.event_listeners
 997            .clone()
 998            .retain(&emitter, |(stored_type, handler)| {
 999                if *stored_type == event_type {
1000                    handler(event.as_ref(), self)
1001                } else {
1002                    true
1003                }
1004            });
1005    }
1006
1007    fn apply_refresh_effect(&mut self) {
1008        for window in self.windows.values_mut() {
1009            if let Some(window) = window.as_mut() {
1010                window.refreshing = true;
1011                window.invalidator.set_dirty(true);
1012            }
1013        }
1014    }
1015
1016    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1017        self.pending_global_notifications.remove(&type_id);
1018        self.global_observers
1019            .clone()
1020            .retain(&type_id, |observer| observer(self));
1021    }
1022
1023    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1024        callback(self);
1025    }
1026
1027    fn apply_entity_created_effect(
1028        &mut self,
1029        entity: AnyEntity,
1030        tid: TypeId,
1031        window: Option<WindowId>,
1032    ) {
1033        self.new_entity_observers.clone().retain(&tid, |observer| {
1034            if let Some(id) = window {
1035                self.update_window_id(id, {
1036                    let entity = entity.clone();
1037                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
1038                })
1039                .expect("All windows should be off the stack when flushing effects");
1040            } else {
1041                (observer)(entity.clone(), &mut None, self)
1042            }
1043            true
1044        });
1045    }
1046
1047    fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1048    where
1049        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1050    {
1051        self.update(|cx| {
1052            let mut window = cx
1053                .windows
1054                .get_mut(id)
1055                .context("window not found")?
1056                .take()
1057                .context("window not found")?;
1058
1059            let root_view = window.root.clone().unwrap();
1060
1061            cx.window_update_stack.push(window.handle.id);
1062            let result = update(root_view, &mut window, cx);
1063            cx.window_update_stack.pop();
1064
1065            if window.removed {
1066                cx.window_handles.remove(&id);
1067                cx.windows.remove(id);
1068
1069                cx.window_closed_observers.clone().retain(&(), |callback| {
1070                    callback(cx);
1071                    true
1072                });
1073            } else {
1074                cx.windows
1075                    .get_mut(id)
1076                    .context("window not found")?
1077                    .replace(window);
1078            }
1079
1080            Ok(result)
1081        })
1082    }
1083    /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1084    /// so it can be held across `await` points.
1085    pub fn to_async(&self) -> AsyncApp {
1086        AsyncApp {
1087            app: self.this.clone(),
1088            background_executor: self.background_executor.clone(),
1089            foreground_executor: self.foreground_executor.clone(),
1090        }
1091    }
1092
1093    /// Obtains a reference to the executor, which can be used to spawn futures.
1094    pub fn background_executor(&self) -> &BackgroundExecutor {
1095        &self.background_executor
1096    }
1097
1098    /// Obtains a reference to the executor, which can be used to spawn futures.
1099    pub fn foreground_executor(&self) -> &ForegroundExecutor {
1100        if self.quitting {
1101            panic!("Can't spawn on main thread after on_app_quit")
1102        };
1103        &self.foreground_executor
1104    }
1105
1106    /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1107    /// with [AsyncApp], which allows the application state to be accessed across await points.
1108    #[track_caller]
1109    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1110    where
1111        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1112        R: 'static,
1113    {
1114        if self.quitting {
1115            debug_panic!("Can't spawn on main thread after on_app_quit")
1116        };
1117
1118        let mut cx = self.to_async();
1119
1120        self.foreground_executor
1121            .spawn(async move { f(&mut cx).await })
1122    }
1123
1124    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1125    /// that are currently on the stack to be returned to the app.
1126    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1127        self.push_effect(Effect::Defer {
1128            callback: Box::new(f),
1129        });
1130    }
1131
1132    /// Accessor for the application's asset source, which is provided when constructing the `App`.
1133    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1134        &self.asset_source
1135    }
1136
1137    /// Accessor for the text system.
1138    pub fn text_system(&self) -> &Arc<TextSystem> {
1139        &self.text_system
1140    }
1141
1142    /// Check whether a global of the given type has been assigned.
1143    pub fn has_global<G: Global>(&self) -> bool {
1144        self.globals_by_type.contains_key(&TypeId::of::<G>())
1145    }
1146
1147    /// Access the global of the given type. Panics if a global for that type has not been assigned.
1148    #[track_caller]
1149    pub fn global<G: Global>(&self) -> &G {
1150        self.globals_by_type
1151            .get(&TypeId::of::<G>())
1152            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1153            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1154            .unwrap()
1155    }
1156
1157    /// Access the global of the given type if a value has been assigned.
1158    pub fn try_global<G: Global>(&self) -> Option<&G> {
1159        self.globals_by_type
1160            .get(&TypeId::of::<G>())
1161            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1162    }
1163
1164    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1165    #[track_caller]
1166    pub fn global_mut<G: Global>(&mut self) -> &mut G {
1167        let global_type = TypeId::of::<G>();
1168        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1169        self.globals_by_type
1170            .get_mut(&global_type)
1171            .and_then(|any_state| any_state.downcast_mut::<G>())
1172            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1173            .unwrap()
1174    }
1175
1176    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1177    /// yet been assigned.
1178    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1179        let global_type = TypeId::of::<G>();
1180        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1181        self.globals_by_type
1182            .entry(global_type)
1183            .or_insert_with(|| Box::<G>::default())
1184            .downcast_mut::<G>()
1185            .unwrap()
1186    }
1187
1188    /// Sets the value of the global of the given type.
1189    pub fn set_global<G: Global>(&mut self, global: G) {
1190        let global_type = TypeId::of::<G>();
1191        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1192        self.globals_by_type.insert(global_type, Box::new(global));
1193    }
1194
1195    /// Clear all stored globals. Does not notify global observers.
1196    #[cfg(any(test, feature = "test-support"))]
1197    pub fn clear_globals(&mut self) {
1198        self.globals_by_type.drain();
1199    }
1200
1201    /// Remove the global of the given type from the app context. Does not notify global observers.
1202    pub fn remove_global<G: Global>(&mut self) -> G {
1203        let global_type = TypeId::of::<G>();
1204        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1205        *self
1206            .globals_by_type
1207            .remove(&global_type)
1208            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1209            .downcast()
1210            .unwrap()
1211    }
1212
1213    /// Register a callback to be invoked when a global of the given type is updated.
1214    pub fn observe_global<G: Global>(
1215        &mut self,
1216        mut f: impl FnMut(&mut Self) + 'static,
1217    ) -> Subscription {
1218        let (subscription, activate) = self.global_observers.insert(
1219            TypeId::of::<G>(),
1220            Box::new(move |cx| {
1221                f(cx);
1222                true
1223            }),
1224        );
1225        self.defer(move |_| activate());
1226        subscription
1227    }
1228
1229    /// Move the global of the given type to the stack.
1230    #[track_caller]
1231    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1232        GlobalLease::new(
1233            self.globals_by_type
1234                .remove(&TypeId::of::<G>())
1235                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1236                .unwrap(),
1237        )
1238    }
1239
1240    /// Restore the global of the given type after it is moved to the stack.
1241    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1242        let global_type = TypeId::of::<G>();
1243
1244        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1245        self.globals_by_type.insert(global_type, lease.global);
1246    }
1247
1248    pub(crate) fn new_entity_observer(
1249        &self,
1250        key: TypeId,
1251        value: NewEntityListener,
1252    ) -> Subscription {
1253        let (subscription, activate) = self.new_entity_observers.insert(key, value);
1254        activate();
1255        subscription
1256    }
1257
1258    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1259    /// The function will be passed a mutable reference to the view along with an appropriate context.
1260    pub fn observe_new<T: 'static>(
1261        &self,
1262        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1263    ) -> Subscription {
1264        self.new_entity_observer(
1265            TypeId::of::<T>(),
1266            Box::new(
1267                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1268                    any_entity
1269                        .downcast::<T>()
1270                        .unwrap()
1271                        .update(cx, |entity_state, cx| {
1272                            on_new(entity_state, window.as_deref_mut(), cx)
1273                        })
1274                },
1275            ),
1276        )
1277    }
1278
1279    /// Observe the release of a entity. The callback is invoked after the entity
1280    /// has no more strong references but before it has been dropped.
1281    pub fn observe_release<T>(
1282        &self,
1283        handle: &Entity<T>,
1284        on_release: impl FnOnce(&mut T, &mut App) + 'static,
1285    ) -> Subscription
1286    where
1287        T: 'static,
1288    {
1289        let (subscription, activate) = self.release_listeners.insert(
1290            handle.entity_id(),
1291            Box::new(move |entity, cx| {
1292                let entity = entity.downcast_mut().expect("invalid entity type");
1293                on_release(entity, cx)
1294            }),
1295        );
1296        activate();
1297        subscription
1298    }
1299
1300    /// Observe the release of a entity. The callback is invoked after the entity
1301    /// has no more strong references but before it has been dropped.
1302    pub fn observe_release_in<T>(
1303        &self,
1304        handle: &Entity<T>,
1305        window: &Window,
1306        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1307    ) -> Subscription
1308    where
1309        T: 'static,
1310    {
1311        let window_handle = window.handle;
1312        self.observe_release(&handle, move |entity, cx| {
1313            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1314        })
1315    }
1316
1317    /// Register a callback to be invoked when a keystroke is received by the application
1318    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1319    /// and that this API will not be invoked if the event's propagation is stopped.
1320    pub fn observe_keystrokes(
1321        &mut self,
1322        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1323    ) -> Subscription {
1324        fn inner(
1325            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1326            handler: KeystrokeObserver,
1327        ) -> Subscription {
1328            let (subscription, activate) = keystroke_observers.insert((), handler);
1329            activate();
1330            subscription
1331        }
1332
1333        inner(
1334            &mut self.keystroke_observers,
1335            Box::new(move |event, window, cx| {
1336                f(event, window, cx);
1337                true
1338            }),
1339        )
1340    }
1341
1342    /// Register a callback to be invoked when a keystroke is received by the application
1343    /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1344    /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1345    /// within interceptors will prevent action dispatch
1346    pub fn intercept_keystrokes(
1347        &mut self,
1348        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1349    ) -> Subscription {
1350        fn inner(
1351            keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1352            handler: KeystrokeObserver,
1353        ) -> Subscription {
1354            let (subscription, activate) = keystroke_interceptors.insert((), handler);
1355            activate();
1356            subscription
1357        }
1358
1359        inner(
1360            &mut self.keystroke_interceptors,
1361            Box::new(move |event, window, cx| {
1362                f(event, window, cx);
1363                true
1364            }),
1365        )
1366    }
1367
1368    /// Register key bindings.
1369    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1370        self.keymap.borrow_mut().add_bindings(bindings);
1371        self.pending_effects.push_back(Effect::RefreshWindows);
1372    }
1373
1374    /// Clear all key bindings in the app.
1375    pub fn clear_key_bindings(&mut self) {
1376        self.keymap.borrow_mut().clear();
1377        self.pending_effects.push_back(Effect::RefreshWindows);
1378    }
1379
1380    /// Get all key bindings in the app.
1381    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1382        self.keymap.clone()
1383    }
1384
1385    /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1386    /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1387    /// handlers or if they called `cx.propagate()`.
1388    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1389        self.global_action_listeners
1390            .entry(TypeId::of::<A>())
1391            .or_default()
1392            .push(Rc::new(move |action, phase, cx| {
1393                if phase == DispatchPhase::Bubble {
1394                    let action = action.downcast_ref().unwrap();
1395                    listener(action, cx)
1396                }
1397            }));
1398    }
1399
1400    /// Event handlers propagate events by default. Call this method to stop dispatching to
1401    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1402    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1403    /// calling this method before effects are flushed.
1404    pub fn stop_propagation(&mut self) {
1405        self.propagate_event = false;
1406    }
1407
1408    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1409    /// dispatching to action handlers higher in the element tree. This is the opposite of
1410    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1411    /// this method before effects are flushed.
1412    pub fn propagate(&mut self) {
1413        self.propagate_event = true;
1414    }
1415
1416    /// Build an action from some arbitrary data, typically a keymap entry.
1417    pub fn build_action(
1418        &self,
1419        name: &str,
1420        data: Option<serde_json::Value>,
1421    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1422        self.actions.build_action(name, data)
1423    }
1424
1425    /// Get all action names that have been registered. Note that registration only allows for
1426    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1427    pub fn all_action_names(&self) -> &[&'static str] {
1428        self.actions.all_action_names()
1429    }
1430
1431    /// Returns key bindings that invoke the given action on the currently focused element, without
1432    /// checking context. Bindings are returned in the order they were added. For display, the last
1433    /// binding should take precedence.
1434    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1435        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1436    }
1437
1438    /// Get all non-internal actions that have been registered, along with their schemas.
1439    pub fn action_schemas(
1440        &self,
1441        generator: &mut schemars::SchemaGenerator,
1442    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1443        self.actions.action_schemas(generator)
1444    }
1445
1446    /// Get a map from a deprecated action name to the canonical name.
1447    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1448        self.actions.deprecated_aliases()
1449    }
1450
1451    /// Get a map from an action name to the deprecation messages.
1452    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1453        self.actions.deprecation_messages()
1454    }
1455
1456    /// Get a map from an action name to the documentation.
1457    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
1458        self.actions.documentation()
1459    }
1460
1461    /// Register a callback to be invoked when the application is about to quit.
1462    /// It is not possible to cancel the quit event at this point.
1463    pub fn on_app_quit<Fut>(
1464        &self,
1465        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1466    ) -> Subscription
1467    where
1468        Fut: 'static + Future<Output = ()>,
1469    {
1470        let (subscription, activate) = self.quit_observers.insert(
1471            (),
1472            Box::new(move |cx| {
1473                let future = on_quit(cx);
1474                future.boxed_local()
1475            }),
1476        );
1477        activate();
1478        subscription
1479    }
1480
1481    /// Register a callback to be invoked when the application is about to restart.
1482    ///
1483    /// These callbacks are called before any `on_app_quit` callbacks.
1484    pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
1485        let (subscription, activate) = self.restart_observers.insert(
1486            (),
1487            Box::new(move |cx| {
1488                on_restart(cx);
1489                true
1490            }),
1491        );
1492        activate();
1493        subscription
1494    }
1495
1496    /// Register a callback to be invoked when a window is closed
1497    /// The window is no longer accessible at the point this callback is invoked.
1498    pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1499        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1500        activate();
1501        subscription
1502    }
1503
1504    pub(crate) fn clear_pending_keystrokes(&mut self) {
1505        for window in self.windows() {
1506            window
1507                .update(self, |_, window, _| {
1508                    window.clear_pending_keystrokes();
1509                })
1510                .ok();
1511        }
1512    }
1513
1514    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1515    /// the bindings in the element tree, and any global action listeners.
1516    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1517        let mut action_available = false;
1518        if let Some(window) = self.active_window() {
1519            if let Ok(window_action_available) =
1520                window.update(self, |_, window, cx| window.is_action_available(action, cx))
1521            {
1522                action_available = window_action_available;
1523            }
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            if 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
1632    /// Is there currently something being dragged?
1633    pub fn has_active_drag(&self) -> bool {
1634        self.active_drag.is_some()
1635    }
1636
1637    /// Gets the cursor style of the currently active drag operation.
1638    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
1639        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
1640    }
1641
1642    /// Stops active drag and clears any related effects.
1643    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
1644        if self.active_drag.is_some() {
1645            self.active_drag = None;
1646            window.refresh();
1647            true
1648        } else {
1649            false
1650        }
1651    }
1652
1653    /// Sets the cursor style for the currently active drag operation.
1654    pub fn set_active_drag_cursor_style(
1655        &mut self,
1656        cursor_style: CursorStyle,
1657        window: &mut Window,
1658    ) -> bool {
1659        if let Some(ref mut drag) = self.active_drag {
1660            drag.cursor_style = Some(cursor_style);
1661            window.refresh();
1662            true
1663        } else {
1664            false
1665        }
1666    }
1667
1668    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1669    /// prompts with this custom implementation.
1670    pub fn set_prompt_builder(
1671        &mut self,
1672        renderer: impl Fn(
1673            PromptLevel,
1674            &str,
1675            Option<&str>,
1676            &[PromptButton],
1677            PromptHandle,
1678            &mut Window,
1679            &mut App,
1680        ) -> RenderablePromptHandle
1681        + 'static,
1682    ) {
1683        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
1684    }
1685
1686    /// Reset the prompt builder to the default implementation.
1687    pub fn reset_prompt_builder(&mut self) {
1688        self.prompt_builder = Some(PromptBuilder::Default);
1689    }
1690
1691    /// Remove an asset from GPUI's cache
1692    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
1693        let asset_id = (TypeId::of::<A>(), hash(source));
1694        self.loading_assets.remove(&asset_id);
1695    }
1696
1697    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1698    ///
1699    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1700    /// time, and the results of this call will be cached
1701    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
1702        let asset_id = (TypeId::of::<A>(), hash(source));
1703        let mut is_first = false;
1704        let task = self
1705            .loading_assets
1706            .remove(&asset_id)
1707            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1708            .unwrap_or_else(|| {
1709                is_first = true;
1710                let future = A::load(source.clone(), self);
1711                let task = self.background_executor().spawn(future).shared();
1712                task
1713            });
1714
1715        self.loading_assets.insert(asset_id, Box::new(task.clone()));
1716
1717        (task, is_first)
1718    }
1719
1720    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
1721    /// for elements rendered within this window.
1722    #[track_caller]
1723    pub fn focus_handle(&self) -> FocusHandle {
1724        FocusHandle::new(&self.focus_handles)
1725    }
1726
1727    /// Tell GPUI that an entity has changed and observers of it should be notified.
1728    pub fn notify(&mut self, entity_id: EntityId) {
1729        let window_invalidators = mem::take(
1730            self.window_invalidators_by_entity
1731                .entry(entity_id)
1732                .or_default(),
1733        );
1734
1735        if window_invalidators.is_empty() {
1736            if self.pending_notifications.insert(entity_id) {
1737                self.pending_effects
1738                    .push_back(Effect::Notify { emitter: entity_id });
1739            }
1740        } else {
1741            for invalidator in window_invalidators.values() {
1742                invalidator.invalidate_view(entity_id, self);
1743            }
1744        }
1745
1746        self.window_invalidators_by_entity
1747            .insert(entity_id, window_invalidators);
1748    }
1749
1750    /// Returns the name for this [`App`].
1751    #[cfg(any(test, feature = "test-support", debug_assertions))]
1752    pub fn get_name(&self) -> Option<&'static str> {
1753        self.name
1754    }
1755
1756    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
1757    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
1758        self.platform.can_select_mixed_files_and_dirs()
1759    }
1760
1761    /// Removes an image from the sprite atlas on all windows.
1762    ///
1763    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
1764    /// This is a no-op if the image is not in the sprite atlas.
1765    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
1766        // remove the texture from all other windows
1767        for window in self.windows.values_mut().flatten() {
1768            _ = window.drop_image(image.clone());
1769        }
1770
1771        // remove the texture from the current window
1772        if let Some(window) = current_window {
1773            _ = window.drop_image(image);
1774        }
1775    }
1776
1777    /// Sets the renderer for the inspector.
1778    #[cfg(any(feature = "inspector", debug_assertions))]
1779    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
1780        self.inspector_renderer = Some(f);
1781    }
1782
1783    /// Registers a renderer specific to an inspector state.
1784    #[cfg(any(feature = "inspector", debug_assertions))]
1785    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
1786        &mut self,
1787        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
1788    ) {
1789        self.inspector_element_registry.register(f);
1790    }
1791
1792    /// Initializes gpui's default colors for the application.
1793    ///
1794    /// These colors can be accessed through `cx.default_colors()`.
1795    pub fn init_colors(&mut self) {
1796        self.set_global(GlobalColors(Arc::new(Colors::default())));
1797    }
1798}
1799
1800impl AppContext for App {
1801    type Result<T> = T;
1802
1803    /// Builds an entity that is owned by the application.
1804    ///
1805    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
1806    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
1807    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
1808        self.update(|cx| {
1809            let slot = cx.entities.reserve();
1810            let handle = slot.clone();
1811            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1812
1813            cx.push_effect(Effect::EntityCreated {
1814                entity: handle.clone().into_any(),
1815                tid: TypeId::of::<T>(),
1816                window: cx.window_update_stack.last().cloned(),
1817            });
1818
1819            cx.entities.insert(slot, entity);
1820            handle
1821        })
1822    }
1823
1824    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
1825        Reservation(self.entities.reserve())
1826    }
1827
1828    fn insert_entity<T: 'static>(
1829        &mut self,
1830        reservation: Reservation<T>,
1831        build_entity: impl FnOnce(&mut Context<T>) -> T,
1832    ) -> Self::Result<Entity<T>> {
1833        self.update(|cx| {
1834            let slot = reservation.0;
1835            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
1836            cx.entities.insert(slot, entity)
1837        })
1838    }
1839
1840    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
1841    /// entity along with a `Context` for the entity.
1842    fn update_entity<T: 'static, R>(
1843        &mut self,
1844        handle: &Entity<T>,
1845        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
1846    ) -> R {
1847        self.update(|cx| {
1848            let mut entity = cx.entities.lease(handle);
1849            let result = update(
1850                &mut entity,
1851                &mut Context::new_context(cx, handle.downgrade()),
1852            );
1853            cx.entities.end_lease(entity);
1854            result
1855        })
1856    }
1857
1858    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
1859    where
1860        T: 'static,
1861    {
1862        GpuiBorrow::new(handle.clone(), self)
1863    }
1864
1865    fn read_entity<T, R>(
1866        &self,
1867        handle: &Entity<T>,
1868        read: impl FnOnce(&T, &App) -> R,
1869    ) -> Self::Result<R>
1870    where
1871        T: 'static,
1872    {
1873        let entity = self.entities.read(handle);
1874        read(entity, self)
1875    }
1876
1877    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1878    where
1879        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1880    {
1881        self.update_window_id(handle.id, update)
1882    }
1883
1884    fn read_window<T, R>(
1885        &self,
1886        window: &WindowHandle<T>,
1887        read: impl FnOnce(Entity<T>, &App) -> R,
1888    ) -> Result<R>
1889    where
1890        T: 'static,
1891    {
1892        let window = self
1893            .windows
1894            .get(window.id)
1895            .context("window not found")?
1896            .as_ref()
1897            .expect("attempted to read a window that is already on the stack");
1898
1899        let root_view = window.root.clone().unwrap();
1900        let view = root_view
1901            .downcast::<T>()
1902            .map_err(|_| anyhow!("root view's type has changed"))?;
1903
1904        Ok(read(view, self))
1905    }
1906
1907    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
1908    where
1909        R: Send + 'static,
1910    {
1911        self.background_executor.spawn(future)
1912    }
1913
1914    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
1915    where
1916        G: Global,
1917    {
1918        let mut g = self.global::<G>();
1919        callback(&g, self)
1920    }
1921}
1922
1923/// These effects are processed at the end of each application update cycle.
1924pub(crate) enum Effect {
1925    Notify {
1926        emitter: EntityId,
1927    },
1928    Emit {
1929        emitter: EntityId,
1930        event_type: TypeId,
1931        event: Box<dyn Any>,
1932    },
1933    RefreshWindows,
1934    NotifyGlobalObservers {
1935        global_type: TypeId,
1936    },
1937    Defer {
1938        callback: Box<dyn FnOnce(&mut App) + 'static>,
1939    },
1940    EntityCreated {
1941        entity: AnyEntity,
1942        tid: TypeId,
1943        window: Option<WindowId>,
1944    },
1945}
1946
1947impl std::fmt::Debug for Effect {
1948    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1949        match self {
1950            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
1951            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
1952            Effect::RefreshWindows => write!(f, "RefreshWindows"),
1953            Effect::NotifyGlobalObservers { global_type } => {
1954                write!(f, "NotifyGlobalObservers({:?})", global_type)
1955            }
1956            Effect::Defer { .. } => write!(f, "Defer(..)"),
1957            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
1958        }
1959    }
1960}
1961
1962/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1963pub(crate) struct GlobalLease<G: Global> {
1964    global: Box<dyn Any>,
1965    global_type: PhantomData<G>,
1966}
1967
1968impl<G: Global> GlobalLease<G> {
1969    fn new(global: Box<dyn Any>) -> Self {
1970        GlobalLease {
1971            global,
1972            global_type: PhantomData,
1973        }
1974    }
1975}
1976
1977impl<G: Global> Deref for GlobalLease<G> {
1978    type Target = G;
1979
1980    fn deref(&self) -> &Self::Target {
1981        self.global.downcast_ref().unwrap()
1982    }
1983}
1984
1985impl<G: Global> DerefMut for GlobalLease<G> {
1986    fn deref_mut(&mut self) -> &mut Self::Target {
1987        self.global.downcast_mut().unwrap()
1988    }
1989}
1990
1991/// Contains state associated with an active drag operation, started by dragging an element
1992/// within the window or by dragging into the app from the underlying platform.
1993pub struct AnyDrag {
1994    /// The view used to render this drag
1995    pub view: AnyView,
1996
1997    /// The value of the dragged item, to be dropped
1998    pub value: Arc<dyn Any>,
1999
2000    /// This is used to render the dragged item in the same place
2001    /// on the original element that the drag was initiated
2002    pub cursor_offset: Point<Pixels>,
2003
2004    /// The cursor style to use while dragging
2005    pub cursor_style: Option<CursorStyle>,
2006}
2007
2008/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2009/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
2010#[derive(Clone)]
2011pub struct AnyTooltip {
2012    /// The view used to display the tooltip
2013    pub view: AnyView,
2014
2015    /// The absolute position of the mouse when the tooltip was deployed.
2016    pub mouse_position: Point<Pixels>,
2017
2018    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2019    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2020    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2021    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2022}
2023
2024/// A keystroke event, and potentially the associated action
2025#[derive(Debug)]
2026pub struct KeystrokeEvent {
2027    /// The keystroke that occurred
2028    pub keystroke: Keystroke,
2029
2030    /// The action that was resolved for the keystroke, if any
2031    pub action: Option<Box<dyn Action>>,
2032
2033    /// The context stack at the time
2034    pub context_stack: Vec<KeyContext>,
2035}
2036
2037struct NullHttpClient;
2038
2039impl HttpClient for NullHttpClient {
2040    fn send(
2041        &self,
2042        _req: http_client::Request<http_client::AsyncBody>,
2043    ) -> futures::future::BoxFuture<
2044        'static,
2045        anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2046    > {
2047        async move {
2048            anyhow::bail!("No HttpClient available");
2049        }
2050        .boxed()
2051    }
2052
2053    fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2054        None
2055    }
2056
2057    fn proxy(&self) -> Option<&Url> {
2058        None
2059    }
2060
2061    fn type_name(&self) -> &'static str {
2062        type_name::<Self>()
2063    }
2064}
2065
2066/// A mutable reference to an entity owned by GPUI
2067pub struct GpuiBorrow<'a, T> {
2068    inner: Option<Lease<T>>,
2069    app: &'a mut App,
2070}
2071
2072impl<'a, T: 'static> GpuiBorrow<'a, T> {
2073    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2074        app.start_update();
2075        let lease = app.entities.lease(&inner);
2076        Self {
2077            inner: Some(lease),
2078            app,
2079        }
2080    }
2081}
2082
2083impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2084    fn borrow(&self) -> &T {
2085        self.inner.as_ref().unwrap().borrow()
2086    }
2087}
2088
2089impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2090    fn borrow_mut(&mut self) -> &mut T {
2091        self.inner.as_mut().unwrap().borrow_mut()
2092    }
2093}
2094
2095impl<'a, T> Drop for GpuiBorrow<'a, T> {
2096    fn drop(&mut self) {
2097        let lease = self.inner.take().unwrap();
2098        self.app.notify(lease.id);
2099        self.app.entities.end_lease(lease);
2100        self.app.finish_update();
2101    }
2102}
2103
2104#[cfg(test)]
2105mod test {
2106    use std::{cell::RefCell, rc::Rc};
2107
2108    use crate::{AppContext, TestAppContext};
2109
2110    #[test]
2111    fn test_gpui_borrow() {
2112        let cx = TestAppContext::single();
2113        let observation_count = Rc::new(RefCell::new(0));
2114
2115        let state = cx.update(|cx| {
2116            let state = cx.new(|_| false);
2117            cx.observe(&state, {
2118                let observation_count = observation_count.clone();
2119                move |_, _| {
2120                    let mut count = observation_count.borrow_mut();
2121                    *count += 1;
2122                }
2123            })
2124            .detach();
2125
2126            state
2127        });
2128
2129        cx.update(|cx| {
2130            // Calling this like this so that we don't clobber the borrow_mut above
2131            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2132        });
2133
2134        cx.update(|cx| {
2135            state.write(cx, false);
2136        });
2137
2138        assert_eq!(*observation_count.borrow(), 2);
2139    }
2140}