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