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