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