app.rs

   1use std::{
   2    any::{TypeId, type_name},
   3    cell::{BorrowMutError, Ref, RefCell, RefMut},
   4    marker::PhantomData,
   5    mem,
   6    ops::{Deref, DerefMut},
   7    path::{Path, PathBuf},
   8    rc::{Rc, Weak},
   9    sync::{Arc, atomic::Ordering::SeqCst},
  10    time::{Duration, Instant},
  11};
  12
  13use anyhow::{Context as _, Result, anyhow};
  14use derive_more::{Deref, DerefMut};
  15use futures::{
  16    Future, FutureExt,
  17    channel::oneshot,
  18    future::{LocalBoxFuture, Shared},
  19};
  20use itertools::Itertools;
  21use parking_lot::RwLock;
  22use slotmap::SlotMap;
  23
  24pub use async_context::*;
  25use collections::{FxHashMap, FxHashSet, HashMap, VecDeque};
  26pub use context::*;
  27pub use entity_map::*;
  28use http_client::{HttpClient, Url};
  29use smallvec::SmallVec;
  30#[cfg(any(test, feature = "test-support"))]
  31pub use test_context::*;
  32use util::{ResultExt, debug_panic};
  33
  34#[cfg(any(feature = "inspector", debug_assertions))]
  35use crate::InspectorElementRegistry;
  36use crate::{
  37    Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Asset,
  38    AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DispatchPhase, DisplayId,
  39    EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext,
  40    Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform,
  41    PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority,
  42    PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
  43    RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
  44    Subscription, SvgRenderer, Task, TextSystem, Window, WindowAppearance, WindowHandle, WindowId,
  45    WindowInvalidator,
  46    colors::{Colors, GlobalColors},
  47    current_platform, hash, init_app_menus,
  48};
  49
  50mod async_context;
  51mod context;
  52mod entity_map;
  53#[cfg(any(test, feature = "test-support"))]
  54mod test_context;
  55
  56/// The duration for which futures returned from [Context::on_app_quit] can run before the application fully quits.
  57pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
  58
  59/// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows.
  60/// Strongly consider removing after stabilization.
  61#[doc(hidden)]
  62pub struct AppCell {
  63    app: RefCell<App>,
  64}
  65
  66impl AppCell {
  67    #[doc(hidden)]
  68    #[track_caller]
  69    pub fn borrow(&self) -> AppRef<'_> {
  70        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  71            let thread_id = std::thread::current().id();
  72            eprintln!("borrowed {thread_id:?}");
  73        }
  74        AppRef(self.app.borrow())
  75    }
  76
  77    #[doc(hidden)]
  78    #[track_caller]
  79    pub fn borrow_mut(&self) -> AppRefMut<'_> {
  80        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  81            let thread_id = std::thread::current().id();
  82            eprintln!("borrowed {thread_id:?}");
  83        }
  84        AppRefMut(self.app.borrow_mut())
  85    }
  86
  87    #[doc(hidden)]
  88    #[track_caller]
  89    pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
  90        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  91            let thread_id = std::thread::current().id();
  92            eprintln!("borrowed {thread_id:?}");
  93        }
  94        Ok(AppRefMut(self.app.try_borrow_mut()?))
  95    }
  96}
  97
  98#[doc(hidden)]
  99#[derive(Deref, DerefMut)]
 100pub struct AppRef<'a>(Ref<'a, App>);
 101
 102impl Drop for AppRef<'_> {
 103    fn drop(&mut self) {
 104        if option_env!("TRACK_THREAD_BORROWS").is_some() {
 105            let thread_id = std::thread::current().id();
 106            eprintln!("dropped borrow from {thread_id:?}");
 107        }
 108    }
 109}
 110
 111#[doc(hidden)]
 112#[derive(Deref, DerefMut)]
 113pub struct AppRefMut<'a>(RefMut<'a, App>);
 114
 115impl Drop for AppRefMut<'_> {
 116    fn drop(&mut self) {
 117        if option_env!("TRACK_THREAD_BORROWS").is_some() {
 118            let thread_id = std::thread::current().id();
 119            eprintln!("dropped {thread_id:?}");
 120        }
 121    }
 122}
 123
 124/// A reference to a GPUI application, typically constructed in the `main` function of your app.
 125/// You won't interact with this type much outside of initial configuration and startup.
 126pub struct Application(Rc<AppCell>);
 127
 128/// Represents an application before it is fully launched. Once your app is
 129/// configured, you'll start the app with `App::run`.
 130impl Application {
 131    /// Builds an app with the given asset source.
 132    #[allow(clippy::new_without_default)]
 133    pub fn new() -> Self {
 134        #[cfg(any(test, feature = "test-support"))]
 135        log::info!("GPUI was compiled in test mode");
 136
 137        Self(App::new_app(
 138            current_platform(false),
 139            Arc::new(()),
 140            Arc::new(NullHttpClient),
 141        ))
 142    }
 143
 144    /// Build an app in headless mode. This prevents opening windows,
 145    /// but makes it possible to run an application in an context like
 146    /// SSH, where GUI applications are not allowed.
 147    pub fn headless() -> Self {
 148        Self(App::new_app(
 149            current_platform(true),
 150            Arc::new(()),
 151            Arc::new(NullHttpClient),
 152        ))
 153    }
 154
 155    /// Assign
 156    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
 157        let mut context_lock = self.0.borrow_mut();
 158        let asset_source = Arc::new(asset_source);
 159        context_lock.asset_source = asset_source.clone();
 160        context_lock.svg_renderer = SvgRenderer::new(asset_source);
 161        drop(context_lock);
 162        self
 163    }
 164
 165    /// Sets the HTTP client for the application.
 166    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
 167        let mut context_lock = self.0.borrow_mut();
 168        context_lock.http_client = http_client;
 169        drop(context_lock);
 170        self
 171    }
 172
 173    /// Configures when the application should automatically quit.
 174    /// By default, [`QuitMode::Default`] is used.
 175    pub fn with_quit_mode(self, mode: QuitMode) -> Self {
 176        self.0.borrow_mut().quit_mode = mode;
 177        self
 178    }
 179
 180    /// Start the application. The provided callback will be called once the
 181    /// app is fully launched.
 182    pub fn run<F>(self, on_finish_launching: F)
 183    where
 184        F: 'static + FnOnce(&mut App),
 185    {
 186        let this = self.0.clone();
 187        let platform = self.0.borrow().platform.clone();
 188        platform.run(Box::new(move || {
 189            let cx = &mut *this.borrow_mut();
 190            on_finish_launching(cx);
 191        }));
 192    }
 193
 194    /// Register a handler to be invoked when the platform instructs the application
 195    /// to open one or more URLs.
 196    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 197    where
 198        F: 'static + FnMut(Vec<String>),
 199    {
 200        self.0.borrow().platform.on_open_urls(Box::new(callback));
 201        self
 202    }
 203
 204    /// Invokes a handler when an already-running application is launched.
 205    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
 206    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 207    where
 208        F: 'static + FnMut(&mut App),
 209    {
 210        let this = Rc::downgrade(&self.0);
 211        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 212            if let Some(app) = this.upgrade() {
 213                callback(&mut app.borrow_mut());
 214            }
 215        }));
 216        self
 217    }
 218
 219    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
 220    pub fn background_executor(&self) -> BackgroundExecutor {
 221        self.0.borrow().background_executor.clone()
 222    }
 223
 224    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
 225    pub fn foreground_executor(&self) -> ForegroundExecutor {
 226        self.0.borrow().foreground_executor.clone()
 227    }
 228
 229    /// Returns a reference to the [`TextSystem`] associated with this app.
 230    pub fn text_system(&self) -> Arc<TextSystem> {
 231        self.0.borrow().text_system.clone()
 232    }
 233
 234    /// Returns the file URL of the executable with the specified name in the application bundle
 235    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 236        self.0.borrow().path_for_auxiliary_executable(name)
 237    }
 238}
 239
 240type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
 241type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
 242pub(crate) type KeystrokeObserver =
 243    Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
 244type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
 245type WindowClosedHandler = Box<dyn FnMut(&mut App)>;
 246type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
 247type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
 248
 249/// Defines when the application should automatically quit.
 250#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 251pub enum QuitMode {
 252    /// Use [`QuitMode::Explicit`] on macOS and [`QuitMode::LastWindowClosed`] on other platforms.
 253    #[default]
 254    Default,
 255    /// Quit automatically when the last window is closed.
 256    LastWindowClosed,
 257    /// Quit only when requested via [`App::quit`].
 258    Explicit,
 259}
 260
 261#[doc(hidden)]
 262#[derive(Clone, PartialEq, Eq)]
 263pub struct SystemWindowTab {
 264    pub id: WindowId,
 265    pub title: SharedString,
 266    pub handle: AnyWindowHandle,
 267    pub last_active_at: Instant,
 268}
 269
 270impl SystemWindowTab {
 271    /// Create a new instance of the window tab.
 272    pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
 273        Self {
 274            id: handle.id,
 275            title,
 276            handle,
 277            last_active_at: Instant::now(),
 278        }
 279    }
 280}
 281
 282/// A controller for managing window tabs.
 283#[derive(Default)]
 284pub struct SystemWindowTabController {
 285    visible: Option<bool>,
 286    tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
 287}
 288
 289impl Global for SystemWindowTabController {}
 290
 291impl SystemWindowTabController {
 292    /// Create a new instance of the window tab controller.
 293    pub fn new() -> Self {
 294        Self {
 295            visible: None,
 296            tab_groups: FxHashMap::default(),
 297        }
 298    }
 299
 300    /// Initialize the global window tab controller.
 301    pub fn init(cx: &mut App) {
 302        cx.set_global(SystemWindowTabController::new());
 303    }
 304
 305    /// Get all tab groups.
 306    pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
 307        &self.tab_groups
 308    }
 309
 310    /// Get the next tab group window handle.
 311    pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
 312        let controller = cx.global::<SystemWindowTabController>();
 313        let current_group = controller
 314            .tab_groups
 315            .iter()
 316            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
 317
 318        let current_group = current_group?;
 319        // TODO: `.keys()` returns arbitrary order, what does "next" mean?
 320        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
 321        let idx = group_ids.iter().position(|g| *g == current_group)?;
 322        let next_idx = (idx + 1) % group_ids.len();
 323
 324        controller
 325            .tab_groups
 326            .get(group_ids[next_idx])
 327            .and_then(|tabs| {
 328                tabs.iter()
 329                    .max_by_key(|tab| tab.last_active_at)
 330                    .or_else(|| tabs.first())
 331                    .map(|tab| &tab.handle)
 332            })
 333    }
 334
 335    /// Get the previous tab group window handle.
 336    pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
 337        let controller = cx.global::<SystemWindowTabController>();
 338        let current_group = controller
 339            .tab_groups
 340            .iter()
 341            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
 342
 343        let current_group = current_group?;
 344        // TODO: `.keys()` returns arbitrary order, what does "previous" mean?
 345        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
 346        let idx = group_ids.iter().position(|g| *g == current_group)?;
 347        let prev_idx = if idx == 0 {
 348            group_ids.len() - 1
 349        } else {
 350            idx - 1
 351        };
 352
 353        controller
 354            .tab_groups
 355            .get(group_ids[prev_idx])
 356            .and_then(|tabs| {
 357                tabs.iter()
 358                    .max_by_key(|tab| tab.last_active_at)
 359                    .or_else(|| tabs.first())
 360                    .map(|tab| &tab.handle)
 361            })
 362    }
 363
 364    /// Get all tabs in the same window.
 365    pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
 366        self.tab_groups
 367            .values()
 368            .find(|tabs| tabs.iter().any(|tab| tab.id == id))
 369    }
 370
 371    /// Initialize the visibility of the system window tab controller.
 372    pub fn init_visible(cx: &mut App, visible: bool) {
 373        let mut controller = cx.global_mut::<SystemWindowTabController>();
 374        if controller.visible.is_none() {
 375            controller.visible = Some(visible);
 376        }
 377    }
 378
 379    /// Get the visibility of the system window tab controller.
 380    pub fn is_visible(&self) -> bool {
 381        self.visible.unwrap_or(false)
 382    }
 383
 384    /// Set the visibility of the system window tab controller.
 385    pub fn set_visible(cx: &mut App, visible: bool) {
 386        let mut controller = cx.global_mut::<SystemWindowTabController>();
 387        controller.visible = Some(visible);
 388    }
 389
 390    /// Update the last active of a window.
 391    pub fn update_last_active(cx: &mut App, id: WindowId) {
 392        let mut controller = cx.global_mut::<SystemWindowTabController>();
 393        for windows in controller.tab_groups.values_mut() {
 394            for tab in windows.iter_mut() {
 395                if tab.id == id {
 396                    tab.last_active_at = Instant::now();
 397                }
 398            }
 399        }
 400    }
 401
 402    /// Update the position of a tab within its group.
 403    pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
 404        let mut controller = cx.global_mut::<SystemWindowTabController>();
 405        for (_, windows) in controller.tab_groups.iter_mut() {
 406            if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
 407                if ix < windows.len() && current_pos != ix {
 408                    let window_tab = windows.remove(current_pos);
 409                    windows.insert(ix, window_tab);
 410                }
 411                break;
 412            }
 413        }
 414    }
 415
 416    /// Update the title of a tab.
 417    pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
 418        let controller = cx.global::<SystemWindowTabController>();
 419        let tab = controller
 420            .tab_groups
 421            .values()
 422            .flat_map(|windows| windows.iter())
 423            .find(|tab| tab.id == id);
 424
 425        if tab.map_or(true, |t| t.title == title) {
 426            return;
 427        }
 428
 429        let mut controller = cx.global_mut::<SystemWindowTabController>();
 430        for windows in controller.tab_groups.values_mut() {
 431            for tab in windows.iter_mut() {
 432                if tab.id == id {
 433                    tab.title = title;
 434                    return;
 435                }
 436            }
 437        }
 438    }
 439
 440    /// Insert a tab into a tab group.
 441    pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
 442        let mut controller = cx.global_mut::<SystemWindowTabController>();
 443        let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
 444            return;
 445        };
 446
 447        let mut expected_tab_ids: Vec<_> = tabs
 448            .iter()
 449            .filter(|tab| tab.id != id)
 450            .map(|tab| tab.id)
 451            .sorted()
 452            .collect();
 453
 454        let mut tab_group_id = None;
 455        for (group_id, group_tabs) in &controller.tab_groups {
 456            let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
 457            if tab_ids == expected_tab_ids {
 458                tab_group_id = Some(*group_id);
 459                break;
 460            }
 461        }
 462
 463        if let Some(tab_group_id) = tab_group_id {
 464            if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
 465                tabs.push(tab);
 466            }
 467        } else {
 468            let new_group_id = controller.tab_groups.len();
 469            controller.tab_groups.insert(new_group_id, tabs);
 470        }
 471    }
 472
 473    /// Remove a tab from a tab group.
 474    pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
 475        let mut controller = cx.global_mut::<SystemWindowTabController>();
 476        let mut removed_tab = None;
 477
 478        controller.tab_groups.retain(|_, tabs| {
 479            if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
 480                removed_tab = Some(tabs.remove(pos));
 481            }
 482            !tabs.is_empty()
 483        });
 484
 485        removed_tab
 486    }
 487
 488    /// Move a tab to a new tab group.
 489    pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
 490        let mut removed_tab = Self::remove_tab(cx, id);
 491        let mut controller = cx.global_mut::<SystemWindowTabController>();
 492
 493        if let Some(tab) = removed_tab {
 494            let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
 495            controller.tab_groups.insert(new_group_id, vec![tab]);
 496        }
 497    }
 498
 499    /// Merge all tab groups into a single group.
 500    pub fn merge_all_windows(cx: &mut App, id: WindowId) {
 501        let mut controller = cx.global_mut::<SystemWindowTabController>();
 502        let Some(initial_tabs) = controller.tabs(id) else {
 503            return;
 504        };
 505
 506        let initial_tabs_len = initial_tabs.len();
 507        let mut all_tabs = initial_tabs.clone();
 508
 509        for (_, mut tabs) in controller.tab_groups.drain() {
 510            tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
 511            all_tabs.extend(tabs);
 512        }
 513
 514        controller.tab_groups.insert(0, all_tabs);
 515    }
 516
 517    /// Selects the next tab in the tab group in the trailing direction.
 518    pub fn select_next_tab(cx: &mut App, id: WindowId) {
 519        let mut controller = cx.global_mut::<SystemWindowTabController>();
 520        let Some(tabs) = controller.tabs(id) else {
 521            return;
 522        };
 523
 524        let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
 525        let next_index = (current_index + 1) % tabs.len();
 526
 527        let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
 528            window.activate_window();
 529        });
 530    }
 531
 532    /// Selects the previous tab in the tab group in the leading direction.
 533    pub fn select_previous_tab(cx: &mut App, id: WindowId) {
 534        let mut controller = cx.global_mut::<SystemWindowTabController>();
 535        let Some(tabs) = controller.tabs(id) else {
 536            return;
 537        };
 538
 539        let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
 540        let previous_index = if current_index == 0 {
 541            tabs.len() - 1
 542        } else {
 543            current_index - 1
 544        };
 545
 546        let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
 547            window.activate_window();
 548        });
 549    }
 550}
 551
 552pub(crate) enum GpuiMode {
 553    #[cfg(any(test, feature = "test-support"))]
 554    Test {
 555        skip_drawing: bool,
 556    },
 557    Production,
 558}
 559
 560impl GpuiMode {
 561    #[cfg(any(test, feature = "test-support"))]
 562    pub fn test() -> Self {
 563        GpuiMode::Test {
 564            skip_drawing: false,
 565        }
 566    }
 567
 568    #[inline]
 569    pub(crate) fn skip_drawing(&self) -> bool {
 570        match self {
 571            #[cfg(any(test, feature = "test-support"))]
 572            GpuiMode::Test { skip_drawing } => *skip_drawing,
 573            GpuiMode::Production => false,
 574        }
 575    }
 576}
 577
 578/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
 579/// Other [Context] derefs to this type.
 580/// You need a reference to an `App` to access the state of a [Entity].
 581pub struct App {
 582    pub(crate) this: Weak<AppCell>,
 583    pub(crate) liveness: std::sync::Arc<()>,
 584    pub(crate) platform: Rc<dyn Platform>,
 585    pub(crate) mode: GpuiMode,
 586    text_system: Arc<TextSystem>,
 587    flushing_effects: bool,
 588    pending_updates: usize,
 589    pub(crate) actions: Rc<ActionRegistry>,
 590    pub(crate) active_drag: Option<AnyDrag>,
 591    pub(crate) background_executor: BackgroundExecutor,
 592    pub(crate) foreground_executor: ForegroundExecutor,
 593    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
 594    asset_source: Arc<dyn AssetSource>,
 595    pub(crate) svg_renderer: SvgRenderer,
 596    http_client: Arc<dyn HttpClient>,
 597    pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
 598    pub(crate) entities: EntityMap,
 599    pub(crate) window_update_stack: Vec<WindowId>,
 600    pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
 601    pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
 602    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
 603    pub(crate) focus_handles: Arc<FocusMap>,
 604    pub(crate) keymap: Rc<RefCell<Keymap>>,
 605    pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
 606    pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
 607    pub(crate) global_action_listeners:
 608        FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
 609    pending_effects: VecDeque<Effect>,
 610    pub(crate) pending_notifications: FxHashSet<EntityId>,
 611    pub(crate) pending_global_notifications: FxHashSet<TypeId>,
 612    pub(crate) observers: SubscriberSet<EntityId, Handler>,
 613    // TypeId is the type of the event that the listener callback expects
 614    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
 615    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
 616    pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
 617    pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
 618    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
 619    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
 620    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
 621    pub(crate) restart_observers: SubscriberSet<(), Handler>,
 622    pub(crate) restart_path: Option<PathBuf>,
 623    pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
 624    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
 625    pub(crate) propagate_event: bool,
 626    pub(crate) prompt_builder: Option<PromptBuilder>,
 627    pub(crate) window_invalidators_by_entity:
 628        FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
 629    pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
 630    #[cfg(any(feature = "inspector", debug_assertions))]
 631    pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
 632    #[cfg(any(feature = "inspector", debug_assertions))]
 633    pub(crate) inspector_element_registry: InspectorElementRegistry,
 634    #[cfg(any(test, feature = "test-support", debug_assertions))]
 635    pub(crate) name: Option<&'static str>,
 636    quit_mode: QuitMode,
 637    quitting: bool,
 638}
 639
 640impl App {
 641    #[allow(clippy::new_ret_no_self)]
 642    pub(crate) fn new_app(
 643        platform: Rc<dyn Platform>,
 644        asset_source: Arc<dyn AssetSource>,
 645        http_client: Arc<dyn HttpClient>,
 646    ) -> Rc<AppCell> {
 647        let executor = platform.background_executor();
 648        let foreground_executor = platform.foreground_executor();
 649        assert!(
 650            executor.is_main_thread(),
 651            "must construct App on main thread"
 652        );
 653
 654        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 655        let entities = EntityMap::new();
 656        let keyboard_layout = platform.keyboard_layout();
 657        let keyboard_mapper = platform.keyboard_mapper();
 658
 659        let app = Rc::new_cyclic(|this| AppCell {
 660            app: RefCell::new(App {
 661                this: this.clone(),
 662                liveness: std::sync::Arc::new(()),
 663                platform: platform.clone(),
 664                text_system,
 665                mode: GpuiMode::Production,
 666                actions: Rc::new(ActionRegistry::default()),
 667                flushing_effects: false,
 668                pending_updates: 0,
 669                active_drag: None,
 670                background_executor: executor,
 671                foreground_executor,
 672                svg_renderer: SvgRenderer::new(asset_source.clone()),
 673                loading_assets: Default::default(),
 674                asset_source,
 675                http_client,
 676                globals_by_type: FxHashMap::default(),
 677                entities,
 678                new_entity_observers: SubscriberSet::new(),
 679                windows: SlotMap::with_key(),
 680                window_update_stack: Vec::new(),
 681                window_handles: FxHashMap::default(),
 682                focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 683                keymap: Rc::new(RefCell::new(Keymap::default())),
 684                keyboard_layout,
 685                keyboard_mapper,
 686                global_action_listeners: FxHashMap::default(),
 687                pending_effects: VecDeque::new(),
 688                pending_notifications: FxHashSet::default(),
 689                pending_global_notifications: FxHashSet::default(),
 690                observers: SubscriberSet::new(),
 691                tracked_entities: FxHashMap::default(),
 692                window_invalidators_by_entity: FxHashMap::default(),
 693                event_listeners: SubscriberSet::new(),
 694                release_listeners: SubscriberSet::new(),
 695                keystroke_observers: SubscriberSet::new(),
 696                keystroke_interceptors: SubscriberSet::new(),
 697                keyboard_layout_observers: SubscriberSet::new(),
 698                global_observers: SubscriberSet::new(),
 699                quit_observers: SubscriberSet::new(),
 700                restart_observers: SubscriberSet::new(),
 701                restart_path: None,
 702                window_closed_observers: SubscriberSet::new(),
 703                layout_id_buffer: Default::default(),
 704                propagate_event: true,
 705                prompt_builder: Some(PromptBuilder::Default),
 706                #[cfg(any(feature = "inspector", debug_assertions))]
 707                inspector_renderer: None,
 708                #[cfg(any(feature = "inspector", debug_assertions))]
 709                inspector_element_registry: InspectorElementRegistry::default(),
 710                quit_mode: QuitMode::default(),
 711                quitting: false,
 712
 713                #[cfg(any(test, feature = "test-support", debug_assertions))]
 714                name: None,
 715            }),
 716        });
 717
 718        init_app_menus(platform.as_ref(), &app.borrow());
 719        SystemWindowTabController::init(&mut app.borrow_mut());
 720
 721        platform.on_keyboard_layout_change(Box::new({
 722            let app = Rc::downgrade(&app);
 723            move || {
 724                if let Some(app) = app.upgrade() {
 725                    let cx = &mut app.borrow_mut();
 726                    cx.keyboard_layout = cx.platform.keyboard_layout();
 727                    cx.keyboard_mapper = cx.platform.keyboard_mapper();
 728                    cx.keyboard_layout_observers
 729                        .clone()
 730                        .retain(&(), move |callback| (callback)(cx));
 731                }
 732            }
 733        }));
 734
 735        platform.on_quit(Box::new({
 736            let cx = app.clone();
 737            move || {
 738                cx.borrow_mut().shutdown();
 739            }
 740        }));
 741
 742        app
 743    }
 744
 745    /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`]
 746    /// will be given 100ms to complete before exiting.
 747    pub fn shutdown(&mut self) {
 748        let mut futures = Vec::new();
 749
 750        for observer in self.quit_observers.remove(&()) {
 751            futures.push(observer(self));
 752        }
 753
 754        self.windows.clear();
 755        self.window_handles.clear();
 756        self.flush_effects();
 757        self.quitting = true;
 758
 759        let futures = futures::future::join_all(futures);
 760        if self
 761            .background_executor
 762            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
 763            .is_err()
 764        {
 765            log::error!("timed out waiting on app_will_quit");
 766        }
 767
 768        self.quitting = false;
 769    }
 770
 771    /// Get the id of the current keyboard layout
 772    pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
 773        self.keyboard_layout.as_ref()
 774    }
 775
 776    /// Get the current keyboard mapper.
 777    pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
 778        &self.keyboard_mapper
 779    }
 780
 781    /// Invokes a handler when the current keyboard layout changes
 782    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
 783    where
 784        F: 'static + FnMut(&mut App),
 785    {
 786        let (subscription, activate) = self.keyboard_layout_observers.insert(
 787            (),
 788            Box::new(move |cx| {
 789                callback(cx);
 790                true
 791            }),
 792        );
 793        activate();
 794        subscription
 795    }
 796
 797    /// Gracefully quit the application via the platform's standard routine.
 798    pub fn quit(&self) {
 799        self.platform.quit();
 800    }
 801
 802    /// Schedules all windows in the application to be redrawn. This can be called
 803    /// multiple times in an update cycle and still result in a single redraw.
 804    pub fn refresh_windows(&mut self) {
 805        self.pending_effects.push_back(Effect::RefreshWindows);
 806    }
 807
 808    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
 809        self.start_update();
 810        let result = update(self);
 811        self.finish_update();
 812        result
 813    }
 814
 815    pub(crate) fn start_update(&mut self) {
 816        self.pending_updates += 1;
 817    }
 818
 819    pub(crate) fn finish_update(&mut self) {
 820        if !self.flushing_effects && self.pending_updates == 1 {
 821            self.flushing_effects = true;
 822            self.flush_effects();
 823            self.flushing_effects = false;
 824        }
 825        self.pending_updates -= 1;
 826    }
 827
 828    /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
 829    pub fn observe<W>(
 830        &mut self,
 831        entity: &Entity<W>,
 832        mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
 833    ) -> Subscription
 834    where
 835        W: 'static,
 836    {
 837        self.observe_internal(entity, move |e, cx| {
 838            on_notify(e, cx);
 839            true
 840        })
 841    }
 842
 843    pub(crate) fn detect_accessed_entities<R>(
 844        &mut self,
 845        callback: impl FnOnce(&mut App) -> R,
 846    ) -> (R, FxHashSet<EntityId>) {
 847        let accessed_entities_start = self.entities.accessed_entities.borrow().clone();
 848        let result = callback(self);
 849        let accessed_entities_end = self.entities.accessed_entities.borrow().clone();
 850        let entities_accessed_in_callback = accessed_entities_end
 851            .difference(&accessed_entities_start)
 852            .copied()
 853            .collect::<FxHashSet<EntityId>>();
 854        (result, entities_accessed_in_callback)
 855    }
 856
 857    pub(crate) fn record_entities_accessed(
 858        &mut self,
 859        window_handle: AnyWindowHandle,
 860        invalidator: WindowInvalidator,
 861        entities: &FxHashSet<EntityId>,
 862    ) {
 863        let mut tracked_entities =
 864            std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
 865        for entity in tracked_entities.iter() {
 866            self.window_invalidators_by_entity
 867                .entry(*entity)
 868                .and_modify(|windows| {
 869                    windows.remove(&window_handle.id);
 870                });
 871        }
 872        for entity in entities.iter() {
 873            self.window_invalidators_by_entity
 874                .entry(*entity)
 875                .or_default()
 876                .insert(window_handle.id, invalidator.clone());
 877        }
 878        tracked_entities.clear();
 879        tracked_entities.extend(entities.iter().copied());
 880        self.tracked_entities
 881            .insert(window_handle.id, tracked_entities);
 882    }
 883
 884    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
 885        let (subscription, activate) = self.observers.insert(key, value);
 886        self.defer(move |_| activate());
 887        subscription
 888    }
 889
 890    pub(crate) fn observe_internal<W>(
 891        &mut self,
 892        entity: &Entity<W>,
 893        mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
 894    ) -> Subscription
 895    where
 896        W: 'static,
 897    {
 898        let entity_id = entity.entity_id();
 899        let handle = entity.downgrade();
 900        self.new_observer(
 901            entity_id,
 902            Box::new(move |cx| {
 903                if let Some(entity) = handle.upgrade() {
 904                    on_notify(entity, cx)
 905                } else {
 906                    false
 907                }
 908            }),
 909        )
 910    }
 911
 912    /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type.
 913    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
 914    pub fn subscribe<T, Event>(
 915        &mut self,
 916        entity: &Entity<T>,
 917        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
 918    ) -> Subscription
 919    where
 920        T: 'static + EventEmitter<Event>,
 921        Event: 'static,
 922    {
 923        self.subscribe_internal(entity, move |entity, event, cx| {
 924            on_event(entity, event, cx);
 925            true
 926        })
 927    }
 928
 929    pub(crate) fn new_subscription(
 930        &mut self,
 931        key: EntityId,
 932        value: (TypeId, Listener),
 933    ) -> Subscription {
 934        let (subscription, activate) = self.event_listeners.insert(key, value);
 935        self.defer(move |_| activate());
 936        subscription
 937    }
 938    pub(crate) fn subscribe_internal<T, Evt>(
 939        &mut self,
 940        entity: &Entity<T>,
 941        mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
 942    ) -> Subscription
 943    where
 944        T: 'static + EventEmitter<Evt>,
 945        Evt: 'static,
 946    {
 947        let entity_id = entity.entity_id();
 948        let handle = entity.downgrade();
 949        self.new_subscription(
 950            entity_id,
 951            (
 952                TypeId::of::<Evt>(),
 953                Box::new(move |event, cx| {
 954                    let event: &Evt = event.downcast_ref().expect("invalid event type");
 955                    if let Some(entity) = handle.upgrade() {
 956                        on_event(entity, event, cx)
 957                    } else {
 958                        false
 959                    }
 960                }),
 961            ),
 962        )
 963    }
 964
 965    /// Returns handles to all open windows in the application.
 966    /// Each handle could be downcast to a handle typed for the root view of that window.
 967    /// To find all windows of a given type, you could filter on
 968    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 969        self.windows
 970            .keys()
 971            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
 972            .collect()
 973    }
 974
 975    /// Returns the window handles ordered by their appearance on screen, front to back.
 976    ///
 977    /// The first window in the returned list is the active/topmost window of the application.
 978    ///
 979    /// This method returns None if the platform doesn't implement the method yet.
 980    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 981        self.platform.window_stack()
 982    }
 983
 984    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
 985    pub fn active_window(&self) -> Option<AnyWindowHandle> {
 986        self.platform.active_window()
 987    }
 988
 989    /// Opens a new window with the given option and the root view returned by the given function.
 990    /// The function is invoked with a `Window`, which can be used to interact with window-specific
 991    /// functionality.
 992    pub fn open_window<V: 'static + Render>(
 993        &mut self,
 994        options: crate::WindowOptions,
 995        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
 996    ) -> anyhow::Result<WindowHandle<V>> {
 997        self.update(|cx| {
 998            let id = cx.windows.insert(None);
 999            let handle = WindowHandle::new(id);
1000            match Window::new(handle.into(), options, cx) {
1001                Ok(mut window) => {
1002                    cx.window_update_stack.push(id);
1003                    let root_view = build_root_view(&mut window, cx);
1004                    cx.window_update_stack.pop();
1005                    window.root.replace(root_view.into());
1006                    window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1007
1008                    // allow a window to draw at least once before returning
1009                    // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
1010                    // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
1011                    // where DispatchTree::root_node_id asserts on empty nodes
1012                    let clear = window.draw(cx);
1013                    clear.clear();
1014
1015                    cx.window_handles.insert(id, window.handle);
1016                    cx.windows.get_mut(id).unwrap().replace(Box::new(window));
1017                    Ok(handle)
1018                }
1019                Err(e) => {
1020                    cx.windows.remove(id);
1021                    Err(e)
1022                }
1023            }
1024        })
1025    }
1026
1027    /// Instructs the platform to activate the application by bringing it to the foreground.
1028    pub fn activate(&self, ignoring_other_apps: bool) {
1029        self.platform.activate(ignoring_other_apps);
1030    }
1031
1032    /// Hide the application at the platform level.
1033    pub fn hide(&self) {
1034        self.platform.hide();
1035    }
1036
1037    /// Hide other applications at the platform level.
1038    pub fn hide_other_apps(&self) {
1039        self.platform.hide_other_apps();
1040    }
1041
1042    /// Unhide other applications at the platform level.
1043    pub fn unhide_other_apps(&self) {
1044        self.platform.unhide_other_apps();
1045    }
1046
1047    /// Returns the list of currently active displays.
1048    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1049        self.platform.displays()
1050    }
1051
1052    /// Returns the primary display that will be used for new windows.
1053    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1054        self.platform.primary_display()
1055    }
1056
1057    /// Returns whether `screen_capture_sources` may work.
1058    pub fn is_screen_capture_supported(&self) -> bool {
1059        self.platform.is_screen_capture_supported()
1060    }
1061
1062    /// Returns a list of available screen capture sources.
1063    pub fn screen_capture_sources(
1064        &self,
1065    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1066        self.platform.screen_capture_sources()
1067    }
1068
1069    /// Returns the display with the given ID, if one exists.
1070    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1071        self.displays()
1072            .iter()
1073            .find(|display| display.id() == id)
1074            .cloned()
1075    }
1076
1077    /// Returns the appearance of the application's windows.
1078    pub fn window_appearance(&self) -> WindowAppearance {
1079        self.platform.window_appearance()
1080    }
1081
1082    /// Reads data from the platform clipboard.
1083    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1084        self.platform.read_from_clipboard()
1085    }
1086
1087    /// Writes data to the platform clipboard.
1088    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1089        self.platform.write_to_clipboard(item)
1090    }
1091
1092    /// Reads data from the primary selection buffer.
1093    /// Only available on Linux.
1094    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1095    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1096        self.platform.read_from_primary()
1097    }
1098
1099    /// Writes data to the primary selection buffer.
1100    /// Only available on Linux.
1101    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1102    pub fn write_to_primary(&self, item: ClipboardItem) {
1103        self.platform.write_to_primary(item)
1104    }
1105
1106    /// Reads data from macOS's "Find" pasteboard.
1107    ///
1108    /// Used to share the current search string between apps.
1109    ///
1110    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1111    #[cfg(target_os = "macos")]
1112    pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1113        self.platform.read_from_find_pasteboard()
1114    }
1115
1116    /// Writes data to macOS's "Find" pasteboard.
1117    ///
1118    /// Used to share the current search string between apps.
1119    ///
1120    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1121    #[cfg(target_os = "macos")]
1122    pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1123        self.platform.write_to_find_pasteboard(item)
1124    }
1125
1126    /// Writes credentials to the platform keychain.
1127    pub fn write_credentials(
1128        &self,
1129        url: &str,
1130        username: &str,
1131        password: &[u8],
1132    ) -> Task<Result<()>> {
1133        self.platform.write_credentials(url, username, password)
1134    }
1135
1136    /// Reads credentials from the platform keychain.
1137    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1138        self.platform.read_credentials(url)
1139    }
1140
1141    /// Deletes credentials from the platform keychain.
1142    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1143        self.platform.delete_credentials(url)
1144    }
1145
1146    /// Directs the platform's default browser to open the given URL.
1147    pub fn open_url(&self, url: &str) {
1148        self.platform.open_url(url);
1149    }
1150
1151    /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be
1152    /// opened by the current app.
1153    ///
1154    /// On some platforms (e.g. macOS) you may be able to register URL schemes
1155    /// as part of app distribution, but this method exists to let you register
1156    /// schemes at runtime.
1157    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1158        self.platform.register_url_scheme(scheme)
1159    }
1160
1161    /// Returns the full pathname of the current app bundle.
1162    ///
1163    /// Returns an error if the app is not being run from a bundle.
1164    pub fn app_path(&self) -> Result<PathBuf> {
1165        self.platform.app_path()
1166    }
1167
1168    /// On Linux, returns the name of the compositor in use.
1169    ///
1170    /// Returns an empty string on other platforms.
1171    pub fn compositor_name(&self) -> &'static str {
1172        self.platform.compositor_name()
1173    }
1174
1175    /// Returns the file URL of the executable with the specified name in the application bundle
1176    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1177        self.platform.path_for_auxiliary_executable(name)
1178    }
1179
1180    /// Displays a platform modal for selecting paths.
1181    ///
1182    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
1183    /// If cancelled, a `None` will be relayed instead.
1184    /// May return an error on Linux if the file picker couldn't be opened.
1185    pub fn prompt_for_paths(
1186        &self,
1187        options: PathPromptOptions,
1188    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1189        self.platform.prompt_for_paths(options)
1190    }
1191
1192    /// Displays a platform modal for selecting a new path where a file can be saved.
1193    ///
1194    /// The provided directory will be used to set the initial location.
1195    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
1196    /// If cancelled, a `None` will be relayed instead.
1197    /// May return an error on Linux if the file picker couldn't be opened.
1198    pub fn prompt_for_new_path(
1199        &self,
1200        directory: &Path,
1201        suggested_name: Option<&str>,
1202    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1203        self.platform.prompt_for_new_path(directory, suggested_name)
1204    }
1205
1206    /// Reveals the specified path at the platform level, such as in Finder on macOS.
1207    pub fn reveal_path(&self, path: &Path) {
1208        self.platform.reveal_path(path)
1209    }
1210
1211    /// Opens the specified path with the system's default application.
1212    pub fn open_with_system(&self, path: &Path) {
1213        self.platform.open_with_system(path)
1214    }
1215
1216    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
1217    pub fn should_auto_hide_scrollbars(&self) -> bool {
1218        self.platform.should_auto_hide_scrollbars()
1219    }
1220
1221    /// Restarts the application.
1222    pub fn restart(&mut self) {
1223        self.restart_observers
1224            .clone()
1225            .retain(&(), |observer| observer(self));
1226        self.platform.restart(self.restart_path.take())
1227    }
1228
1229    /// Sets the path to use when restarting the application.
1230    pub fn set_restart_path(&mut self, path: PathBuf) {
1231        self.restart_path = Some(path);
1232    }
1233
1234    /// Returns the HTTP client for the application.
1235    pub fn http_client(&self) -> Arc<dyn HttpClient> {
1236        self.http_client.clone()
1237    }
1238
1239    /// Sets the HTTP client for the application.
1240    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1241        self.http_client = new_client;
1242    }
1243
1244    /// Configures when the application should automatically quit.
1245    /// By default, [`QuitMode::Default`] is used.
1246    pub fn set_quit_mode(&mut self, mode: QuitMode) {
1247        self.quit_mode = mode;
1248    }
1249
1250    /// Returns the SVG renderer used by the application.
1251    pub fn svg_renderer(&self) -> SvgRenderer {
1252        self.svg_renderer.clone()
1253    }
1254
1255    pub(crate) fn push_effect(&mut self, effect: Effect) {
1256        match &effect {
1257            Effect::Notify { emitter } => {
1258                if !self.pending_notifications.insert(*emitter) {
1259                    return;
1260                }
1261            }
1262            Effect::NotifyGlobalObservers { global_type } => {
1263                if !self.pending_global_notifications.insert(*global_type) {
1264                    return;
1265                }
1266            }
1267            _ => {}
1268        };
1269
1270        self.pending_effects.push_back(effect);
1271    }
1272
1273    /// Called at the end of [`App::update`] to complete any side effects
1274    /// such as notifying observers, emitting events, etc. Effects can themselves
1275    /// cause effects, so we continue looping until all effects are processed.
1276    fn flush_effects(&mut self) {
1277        loop {
1278            self.release_dropped_entities();
1279            self.release_dropped_focus_handles();
1280            if let Some(effect) = self.pending_effects.pop_front() {
1281                match effect {
1282                    Effect::Notify { emitter } => {
1283                        self.apply_notify_effect(emitter);
1284                    }
1285
1286                    Effect::Emit {
1287                        emitter,
1288                        event_type,
1289                        event,
1290                    } => self.apply_emit_effect(emitter, event_type, event),
1291
1292                    Effect::RefreshWindows => {
1293                        self.apply_refresh_effect();
1294                    }
1295
1296                    Effect::NotifyGlobalObservers { global_type } => {
1297                        self.apply_notify_global_observers_effect(global_type);
1298                    }
1299
1300                    Effect::Defer { callback } => {
1301                        self.apply_defer_effect(callback);
1302                    }
1303                    Effect::EntityCreated {
1304                        entity,
1305                        tid,
1306                        window,
1307                    } => {
1308                        self.apply_entity_created_effect(entity, tid, window);
1309                    }
1310                }
1311            } else {
1312                #[cfg(any(test, feature = "test-support"))]
1313                for window in self
1314                    .windows
1315                    .values()
1316                    .filter_map(|window| {
1317                        let window = window.as_deref()?;
1318                        window.invalidator.is_dirty().then_some(window.handle)
1319                    })
1320                    .collect::<Vec<_>>()
1321                {
1322                    self.update_window(window, |_, window, cx| window.draw(cx).clear())
1323                        .unwrap();
1324                }
1325
1326                if self.pending_effects.is_empty() {
1327                    break;
1328                }
1329            }
1330        }
1331    }
1332
1333    /// Repeatedly called during `flush_effects` to release any entities whose
1334    /// reference count has become zero. We invoke any release observers before dropping
1335    /// each entity.
1336    fn release_dropped_entities(&mut self) {
1337        loop {
1338            let dropped = self.entities.take_dropped();
1339            if dropped.is_empty() {
1340                break;
1341            }
1342
1343            for (entity_id, mut entity) in dropped {
1344                self.observers.remove(&entity_id);
1345                self.event_listeners.remove(&entity_id);
1346                for release_callback in self.release_listeners.remove(&entity_id) {
1347                    release_callback(entity.as_mut(), self);
1348                }
1349            }
1350        }
1351    }
1352
1353    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
1354    fn release_dropped_focus_handles(&mut self) {
1355        self.focus_handles
1356            .clone()
1357            .write()
1358            .retain(|handle_id, focus| {
1359                if focus.ref_count.load(SeqCst) == 0 {
1360                    for window_handle in self.windows() {
1361                        window_handle
1362                            .update(self, |_, window, _| {
1363                                if window.focus == Some(handle_id) {
1364                                    window.blur();
1365                                }
1366                            })
1367                            .unwrap();
1368                    }
1369                    false
1370                } else {
1371                    true
1372                }
1373            });
1374    }
1375
1376    fn apply_notify_effect(&mut self, emitter: EntityId) {
1377        self.pending_notifications.remove(&emitter);
1378
1379        self.observers
1380            .clone()
1381            .retain(&emitter, |handler| handler(self));
1382    }
1383
1384    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
1385        self.event_listeners
1386            .clone()
1387            .retain(&emitter, |(stored_type, handler)| {
1388                if *stored_type == event_type {
1389                    handler(event.as_ref(), self)
1390                } else {
1391                    true
1392                }
1393            });
1394    }
1395
1396    fn apply_refresh_effect(&mut self) {
1397        for window in self.windows.values_mut() {
1398            if let Some(window) = window.as_deref_mut() {
1399                window.refreshing = true;
1400                window.invalidator.set_dirty(true);
1401            }
1402        }
1403    }
1404
1405    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1406        self.pending_global_notifications.remove(&type_id);
1407        self.global_observers
1408            .clone()
1409            .retain(&type_id, |observer| observer(self));
1410    }
1411
1412    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1413        callback(self);
1414    }
1415
1416    fn apply_entity_created_effect(
1417        &mut self,
1418        entity: AnyEntity,
1419        tid: TypeId,
1420        window: Option<WindowId>,
1421    ) {
1422        self.new_entity_observers.clone().retain(&tid, |observer| {
1423            if let Some(id) = window {
1424                self.update_window_id(id, {
1425                    let entity = entity.clone();
1426                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
1427                })
1428                .expect("All windows should be off the stack when flushing effects");
1429            } else {
1430                (observer)(entity.clone(), &mut None, self)
1431            }
1432            true
1433        });
1434    }
1435
1436    fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1437    where
1438        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1439    {
1440        self.update(|cx| {
1441            let mut window = cx.windows.get_mut(id)?.take()?;
1442
1443            let root_view = window.root.clone().unwrap();
1444
1445            cx.window_update_stack.push(window.handle.id);
1446            let result = update(root_view, &mut window, cx);
1447            cx.window_update_stack.pop();
1448
1449            if window.removed {
1450                cx.window_handles.remove(&id);
1451                cx.windows.remove(id);
1452
1453                cx.window_closed_observers.clone().retain(&(), |callback| {
1454                    callback(cx);
1455                    true
1456                });
1457
1458                let quit_on_empty = match cx.quit_mode {
1459                    QuitMode::Explicit => false,
1460                    QuitMode::LastWindowClosed => true,
1461                    QuitMode::Default => cfg!(not(target_os = "macos")),
1462                };
1463
1464                if quit_on_empty && cx.windows.is_empty() {
1465                    cx.quit();
1466                }
1467            } else {
1468                cx.windows.get_mut(id)?.replace(window);
1469            }
1470
1471            Some(result)
1472        })
1473        .context("window not found")
1474    }
1475
1476    /// Creates an `AsyncApp`, which can be cloned and has a static lifetime
1477    /// so it can be held across `await` points.
1478    pub fn to_async(&self) -> AsyncApp {
1479        AsyncApp {
1480            app: self.this.clone(),
1481            liveness_token: std::sync::Arc::downgrade(&self.liveness),
1482            background_executor: self.background_executor.clone(),
1483            foreground_executor: self.foreground_executor.clone(),
1484        }
1485    }
1486
1487    /// Obtains a reference to the executor, which can be used to spawn futures.
1488    pub fn background_executor(&self) -> &BackgroundExecutor {
1489        &self.background_executor
1490    }
1491
1492    /// Obtains a reference to the executor, which can be used to spawn futures.
1493    pub fn foreground_executor(&self) -> &ForegroundExecutor {
1494        if self.quitting {
1495            panic!("Can't spawn on main thread after on_app_quit")
1496        };
1497        &self.foreground_executor
1498    }
1499
1500    /// Spawns the future returned by the given function on the main thread. The closure will be invoked
1501    /// with [AsyncApp], which allows the application state to be accessed across await points.
1502    #[track_caller]
1503    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
1504    where
1505        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1506        R: 'static,
1507    {
1508        if self.quitting {
1509            debug_panic!("Can't spawn on main thread after on_app_quit")
1510        };
1511
1512        let mut cx = self.to_async();
1513
1514        self.foreground_executor
1515            .spawn(async move { f(&mut cx).await })
1516    }
1517
1518    /// Spawns the future returned by the given function on the main thread with
1519    /// the given priority. The closure will be invoked with [AsyncApp], which
1520    /// allows the application state to be accessed across await points.
1521    pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
1522    where
1523        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
1524        R: 'static,
1525    {
1526        if self.quitting {
1527            debug_panic!("Can't spawn on main thread after on_app_quit")
1528        };
1529
1530        let mut cx = self.to_async();
1531
1532        self.foreground_executor
1533            .spawn_with_priority(priority, async move { f(&mut cx).await })
1534    }
1535
1536    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1537    /// that are currently on the stack to be returned to the app.
1538    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
1539        self.push_effect(Effect::Defer {
1540            callback: Box::new(f),
1541        });
1542    }
1543
1544    /// Accessor for the application's asset source, which is provided when constructing the `App`.
1545    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
1546        &self.asset_source
1547    }
1548
1549    /// Accessor for the text system.
1550    pub fn text_system(&self) -> &Arc<TextSystem> {
1551        &self.text_system
1552    }
1553
1554    /// Check whether a global of the given type has been assigned.
1555    pub fn has_global<G: Global>(&self) -> bool {
1556        self.globals_by_type.contains_key(&TypeId::of::<G>())
1557    }
1558
1559    /// Access the global of the given type. Panics if a global for that type has not been assigned.
1560    #[track_caller]
1561    pub fn global<G: Global>(&self) -> &G {
1562        self.globals_by_type
1563            .get(&TypeId::of::<G>())
1564            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1565            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1566            .unwrap()
1567    }
1568
1569    /// Access the global of the given type if a value has been assigned.
1570    pub fn try_global<G: Global>(&self) -> Option<&G> {
1571        self.globals_by_type
1572            .get(&TypeId::of::<G>())
1573            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1574    }
1575
1576    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1577    #[track_caller]
1578    pub fn global_mut<G: Global>(&mut self) -> &mut G {
1579        let global_type = TypeId::of::<G>();
1580        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1581        self.globals_by_type
1582            .get_mut(&global_type)
1583            .and_then(|any_state| any_state.downcast_mut::<G>())
1584            .with_context(|| format!("no state of type {} exists", type_name::<G>()))
1585            .unwrap()
1586    }
1587
1588    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1589    /// yet been assigned.
1590    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1591        let global_type = TypeId::of::<G>();
1592        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1593        self.globals_by_type
1594            .entry(global_type)
1595            .or_insert_with(|| Box::<G>::default())
1596            .downcast_mut::<G>()
1597            .unwrap()
1598    }
1599
1600    /// Sets the value of the global of the given type.
1601    pub fn set_global<G: Global>(&mut self, global: G) {
1602        let global_type = TypeId::of::<G>();
1603        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1604        self.globals_by_type.insert(global_type, Box::new(global));
1605    }
1606
1607    /// Clear all stored globals. Does not notify global observers.
1608    #[cfg(any(test, feature = "test-support"))]
1609    pub fn clear_globals(&mut self) {
1610        self.globals_by_type.drain();
1611    }
1612
1613    /// Remove the global of the given type from the app context. Does not notify global observers.
1614    pub fn remove_global<G: Global>(&mut self) -> G {
1615        let global_type = TypeId::of::<G>();
1616        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1617        *self
1618            .globals_by_type
1619            .remove(&global_type)
1620            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
1621            .downcast()
1622            .unwrap()
1623    }
1624
1625    /// Register a callback to be invoked when a global of the given type is updated.
1626    pub fn observe_global<G: Global>(
1627        &mut self,
1628        mut f: impl FnMut(&mut Self) + 'static,
1629    ) -> Subscription {
1630        let (subscription, activate) = self.global_observers.insert(
1631            TypeId::of::<G>(),
1632            Box::new(move |cx| {
1633                f(cx);
1634                true
1635            }),
1636        );
1637        self.defer(move |_| activate());
1638        subscription
1639    }
1640
1641    /// Move the global of the given type to the stack.
1642    #[track_caller]
1643    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1644        GlobalLease::new(
1645            self.globals_by_type
1646                .remove(&TypeId::of::<G>())
1647                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1648                .unwrap(),
1649        )
1650    }
1651
1652    /// Restore the global of the given type after it is moved to the stack.
1653    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1654        let global_type = TypeId::of::<G>();
1655
1656        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1657        self.globals_by_type.insert(global_type, lease.global);
1658    }
1659
1660    pub(crate) fn new_entity_observer(
1661        &self,
1662        key: TypeId,
1663        value: NewEntityListener,
1664    ) -> Subscription {
1665        let (subscription, activate) = self.new_entity_observers.insert(key, value);
1666        activate();
1667        subscription
1668    }
1669
1670    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1671    /// The function will be passed a mutable reference to the view along with an appropriate context.
1672    pub fn observe_new<T: 'static>(
1673        &self,
1674        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1675    ) -> Subscription {
1676        self.new_entity_observer(
1677            TypeId::of::<T>(),
1678            Box::new(
1679                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1680                    any_entity
1681                        .downcast::<T>()
1682                        .unwrap()
1683                        .update(cx, |entity_state, cx| {
1684                            on_new(entity_state, window.as_deref_mut(), cx)
1685                        })
1686                },
1687            ),
1688        )
1689    }
1690
1691    /// Observe the release of a entity. The callback is invoked after the entity
1692    /// has no more strong references but before it has been dropped.
1693    pub fn observe_release<T>(
1694        &self,
1695        handle: &Entity<T>,
1696        on_release: impl FnOnce(&mut T, &mut App) + 'static,
1697    ) -> Subscription
1698    where
1699        T: 'static,
1700    {
1701        let (subscription, activate) = self.release_listeners.insert(
1702            handle.entity_id(),
1703            Box::new(move |entity, cx| {
1704                let entity = entity.downcast_mut().expect("invalid entity type");
1705                on_release(entity, cx)
1706            }),
1707        );
1708        activate();
1709        subscription
1710    }
1711
1712    /// Observe the release of a entity. The callback is invoked after the entity
1713    /// has no more strong references but before it has been dropped.
1714    pub fn observe_release_in<T>(
1715        &self,
1716        handle: &Entity<T>,
1717        window: &Window,
1718        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1719    ) -> Subscription
1720    where
1721        T: 'static,
1722    {
1723        let window_handle = window.handle;
1724        self.observe_release(handle, move |entity, cx| {
1725            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1726        })
1727    }
1728
1729    /// Register a callback to be invoked when a keystroke is received by the application
1730    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1731    /// and that this API will not be invoked if the event's propagation is stopped.
1732    pub fn observe_keystrokes(
1733        &mut self,
1734        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1735    ) -> Subscription {
1736        fn inner(
1737            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1738            handler: KeystrokeObserver,
1739        ) -> Subscription {
1740            let (subscription, activate) = keystroke_observers.insert((), handler);
1741            activate();
1742            subscription
1743        }
1744
1745        inner(
1746            &self.keystroke_observers,
1747            Box::new(move |event, window, cx| {
1748                f(event, window, cx);
1749                true
1750            }),
1751        )
1752    }
1753
1754    /// Register a callback to be invoked when a keystroke is received by the application
1755    /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1756    /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1757    /// within interceptors will prevent action dispatch
1758    pub fn intercept_keystrokes(
1759        &mut self,
1760        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1761    ) -> Subscription {
1762        fn inner(
1763            keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1764            handler: KeystrokeObserver,
1765        ) -> Subscription {
1766            let (subscription, activate) = keystroke_interceptors.insert((), handler);
1767            activate();
1768            subscription
1769        }
1770
1771        inner(
1772            &self.keystroke_interceptors,
1773            Box::new(move |event, window, cx| {
1774                f(event, window, cx);
1775                true
1776            }),
1777        )
1778    }
1779
1780    /// Register key bindings.
1781    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1782        self.keymap.borrow_mut().add_bindings(bindings);
1783        self.pending_effects.push_back(Effect::RefreshWindows);
1784    }
1785
1786    /// Clear all key bindings in the app.
1787    pub fn clear_key_bindings(&mut self) {
1788        self.keymap.borrow_mut().clear();
1789        self.pending_effects.push_back(Effect::RefreshWindows);
1790    }
1791
1792    /// Get all key bindings in the app.
1793    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1794        self.keymap.clone()
1795    }
1796
1797    /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1798    /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1799    /// handlers or if they called `cx.propagate()`.
1800    pub fn on_action<A: Action>(
1801        &mut self,
1802        listener: impl Fn(&A, &mut Self) + 'static,
1803    ) -> &mut Self {
1804        self.global_action_listeners
1805            .entry(TypeId::of::<A>())
1806            .or_default()
1807            .push(Rc::new(move |action, phase, cx| {
1808                if phase == DispatchPhase::Bubble {
1809                    let action = action.downcast_ref().unwrap();
1810                    listener(action, cx)
1811                }
1812            }));
1813        self
1814    }
1815
1816    /// Event handlers propagate events by default. Call this method to stop dispatching to
1817    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1818    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1819    /// calling this method before effects are flushed.
1820    pub fn stop_propagation(&mut self) {
1821        self.propagate_event = false;
1822    }
1823
1824    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1825    /// dispatching to action handlers higher in the element tree. This is the opposite of
1826    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1827    /// this method before effects are flushed.
1828    pub fn propagate(&mut self) {
1829        self.propagate_event = true;
1830    }
1831
1832    /// Build an action from some arbitrary data, typically a keymap entry.
1833    pub fn build_action(
1834        &self,
1835        name: &str,
1836        data: Option<serde_json::Value>,
1837    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1838        self.actions.build_action(name, data)
1839    }
1840
1841    /// Get all action names that have been registered. Note that registration only allows for
1842    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1843    pub fn all_action_names(&self) -> &[&'static str] {
1844        self.actions.all_action_names()
1845    }
1846
1847    /// Returns key bindings that invoke the given action on the currently focused element, without
1848    /// checking context. Bindings are returned in the order they were added. For display, the last
1849    /// binding should take precedence.
1850    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1851        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1852    }
1853
1854    /// Get all non-internal actions that have been registered, along with their schemas.
1855    pub fn action_schemas(
1856        &self,
1857        generator: &mut schemars::SchemaGenerator,
1858    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1859        self.actions.action_schemas(generator)
1860    }
1861
1862    /// Get a map from a deprecated action name to the canonical name.
1863    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1864        self.actions.deprecated_aliases()
1865    }
1866
1867    /// Get a map from an action name to the deprecation messages.
1868    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1869        self.actions.deprecation_messages()
1870    }
1871
1872    /// Get a map from an action name to the documentation.
1873    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
1874        self.actions.documentation()
1875    }
1876
1877    /// Register a callback to be invoked when the application is about to quit.
1878    /// It is not possible to cancel the quit event at this point.
1879    pub fn on_app_quit<Fut>(
1880        &self,
1881        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
1882    ) -> Subscription
1883    where
1884        Fut: 'static + Future<Output = ()>,
1885    {
1886        let (subscription, activate) = self.quit_observers.insert(
1887            (),
1888            Box::new(move |cx| {
1889                let future = on_quit(cx);
1890                future.boxed_local()
1891            }),
1892        );
1893        activate();
1894        subscription
1895    }
1896
1897    /// Register a callback to be invoked when the application is about to restart.
1898    ///
1899    /// These callbacks are called before any `on_app_quit` callbacks.
1900    pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
1901        let (subscription, activate) = self.restart_observers.insert(
1902            (),
1903            Box::new(move |cx| {
1904                on_restart(cx);
1905                true
1906            }),
1907        );
1908        activate();
1909        subscription
1910    }
1911
1912    /// Register a callback to be invoked when a window is closed
1913    /// The window is no longer accessible at the point this callback is invoked.
1914    pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription {
1915        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
1916        activate();
1917        subscription
1918    }
1919
1920    pub(crate) fn clear_pending_keystrokes(&mut self) {
1921        for window in self.windows() {
1922            window
1923                .update(self, |_, window, cx| {
1924                    if window.pending_input_keystrokes().is_some() {
1925                        window.clear_pending_keystrokes();
1926                        window.pending_input_changed(cx);
1927                    }
1928                })
1929                .ok();
1930        }
1931    }
1932
1933    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1934    /// the bindings in the element tree, and any global action listeners.
1935    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1936        let mut action_available = false;
1937        if let Some(window) = self.active_window()
1938            && let Ok(window_action_available) =
1939                window.update(self, |_, window, cx| window.is_action_available(action, cx))
1940        {
1941            action_available = window_action_available;
1942        }
1943
1944        action_available
1945            || self
1946                .global_action_listeners
1947                .contains_key(&action.as_any().type_id())
1948    }
1949
1950    /// Sets the menu bar for this application. This will replace any existing menu bar.
1951    pub fn set_menus(&self, menus: Vec<Menu>) {
1952        self.platform.set_menus(menus, &self.keymap.borrow());
1953    }
1954
1955    /// Gets the menu bar for this application.
1956    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
1957        self.platform.get_menus()
1958    }
1959
1960    /// Sets the right click menu for the app icon in the dock
1961    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
1962        self.platform.set_dock_menu(menus, &self.keymap.borrow())
1963    }
1964
1965    /// Performs the action associated with the given dock menu item, only used on Windows for now.
1966    pub fn perform_dock_menu_action(&self, action: usize) {
1967        self.platform.perform_dock_menu_action(action);
1968    }
1969
1970    /// Adds given path to the bottom of the list of recent paths for the application.
1971    /// The list is usually shown on the application icon's context menu in the dock,
1972    /// and allows to open the recent files via that context menu.
1973    /// If the path is already in the list, it will be moved to the bottom of the list.
1974    pub fn add_recent_document(&self, path: &Path) {
1975        self.platform.add_recent_document(path);
1976    }
1977
1978    /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
1979    /// Note that this also sets the dock menu on Windows.
1980    pub fn update_jump_list(
1981        &self,
1982        menus: Vec<MenuItem>,
1983        entries: Vec<SmallVec<[PathBuf; 2]>>,
1984    ) -> Vec<SmallVec<[PathBuf; 2]>> {
1985        self.platform.update_jump_list(menus, entries)
1986    }
1987
1988    /// Dispatch an action to the currently active window or global action handler
1989    /// See [`crate::Action`] for more information on how actions work
1990    pub fn dispatch_action(&mut self, action: &dyn Action) {
1991        if let Some(active_window) = self.active_window() {
1992            active_window
1993                .update(self, |_, window, cx| {
1994                    window.dispatch_action(action.boxed_clone(), cx)
1995                })
1996                .log_err();
1997        } else {
1998            self.dispatch_global_action(action);
1999        }
2000    }
2001
2002    fn dispatch_global_action(&mut self, action: &dyn Action) {
2003        self.propagate_event = true;
2004
2005        if let Some(mut global_listeners) = self
2006            .global_action_listeners
2007            .remove(&action.as_any().type_id())
2008        {
2009            for listener in &global_listeners {
2010                listener(action.as_any(), DispatchPhase::Capture, self);
2011                if !self.propagate_event {
2012                    break;
2013                }
2014            }
2015
2016            global_listeners.extend(
2017                self.global_action_listeners
2018                    .remove(&action.as_any().type_id())
2019                    .unwrap_or_default(),
2020            );
2021
2022            self.global_action_listeners
2023                .insert(action.as_any().type_id(), global_listeners);
2024        }
2025
2026        if self.propagate_event
2027            && let Some(mut global_listeners) = self
2028                .global_action_listeners
2029                .remove(&action.as_any().type_id())
2030        {
2031            for listener in global_listeners.iter().rev() {
2032                listener(action.as_any(), DispatchPhase::Bubble, self);
2033                if !self.propagate_event {
2034                    break;
2035                }
2036            }
2037
2038            global_listeners.extend(
2039                self.global_action_listeners
2040                    .remove(&action.as_any().type_id())
2041                    .unwrap_or_default(),
2042            );
2043
2044            self.global_action_listeners
2045                .insert(action.as_any().type_id(), global_listeners);
2046        }
2047    }
2048
2049    /// Is there currently something being dragged?
2050    pub fn has_active_drag(&self) -> bool {
2051        self.active_drag.is_some()
2052    }
2053
2054    /// Gets the cursor style of the currently active drag operation.
2055    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2056        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2057    }
2058
2059    /// Stops active drag and clears any related effects.
2060    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2061        if self.active_drag.is_some() {
2062            self.active_drag = None;
2063            window.refresh();
2064            true
2065        } else {
2066            false
2067        }
2068    }
2069
2070    /// Sets the cursor style for the currently active drag operation.
2071    pub fn set_active_drag_cursor_style(
2072        &mut self,
2073        cursor_style: CursorStyle,
2074        window: &mut Window,
2075    ) -> bool {
2076        if let Some(ref mut drag) = self.active_drag {
2077            drag.cursor_style = Some(cursor_style);
2078            window.refresh();
2079            true
2080        } else {
2081            false
2082        }
2083    }
2084
2085    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
2086    /// prompts with this custom implementation.
2087    pub fn set_prompt_builder(
2088        &mut self,
2089        renderer: impl Fn(
2090            PromptLevel,
2091            &str,
2092            Option<&str>,
2093            &[PromptButton],
2094            PromptHandle,
2095            &mut Window,
2096            &mut App,
2097        ) -> RenderablePromptHandle
2098        + 'static,
2099    ) {
2100        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2101    }
2102
2103    /// Reset the prompt builder to the default implementation.
2104    pub fn reset_prompt_builder(&mut self) {
2105        self.prompt_builder = Some(PromptBuilder::Default);
2106    }
2107
2108    /// Remove an asset from GPUI's cache
2109    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2110        let asset_id = (TypeId::of::<A>(), hash(source));
2111        self.loading_assets.remove(&asset_id);
2112    }
2113
2114    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2115    ///
2116    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2117    /// time, and the results of this call will be cached
2118    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2119        let asset_id = (TypeId::of::<A>(), hash(source));
2120        let mut is_first = false;
2121        let task = self
2122            .loading_assets
2123            .remove(&asset_id)
2124            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2125            .unwrap_or_else(|| {
2126                is_first = true;
2127                let future = A::load(source.clone(), self);
2128
2129                self.background_executor().spawn(future).shared()
2130            });
2131
2132        self.loading_assets.insert(asset_id, Box::new(task.clone()));
2133
2134        (task, is_first)
2135    }
2136
2137    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2138    /// for elements rendered within this window.
2139    #[track_caller]
2140    pub fn focus_handle(&self) -> FocusHandle {
2141        FocusHandle::new(&self.focus_handles)
2142    }
2143
2144    /// Tell GPUI that an entity has changed and observers of it should be notified.
2145    pub fn notify(&mut self, entity_id: EntityId) {
2146        let window_invalidators = mem::take(
2147            self.window_invalidators_by_entity
2148                .entry(entity_id)
2149                .or_default(),
2150        );
2151
2152        if window_invalidators.is_empty() {
2153            if self.pending_notifications.insert(entity_id) {
2154                self.pending_effects
2155                    .push_back(Effect::Notify { emitter: entity_id });
2156            }
2157        } else {
2158            for invalidator in window_invalidators.values() {
2159                invalidator.invalidate_view(entity_id, self);
2160            }
2161        }
2162
2163        self.window_invalidators_by_entity
2164            .insert(entity_id, window_invalidators);
2165    }
2166
2167    /// Returns the name for this [`App`].
2168    #[cfg(any(test, feature = "test-support", debug_assertions))]
2169    pub fn get_name(&self) -> Option<&'static str> {
2170        self.name
2171    }
2172
2173    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2174    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2175        self.platform.can_select_mixed_files_and_dirs()
2176    }
2177
2178    /// Removes an image from the sprite atlas on all windows.
2179    ///
2180    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2181    /// This is a no-op if the image is not in the sprite atlas.
2182    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2183        // remove the texture from all other windows
2184        for window in self.windows.values_mut().flatten() {
2185            _ = window.drop_image(image.clone());
2186        }
2187
2188        // remove the texture from the current window
2189        if let Some(window) = current_window {
2190            _ = window.drop_image(image);
2191        }
2192    }
2193
2194    /// Sets the renderer for the inspector.
2195    #[cfg(any(feature = "inspector", debug_assertions))]
2196    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2197        self.inspector_renderer = Some(f);
2198    }
2199
2200    /// Registers a renderer specific to an inspector state.
2201    #[cfg(any(feature = "inspector", debug_assertions))]
2202    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2203        &mut self,
2204        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2205    ) {
2206        self.inspector_element_registry.register(f);
2207    }
2208
2209    /// Initializes gpui's default colors for the application.
2210    ///
2211    /// These colors can be accessed through `cx.default_colors()`.
2212    pub fn init_colors(&mut self) {
2213        self.set_global(GlobalColors(Arc::new(Colors::default())));
2214    }
2215}
2216
2217impl AppContext for App {
2218    type Result<T> = T;
2219
2220    /// Builds an entity that is owned by the application.
2221    ///
2222    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2223    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2224    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2225        self.update(|cx| {
2226            let slot = cx.entities.reserve();
2227            let handle = slot.clone();
2228            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2229
2230            cx.push_effect(Effect::EntityCreated {
2231                entity: handle.clone().into_any(),
2232                tid: TypeId::of::<T>(),
2233                window: cx.window_update_stack.last().cloned(),
2234            });
2235
2236            cx.entities.insert(slot, entity);
2237            handle
2238        })
2239    }
2240
2241    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> {
2242        Reservation(self.entities.reserve())
2243    }
2244
2245    fn insert_entity<T: 'static>(
2246        &mut self,
2247        reservation: Reservation<T>,
2248        build_entity: impl FnOnce(&mut Context<T>) -> T,
2249    ) -> Self::Result<Entity<T>> {
2250        self.update(|cx| {
2251            let slot = reservation.0;
2252            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2253            cx.entities.insert(slot, entity)
2254        })
2255    }
2256
2257    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2258    /// entity along with a `Context` for the entity.
2259    fn update_entity<T: 'static, R>(
2260        &mut self,
2261        handle: &Entity<T>,
2262        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2263    ) -> R {
2264        self.update(|cx| {
2265            let mut entity = cx.entities.lease(handle);
2266            let result = update(
2267                &mut entity,
2268                &mut Context::new_context(cx, handle.downgrade()),
2269            );
2270            cx.entities.end_lease(entity);
2271            result
2272        })
2273    }
2274
2275    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2276    where
2277        T: 'static,
2278    {
2279        GpuiBorrow::new(handle.clone(), self)
2280    }
2281
2282    fn read_entity<T, R>(
2283        &self,
2284        handle: &Entity<T>,
2285        read: impl FnOnce(&T, &App) -> R,
2286    ) -> Self::Result<R>
2287    where
2288        T: 'static,
2289    {
2290        let entity = self.entities.read(handle);
2291        read(entity, self)
2292    }
2293
2294    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2295    where
2296        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2297    {
2298        self.update_window_id(handle.id, update)
2299    }
2300
2301    fn read_window<T, R>(
2302        &self,
2303        window: &WindowHandle<T>,
2304        read: impl FnOnce(Entity<T>, &App) -> R,
2305    ) -> Result<R>
2306    where
2307        T: 'static,
2308    {
2309        let window = self
2310            .windows
2311            .get(window.id)
2312            .context("window not found")?
2313            .as_deref()
2314            .expect("attempted to read a window that is already on the stack");
2315
2316        let root_view = window.root.clone().unwrap();
2317        let view = root_view
2318            .downcast::<T>()
2319            .map_err(|_| anyhow!("root view's type has changed"))?;
2320
2321        Ok(read(view, self))
2322    }
2323
2324    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2325    where
2326        R: Send + 'static,
2327    {
2328        self.background_executor.spawn(future)
2329    }
2330
2331    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
2332    where
2333        G: Global,
2334    {
2335        let mut g = self.global::<G>();
2336        callback(g, self)
2337    }
2338}
2339
2340/// These effects are processed at the end of each application update cycle.
2341pub(crate) enum Effect {
2342    Notify {
2343        emitter: EntityId,
2344    },
2345    Emit {
2346        emitter: EntityId,
2347        event_type: TypeId,
2348        event: Box<dyn Any>,
2349    },
2350    RefreshWindows,
2351    NotifyGlobalObservers {
2352        global_type: TypeId,
2353    },
2354    Defer {
2355        callback: Box<dyn FnOnce(&mut App) + 'static>,
2356    },
2357    EntityCreated {
2358        entity: AnyEntity,
2359        tid: TypeId,
2360        window: Option<WindowId>,
2361    },
2362}
2363
2364impl std::fmt::Debug for Effect {
2365    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2366        match self {
2367            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2368            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2369            Effect::RefreshWindows => write!(f, "RefreshWindows"),
2370            Effect::NotifyGlobalObservers { global_type } => {
2371                write!(f, "NotifyGlobalObservers({:?})", global_type)
2372            }
2373            Effect::Defer { .. } => write!(f, "Defer(..)"),
2374            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2375        }
2376    }
2377}
2378
2379/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2380pub(crate) struct GlobalLease<G: Global> {
2381    global: Box<dyn Any>,
2382    global_type: PhantomData<G>,
2383}
2384
2385impl<G: Global> GlobalLease<G> {
2386    fn new(global: Box<dyn Any>) -> Self {
2387        GlobalLease {
2388            global,
2389            global_type: PhantomData,
2390        }
2391    }
2392}
2393
2394impl<G: Global> Deref for GlobalLease<G> {
2395    type Target = G;
2396
2397    fn deref(&self) -> &Self::Target {
2398        self.global.downcast_ref().unwrap()
2399    }
2400}
2401
2402impl<G: Global> DerefMut for GlobalLease<G> {
2403    fn deref_mut(&mut self) -> &mut Self::Target {
2404        self.global.downcast_mut().unwrap()
2405    }
2406}
2407
2408/// Contains state associated with an active drag operation, started by dragging an element
2409/// within the window or by dragging into the app from the underlying platform.
2410pub struct AnyDrag {
2411    /// The view used to render this drag
2412    pub view: AnyView,
2413
2414    /// The value of the dragged item, to be dropped
2415    pub value: Arc<dyn Any>,
2416
2417    /// This is used to render the dragged item in the same place
2418    /// on the original element that the drag was initiated
2419    pub cursor_offset: Point<Pixels>,
2420
2421    /// The cursor style to use while dragging
2422    pub cursor_style: Option<CursorStyle>,
2423}
2424
2425/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2426/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2427#[derive(Clone)]
2428pub struct AnyTooltip {
2429    /// The view used to display the tooltip
2430    pub view: AnyView,
2431
2432    /// The absolute position of the mouse when the tooltip was deployed.
2433    pub mouse_position: Point<Pixels>,
2434
2435    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2436    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2437    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2438    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2439}
2440
2441/// A keystroke event, and potentially the associated action
2442#[derive(Debug)]
2443pub struct KeystrokeEvent {
2444    /// The keystroke that occurred
2445    pub keystroke: Keystroke,
2446
2447    /// The action that was resolved for the keystroke, if any
2448    pub action: Option<Box<dyn Action>>,
2449
2450    /// The context stack at the time
2451    pub context_stack: Vec<KeyContext>,
2452}
2453
2454struct NullHttpClient;
2455
2456impl HttpClient for NullHttpClient {
2457    fn send(
2458        &self,
2459        _req: http_client::Request<http_client::AsyncBody>,
2460    ) -> futures::future::BoxFuture<
2461        'static,
2462        anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2463    > {
2464        async move {
2465            anyhow::bail!("No HttpClient available");
2466        }
2467        .boxed()
2468    }
2469
2470    fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2471        None
2472    }
2473
2474    fn proxy(&self) -> Option<&Url> {
2475        None
2476    }
2477}
2478
2479/// A mutable reference to an entity owned by GPUI
2480pub struct GpuiBorrow<'a, T> {
2481    inner: Option<Lease<T>>,
2482    app: &'a mut App,
2483}
2484
2485impl<'a, T: 'static> GpuiBorrow<'a, T> {
2486    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2487        app.start_update();
2488        let lease = app.entities.lease(&inner);
2489        Self {
2490            inner: Some(lease),
2491            app,
2492        }
2493    }
2494}
2495
2496impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2497    fn borrow(&self) -> &T {
2498        self.inner.as_ref().unwrap().borrow()
2499    }
2500}
2501
2502impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2503    fn borrow_mut(&mut self) -> &mut T {
2504        self.inner.as_mut().unwrap().borrow_mut()
2505    }
2506}
2507
2508impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
2509    type Target = T;
2510
2511    fn deref(&self) -> &Self::Target {
2512        self.inner.as_ref().unwrap()
2513    }
2514}
2515
2516impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
2517    fn deref_mut(&mut self) -> &mut T {
2518        self.inner.as_mut().unwrap()
2519    }
2520}
2521
2522impl<'a, T> Drop for GpuiBorrow<'a, T> {
2523    fn drop(&mut self) {
2524        let lease = self.inner.take().unwrap();
2525        self.app.notify(lease.id);
2526        self.app.entities.end_lease(lease);
2527        self.app.finish_update();
2528    }
2529}
2530
2531#[cfg(test)]
2532mod test {
2533    use std::{cell::RefCell, rc::Rc};
2534
2535    use crate::{AppContext, TestAppContext};
2536
2537    #[test]
2538    fn test_gpui_borrow() {
2539        let cx = TestAppContext::single();
2540        let observation_count = Rc::new(RefCell::new(0));
2541
2542        let state = cx.update(|cx| {
2543            let state = cx.new(|_| false);
2544            cx.observe(&state, {
2545                let observation_count = observation_count.clone();
2546                move |_, _| {
2547                    let mut count = observation_count.borrow_mut();
2548                    *count += 1;
2549                }
2550            })
2551            .detach();
2552
2553            state
2554        });
2555
2556        cx.update(|cx| {
2557            // Calling this like this so that we don't clobber the borrow_mut above
2558            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2559        });
2560
2561        cx.update(|cx| {
2562            state.write(cx, false);
2563        });
2564
2565        assert_eq!(*observation_count.borrow(), 2);
2566    }
2567}