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