app.rs

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