app.rs

   1use std::{
   2    any::{type_name, TypeId},
   3    cell::{Ref, RefCell, RefMut},
   4    marker::PhantomData,
   5    ops::{Deref, DerefMut},
   6    path::{Path, PathBuf},
   7    rc::{Rc, Weak},
   8    sync::{atomic::Ordering::SeqCst, Arc},
   9    time::Duration,
  10};
  11
  12use anyhow::{anyhow, Result};
  13use derive_more::{Deref, DerefMut};
  14use futures::{channel::oneshot, future::LocalBoxFuture, Future};
  15use slotmap::SlotMap;
  16use smol::future::FutureExt;
  17use time::UtcOffset;
  18
  19pub use async_context::*;
  20use collections::{FxHashMap, FxHashSet, VecDeque};
  21pub use entity_map::*;
  22pub use model_context::*;
  23#[cfg(any(test, feature = "test-support"))]
  24pub use test_context::*;
  25use util::{
  26    http::{self, HttpClient},
  27    ResultExt,
  28};
  29
  30use crate::{
  31    current_platform, image_cache::ImageCache, init_app_menus, Action, ActionRegistry, Any,
  32    AnyView, AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
  33    DispatchPhase, Entity, EventEmitter, ForegroundExecutor, Global, KeyBinding, Keymap, Keystroke,
  34    LayoutId, Menu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, PromptBuilder,
  35    PromptHandle, PromptLevel, Render, RenderablePromptHandle, SharedString, SubscriberSet,
  36    Subscription, SvgRenderer, Task, TextSystem, View, ViewContext, Window, WindowAppearance,
  37    WindowContext, WindowHandle, WindowId,
  38};
  39
  40mod async_context;
  41mod entity_map;
  42mod model_context;
  43#[cfg(any(test, feature = "test-support"))]
  44mod test_context;
  45
  46/// The duration for which futures returned from [AppContext::on_app_context] or [ModelContext::on_app_quit] can run before the application fully quits.
  47pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
  48
  49/// Temporary(?) wrapper around [`RefCell<AppContext>`] to help us debug any double borrows.
  50/// Strongly consider removing after stabilization.
  51#[doc(hidden)]
  52pub struct AppCell {
  53    app: RefCell<AppContext>,
  54}
  55
  56impl AppCell {
  57    #[doc(hidden)]
  58    #[track_caller]
  59    pub fn borrow(&self) -> AppRef {
  60        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  61            let thread_id = std::thread::current().id();
  62            eprintln!("borrowed {thread_id:?}");
  63        }
  64        AppRef(self.app.borrow())
  65    }
  66
  67    #[doc(hidden)]
  68    #[track_caller]
  69    pub fn borrow_mut(&self) -> AppRefMut {
  70        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  71            let thread_id = std::thread::current().id();
  72            eprintln!("borrowed {thread_id:?}");
  73        }
  74        AppRefMut(self.app.borrow_mut())
  75    }
  76}
  77
  78#[doc(hidden)]
  79#[derive(Deref, DerefMut)]
  80pub struct AppRef<'a>(Ref<'a, AppContext>);
  81
  82impl<'a> Drop for AppRef<'a> {
  83    fn drop(&mut self) {
  84        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  85            let thread_id = std::thread::current().id();
  86            eprintln!("dropped borrow from {thread_id:?}");
  87        }
  88    }
  89}
  90
  91#[doc(hidden)]
  92#[derive(Deref, DerefMut)]
  93pub struct AppRefMut<'a>(RefMut<'a, AppContext>);
  94
  95impl<'a> Drop for AppRefMut<'a> {
  96    fn drop(&mut self) {
  97        if option_env!("TRACK_THREAD_BORROWS").is_some() {
  98            let thread_id = std::thread::current().id();
  99            eprintln!("dropped {thread_id:?}");
 100        }
 101    }
 102}
 103
 104/// A reference to a GPUI application, typically constructed in the `main` function of your app.
 105/// You won't interact with this type much outside of initial configuration and startup.
 106pub struct App(Rc<AppCell>);
 107
 108/// Represents an application before it is fully launched. Once your app is
 109/// configured, you'll start the app with `App::run`.
 110impl App {
 111    /// Builds an app with the given asset source.
 112    #[allow(clippy::new_without_default)]
 113    pub fn new() -> Self {
 114        #[cfg(any(test, feature = "test-support"))]
 115        log::info!("GPUI was compiled in test mode");
 116
 117        Self(AppContext::new(
 118            current_platform(),
 119            Arc::new(()),
 120            http::client(),
 121        ))
 122    }
 123
 124    /// Assign
 125    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
 126        let mut context_lock = self.0.borrow_mut();
 127        let asset_source = Arc::new(asset_source);
 128        context_lock.asset_source = asset_source.clone();
 129        context_lock.svg_renderer = SvgRenderer::new(asset_source);
 130        drop(context_lock);
 131        self
 132    }
 133
 134    /// Start the application. The provided callback will be called once the
 135    /// app is fully launched.
 136    pub fn run<F>(self, on_finish_launching: F)
 137    where
 138        F: 'static + FnOnce(&mut AppContext),
 139    {
 140        let this = self.0.clone();
 141        let platform = self.0.borrow().platform.clone();
 142        platform.run(Box::new(move || {
 143            let cx = &mut *this.borrow_mut();
 144            on_finish_launching(cx);
 145        }));
 146    }
 147
 148    /// Register a handler to be invoked when the platform instructs the application
 149    /// to open one or more URLs.
 150    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 151    where
 152        F: 'static + FnMut(Vec<String>),
 153    {
 154        self.0.borrow().platform.on_open_urls(Box::new(callback));
 155        self
 156    }
 157
 158    /// Invokes a handler when an already-running application is launched.
 159    /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
 160    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 161    where
 162        F: 'static + FnMut(&mut AppContext),
 163    {
 164        let this = Rc::downgrade(&self.0);
 165        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 166            if let Some(app) = this.upgrade() {
 167                callback(&mut app.borrow_mut());
 168            }
 169        }));
 170        self
 171    }
 172
 173    /// Returns metadata associated with the application
 174    pub fn metadata(&self) -> AppMetadata {
 175        self.0.borrow().app_metadata.clone()
 176    }
 177
 178    /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
 179    pub fn background_executor(&self) -> BackgroundExecutor {
 180        self.0.borrow().background_executor.clone()
 181    }
 182
 183    /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
 184    pub fn foreground_executor(&self) -> ForegroundExecutor {
 185        self.0.borrow().foreground_executor.clone()
 186    }
 187
 188    /// Returns a reference to the [`TextSystem`] associated with this app.
 189    pub fn text_system(&self) -> Arc<TextSystem> {
 190        self.0.borrow().text_system.clone()
 191    }
 192}
 193
 194type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
 195type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
 196type KeystrokeObserver = Box<dyn FnMut(&KeystrokeEvent, &mut WindowContext) + 'static>;
 197type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
 198type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
 199type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
 200
 201/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
 202/// Other contexts such as [ModelContext], [WindowContext], and [ViewContext] deref to this type, making it the most general context type.
 203/// You need a reference to an `AppContext` to access the state of a [Model].
 204pub struct AppContext {
 205    pub(crate) this: Weak<AppCell>,
 206    pub(crate) platform: Rc<dyn Platform>,
 207    app_metadata: AppMetadata,
 208    text_system: Arc<TextSystem>,
 209    flushing_effects: bool,
 210    pending_updates: usize,
 211    pub(crate) actions: Rc<ActionRegistry>,
 212    pub(crate) active_drag: Option<AnyDrag>,
 213    pub(crate) background_executor: BackgroundExecutor,
 214    pub(crate) foreground_executor: ForegroundExecutor,
 215    pub(crate) svg_renderer: SvgRenderer,
 216    asset_source: Arc<dyn AssetSource>,
 217    pub(crate) image_cache: ImageCache,
 218    pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
 219    pub(crate) entities: EntityMap,
 220    pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
 221    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
 222    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
 223    pub(crate) keymap: Rc<RefCell<Keymap>>,
 224    pub(crate) global_action_listeners:
 225        FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
 226    pending_effects: VecDeque<Effect>,
 227    pub(crate) pending_notifications: FxHashSet<EntityId>,
 228    pub(crate) pending_global_notifications: FxHashSet<TypeId>,
 229    pub(crate) observers: SubscriberSet<EntityId, Handler>,
 230    // TypeId is the type of the event that the listener callback expects
 231    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
 232    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
 233    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
 234    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
 235    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
 236    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
 237    pub(crate) propagate_event: bool,
 238    pub(crate) prompt_builder: Option<PromptBuilder>,
 239}
 240
 241impl AppContext {
 242    #[allow(clippy::new_ret_no_self)]
 243    pub(crate) fn new(
 244        platform: Rc<dyn Platform>,
 245        asset_source: Arc<dyn AssetSource>,
 246        http_client: Arc<dyn HttpClient>,
 247    ) -> Rc<AppCell> {
 248        let executor = platform.background_executor();
 249        let foreground_executor = platform.foreground_executor();
 250        assert!(
 251            executor.is_main_thread(),
 252            "must construct App on main thread"
 253        );
 254
 255        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 256        let entities = EntityMap::new();
 257
 258        let app_metadata = AppMetadata {
 259            os_name: platform.os_name(),
 260            os_version: platform.os_version().ok(),
 261            app_version: platform.app_version().ok(),
 262        };
 263
 264        let app = Rc::new_cyclic(|this| AppCell {
 265            app: RefCell::new(AppContext {
 266                this: this.clone(),
 267                platform: platform.clone(),
 268                app_metadata,
 269                text_system,
 270                actions: Rc::new(ActionRegistry::default()),
 271                flushing_effects: false,
 272                pending_updates: 0,
 273                active_drag: None,
 274                background_executor: executor,
 275                foreground_executor,
 276                svg_renderer: SvgRenderer::new(asset_source.clone()),
 277                asset_source,
 278                image_cache: ImageCache::new(http_client),
 279                globals_by_type: FxHashMap::default(),
 280                entities,
 281                new_view_observers: SubscriberSet::new(),
 282                window_handles: FxHashMap::default(),
 283                windows: SlotMap::with_key(),
 284                keymap: Rc::new(RefCell::new(Keymap::default())),
 285                global_action_listeners: FxHashMap::default(),
 286                pending_effects: VecDeque::new(),
 287                pending_notifications: FxHashSet::default(),
 288                pending_global_notifications: FxHashSet::default(),
 289                observers: SubscriberSet::new(),
 290                event_listeners: SubscriberSet::new(),
 291                release_listeners: SubscriberSet::new(),
 292                keystroke_observers: SubscriberSet::new(),
 293                global_observers: SubscriberSet::new(),
 294                quit_observers: SubscriberSet::new(),
 295                layout_id_buffer: Default::default(),
 296                propagate_event: true,
 297                prompt_builder: Some(PromptBuilder::Default),
 298            }),
 299        });
 300
 301        init_app_menus(platform.as_ref(), &mut app.borrow_mut());
 302
 303        platform.on_quit(Box::new({
 304            let cx = app.clone();
 305            move || {
 306                cx.borrow_mut().shutdown();
 307            }
 308        }));
 309
 310        app
 311    }
 312
 313    /// Quit the application gracefully. Handlers registered with [`ModelContext::on_app_quit`]
 314    /// will be given 100ms to complete before exiting.
 315    pub fn shutdown(&mut self) {
 316        let mut futures = Vec::new();
 317
 318        for observer in self.quit_observers.remove(&()) {
 319            futures.push(observer(self));
 320        }
 321
 322        self.windows.clear();
 323        self.window_handles.clear();
 324        self.flush_effects();
 325
 326        let futures = futures::future::join_all(futures);
 327        if self
 328            .background_executor
 329            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
 330            .is_err()
 331        {
 332            log::error!("timed out waiting on app_will_quit");
 333        }
 334    }
 335
 336    /// Gracefully quit the application via the platform's standard routine.
 337    pub fn quit(&mut self) {
 338        self.platform.quit();
 339    }
 340
 341    /// Get metadata about the app and platform.
 342    pub fn app_metadata(&self) -> AppMetadata {
 343        self.app_metadata.clone()
 344    }
 345
 346    /// Schedules all windows in the application to be redrawn. This can be called
 347    /// multiple times in an update cycle and still result in a single redraw.
 348    pub fn refresh(&mut self) {
 349        self.pending_effects.push_back(Effect::Refresh);
 350    }
 351
 352    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
 353        self.pending_updates += 1;
 354        let result = update(self);
 355        if !self.flushing_effects && self.pending_updates == 1 {
 356            self.flushing_effects = true;
 357            self.flush_effects();
 358            self.flushing_effects = false;
 359        }
 360        self.pending_updates -= 1;
 361        result
 362    }
 363
 364    /// Arrange a callback to be invoked when the given model or view calls `notify` on its respective context.
 365    pub fn observe<W, E>(
 366        &mut self,
 367        entity: &E,
 368        mut on_notify: impl FnMut(E, &mut AppContext) + 'static,
 369    ) -> Subscription
 370    where
 371        W: 'static,
 372        E: Entity<W>,
 373    {
 374        self.observe_internal(entity, move |e, cx| {
 375            on_notify(e, cx);
 376            true
 377        })
 378    }
 379
 380    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
 381        let (subscription, activate) = self.observers.insert(key, value);
 382        self.defer(move |_| activate());
 383        subscription
 384    }
 385    pub(crate) fn observe_internal<W, E>(
 386        &mut self,
 387        entity: &E,
 388        mut on_notify: impl FnMut(E, &mut AppContext) -> bool + 'static,
 389    ) -> Subscription
 390    where
 391        W: 'static,
 392        E: Entity<W>,
 393    {
 394        let entity_id = entity.entity_id();
 395        let handle = entity.downgrade();
 396        self.new_observer(
 397            entity_id,
 398            Box::new(move |cx| {
 399                if let Some(handle) = E::upgrade_from(&handle) {
 400                    on_notify(handle, cx)
 401                } else {
 402                    false
 403                }
 404            }),
 405        )
 406    }
 407
 408    /// Arrange for the given callback to be invoked whenever the given model or view emits an event of a given type.
 409    /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
 410    pub fn subscribe<T, E, Event>(
 411        &mut self,
 412        entity: &E,
 413        mut on_event: impl FnMut(E, &Event, &mut AppContext) + 'static,
 414    ) -> Subscription
 415    where
 416        T: 'static + EventEmitter<Event>,
 417        E: Entity<T>,
 418        Event: 'static,
 419    {
 420        self.subscribe_internal(entity, move |entity, event, cx| {
 421            on_event(entity, event, cx);
 422            true
 423        })
 424    }
 425
 426    pub(crate) fn new_subscription(
 427        &mut self,
 428        key: EntityId,
 429        value: (TypeId, Listener),
 430    ) -> Subscription {
 431        let (subscription, activate) = self.event_listeners.insert(key, value);
 432        self.defer(move |_| activate());
 433        subscription
 434    }
 435    pub(crate) fn subscribe_internal<T, E, Evt>(
 436        &mut self,
 437        entity: &E,
 438        mut on_event: impl FnMut(E, &Evt, &mut AppContext) -> bool + 'static,
 439    ) -> Subscription
 440    where
 441        T: 'static + EventEmitter<Evt>,
 442        E: Entity<T>,
 443        Evt: 'static,
 444    {
 445        let entity_id = entity.entity_id();
 446        let entity = entity.downgrade();
 447        self.new_subscription(
 448            entity_id,
 449            (
 450                TypeId::of::<Evt>(),
 451                Box::new(move |event, cx| {
 452                    let event: &Evt = event.downcast_ref().expect("invalid event type");
 453                    if let Some(handle) = E::upgrade_from(&entity) {
 454                        on_event(handle, event, cx)
 455                    } else {
 456                        false
 457                    }
 458                }),
 459            ),
 460        )
 461    }
 462
 463    /// Returns handles to all open windows in the application.
 464    /// Each handle could be downcast to a handle typed for the root view of that window.
 465    /// To find all windows of a given type, you could filter on
 466    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 467        self.windows
 468            .keys()
 469            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
 470            .collect()
 471    }
 472
 473    /// Returns a handle to the window that is currently focused at the platform level, if one exists.
 474    pub fn active_window(&self) -> Option<AnyWindowHandle> {
 475        self.platform.active_window()
 476    }
 477
 478    /// Opens a new window with the given option and the root view returned by the given function.
 479    /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
 480    /// functionality.
 481    pub fn open_window<V: 'static + Render>(
 482        &mut self,
 483        options: crate::WindowOptions,
 484        build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
 485    ) -> WindowHandle<V> {
 486        self.update(|cx| {
 487            let id = cx.windows.insert(None);
 488            let handle = WindowHandle::new(id);
 489            let mut window = Window::new(handle.into(), options, cx);
 490            let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
 491            window.root_view.replace(root_view.into());
 492            cx.window_handles.insert(id, window.handle);
 493            cx.windows.get_mut(id).unwrap().replace(window);
 494            handle
 495        })
 496    }
 497
 498    /// Instructs the platform to activate the application by bringing it to the foreground.
 499    pub fn activate(&self, ignoring_other_apps: bool) {
 500        self.platform.activate(ignoring_other_apps);
 501    }
 502
 503    /// Hide the application at the platform level.
 504    pub fn hide(&self) {
 505        self.platform.hide();
 506    }
 507
 508    /// Hide other applications at the platform level.
 509    pub fn hide_other_apps(&self) {
 510        self.platform.hide_other_apps();
 511    }
 512
 513    /// Unhide other applications at the platform level.
 514    pub fn unhide_other_apps(&self) {
 515        self.platform.unhide_other_apps();
 516    }
 517
 518    /// Returns the list of currently active displays.
 519    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 520        self.platform.displays()
 521    }
 522
 523    /// Returns the primary display that will be used for new windows.
 524    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 525        self.platform.primary_display()
 526    }
 527
 528    /// Returns the appearance of the application's windows.
 529    pub fn window_appearance(&self) -> WindowAppearance {
 530        self.platform.window_appearance()
 531    }
 532
 533    /// Writes data to the platform clipboard.
 534    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 535        self.platform.write_to_clipboard(item)
 536    }
 537
 538    /// Reads data from the platform clipboard.
 539    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 540        self.platform.read_from_clipboard()
 541    }
 542
 543    /// Writes credentials to the platform keychain.
 544    pub fn write_credentials(
 545        &self,
 546        url: &str,
 547        username: &str,
 548        password: &[u8],
 549    ) -> Task<Result<()>> {
 550        self.platform.write_credentials(url, username, password)
 551    }
 552
 553    /// Reads credentials from the platform keychain.
 554    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 555        self.platform.read_credentials(url)
 556    }
 557
 558    /// Deletes credentials from the platform keychain.
 559    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 560        self.platform.delete_credentials(url)
 561    }
 562
 563    /// Directs the platform's default browser to open the given URL.
 564    pub fn open_url(&self, url: &str) {
 565        self.platform.open_url(url);
 566    }
 567
 568    /// register_url_scheme requests that the given scheme (e.g. `zed` for `zed://` urls)
 569    /// is opened by the current app.
 570    /// On some platforms (e.g. macOS) you may be able to register URL schemes as part of app
 571    /// distribution, but this method exists to let you register schemes at runtime.
 572    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
 573        self.platform.register_url_scheme(scheme)
 574    }
 575
 576    /// Returns the full pathname of the current app bundle.
 577    /// If the app is not being run from a bundle, returns an error.
 578    pub fn app_path(&self) -> Result<PathBuf> {
 579        self.platform.app_path()
 580    }
 581
 582    /// Returns the file URL of the executable with the specified name in the application bundle
 583    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 584        self.platform.path_for_auxiliary_executable(name)
 585    }
 586
 587    /// Returns the maximum duration in which a second mouse click must occur for an event to be a double-click event.
 588    pub fn double_click_interval(&self) -> Duration {
 589        self.platform.double_click_interval()
 590    }
 591
 592    /// Displays a platform modal for selecting paths.
 593    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
 594    /// If cancelled, a `None` will be relayed instead.
 595    pub fn prompt_for_paths(
 596        &self,
 597        options: PathPromptOptions,
 598    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 599        self.platform.prompt_for_paths(options)
 600    }
 601
 602    /// Displays a platform modal for selecting a new path where a file can be saved.
 603    /// The provided directory will be used to set the initial location.
 604    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
 605    /// If cancelled, a `None` will be relayed instead.
 606    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 607        self.platform.prompt_for_new_path(directory)
 608    }
 609
 610    /// Reveals the specified path at the platform level, such as in Finder on macOS.
 611    pub fn reveal_path(&self, path: &Path) {
 612        self.platform.reveal_path(path)
 613    }
 614
 615    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
 616    pub fn should_auto_hide_scrollbars(&self) -> bool {
 617        self.platform.should_auto_hide_scrollbars()
 618    }
 619
 620    /// Restart the application.
 621    pub fn restart(&self) {
 622        self.platform.restart()
 623    }
 624
 625    /// Returns the local timezone at the platform level.
 626    pub fn local_timezone(&self) -> UtcOffset {
 627        self.platform.local_timezone()
 628    }
 629
 630    pub(crate) fn push_effect(&mut self, effect: Effect) {
 631        match &effect {
 632            Effect::Notify { emitter } => {
 633                if !self.pending_notifications.insert(*emitter) {
 634                    return;
 635                }
 636            }
 637            Effect::NotifyGlobalObservers { global_type } => {
 638                if !self.pending_global_notifications.insert(*global_type) {
 639                    return;
 640                }
 641            }
 642            _ => {}
 643        };
 644
 645        self.pending_effects.push_back(effect);
 646    }
 647
 648    /// Called at the end of [`AppContext::update`] to complete any side effects
 649    /// such as notifying observers, emitting events, etc. Effects can themselves
 650    /// cause effects, so we continue looping until all effects are processed.
 651    fn flush_effects(&mut self) {
 652        loop {
 653            self.release_dropped_entities();
 654            self.release_dropped_focus_handles();
 655
 656            if let Some(effect) = self.pending_effects.pop_front() {
 657                match effect {
 658                    Effect::Notify { emitter } => {
 659                        self.apply_notify_effect(emitter);
 660                    }
 661
 662                    Effect::Emit {
 663                        emitter,
 664                        event_type,
 665                        event,
 666                    } => self.apply_emit_effect(emitter, event_type, event),
 667
 668                    Effect::Refresh => {
 669                        self.apply_refresh_effect();
 670                    }
 671
 672                    Effect::NotifyGlobalObservers { global_type } => {
 673                        self.apply_notify_global_observers_effect(global_type);
 674                    }
 675
 676                    Effect::Defer { callback } => {
 677                        self.apply_defer_effect(callback);
 678                    }
 679                }
 680            } else {
 681                #[cfg(any(test, feature = "test-support"))]
 682                for window in self
 683                    .windows
 684                    .values()
 685                    .filter_map(|window| {
 686                        let window = window.as_ref()?;
 687                        window.dirty.get().then_some(window.handle)
 688                    })
 689                    .collect::<Vec<_>>()
 690                {
 691                    self.update_window(window, |_, cx| cx.draw()).unwrap();
 692                }
 693
 694                if self.pending_effects.is_empty() {
 695                    break;
 696                }
 697            }
 698        }
 699    }
 700
 701    /// Repeatedly called during `flush_effects` to release any entities whose
 702    /// reference count has become zero. We invoke any release observers before dropping
 703    /// each entity.
 704    fn release_dropped_entities(&mut self) {
 705        loop {
 706            let dropped = self.entities.take_dropped();
 707            if dropped.is_empty() {
 708                break;
 709            }
 710
 711            for (entity_id, mut entity) in dropped {
 712                self.observers.remove(&entity_id);
 713                self.event_listeners.remove(&entity_id);
 714                for release_callback in self.release_listeners.remove(&entity_id) {
 715                    release_callback(entity.as_mut(), self);
 716                }
 717            }
 718        }
 719    }
 720
 721    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 722    fn release_dropped_focus_handles(&mut self) {
 723        for window_handle in self.windows() {
 724            window_handle
 725                .update(self, |_, cx| {
 726                    let mut blur_window = false;
 727                    let focus = cx.window.focus;
 728                    cx.window.focus_handles.write().retain(|handle_id, count| {
 729                        if count.load(SeqCst) == 0 {
 730                            if focus == Some(handle_id) {
 731                                blur_window = true;
 732                            }
 733                            false
 734                        } else {
 735                            true
 736                        }
 737                    });
 738
 739                    if blur_window {
 740                        cx.blur();
 741                    }
 742                })
 743                .unwrap();
 744        }
 745    }
 746
 747    fn apply_notify_effect(&mut self, emitter: EntityId) {
 748        self.pending_notifications.remove(&emitter);
 749
 750        self.observers
 751            .clone()
 752            .retain(&emitter, |handler| handler(self));
 753    }
 754
 755    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 756        self.event_listeners
 757            .clone()
 758            .retain(&emitter, |(stored_type, handler)| {
 759                if *stored_type == event_type {
 760                    handler(event.as_ref(), self)
 761                } else {
 762                    true
 763                }
 764            });
 765    }
 766
 767    fn apply_refresh_effect(&mut self) {
 768        for window in self.windows.values_mut() {
 769            if let Some(window) = window.as_mut() {
 770                window.dirty.set(true);
 771            }
 772        }
 773    }
 774
 775    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
 776        self.pending_global_notifications.remove(&type_id);
 777        self.global_observers
 778            .clone()
 779            .retain(&type_id, |observer| observer(self));
 780    }
 781
 782    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
 783        callback(self);
 784    }
 785
 786    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
 787    /// so it can be held across `await` points.
 788    pub fn to_async(&self) -> AsyncAppContext {
 789        AsyncAppContext {
 790            app: self.this.clone(),
 791            background_executor: self.background_executor.clone(),
 792            foreground_executor: self.foreground_executor.clone(),
 793        }
 794    }
 795
 796    /// Obtains a reference to the executor, which can be used to spawn futures.
 797    pub fn background_executor(&self) -> &BackgroundExecutor {
 798        &self.background_executor
 799    }
 800
 801    /// Obtains a reference to the executor, which can be used to spawn futures.
 802    pub fn foreground_executor(&self) -> &ForegroundExecutor {
 803        &self.foreground_executor
 804    }
 805
 806    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
 807    /// with [AsyncAppContext], which allows the application state to be accessed across await points.
 808    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
 809    where
 810        Fut: Future<Output = R> + 'static,
 811        R: 'static,
 812    {
 813        self.foreground_executor.spawn(f(self.to_async()))
 814    }
 815
 816    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 817    /// that are currently on the stack to be returned to the app.
 818    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
 819        self.push_effect(Effect::Defer {
 820            callback: Box::new(f),
 821        });
 822    }
 823
 824    /// Accessor for the application's asset source, which is provided when constructing the `App`.
 825    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
 826        &self.asset_source
 827    }
 828
 829    /// Accessor for the text system.
 830    pub fn text_system(&self) -> &Arc<TextSystem> {
 831        &self.text_system
 832    }
 833
 834    /// Check whether a global of the given type has been assigned.
 835    pub fn has_global<G: Global>(&self) -> bool {
 836        self.globals_by_type.contains_key(&TypeId::of::<G>())
 837    }
 838
 839    /// Access the global of the given type. Panics if a global for that type has not been assigned.
 840    #[track_caller]
 841    pub fn global<G: Global>(&self) -> &G {
 842        self.globals_by_type
 843            .get(&TypeId::of::<G>())
 844            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 845            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 846            .unwrap()
 847    }
 848
 849    /// Access the global of the given type if a value has been assigned.
 850    pub fn try_global<G: Global>(&self) -> Option<&G> {
 851        self.globals_by_type
 852            .get(&TypeId::of::<G>())
 853            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 854    }
 855
 856    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
 857    #[track_caller]
 858    pub fn global_mut<G: Global>(&mut self) -> &mut G {
 859        let global_type = TypeId::of::<G>();
 860        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 861        self.globals_by_type
 862            .get_mut(&global_type)
 863            .and_then(|any_state| any_state.downcast_mut::<G>())
 864            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 865            .unwrap()
 866    }
 867
 868    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
 869    /// yet been assigned.
 870    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
 871        let global_type = TypeId::of::<G>();
 872        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 873        self.globals_by_type
 874            .entry(global_type)
 875            .or_insert_with(|| Box::<G>::default())
 876            .downcast_mut::<G>()
 877            .unwrap()
 878    }
 879
 880    /// Sets the value of the global of the given type.
 881    pub fn set_global<G: Global>(&mut self, global: G) {
 882        let global_type = TypeId::of::<G>();
 883        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 884        self.globals_by_type.insert(global_type, Box::new(global));
 885    }
 886
 887    /// Clear all stored globals. Does not notify global observers.
 888    #[cfg(any(test, feature = "test-support"))]
 889    pub fn clear_globals(&mut self) {
 890        self.globals_by_type.drain();
 891    }
 892
 893    /// Remove the global of the given type from the app context. Does not notify global observers.
 894    pub fn remove_global<G: Global>(&mut self) -> G {
 895        let global_type = TypeId::of::<G>();
 896        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 897        *self
 898            .globals_by_type
 899            .remove(&global_type)
 900            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
 901            .downcast()
 902            .unwrap()
 903    }
 904
 905    /// Updates the global of the given type with a closure. Unlike `global_mut`, this method provides
 906    /// your closure with mutable access to the `AppContext` and the global simultaneously.
 907    pub fn update_global<G: Global, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
 908        self.update(|cx| {
 909            let mut global = cx.lease_global::<G>();
 910            let result = f(&mut global, cx);
 911            cx.end_global_lease(global);
 912            result
 913        })
 914    }
 915
 916    /// Register a callback to be invoked when a global of the given type is updated.
 917    pub fn observe_global<G: Global>(
 918        &mut self,
 919        mut f: impl FnMut(&mut Self) + 'static,
 920    ) -> Subscription {
 921        let (subscription, activate) = self.global_observers.insert(
 922            TypeId::of::<G>(),
 923            Box::new(move |cx| {
 924                f(cx);
 925                true
 926            }),
 927        );
 928        self.defer(move |_| activate());
 929        subscription
 930    }
 931
 932    /// Move the global of the given type to the stack.
 933    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
 934        GlobalLease::new(
 935            self.globals_by_type
 936                .remove(&TypeId::of::<G>())
 937                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
 938                .unwrap(),
 939        )
 940    }
 941
 942    /// Restore the global of the given type after it is moved to the stack.
 943    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
 944        let global_type = TypeId::of::<G>();
 945        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 946        self.globals_by_type.insert(global_type, lease.global);
 947    }
 948
 949    pub(crate) fn new_view_observer(
 950        &mut self,
 951        key: TypeId,
 952        value: NewViewListener,
 953    ) -> Subscription {
 954        let (subscription, activate) = self.new_view_observers.insert(key, value);
 955        activate();
 956        subscription
 957    }
 958    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
 959    /// The function will be passed a mutable reference to the view along with an appropriate context.
 960    pub fn observe_new_views<V: 'static>(
 961        &mut self,
 962        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
 963    ) -> Subscription {
 964        self.new_view_observer(
 965            TypeId::of::<V>(),
 966            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
 967                any_view
 968                    .downcast::<V>()
 969                    .unwrap()
 970                    .update(cx, |view_state, cx| {
 971                        on_new(view_state, cx);
 972                    })
 973            }),
 974        )
 975    }
 976
 977    /// Observe the release of a model or view. The callback is invoked after the model or view
 978    /// has no more strong references but before it has been dropped.
 979    pub fn observe_release<E, T>(
 980        &mut self,
 981        handle: &E,
 982        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
 983    ) -> Subscription
 984    where
 985        E: Entity<T>,
 986        T: 'static,
 987    {
 988        let (subscription, activate) = self.release_listeners.insert(
 989            handle.entity_id(),
 990            Box::new(move |entity, cx| {
 991                let entity = entity.downcast_mut().expect("invalid entity type");
 992                on_release(entity, cx)
 993            }),
 994        );
 995        activate();
 996        subscription
 997    }
 998
 999    /// Register a callback to be invoked when a keystroke is received by the application
