app.rs

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