app.rs

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