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, DisplayId, Entity, EventEmitter, ForegroundExecutor, Global, KeyBinding, Keymap,
  34    Keystroke, LayoutId, Menu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point,
  35    PromptBuilder, PromptHandle, PromptLevel, Render, RenderablePromptHandle, SharedString,
  36    SubscriberSet, Subscription, SvgRenderer, Task, TextSystem, View, ViewContext, Window,
  37    WindowAppearance, 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 display with the given ID, if one exists.
 529    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 530        self.displays()
 531            .iter()
 532            .find(|display| display.id() == id)
 533            .cloned()
 534    }
 535
 536    /// Returns the appearance of the application's windows.
 537    pub fn window_appearance(&self) -> WindowAppearance {
 538        self.platform.window_appearance()
 539    }
 540
 541    /// Writes data to the platform clipboard.
 542    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 543        self.platform.write_to_clipboard(item)
 544    }
 545
 546    /// Reads data from the platform clipboard.
 547    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 548        self.platform.read_from_clipboard()
 549    }
 550
 551    /// Writes credentials to the platform keychain.
 552    pub fn write_credentials(
 553        &self,
 554        url: &str,
 555        username: &str,
 556        password: &[u8],
 557    ) -> Task<Result<()>> {
 558        self.platform.write_credentials(url, username, password)
 559    }
 560
 561    /// Reads credentials from the platform keychain.
 562    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 563        self.platform.read_credentials(url)
 564    }
 565
 566    /// Deletes credentials from the platform keychain.
 567    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 568        self.platform.delete_credentials(url)
 569    }
 570
 571    /// Directs the platform's default browser to open the given URL.
 572    pub fn open_url(&self, url: &str) {
 573        self.platform.open_url(url);
 574    }
 575
 576    /// register_url_scheme requests that the given scheme (e.g. `zed` for `zed://` urls)
 577    /// is opened by the current app.
 578    /// On some platforms (e.g. macOS) you may be able to register URL schemes as part of app
 579    /// distribution, but this method exists to let you register schemes at runtime.
 580    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
 581        self.platform.register_url_scheme(scheme)
 582    }
 583
 584    /// Returns the full pathname of the current app bundle.
 585    /// If the app is not being run from a bundle, returns an error.
 586    pub fn app_path(&self) -> Result<PathBuf> {
 587        self.platform.app_path()
 588    }
 589
 590    /// Returns the file URL of the executable with the specified name in the application bundle
 591    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 592        self.platform.path_for_auxiliary_executable(name)
 593    }
 594
 595    /// Displays a platform modal for selecting paths.
 596    /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
 597    /// If cancelled, a `None` will be relayed instead.
 598    pub fn prompt_for_paths(
 599        &self,
 600        options: PathPromptOptions,
 601    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 602        self.platform.prompt_for_paths(options)
 603    }
 604
 605    /// Displays a platform modal for selecting a new path where a file can be saved.
 606    /// The provided directory will be used to set the initial location.
 607    /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
 608    /// If cancelled, a `None` will be relayed instead.
 609    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 610        self.platform.prompt_for_new_path(directory)
 611    }
 612
 613    /// Reveals the specified path at the platform level, such as in Finder on macOS.
 614    pub fn reveal_path(&self, path: &Path) {
 615        self.platform.reveal_path(path)
 616    }
 617
 618    /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
 619    pub fn should_auto_hide_scrollbars(&self) -> bool {
 620        self.platform.should_auto_hide_scrollbars()
 621    }
 622
 623    /// Restart the application.
 624    pub fn restart(&self) {
 625        self.platform.restart()
 626    }
 627
 628    /// Returns the local timezone at the platform level.
 629    pub fn local_timezone(&self) -> UtcOffset {
 630        self.platform.local_timezone()
 631    }
 632
 633    pub(crate) fn push_effect(&mut self, effect: Effect) {
 634        match &effect {
 635            Effect::Notify { emitter } => {
 636                if !self.pending_notifications.insert(*emitter) {
 637                    return;
 638                }
 639            }
 640            Effect::NotifyGlobalObservers { global_type } => {
 641                if !self.pending_global_notifications.insert(*global_type) {
 642                    return;
 643                }
 644            }
 645            _ => {}
 646        };
 647
 648        self.pending_effects.push_back(effect);
 649    }
 650
 651    /// Called at the end of [`AppContext::update`] to complete any side effects
 652    /// such as notifying observers, emitting events, etc. Effects can themselves
 653    /// cause effects, so we continue looping until all effects are processed.
 654    fn flush_effects(&mut self) {
 655        loop {
 656            self.release_dropped_entities();
 657            self.release_dropped_focus_handles();
 658
 659            if let Some(effect) = self.pending_effects.pop_front() {
 660                match effect {
 661                    Effect::Notify { emitter } => {
 662                        self.apply_notify_effect(emitter);
 663                    }
 664
 665                    Effect::Emit {
 666                        emitter,
 667                        event_type,
 668                        event,
 669                    } => self.apply_emit_effect(emitter, event_type, event),
 670
 671                    Effect::Refresh => {
 672                        self.apply_refresh_effect();
 673                    }
 674
 675                    Effect::NotifyGlobalObservers { global_type } => {
 676                        self.apply_notify_global_observers_effect(global_type);
 677                    }
 678
 679                    Effect::Defer { callback } => {
 680                        self.apply_defer_effect(callback);
 681                    }
 682                }
 683            } else {
 684                #[cfg(any(test, feature = "test-support"))]
 685                for window in self
 686                    .windows
 687                    .values()
 688                    .filter_map(|window| {
 689                        let window = window.as_ref()?;
 690                        window.dirty.get().then_some(window.handle)
 691                    })
 692                    .collect::<Vec<_>>()
 693                {
 694                    self.update_window(window, |_, cx| cx.draw()).unwrap();
 695                }
 696
 697                if self.pending_effects.is_empty() {
 698                    break;
 699                }
 700            }
 701        }
 702    }
 703
 704    /// Repeatedly called during `flush_effects` to release any entities whose
 705    /// reference count has become zero. We invoke any release observers before dropping
 706    /// each entity.
 707    fn release_dropped_entities(&mut self) {
 708        loop {
 709            let dropped = self.entities.take_dropped();
 710            if dropped.is_empty() {
 711                break;
 712            }
 713
 714            for (entity_id, mut entity) in dropped {
 715                self.observers.remove(&entity_id);
 716                self.event_listeners.remove(&entity_id);
 717                for release_callback in self.release_listeners.remove(&entity_id) {
 718                    release_callback(entity.as_mut(), self);
 719                }
 720            }
 721        }
 722    }
 723
 724    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
 725    fn release_dropped_focus_handles(&mut self) {
 726        for window_handle in self.windows() {
 727            window_handle
 728                .update(self, |_, cx| {
 729                    let mut blur_window = false;
 730                    let focus = cx.window.focus;
 731                    cx.window.focus_handles.write().retain(|handle_id, count| {
 732                        if count.load(SeqCst) == 0 {
 733                            if focus == Some(handle_id) {
 734                                blur_window = true;
 735                            }
 736                            false
 737                        } else {
 738                            true
 739                        }
 740                    });
 741
 742                    if blur_window {
 743                        cx.blur();
 744                    }
 745                })
 746                .unwrap();
 747        }
 748    }
 749
 750    fn apply_notify_effect(&mut self, emitter: EntityId) {
 751        self.pending_notifications.remove(&emitter);
 752
 753        self.observers
 754            .clone()
 755            .retain(&emitter, |handler| handler(self));
 756    }
 757
 758    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
 759        self.event_listeners
 760            .clone()
 761            .retain(&emitter, |(stored_type, handler)| {
 762                if *stored_type == event_type {
 763                    handler(event.as_ref(), self)
 764                } else {
 765                    true
 766                }
 767            });
 768    }
 769
 770    fn apply_refresh_effect(&mut self) {
 771        for window in self.windows.values_mut() {
 772            if let Some(window) = window.as_mut() {
 773                window.dirty.set(true);
 774            }
 775        }
 776    }
 777
 778    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
 779        self.pending_global_notifications.remove(&type_id);
 780        self.global_observers
 781            .clone()
 782            .retain(&type_id, |observer| observer(self));
 783    }
 784
 785    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
 786        callback(self);
 787    }
 788
 789    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
 790    /// so it can be held across `await` points.
 791    pub fn to_async(&self) -> AsyncAppContext {
 792        AsyncAppContext {
 793            app: self.this.clone(),
 794            background_executor: self.background_executor.clone(),
 795            foreground_executor: self.foreground_executor.clone(),
 796        }
 797    }
 798
 799    /// Obtains a reference to the executor, which can be used to spawn futures.
 800    pub fn background_executor(&self) -> &BackgroundExecutor {
 801        &self.background_executor
 802    }
 803
 804    /// Obtains a reference to the executor, which can be used to spawn futures.
 805    pub fn foreground_executor(&self) -> &ForegroundExecutor {
 806        &self.foreground_executor
 807    }
 808
 809    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
 810    /// with [AsyncAppContext], which allows the application state to be accessed across await points.
 811    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
 812    where
 813        Fut: Future<Output = R> + 'static,
 814        R: 'static,
 815    {
 816        self.foreground_executor.spawn(f(self.to_async()))
 817    }
 818
 819    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 820    /// that are currently on the stack to be returned to the app.
 821    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
 822        self.push_effect(Effect::Defer {
 823            callback: Box::new(f),
 824        });
 825    }
 826
 827    /// Accessor for the application's asset source, which is provided when constructing the `App`.
 828    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
 829        &self.asset_source
 830    }
 831
 832    /// Accessor for the text system.
 833    pub fn text_system(&self) -> &Arc<TextSystem> {
 834        &self.text_system
 835    }
 836
 837    /// Check whether a global of the given type has been assigned.
 838    pub fn has_global<G: Global>(&self) -> bool {
 839        self.globals_by_type.contains_key(&TypeId::of::<G>())
 840    }
 841
 842    /// Access the global of the given type. Panics if a global for that type has not been assigned.
 843    #[track_caller]
 844    pub fn global<G: Global>(&self) -> &G {
 845        self.globals_by_type
 846            .get(&TypeId::of::<G>())
 847            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 848            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 849            .unwrap()
 850    }
 851
 852    /// Access the global of the given type if a value has been assigned.
 853    pub fn try_global<G: Global>(&self) -> Option<&G> {
 854        self.globals_by_type
 855            .get(&TypeId::of::<G>())
 856            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
 857    }
 858
 859    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
 860    #[track_caller]
 861    pub fn global_mut<G: Global>(&mut self) -> &mut G {
 862        let global_type = TypeId::of::<G>();
 863        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 864        self.globals_by_type
 865            .get_mut(&global_type)
 866            .and_then(|any_state| any_state.downcast_mut::<G>())
 867            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
 868            .unwrap()
 869    }
 870
 871    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
 872    /// yet been assigned.
 873    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
 874        let global_type = TypeId::of::<G>();
 875        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 876        self.globals_by_type
 877            .entry(global_type)
 878            .or_insert_with(|| Box::<G>::default())
 879            .downcast_mut::<G>()
 880            .unwrap()
 881    }
 882
 883    /// Sets the value of the global of the given type.
 884    pub fn set_global<G: Global>(&mut self, global: G) {
 885        let global_type = TypeId::of::<G>();
 886        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 887        self.globals_by_type.insert(global_type, Box::new(global));
 888    }
 889
 890    /// Clear all stored globals. Does not notify global observers.
 891    #[cfg(any(test, feature = "test-support"))]
 892    pub fn clear_globals(&mut self) {
 893        self.globals_by_type.drain();
 894    }
 895
 896    /// Remove the global of the given type from the app context. Does not notify global observers.
 897    pub fn remove_global<G: Global>(&mut self) -> G {
 898        let global_type = TypeId::of::<G>();
 899        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 900        *self
 901            .globals_by_type
 902            .remove(&global_type)
 903            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
 904            .downcast()
 905            .unwrap()
 906    }
 907
 908    /// Register a callback to be invoked when a global of the given type is updated.
 909    pub fn observe_global<G: Global>(
 910        &mut self,
 911        mut f: impl FnMut(&mut Self) + 'static,
 912    ) -> Subscription {
 913        let (subscription, activate) = self.global_observers.insert(
 914            TypeId::of::<G>(),
 915            Box::new(move |cx| {
 916                f(cx);
 917                true
 918            }),
 919        );
 920        self.defer(move |_| activate());
 921        subscription
 922    }
 923
 924    /// Move the global of the given type to the stack.
 925    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
 926        GlobalLease::new(
 927            self.globals_by_type
 928                .remove(&TypeId::of::<G>())
 929                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
 930                .unwrap(),
 931        )
 932    }
 933
 934    /// Restore the global of the given type after it is moved to the stack.
 935    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
 936        let global_type = TypeId::of::<G>();
 937        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 938        self.globals_by_type.insert(global_type, lease.global);
 939    }
 940
 941    pub(crate) fn new_view_observer(
 942        &mut self,
 943        key: TypeId,
 944        value: NewViewListener,
 945    ) -> Subscription {
 946        let (subscription, activate) = self.new_view_observers.insert(key, value);
 947        activate();
 948        subscription
 949    }
 950    /// Arrange for the given function to be invoked whenever a view of the specified type is created.
 951    /// The function will be passed a mutable reference to the view along with an appropriate context.
 952    pub fn observe_new_views<V: 'static>(
 953        &mut self,
 954        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
 955    ) -> Subscription {
 956        self.new_view_observer(
 957            TypeId::of::<V>(),
 958            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
 959                any_view
 960                    .downcast::<V>()
 961                    .unwrap()
 962                    .update(cx, |view_state, cx| {
 963                        on_new(view_state, cx);
 964                    })
 965            }),
 966        )
 967    }
 968
 969    /// Observe the release of a model or view. The callback is invoked after the model or view
 970    /// has no more strong references but before it has been dropped.
 971    pub fn observe_release<E, T>(
 972        &mut self,
 973        handle: &E,
 974        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
 975    ) -> Subscription
 976    where
 977        E: Entity<T>,
 978        T: 'static,
 979    {
 980        let (subscription, activate) = self.release_listeners.insert(
 981            handle.entity_id(),
 982            Box::new(move |entity, cx| {
 983                let entity = entity.downcast_mut().expect("invalid entity type");
 984                on_release(entity, cx)
 985            }),
 986        );
 987        activate();
 988        subscription
 989    }
 990
 991    /// Register a callback to be invoked when a keystroke is received by the application
 992    /// in any window. Note that this fires after all other action and event mechanisms have resolved
 993    /// and that this API will not be invoked if the event's propagation is stopped.
 994    pub fn observe_keystrokes(
 995        &mut self,
 996        f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
 997    ) -> Subscription {
 998        fn inner(
 999            keystroke_observers: &mut SubscriberSet<(), KeystrokeObserver>,
1000            handler: KeystrokeObserver,
1001        ) -> Subscription {
1002            let (subscription, activate) = keystroke_observers.insert((), handler);
1003            activate();
1004            subscription
1005        }
1006        inner(&mut self.keystroke_observers, Box::new(f))
1007    }
1008
1009    /// Register key bindings.
1010    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1011        self.keymap.borrow_mut().add_bindings(bindings);
1012        self.pending_effects.push_back(Effect::Refresh);
1013    }
1014
1015    /// Clear all key bindings in the app.
1016    pub fn clear_key_bindings(&mut self) {
1017        self.keymap.borrow_mut().clear();
1018        self.pending_effects.push_back(Effect::Refresh);
1019    }
1020
1021    /// Register a global listener for actions invoked via the keyboard.
1022    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1023        self.global_action_listeners
1024            .entry(TypeId::of::<A>())
1025            .or_default()
1026            .push(Rc::new(move |action, phase, cx| {
1027                if phase == DispatchPhase::Bubble {
1028                    let action = action.downcast_ref().unwrap();
1029                    listener(action, cx)
1030                }
1031            }));
1032    }
1033
1034    /// Event handlers propagate events by default. Call this method to stop dispatching to
1035    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1036    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1037    /// calling this method before effects are flushed.
1038    pub fn stop_propagation(&mut self) {
1039        self.propagate_event = false;
1040    }
1041
1042    /// Action handlers stop propagation by default during the bubble phase of action dispatch
1043    /// dispatching to action handlers higher in the element tree. This is the opposite of
1044    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1045    /// this method before effects are flushed.
1046    pub fn propagate(&mut self) {
1047        self.propagate_event = true;
1048    }
1049
1050    /// Build an action from some arbitrary data, typically a keymap entry.
1051    pub fn build_action(
1052        &self,
1053        name: &str,
1054        data: Option<serde_json::Value>,
1055    ) -> Result<Box<dyn Action>> {
1056        self.actions.build_action(name, data)
1057    }
1058
1059    /// Get a list of all action names that have been registered.
1060    /// in the application. Note that registration only allows for
1061    /// actions to be built dynamically, and is unrelated to binding
1062    /// actions in the element tree.
1063    pub fn all_action_names(&self) -> &[SharedString] {
1064        self.actions.all_action_names()
1065    }
1066
1067    /// Register a callback to be invoked when the application is about to quit.
1068    /// It is not possible to cancel the quit event at this point.
1069    pub fn on_app_quit<Fut>(
1070        &mut self,
1071        mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1072    ) -> Subscription
1073    where
1074        Fut: 'static + Future<Output = ()>,
1075    {
1076        let (subscription, activate) = self.quit_observers.insert(
1077            (),
1078            Box::new(move |cx| {
1079                let future = on_quit(cx);
1080                future.boxed_local()
1081            }),
1082        );
1083        activate();
1084        subscription
1085    }
1086
1087    pub(crate) fn clear_pending_keystrokes(&mut self) {
1088        for window in self.windows() {
1089            window
1090                .update(self, |_, cx| {
1091                    cx.window
1092                        .rendered_frame
1093                        .dispatch_tree
1094                        .clear_pending_keystrokes();
1095                    cx.window
1096                        .next_frame
1097                        .dispatch_tree
1098                        .clear_pending_keystrokes();
1099                })
1100                .ok();
1101        }
1102    }
1103
1104    /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1105    /// the bindings in the element tree, and any global action listeners.
1106    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1107        let mut action_available = false;
1108        if let Some(window) = self.active_window() {
1109            if let Ok(window_action_available) =
1110                window.update(self, |_, cx| cx.is_action_available(action))
1111            {
1112                action_available = window_action_available;
1113            }
1114        }
1115
1116        action_available
1117            || self
1118                .global_action_listeners
1119                .contains_key(&action.as_any().type_id())
1120    }
1121
1122    /// Sets the menu bar for this application. This will replace any existing menu bar.
1123    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1124        self.platform.set_menus(menus, &self.keymap.borrow());
1125    }
1126
1127    /// Adds given path to list of recent paths for the application.
1128    /// The list is usually shown on the application icon's context menu in the dock,
1129    /// and allows to open the recent files via that context menu.
1130    pub fn add_recent_documents(&mut self, paths: &[PathBuf]) {
1131        self.platform.add_recent_documents(paths);
1132    }
1133
1134    /// Clears the list of recent paths from the application.
1135    pub fn clear_recent_documents(&mut self) {
1136        self.platform.clear_recent_documents();
1137    }
1138    /// Dispatch an action to the currently active window or global action handler
1139    /// See [action::Action] for more information on how actions work
1140    pub fn dispatch_action(&mut self, action: &dyn Action) {
1141        if let Some(active_window) = self.active_window() {
1142            active_window
1143                .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1144                .log_err();
1145        } else {
1146            self.dispatch_global_action(action);
1147        }
1148    }
1149
1150    fn dispatch_global_action(&mut self, action: &dyn Action) {
1151        self.propagate_event = true;
1152
1153        if let Some(mut global_listeners) = self
1154            .global_action_listeners
1155            .remove(&action.as_any().type_id())
1156        {
1157            for listener in &global_listeners {
1158                listener(action.as_any(), DispatchPhase::Capture, self);
1159                if !self.propagate_event {
1160                    break;
1161                }
1162            }
1163
1164            global_listeners.extend(
1165                self.global_action_listeners
1166                    .remove(&action.as_any().type_id())
1167                    .unwrap_or_default(),
1168            );
1169
1170            self.global_action_listeners
1171                .insert(action.as_any().type_id(), global_listeners);
1172        }
1173
1174        if self.propagate_event {
1175            if let Some(mut global_listeners) = self
1176                .global_action_listeners
1177                .remove(&action.as_any().type_id())
1178            {
1179                for listener in global_listeners.iter().rev() {
1180                    listener(action.as_any(), DispatchPhase::Bubble, self);
1181                    if !self.propagate_event {
1182                        break;
1183                    }
1184                }
1185
1186                global_listeners.extend(
1187                    self.global_action_listeners
1188                        .remove(&action.as_any().type_id())
1189                        .unwrap_or_default(),
1190                );
1191
1192                self.global_action_listeners
1193                    .insert(action.as_any().type_id(), global_listeners);
1194            }
1195        }
1196    }
1197
1198    /// Is there currently something being dragged?
1199    pub fn has_active_drag(&self) -> bool {
1200        self.active_drag.is_some()
1201    }
1202
1203    /// Set the prompt renderer for GPUI. This will replace the default or platform specific
1204    /// prompts with this custom implementation.
1205    pub fn set_prompt_builder(
1206        &mut self,
1207        renderer: impl Fn(
1208                PromptLevel,
1209                &str,
1210                Option<&str>,
1211                &[&str],
1212                PromptHandle,
1213                &mut WindowContext,
1214            ) -> RenderablePromptHandle
1215            + 'static,
1216    ) {
1217        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)))
1218    }
1219}
1220
1221impl Context for AppContext {
1222    type Result<T> = T;
1223
1224    /// Build an entity that is owned by the application. The given function will be invoked with
1225    /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1226    /// which can be used to access the entity in a context.
1227    fn new_model<T: 'static>(
1228        &mut self,
1229        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1230    ) -> Model<T> {
1231        self.update(|cx| {
1232            let slot = cx.entities.reserve();
1233            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1234            cx.entities.insert(slot, entity)
1235        })
1236    }
1237
1238    /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1239    /// entity along with a `ModelContext` for the entity.
1240    fn update_model<T: 'static, R>(
1241        &mut self,
1242        model: &Model<T>,
1243        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1244    ) -> R {
1245        self.update(|cx| {
1246            let mut entity = cx.entities.lease(model);
1247            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1248            cx.entities.end_lease(entity);
1249            result
1250        })
1251    }
1252
1253    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1254    where
1255        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1256    {
1257        self.update(|cx| {
1258            let mut window = cx
1259                .windows
1260                .get_mut(handle.id)
1261                .ok_or_else(|| anyhow!("window not found"))?
1262                .take()
1263                .ok_or_else(|| anyhow!("window not found"))?;
1264
1265            let root_view = window.root_view.clone().unwrap();
1266            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1267
1268            if window.removed {
1269                cx.window_handles.remove(&handle.id);
1270                cx.windows.remove(handle.id);
1271            } else {
1272                cx.windows
1273                    .get_mut(handle.id)
1274                    .ok_or_else(|| anyhow!("window not found"))?
1275                    .replace(window);
1276            }
1277
1278            Ok(result)
1279        })
1280    }
1281
1282    fn read_model<T, R>(
1283        &self,
1284        handle: &Model<T>,
1285        read: impl FnOnce(&T, &AppContext) -> R,
1286    ) -> Self::Result<R>
1287    where
1288        T: 'static,
1289    {
1290        let entity = self.entities.read(handle);
1291        read(entity, self)
1292    }
1293
1294    fn read_window<T, R>(
1295        &self,
1296        window: &WindowHandle<T>,
1297        read: impl FnOnce(View<T>, &AppContext) -> R,
1298    ) -> Result<R>
1299    where
1300        T: 'static,
1301    {
1302        let window = self
1303            .windows
1304            .get(window.id)
1305            .ok_or_else(|| anyhow!("window not found"))?
1306            .as_ref()
1307            .unwrap();
1308
1309        let root_view = window.root_view.clone().unwrap();
1310        let view = root_view
1311            .downcast::<T>()
1312            .map_err(|_| anyhow!("root view's type has changed"))?;
1313
1314        Ok(read(view, self))
1315    }
1316}
1317
1318/// These effects are processed at the end of each application update cycle.
1319pub(crate) enum Effect {
1320    Notify {
1321        emitter: EntityId,
1322    },
1323    Emit {
1324        emitter: EntityId,
1325        event_type: TypeId,
1326        event: Box<dyn Any>,
1327    },
1328    Refresh,
1329    NotifyGlobalObservers {
1330        global_type: TypeId,
1331    },
1332    Defer {
1333        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1334    },
1335}
1336
1337/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1338pub(crate) struct GlobalLease<G: Global> {
1339    global: Box<dyn Any>,
1340    global_type: PhantomData<G>,
1341}
1342
1343impl<G: Global> GlobalLease<G> {
1344    fn new(global: Box<dyn Any>) -> Self {
1345        GlobalLease {
1346            global,
1347            global_type: PhantomData,
1348        }
1349    }
1350}
1351
1352impl<G: Global> Deref for GlobalLease<G> {
1353    type Target = G;
1354
1355    fn deref(&self) -> &Self::Target {
1356        self.global.downcast_ref().unwrap()
1357    }
1358}
1359
1360impl<G: Global> DerefMut for GlobalLease<G> {
1361    fn deref_mut(&mut self) -> &mut Self::Target {
1362        self.global.downcast_mut().unwrap()
1363    }
1364}
1365
1366/// Contains state associated with an active drag operation, started by dragging an element
1367/// within the window or by dragging into the app from the underlying platform.
1368pub struct AnyDrag {
1369    /// The view used to render this drag
1370    pub view: AnyView,
1371
1372    /// The value of the dragged item, to be dropped
1373    pub value: Box<dyn Any>,
1374
1375    /// This is used to render the dragged item in the same place
1376    /// on the original element that the drag was initiated
1377    pub cursor_offset: Point<Pixels>,
1378}
1379
1380/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1381/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1382#[derive(Clone)]
1383pub struct AnyTooltip {
1384    /// The view used to display the tooltip
1385    pub view: AnyView,
1386
1387    /// The offset from the cursor to use, relative to the parent view
1388    pub cursor_offset: Point<Pixels>,
1389}
1390
1391/// A keystroke event, and potentially the associated action
1392#[derive(Debug)]
1393pub struct KeystrokeEvent {
1394    /// The keystroke that occurred
1395    pub keystroke: Keystroke,
1396
1397    /// The action that was resolved for the keystroke, if any
1398    pub action: Option<Box<dyn Action>>,
1399}