app.rs

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