app.rs

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