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