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