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