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