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