app.rs

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