app.rs

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