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