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