app.rs

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