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            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1684    }
1685
1686    /// Access the global of the given type if a value has been assigned.
1687    pub fn try_global<G: Global>(&self) -> Option<&G> {
1688        self.globals_by_type
1689            .get(&TypeId::of::<G>())
1690            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
1691    }
1692
1693    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
1694    #[track_caller]
1695    pub fn global_mut<G: Global>(&mut self) -> &mut G {
1696        let global_type = TypeId::of::<G>();
1697        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1698        self.globals_by_type
1699            .get_mut(&global_type)
1700            .and_then(|any_state| any_state.downcast_mut::<G>())
1701            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
1702    }
1703
1704    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
1705    /// yet been assigned.
1706    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
1707        let global_type = TypeId::of::<G>();
1708        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1709        self.globals_by_type
1710            .entry(global_type)
1711            .or_insert_with(|| Box::<G>::default())
1712            .downcast_mut::<G>()
1713            .unwrap()
1714    }
1715
1716    /// Sets the value of the global of the given type.
1717    pub fn set_global<G: Global>(&mut self, global: G) {
1718        let global_type = TypeId::of::<G>();
1719        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1720        self.globals_by_type.insert(global_type, Box::new(global));
1721    }
1722
1723    /// Clear all stored globals. Does not notify global observers.
1724    #[cfg(any(test, feature = "test-support"))]
1725    pub fn clear_globals(&mut self) {
1726        self.globals_by_type.drain();
1727    }
1728
1729    /// Remove the global of the given type from the app context. Does not notify global observers.
1730    pub fn remove_global<G: Global>(&mut self) -> G {
1731        let global_type = TypeId::of::<G>();
1732        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1733        *self
1734            .globals_by_type
1735            .remove(&global_type)
1736            .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
1737            .downcast()
1738            .unwrap()
1739    }
1740
1741    /// Register a callback to be invoked when a global of the given type is updated.
1742    pub fn observe_global<G: Global>(
1743        &mut self,
1744        mut f: impl FnMut(&mut Self) + 'static,
1745    ) -> Subscription {
1746        let (subscription, activate) = self.global_observers.insert(
1747            TypeId::of::<G>(),
1748            Box::new(move |cx| {
1749                f(cx);
1750                true
1751            }),
1752        );
1753        self.defer(move |_| activate());
1754        subscription
1755    }
1756
1757    /// Move the global of the given type to the stack.
1758    #[track_caller]
1759    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
1760        GlobalLease::new(
1761            self.globals_by_type
1762                .remove(&TypeId::of::<G>())
1763                .with_context(|| format!("no global registered of type {}", type_name::<G>()))
1764                .unwrap(),
1765        )
1766    }
1767
1768    /// Restore the global of the given type after it is moved to the stack.
1769    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
1770        let global_type = TypeId::of::<G>();
1771
1772        self.push_effect(Effect::NotifyGlobalObservers { global_type });
1773        self.globals_by_type.insert(global_type, lease.global);
1774    }
1775
1776    pub(crate) fn new_entity_observer(
1777        &self,
1778        key: TypeId,
1779        value: NewEntityListener,
1780    ) -> Subscription {
1781        let (subscription, activate) = self.new_entity_observers.insert(key, value);
1782        activate();
1783        subscription
1784    }
1785
1786    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
1787    /// The function will be passed a mutable reference to the view along with an appropriate context.
1788    pub fn observe_new<T: 'static>(
1789        &self,
1790        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
1791    ) -> Subscription {
1792        self.new_entity_observer(
1793            TypeId::of::<T>(),
1794            Box::new(
1795                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
1796                    any_entity
1797                        .downcast::<T>()
1798                        .unwrap()
1799                        .update(cx, |entity_state, cx| {
1800                            on_new(entity_state, window.as_deref_mut(), cx)
1801                        })
1802                },
1803            ),
1804        )
1805    }
1806
1807    /// Observe the release of a entity. The callback is invoked after the entity
1808    /// has no more strong references but before it has been dropped.
1809    pub fn observe_release<T>(
1810        &self,
1811        handle: &Entity<T>,
1812        on_release: impl FnOnce(&mut T, &mut App) + 'static,
1813    ) -> Subscription
1814    where
1815        T: 'static,
1816    {
1817        let (subscription, activate) = self.release_listeners.insert(
1818            handle.entity_id(),
1819            Box::new(move |entity, cx| {
1820                let entity = entity.downcast_mut().expect("invalid entity type");
1821                on_release(entity, cx)
1822            }),
1823        );
1824        activate();
1825        subscription
1826    }
1827
1828    /// Observe the release of a entity. The callback is invoked after the entity
1829    /// has no more strong references but before it has been dropped.
1830    pub fn observe_release_in<T>(
1831        &self,
1832        handle: &Entity<T>,
1833        window: &Window,
1834        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1835    ) -> Subscription
1836    where
1837        T: 'static,
1838    {
1839        let window_handle = window.handle;
1840        self.observe_release(handle, move |entity, cx| {
1841            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1842        })
1843    }
1844
1845    /// Register a callback to be invoked when a keystroke is received by the application
1846    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1847    /// and that this API will not be invoked if the event's propagation is stopped.
1848    pub fn observe_keystrokes(
1849        &mut self,
1850        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1851    ) -> Subscription {
1852        fn inner(
1853            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
1854            handler: KeystrokeObserver,
1855        ) -> Subscription {
1856            let (subscription, activate) = keystroke_observers.insert((), handler);
1857            activate();
1858            subscription
1859        }
1860
1861        inner(
1862            &self.keystroke_observers,
1863            Box::new(move |event, window, cx| {
1864                f(event, window, cx);
1865                true
1866            }),
1867        )
1868    }
1869
1870    /// Register a callback to be invoked when a keystroke is received by the application
1871    /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
1872    /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
1873    /// within interceptors will prevent action dispatch
1874    pub fn intercept_keystrokes(
1875        &mut self,
1876        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
1877    ) -> Subscription {
1878        fn inner(
1879            keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
1880            handler: KeystrokeObserver,
1881        ) -> Subscription {
1882            let (subscription, activate) = keystroke_interceptors.insert((), handler);
1883            activate();
1884            subscription
1885        }
1886
1887        inner(
1888            &self.keystroke_interceptors,
1889            Box::new(move |event, window, cx| {
1890                f(event, window, cx);
1891                true
1892            }),
1893        )
1894    }
1895
1896    /// Register key bindings.
1897    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1898        self.keymap.borrow_mut().add_bindings(bindings);
1899        self.pending_effects.push_back(Effect::RefreshWindows);
1900    }
1901
1902    /// Clear all key bindings in the app.
1903    pub fn clear_key_bindings(&mut self) {
1904        self.keymap.borrow_mut().clear();
1905        self.pending_effects.push_back(Effect::RefreshWindows);
1906    }
1907
1908    /// Get all key bindings in the app.
1909    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
1910        self.keymap.clone()
1911    }
1912
1913    /// Register a global handler for actions invoked via the keyboard. These handlers are run at
1914    /// the end of the bubble phase for actions, and so will only be invoked if there are no other
1915    /// handlers or if they called `cx.propagate()`.
1916    pub fn on_action<A: Action>(
1917        &mut self,
1918        listener: impl Fn(&A, &mut Self) + 'static,
1919    ) -> &mut Self {
1920        self.global_action_listeners
1921            .entry(TypeId::of::<A>())
1922            .or_default()
1923            .push(Rc::new(move |action, phase, cx| {
1924                if phase == DispatchPhase::Bubble {
1925                    let action = action.downcast_ref().unwrap();
1926                    listener(action, cx)
1927                }
1928            }));
1929        self
1930    }
1931
1932    /// Event handlers propagate events by default. Call this method to stop dispatching to
1933    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1934    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1935    /// calling this method before effects are flushed.
1936    pub fn stop_propagation(&mut self) {
1937        self.propagate_event = false;
1938    }
1939
1940    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1941    /// dispatching to action handlers higher in the element tree. This is the opposite of
1942    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1943    /// this method before effects are flushed.
1944    pub fn propagate(&mut self) {
1945        self.propagate_event = true;
1946    }
1947
1948    /// Build an action from some arbitrary data, typically a keymap entry.
1949    pub fn build_action(
1950        &self,
1951        name: &str,
1952        data: Option<serde_json::Value>,
1953    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1954        self.actions.build_action(name, data)
1955    }
1956
1957    /// Get all action names that have been registered. Note that registration only allows for
1958    /// actions to be built dynamically, and is unrelated to binding actions in the element tree.
1959    pub fn all_action_names(&self) -> &[&'static str] {
1960        self.actions.all_action_names()
1961    }
1962
1963    /// Returns key bindings that invoke the given action on the currently focused element, without
1964    /// checking context. Bindings are returned in the order they were added. For display, the last
1965    /// binding should take precedence.
1966    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
1967        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
1968    }
1969
1970    /// Get all non-internal actions that have been registered, along with their schemas.
1971    pub fn action_schemas(
1972        &self,
1973        generator: &mut schemars::SchemaGenerator,
1974    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
1975        self.actions.action_schemas(generator)
1976    }
1977
1978    /// Get the schema for a specific action by name.
1979    /// Returns `None` if the action is not found.
1980    /// Returns `Some(None)` if the action exists but has no schema.
1981    /// Returns `Some(Some(schema))` if the action exists and has a schema.
1982    pub fn action_schema_by_name(
1983        &self,
1984        name: &str,
1985        generator: &mut schemars::SchemaGenerator,
1986    ) -> Option<Option<schemars::Schema>> {
1987        self.actions.action_schema_by_name(name, generator)
1988    }
1989
1990    /// Get a map from a deprecated action name to the canonical name.
1991    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
1992        self.actions.deprecated_aliases()
1993    }
1994
1995    /// Get a map from an action name to the deprecation messages.
1996    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
1997        self.actions.deprecation_messages()
1998    }
1999
2000    /// Get a map from an action name to the documentation.
2001    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2002        self.actions.documentation()
2003    }
2004
2005    /// Register a callback to be invoked when the application is about to quit.
2006    /// It is not possible to cancel the quit event at this point.
2007    pub fn on_app_quit<Fut>(
2008        &self,
2009        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2010    ) -> Subscription
2011    where
2012        Fut: 'static + Future<Output = ()>,
2013    {
2014        let (subscription, activate) = self.quit_observers.insert(
2015            (),
2016            Box::new(move |cx| {
2017                let future = on_quit(cx);
2018                future.boxed_local()
2019            }),
2020        );
2021        activate();
2022        subscription
2023    }
2024
2025    /// Register a callback to be invoked when the application is about to restart.
2026    ///
2027    /// These callbacks are called before any `on_app_quit` callbacks.
2028    pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2029        let (subscription, activate) = self.restart_observers.insert(
2030            (),
2031            Box::new(move |cx| {
2032                on_restart(cx);
2033                true
2034            }),
2035        );
2036        activate();
2037        subscription
2038    }
2039
2040    /// Register a callback to be invoked when a window is closed
2041    /// The window is no longer accessible at the point this callback is invoked.
2042    pub fn on_window_closed(
2043        &self,
2044        mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2045    ) -> Subscription {
2046        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2047        activate();
2048        subscription
2049    }
2050
2051    pub(crate) fn clear_pending_keystrokes(&mut self) {
2052        for window in self.windows() {
2053            window
2054                .update(self, |_, window, cx| {
2055                    if window.pending_input_keystrokes().is_some() {
2056                        window.clear_pending_keystrokes();
2057                        window.pending_input_changed(cx);
2058                    }
2059                })
2060                .ok();
2061        }
2062    }
2063
2064    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
2065    /// the bindings in the element tree, and any global action listeners.
2066    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2067        let mut action_available = false;
2068        if let Some(window) = self.active_window()
2069            && let Ok(window_action_available) =
2070                window.update(self, |_, window, cx| window.is_action_available(action, cx))
2071        {
2072            action_available = window_action_available;
2073        }
2074
2075        action_available
2076            || self
2077                .global_action_listeners
2078                .contains_key(&action.as_any().type_id())
2079    }
2080
2081    /// Sets the menu bar for this application. This will replace any existing menu bar.
2082    pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2083        let menus: Vec<Menu> = menus.into_iter().collect();
2084        self.platform.set_menus(menus, &self.keymap.borrow());
2085    }
2086
2087    /// Gets the menu bar for this application.
2088    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2089        self.platform.get_menus()
2090    }
2091
2092    /// Sets the right click menu for the app icon in the dock
2093    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2094        self.platform.set_dock_menu(menus, &self.keymap.borrow())
2095    }
2096
2097    /// Performs the action associated with the given dock menu item, only used on Windows for now.
2098    pub fn perform_dock_menu_action(&self, action: usize) {
2099        self.platform.perform_dock_menu_action(action);
2100    }
2101
2102    /// Adds given path to the bottom of the list of recent paths for the application.
2103    /// The list is usually shown on the application icon's context menu in the dock,
2104    /// and allows to open the recent files via that context menu.
2105    /// If the path is already in the list, it will be moved to the bottom of the list.
2106    pub fn add_recent_document(&self, path: &Path) {
2107        self.platform.add_recent_document(path);
2108    }
2109
2110    /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now.
2111    /// Note that this also sets the dock menu on Windows.
2112    pub fn update_jump_list(
2113        &self,
2114        menus: Vec<MenuItem>,
2115        entries: Vec<SmallVec<[PathBuf; 2]>>,
2116    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2117        self.platform.update_jump_list(menus, entries)
2118    }
2119
2120    /// Dispatch an action to the currently active window or global action handler
2121    /// See [`crate::Action`] for more information on how actions work
2122    pub fn dispatch_action(&mut self, action: &dyn Action) {
2123        if let Some(active_window) = self.active_window() {
2124            active_window
2125                .update(self, |_, window, cx| {
2126                    window.dispatch_action(action.boxed_clone(), cx)
2127                })
2128                .log_err();
2129        } else {
2130            self.dispatch_global_action(action);
2131        }
2132    }
2133
2134    fn dispatch_global_action(&mut self, action: &dyn Action) {
2135        self.propagate_event = true;
2136
2137        if let Some(mut global_listeners) = self
2138            .global_action_listeners
2139            .remove(&action.as_any().type_id())
2140        {
2141            for listener in &global_listeners {
2142                listener(action.as_any(), DispatchPhase::Capture, self);
2143                if !self.propagate_event {
2144                    break;
2145                }
2146            }
2147
2148            global_listeners.extend(
2149                self.global_action_listeners
2150                    .remove(&action.as_any().type_id())
2151                    .unwrap_or_default(),
2152            );
2153
2154            self.global_action_listeners
2155                .insert(action.as_any().type_id(), global_listeners);
2156        }
2157
2158        if self.propagate_event
2159            && let Some(mut global_listeners) = self
2160                .global_action_listeners
2161                .remove(&action.as_any().type_id())
2162        {
2163            for listener in global_listeners.iter().rev() {
2164                listener(action.as_any(), DispatchPhase::Bubble, self);
2165                if !self.propagate_event {
2166                    break;
2167                }
2168            }
2169
2170            global_listeners.extend(
2171                self.global_action_listeners
2172                    .remove(&action.as_any().type_id())
2173                    .unwrap_or_default(),
2174            );
2175
2176            self.global_action_listeners
2177                .insert(action.as_any().type_id(), global_listeners);
2178        }
2179    }
2180
2181    /// Is there currently something being dragged?
2182    pub fn has_active_drag(&self) -> bool {
2183        self.active_drag.is_some()
2184    }
2185
2186    /// Gets the cursor style of the currently active drag operation.
2187    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
2188        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
2189    }
2190
2191    /// Stops active drag and clears any related effects.
2192    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
2193        if self.active_drag.is_some() {
2194            self.active_drag = None;
2195            window.refresh();
2196            true
2197        } else {
2198            false
2199        }
2200    }
2201
2202    /// Sets the cursor style for the currently active drag operation.
2203    pub fn set_active_drag_cursor_style(
2204        &mut self,
2205        cursor_style: CursorStyle,
2206        window: &mut Window,
2207    ) -> bool {
2208        if let Some(ref mut drag) = self.active_drag {
2209            drag.cursor_style = Some(cursor_style);
2210            window.refresh();
2211            true
2212        } else {
2213            false
2214        }
2215    }
2216
2217    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
2218    /// prompts with this custom implementation.
2219    pub fn set_prompt_builder(
2220        &mut self,
2221        renderer: impl Fn(
2222            PromptLevel,
2223            &str,
2224            Option<&str>,
2225            &[PromptButton],
2226            PromptHandle,
2227            &mut Window,
2228            &mut App,
2229        ) -> RenderablePromptHandle
2230        + 'static,
2231    ) {
2232        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
2233    }
2234
2235    /// Reset the prompt builder to the default implementation.
2236    pub fn reset_prompt_builder(&mut self) {
2237        self.prompt_builder = Some(PromptBuilder::Default);
2238    }
2239
2240    /// Remove an asset from GPUI's cache
2241    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
2242        let asset_id = (TypeId::of::<A>(), hash(source));
2243        self.loading_assets.remove(&asset_id);
2244    }
2245
2246    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2247    ///
2248    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2249    /// time, and the results of this call will be cached
2250    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
2251        let asset_id = (TypeId::of::<A>(), hash(source));
2252        let mut is_first = false;
2253        let task = self
2254            .loading_assets
2255            .remove(&asset_id)
2256            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
2257            .unwrap_or_else(|| {
2258                is_first = true;
2259                let future = A::load(source.clone(), self);
2260
2261                self.background_executor().spawn(future).shared()
2262            });
2263
2264        self.loading_assets.insert(asset_id, Box::new(task.clone()));
2265
2266        (task, is_first)
2267    }
2268
2269    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
2270    /// for elements rendered within this window.
2271    #[track_caller]
2272    pub fn focus_handle(&self) -> FocusHandle {
2273        FocusHandle::new(&self.focus_handles)
2274    }
2275
2276    /// Tell GPUI that an entity has changed and observers of it should be notified.
2277    pub fn notify(&mut self, entity_id: EntityId) {
2278        let window_invalidators = mem::take(
2279            self.window_invalidators_by_entity
2280                .entry(entity_id)
2281                .or_default(),
2282        );
2283
2284        if window_invalidators.is_empty() {
2285            if self.pending_notifications.insert(entity_id) {
2286                self.pending_effects
2287                    .push_back(Effect::Notify { emitter: entity_id });
2288            }
2289        } else {
2290            for invalidator in window_invalidators.values() {
2291                invalidator.invalidate_view(entity_id, self);
2292            }
2293        }
2294
2295        self.window_invalidators_by_entity
2296            .insert(entity_id, window_invalidators);
2297    }
2298
2299    /// Returns the name for this [`App`].
2300    #[cfg(any(test, feature = "test-support", debug_assertions))]
2301    pub fn get_name(&self) -> Option<&'static str> {
2302        self.name
2303    }
2304
2305    /// Returns `true` if the platform file picker supports selecting a mix of files and directories.
2306    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
2307        self.platform.can_select_mixed_files_and_dirs()
2308    }
2309
2310    /// Removes an image from the sprite atlas on all windows.
2311    ///
2312    /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window.
2313    /// This is a no-op if the image is not in the sprite atlas.
2314    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
2315        // remove the texture from all other windows
2316        for window in self.windows.values_mut().flatten() {
2317            _ = window.drop_image(image.clone());
2318        }
2319
2320        // remove the texture from the current window
2321        if let Some(window) = current_window {
2322            _ = window.drop_image(image);
2323        }
2324    }
2325
2326    /// Sets the renderer for the inspector.
2327    #[cfg(any(feature = "inspector", debug_assertions))]
2328    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
2329        self.inspector_renderer = Some(f);
2330    }
2331
2332    /// Registers a renderer specific to an inspector state.
2333    #[cfg(any(feature = "inspector", debug_assertions))]
2334    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
2335        &mut self,
2336        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
2337    ) {
2338        self.inspector_element_registry.register(f);
2339    }
2340
2341    /// Initializes gpui's default colors for the application.
2342    ///
2343    /// These colors can be accessed through `cx.default_colors()`.
2344    pub fn init_colors(&mut self) {
2345        self.set_global(GlobalColors(Arc::new(Colors::default())));
2346    }
2347}
2348
2349impl AppContext for App {
2350    /// Builds an entity that is owned by the application.
2351    ///
2352    /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
2353    /// [`Entity`] handle will be returned, which can be used to access the entity in a context.
2354    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
2355        self.update(|cx| {
2356            let slot = cx.entities.reserve();
2357            let handle = slot.clone();
2358            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2359
2360            cx.push_effect(Effect::EntityCreated {
2361                entity: handle.into_any(),
2362                tid: TypeId::of::<T>(),
2363                window: cx.window_update_stack.last().cloned(),
2364            });
2365
2366            cx.entities.insert(slot, entity)
2367        })
2368    }
2369
2370    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
2371        Reservation(self.entities.reserve())
2372    }
2373
2374    fn insert_entity<T: 'static>(
2375        &mut self,
2376        reservation: Reservation<T>,
2377        build_entity: impl FnOnce(&mut Context<T>) -> T,
2378    ) -> Entity<T> {
2379        self.update(|cx| {
2380            let slot = reservation.0;
2381            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
2382            cx.entities.insert(slot, entity)
2383        })
2384    }
2385
2386    /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
2387    /// entity along with a `Context` for the entity.
2388    fn update_entity<T: 'static, R>(
2389        &mut self,
2390        handle: &Entity<T>,
2391        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
2392    ) -> R {
2393        self.update(|cx| {
2394            let mut entity = cx.entities.lease(handle);
2395            let result = update(
2396                &mut entity,
2397                &mut Context::new_context(cx, handle.downgrade()),
2398            );
2399            cx.entities.end_lease(entity);
2400            result
2401        })
2402    }
2403
2404    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
2405    where
2406        T: 'static,
2407    {
2408        GpuiBorrow::new(handle.clone(), self)
2409    }
2410
2411    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
2412    where
2413        T: 'static,
2414    {
2415        let entity = self.entities.read(handle);
2416        read(entity, self)
2417    }
2418
2419    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
2420    where
2421        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
2422    {
2423        self.update_window_id(handle.id, update)
2424    }
2425
2426    fn read_window<T, R>(
2427        &self,
2428        window: &WindowHandle<T>,
2429        read: impl FnOnce(Entity<T>, &App) -> R,
2430    ) -> Result<R>
2431    where
2432        T: 'static,
2433    {
2434        let window = self
2435            .windows
2436            .get(window.id)
2437            .context("window not found")?
2438            .as_deref()
2439            .expect("attempted to read a window that is already on the stack");
2440
2441        let root_view = window.root.clone().unwrap();
2442        let view = root_view
2443            .downcast::<T>()
2444            .map_err(|_| anyhow!("root view's type has changed"))?;
2445
2446        Ok(read(view, self))
2447    }
2448
2449    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
2450    where
2451        R: Send + 'static,
2452    {
2453        self.background_executor.spawn(future)
2454    }
2455
2456    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
2457    where
2458        G: Global,
2459    {
2460        let mut g = self.global::<G>();
2461        callback(g, self)
2462    }
2463}
2464
2465/// These effects are processed at the end of each application update cycle.
2466pub(crate) enum Effect {
2467    Notify {
2468        emitter: EntityId,
2469    },
2470    Emit {
2471        emitter: EntityId,
2472        event_type: TypeId,
2473        event: ArenaBox<dyn Any>,
2474    },
2475    RefreshWindows,
2476    NotifyGlobalObservers {
2477        global_type: TypeId,
2478    },
2479    Defer {
2480        callback: Box<dyn FnOnce(&mut App) + 'static>,
2481    },
2482    EntityCreated {
2483        entity: AnyEntity,
2484        tid: TypeId,
2485        window: Option<WindowId>,
2486    },
2487}
2488
2489impl std::fmt::Debug for Effect {
2490    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2491        match self {
2492            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
2493            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
2494            Effect::RefreshWindows => write!(f, "RefreshWindows"),
2495            Effect::NotifyGlobalObservers { global_type } => {
2496                write!(f, "NotifyGlobalObservers({:?})", global_type)
2497            }
2498            Effect::Defer { .. } => write!(f, "Defer(..)"),
2499            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
2500        }
2501    }
2502}
2503
2504/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
2505pub(crate) struct GlobalLease<G: Global> {
2506    global: Box<dyn Any>,
2507    global_type: PhantomData<G>,
2508}
2509
2510impl<G: Global> GlobalLease<G> {
2511    fn new(global: Box<dyn Any>) -> Self {
2512        GlobalLease {
2513            global,
2514            global_type: PhantomData,
2515        }
2516    }
2517}
2518
2519impl<G: Global> Deref for GlobalLease<G> {
2520    type Target = G;
2521
2522    fn deref(&self) -> &Self::Target {
2523        self.global.downcast_ref().unwrap()
2524    }
2525}
2526
2527impl<G: Global> DerefMut for GlobalLease<G> {
2528    fn deref_mut(&mut self) -> &mut Self::Target {
2529        self.global.downcast_mut().unwrap()
2530    }
2531}
2532
2533/// Contains state associated with an active drag operation, started by dragging an element
2534/// within the window or by dragging into the app from the underlying platform.
2535pub struct AnyDrag {
2536    /// The view used to render this drag
2537    pub view: AnyView,
2538
2539    /// The value of the dragged item, to be dropped
2540    pub value: Arc<dyn Any>,
2541
2542    /// This is used to render the dragged item in the same place
2543    /// on the original element that the drag was initiated
2544    pub cursor_offset: Point<Pixels>,
2545
2546    /// The cursor style to use while dragging
2547    pub cursor_style: Option<CursorStyle>,
2548}
2549
2550/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
2551/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip).
2552#[derive(Clone)]
2553pub struct AnyTooltip {
2554    /// The view used to display the tooltip
2555    pub view: AnyView,
2556
2557    /// The absolute position of the mouse when the tooltip was deployed.
2558    pub mouse_position: Point<Pixels>,
2559
2560    /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
2561    /// updates its state accordingly. This is needed atop the hovered element's mouse move handler
2562    /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
2563    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
2564}
2565
2566/// A keystroke event, and potentially the associated action
2567#[derive(Debug)]
2568pub struct KeystrokeEvent {
2569    /// The keystroke that occurred
2570    pub keystroke: Keystroke,
2571
2572    /// The action that was resolved for the keystroke, if any
2573    pub action: Option<Box<dyn Action>>,
2574
2575    /// The context stack at the time
2576    pub context_stack: Vec<KeyContext>,
2577}
2578
2579struct NullHttpClient;
2580
2581impl HttpClient for NullHttpClient {
2582    fn send(
2583        &self,
2584        _req: http_client::Request<http_client::AsyncBody>,
2585    ) -> futures::future::BoxFuture<
2586        'static,
2587        anyhow::Result<http_client::Response<http_client::AsyncBody>>,
2588    > {
2589        async move {
2590            anyhow::bail!("No HttpClient available");
2591        }
2592        .boxed()
2593    }
2594
2595    fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {
2596        None
2597    }
2598
2599    fn proxy(&self) -> Option<&Url> {
2600        None
2601    }
2602}
2603
2604/// A mutable reference to an entity owned by GPUI
2605pub struct GpuiBorrow<'a, T> {
2606    inner: Option<Lease<T>>,
2607    app: &'a mut App,
2608}
2609
2610impl<'a, T: 'static> GpuiBorrow<'a, T> {
2611    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
2612        app.start_update();
2613        let lease = app.entities.lease(&inner);
2614        Self {
2615            inner: Some(lease),
2616            app,
2617        }
2618    }
2619}
2620
2621impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
2622    fn borrow(&self) -> &T {
2623        self.inner.as_ref().unwrap().borrow()
2624    }
2625}
2626
2627impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
2628    fn borrow_mut(&mut self) -> &mut T {
2629        self.inner.as_mut().unwrap().borrow_mut()
2630    }
2631}
2632
2633impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
2634    type Target = T;
2635
2636    fn deref(&self) -> &Self::Target {
2637        self.inner.as_ref().unwrap()
2638    }
2639}
2640
2641impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
2642    fn deref_mut(&mut self) -> &mut T {
2643        self.inner.as_mut().unwrap()
2644    }
2645}
2646
2647impl<'a, T> Drop for GpuiBorrow<'a, T> {
2648    fn drop(&mut self) {
2649        let lease = self.inner.take().unwrap();
2650        self.app.notify(lease.id);
2651        self.app.entities.end_lease(lease);
2652        self.app.finish_update();
2653    }
2654}
2655
2656#[cfg(test)]
2657mod test {
2658    use std::{cell::RefCell, rc::Rc};
2659
2660    use crate::{AppContext, TestAppContext};
2661
2662    #[test]
2663    fn test_gpui_borrow() {
2664        let cx = TestAppContext::single();
2665        let observation_count = Rc::new(RefCell::new(0));
2666
2667        let state = cx.update(|cx| {
2668            let state = cx.new(|_| false);
2669            cx.observe(&state, {
2670                let observation_count = observation_count.clone();
2671                move |_, _| {
2672                    let mut count = observation_count.borrow_mut();
2673                    *count += 1;
2674                }
2675            })
2676            .detach();
2677
2678            state
2679        });
2680
2681        cx.update(|cx| {
2682            // Calling this like this so that we don't clobber the borrow_mut above
2683            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
2684        });
2685
2686        cx.update(|cx| {
2687            state.write(cx, false);
2688        });
2689
2690        assert_eq!(*observation_count.borrow(), 2);
2691    }
2692}