app.rs

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