app.rs

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