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