app.rs

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