1000    /// in any window. Note that this fires after all other action and event mechanisms have resolved
1001    /// and that this API will not be invoked if the event's propagation is stopped.
1002    pub fn observe_keystrokes(
1003        &mut self,
1004        f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
1005    ) -> Subscription {
1006        fn inner(
1007            keystroke_observers: &mut SubscriberSet<(), KeystrokeObserver>,
1008            handler: KeystrokeObserver,
1009        ) -> Subscription {
1010            let (subscription, activate) = keystroke_observers.insert((), handler);
1011            activate();
1012            subscription
1013        }
1014        inner(&mut self.keystroke_observers, Box::new(f))
1015    }
1016
1017    /// Register key bindings.
1018    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1019        self.keymap.borrow_mut().add_bindings(bindings);
1020        self.pending_effects.push_back(Effect::Refresh);
1021    }
1022
1023    /// Clear all key bindings in the app.
1024    pub fn clear_key_bindings(&mut self) {
1025        self.keymap.borrow_mut().clear();
1026        self.pending_effects.push_back(Effect::Refresh);
1027    }
1028
1029    /// Register a global listener for actions invoked via the keyboard.
1030    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1031        self.global_action_listeners
1032            .entry(TypeId::of::<A>())
1033            .or_default()
1034            .push(Rc::new(move |action, phase, cx| {
1035                if phase == DispatchPhase::Bubble {
1036                    let action = action.downcast_ref().unwrap();
1037                    listener(action, cx)
1038                }
1039            }));
1040    }
1041
1042    /// Event handlers propagate events by default. Call this method to stop dispatching to
1043    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1044    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1045    /// calling this method before effects are flushed.
1046    pub fn stop_propagation(&mut self) {
1047        self.propagate_event = false;
1048    }
1049
1050    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1051    /// dispatching to action handlers higher in the element tree. This is the opposite of
1052    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1053    /// this method before effects are flushed.
1054    pub fn propagate(&mut self) {
1055        self.propagate_event = true;
1056    }
1057
1058    /// Build an action from some arbitrary data, typically a keymap entry.
1059    pub fn build_action(
1060        &self,
1061        name: &str,
1062        data: Option<serde_json::Value>,
1063    ) -> Result<Box<dyn Action>> {
1064        self.actions.build_action(name, data)
1065    }
1066
1067    /// Get a list of all action names that have been registered.
1068    /// in the application. Note that registration only allows for
1069    /// actions to be built dynamically, and is unrelated to binding
1070    /// actions in the element tree.
1071    pub fn all_action_names(&self) -> &[SharedString] {
1072        self.actions.all_action_names()
1073    }
1074
1075    /// Register a callback to be invoked when the application is about to quit.
1076    /// It is not possible to cancel the quit event at this point.
1077    pub fn on_app_quit<Fut>(
1078        &mut self,
1079        mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1080    ) -> Subscription
1081    where
1082        Fut: 'static + Future<Output = ()>,
1083    {
1084        let (subscription, activate) = self.quit_observers.insert(
1085            (),
1086            Box::new(move |cx| {
1087                let future = on_quit(cx);
1088                future.boxed_local()
1089            }),
1090        );
1091        activate();
1092        subscription
1093    }
1094
1095    pub(crate) fn clear_pending_keystrokes(&mut self) {
1096        for window in self.windows() {
1097            window
1098                .update(self, |_, cx| {
1099                    cx.window
1100                        .rendered_frame
1101                        .dispatch_tree
1102                        .clear_pending_keystrokes();
1103                    cx.window
1104                        .next_frame
1105                        .dispatch_tree
1106                        .clear_pending_keystrokes();
1107                })
1108                .ok();
1109        }
1110    }
1111
1112    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1113    /// the bindings in the element tree, and any global action listeners.
1114    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1115        let mut action_available = false;
1116        if let Some(window) = self.active_window() {
1117            if let Ok(window_action_available) =
1118                window.update(self, |_, cx| cx.is_action_available(action))
1119            {
1120                action_available = window_action_available;
1121            }
1122        }
1123
1124        action_available
1125            || self
1126                .global_action_listeners
1127                .contains_key(&action.as_any().type_id())
1128    }
1129
1130    /// Sets the menu bar for this application. This will replace any existing menu bar.
1131    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1132        self.platform.set_menus(menus, &self.keymap.borrow());
1133    }
1134
1135    /// Dispatch an action to the currently active window or global action handler
1136    /// See [action::Action] for more information on how actions work
1137    pub fn dispatch_action(&mut self, action: &dyn Action) {
1138        if let Some(active_window) = self.active_window() {
1139            active_window
1140                .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1141                .log_err();
1142        } else {
1143            self.dispatch_global_action(action);
1144        }
1145    }
1146
1147    fn dispatch_global_action(&mut self, action: &dyn Action) {
1148        self.propagate_event = true;
1149
1150        if let Some(mut global_listeners) = self
1151            .global_action_listeners
1152            .remove(&action.as_any().type_id())
1153        {
1154            for listener in &global_listeners {
1155                listener(action.as_any(), DispatchPhase::Capture, self);
1156                if !self.propagate_event {
1157                    break;
1158                }
1159            }
1160
1161            global_listeners.extend(
1162                self.global_action_listeners
1163                    .remove(&action.as_any().type_id())
1164                    .unwrap_or_default(),
1165            );
1166
1167            self.global_action_listeners
1168                .insert(action.as_any().type_id(), global_listeners);
1169        }
1170
1171        if self.propagate_event {
1172            if let Some(mut global_listeners) = self
1173                .global_action_listeners
1174                .remove(&action.as_any().type_id())
1175            {
1176                for listener in global_listeners.iter().rev() {
1177                    listener(action.as_any(), DispatchPhase::Bubble, self);
1178                    if !self.propagate_event {
1179                        break;
1180                    }
1181                }
1182
1183                global_listeners.extend(
1184                    self.global_action_listeners
1185                        .remove(&action.as_any().type_id())
1186                        .unwrap_or_default(),
1187                );
1188
1189                self.global_action_listeners
1190                    .insert(action.as_any().type_id(), global_listeners);
1191            }
1192        }
1193    }
1194
1195    /// Is there currently something being dragged?
1196    pub fn has_active_drag(&self) -> bool {
1197        self.active_drag.is_some()
1198    }
1199
1200    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1201    /// prompts with this custom implementation.
1202    pub fn set_prompt_builder(
1203        &mut self,
1204        renderer: impl Fn(
1205                PromptLevel,
1206                &str,
1207                Option<&str>,
1208                &[&str],
1209                PromptHandle,
1210                &mut WindowContext,
1211            ) -> RenderablePromptHandle
1212            + 'static,
1213    ) {
1214        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1215    }
1216}
1217
1218impl Context for AppContext {
1219    type Result<T> = T;
1220
1221    /// Build an entity that is owned by the application. The given function will be invoked with
1222    /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1223    /// which can be used to access the entity in a context.
1224    fn new_model<T: 'static>(
1225        &mut self,
1226        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1227    ) -> Model<T> {
1228        self.update(|cx| {
1229            let slot = cx.entities.reserve();
1230            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1231            cx.entities.insert(slot, entity)
1232        })
1233    }
1234
1235    /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1236    /// entity along with a `ModelContext` for the entity.
1237    fn update_model<T: 'static, R>(
1238        &mut self,
1239        model: &Model<T>,
1240        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1241    ) -> R {
1242        self.update(|cx| {
1243            let mut entity = cx.entities.lease(model);
1244            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1245            cx.entities.end_lease(entity);
1246            result
1247        })
1248    }
1249
1250    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1251    where
1252        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1253    {
1254        self.update(|cx| {
1255            let mut window = cx
1256                .windows
1257                .get_mut(handle.id)
1258                .ok_or_else(|| anyhow!("window not found"))?
1259                .take()
1260                .ok_or_else(|| anyhow!("window not found"))?;
1261
1262            let root_view = window.root_view.clone().unwrap();
1263            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1264
1265            if window.removed {
1266                cx.window_handles.remove(&handle.id);
1267                cx.windows.remove(handle.id);
1268            } else {
1269                cx.windows
1270                    .get_mut(handle.id)
1271                    .ok_or_else(|| anyhow!("window not found"))?
1272                    .replace(window);
1273            }
1274
1275            Ok(result)
1276        })
1277    }
1278
1279    fn read_model<T, R>(
1280        &self,
1281        handle: &Model<T>,
1282        read: impl FnOnce(&T, &AppContext) -> R,
1283    ) -> Self::Result<R>
1284    where
1285        T: 'static,
1286    {
1287        let entity = self.entities.read(handle);
1288        read(entity, self)
1289    }
1290
1291    fn read_window<T, R>(
1292        &self,
1293        window: &WindowHandle<T>,
1294        read: impl FnOnce(View<T>, &AppContext) -> R,
1295    ) -> Result<R>
1296    where
1297        T: 'static,
1298    {
1299        let window = self
1300            .windows
1301            .get(window.id)
1302            .ok_or_else(|| anyhow!("window not found"))?
1303            .as_ref()
1304            .unwrap();
1305
1306        let root_view = window.root_view.clone().unwrap();
1307        let view = root_view
1308            .downcast::<T>()
1309            .map_err(|_| anyhow!("root view's type has changed"))?;
1310
1311        Ok(read(view, self))
1312    }
1313}
1314
1315/// These effects are processed at the end of each application update cycle.
1316pub(crate) enum Effect {
1317    Notify {
1318        emitter: EntityId,
1319    },
1320    Emit {
1321        emitter: EntityId,
1322        event_type: TypeId,
1323        event: Box<dyn Any>,
1324    },
1325    Refresh,
1326    NotifyGlobalObservers {
1327        global_type: TypeId,
1328    },
1329    Defer {
1330        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1331    },
1332}
1333
1334/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1335pub(crate) struct GlobalLease<G: Global> {
1336    global: Box<dyn Any>,
1337    global_type: PhantomData<G>,
1338}
1339
1340impl<G: Global> GlobalLease<G> {
1341    fn new(global: Box<dyn Any>) -> Self {
1342        GlobalLease {
1343            global,
1344            global_type: PhantomData,
1345        }
1346    }
1347}
1348
1349impl<G: Global> Deref for GlobalLease<G> {
1350    type Target = G;
1351
1352    fn deref(&self) -> &Self::Target {
1353        self.global.downcast_ref().unwrap()
1354    }
1355}
1356
1357impl<G: Global> DerefMut for GlobalLease<G> {
1358    fn deref_mut(&mut self) -> &mut Self::Target {
1359        self.global.downcast_mut().unwrap()
1360    }
1361}
1362
1363/// Contains state associated with an active drag operation, started by dragging an element
1364/// within the window or by dragging into the app from the underlying platform.
1365pub struct AnyDrag {
1366    /// The view used to render this drag
1367    pub view: AnyView,
1368
1369    /// The value of the dragged item, to be dropped
1370    pub value: Box<dyn Any>,
1371
1372    /// This is used to render the dragged item in the same place
1373    /// on the original element that the drag was initiated
1374    pub cursor_offset: Point<Pixels>,
1375}
1376
1377/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1378/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1379#[derive(Clone)]
1380pub struct AnyTooltip {
1381    /// The view used to display the tooltip
1382    pub view: AnyView,
1383
1384    /// The offset from the cursor to use, relative to the parent view
1385    pub cursor_offset: Point<Pixels>,
1386}
1387
1388/// A keystroke event, and potentially the associated action
1389#[derive(Debug)]
1390pub struct KeystrokeEvent {
1391    /// The keystroke that occurred
1392    pub keystroke: Keystroke,
1393
1394    /// The action that was resolved for the keystroke, if any
1395    pub action: Option<Box<dyn Action>>,
1396}