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