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