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