app.rs

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