app.rs

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