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.push_effect(Effect::NotifyGlobalObservers { global_type });
 847        *self
 848            .globals_by_type
 849            .remove(&global_type)
 850            .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
 851            .downcast()
 852            .unwrap()
 853    }
 854
 855    /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
 856    /// your closure with mutable access to the `AppContext` and the global simultaneously.
 857    pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
 858        self.update(|cx| {
 859            let mut global = cx.lease_global::<G>();
 860            let result = f(&mut global, cx);
 861            cx.end_global_lease(global);
 862            result
 863        })
 864    }
 865
 866    /// Register a callback to be invoked when a global of the given type is updated.
 867    pub fn observe_global<G: 'static>(
 868        &mut self,
 869        mut f: impl FnMut(&mut Self) + 'static,
 870    ) -> Subscription {
 871        let (subscription, activate) = self.global_observers.insert(
 872            TypeId::of::<G>(),
 873            Box::new(move |cx| {
 874                f(cx);
 875                true
 876            }),
 877        );
 878        self.defer(move |_| activate());
 879        subscription
 880    }
 881
 882    /// Move the global of the given type to the stack.
 883    pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
 884        GlobalLease::new(
 885            self.globals_by_type
 886                .remove(&TypeId::of::<G>())
 887                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
 888                .unwrap(),
 889        )
 890    }
 891
 892    /// Restore the global of the given type after it is moved to the stack.
 893    pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
 894        let global_type = TypeId::of::<G>();
 895        self.push_effect(Effect::NotifyGlobalObservers { global_type });
 896        self.globals_by_type.insert(global_type, lease.global);
 897    }
 898
 899    pub fn observe_new_views<V: 'static>(
 900        &mut self,
 901        on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
 902    ) -> Subscription {
 903        let (subscription, activate) = self.new_view_observers.insert(
 904            TypeId::of::<V>(),
 905            Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
 906                any_view
 907                    .downcast::<V>()
 908                    .unwrap()
 909                    .update(cx, |view_state, cx| {
 910                        on_new(view_state, cx);
 911                    })
 912            }),
 913        );
 914        activate();
 915        subscription
 916    }
 917
 918    pub fn observe_release<E, T>(
 919        &mut self,
 920        handle: &E,
 921        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
 922    ) -> Subscription
 923    where
 924        E: Entity<T>,
 925        T: 'static,
 926    {
 927        let (subscription, activate) = self.release_listeners.insert(
 928            handle.entity_id(),
 929            Box::new(move |entity, cx| {
 930                let entity = entity.downcast_mut().expect("invalid entity type");
 931                on_release(entity, cx)
 932            }),
 933        );
 934        activate();
 935        subscription
 936    }
 937
 938    pub fn observe_keystrokes(
 939        &mut self,
 940        f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
 941    ) -> Subscription {
 942        let (subscription, activate) = self.keystroke_observers.insert((), Box::new(f));
 943        activate();
 944        subscription
 945    }
 946
 947    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
 948        self.text_style_stack.push(text_style);
 949    }
 950
 951    pub(crate) fn pop_text_style(&mut self) {
 952        self.text_style_stack.pop();
 953    }
 954
 955    /// Register key bindings.
 956    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
 957        self.keymap.lock().add_bindings(bindings);
 958        self.pending_effects.push_back(Effect::Refresh);
 959    }
 960
 961    pub fn clear_key_bindings(&mut self) {
 962        self.keymap.lock().clear();
 963        self.pending_effects.push_back(Effect::Refresh);
 964    }
 965
 966    /// Register a global listener for actions invoked via the keyboard.
 967    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
 968        self.global_action_listeners
 969            .entry(TypeId::of::<A>())
 970            .or_default()
 971            .push(Rc::new(move |action, phase, cx| {
 972                if phase == DispatchPhase::Bubble {
 973                    let action = action.downcast_ref().unwrap();
 974                    listener(action, cx)
 975                }
 976            }));
 977    }
 978
 979    /// Event handlers propagate events by default. Call this method to stop dispatching to
 980    /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
 981    /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
 982    /// calling this method before effects are flushed.
 983    pub fn stop_propagation(&mut self) {
 984        self.propagate_event = false;
 985    }
 986
 987    /// Action handlers stop propagation by default during the bubble phase of action dispatch
 988    /// dispatching to action handlers higher in the element tree. This is the opposite of
 989    /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
 990    /// this method before effects are flushed.
 991    pub fn propagate(&mut self) {
 992        self.propagate_event = true;
 993    }
 994
 995    pub fn build_action(
 996        &self,
 997        name: &str,
 998        data: Option<serde_json::Value>,
 999    ) -> Result<Box<dyn Action>> {
1000        self.actions.build_action(name, data)
1001    }
1002
1003    pub fn all_action_names(&self) -> &[SharedString] {
1004        self.actions.all_action_names()
1005    }
1006
1007    pub fn on_app_quit<Fut>(
1008        &mut self,
1009        mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1010    ) -> Subscription
1011    where
1012        Fut: 'static + Future<Output = ()>,
1013    {
1014        let (subscription, activate) = self.quit_observers.insert(
1015            (),
1016            Box::new(move |cx| {
1017                let future = on_quit(cx);
1018                future.boxed_local()
1019            }),
1020        );
1021        activate();
1022        subscription
1023    }
1024
1025    pub(crate) fn clear_pending_keystrokes(&mut self) {
1026        for window in self.windows() {
1027            window
1028                .update(self, |_, cx| {
1029                    cx.window
1030                        .rendered_frame
1031                        .dispatch_tree
1032                        .clear_pending_keystrokes();
1033                    cx.window
1034                        .next_frame
1035                        .dispatch_tree
1036                        .clear_pending_keystrokes();
1037                })
1038                .ok();
1039        }
1040    }
1041
1042    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1043        if let Some(window) = self.active_window() {
1044            if let Ok(window_action_available) =
1045                window.update(self, |_, cx| cx.is_action_available(action))
1046            {
1047                return window_action_available;
1048            }
1049        }
1050
1051        self.global_action_listeners
1052            .contains_key(&action.as_any().type_id())
1053    }
1054
1055    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1056        self.platform.set_menus(menus, &self.keymap.lock());
1057    }
1058
1059    pub fn dispatch_action(&mut self, action: &dyn Action) {
1060        if let Some(active_window) = self.active_window() {
1061            active_window
1062                .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1063                .log_err();
1064        } else {
1065            self.propagate_event = true;
1066
1067            if let Some(mut global_listeners) = self
1068                .global_action_listeners
1069                .remove(&action.as_any().type_id())
1070            {
1071                for listener in &global_listeners {
1072                    listener(action.as_any(), DispatchPhase::Capture, self);
1073                    if !self.propagate_event {
1074                        break;
1075                    }
1076                }
1077
1078                global_listeners.extend(
1079                    self.global_action_listeners
1080                        .remove(&action.as_any().type_id())
1081                        .unwrap_or_default(),
1082                );
1083
1084                self.global_action_listeners
1085                    .insert(action.as_any().type_id(), global_listeners);
1086            }
1087
1088            if self.propagate_event {
1089                if let Some(mut global_listeners) = self
1090                    .global_action_listeners
1091                    .remove(&action.as_any().type_id())
1092                {
1093                    for listener in global_listeners.iter().rev() {
1094                        listener(action.as_any(), DispatchPhase::Bubble, self);
1095                        if !self.propagate_event {
1096                            break;
1097                        }
1098                    }
1099
1100                    global_listeners.extend(
1101                        self.global_action_listeners
1102                            .remove(&action.as_any().type_id())
1103                            .unwrap_or_default(),
1104                    );
1105
1106                    self.global_action_listeners
1107                        .insert(action.as_any().type_id(), global_listeners);
1108                }
1109            }
1110        }
1111    }
1112
1113    pub fn has_active_drag(&self) -> bool {
1114        self.active_drag.is_some()
1115    }
1116}
1117
1118impl Context for AppContext {
1119    type Result<T> = T;
1120
1121    /// Build an entity that is owned by the application. The given function will be invoked with
1122    /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
1123    /// which can be used to access the entity in a context.
1124    fn new_model<T: 'static>(
1125        &mut self,
1126        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1127    ) -> Model<T> {
1128        self.update(|cx| {
1129            let slot = cx.entities.reserve();
1130            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1131            cx.entities.insert(slot, entity)
1132        })
1133    }
1134
1135    /// Update the entity referenced by the given model. The function is passed a mutable reference to the
1136    /// entity along with a `ModelContext` for the entity.
1137    fn update_model<T: 'static, R>(
1138        &mut self,
1139        model: &Model<T>,
1140        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1141    ) -> R {
1142        self.update(|cx| {
1143            let mut entity = cx.entities.lease(model);
1144            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1145            cx.entities.end_lease(entity);
1146            result
1147        })
1148    }
1149
1150    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1151    where
1152        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1153    {
1154        self.update(|cx| {
1155            let mut window = cx
1156                .windows
1157                .get_mut(handle.id)
1158                .ok_or_else(|| anyhow!("window not found"))?
1159                .take()
1160                .unwrap();
1161
1162            let root_view = window.root_view.clone().unwrap();
1163            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1164
1165            if window.removed {
1166                cx.windows.remove(handle.id);
1167            } else {
1168                cx.windows
1169                    .get_mut(handle.id)
1170                    .ok_or_else(|| anyhow!("window not found"))?
1171                    .replace(window);
1172            }
1173
1174            Ok(result)
1175        })
1176    }
1177
1178    fn read_model<T, R>(
1179        &self,
1180        handle: &Model<T>,
1181        read: impl FnOnce(&T, &AppContext) -> R,
1182    ) -> Self::Result<R>
1183    where
1184        T: 'static,
1185    {
1186        let entity = self.entities.read(handle);
1187        read(entity, self)
1188    }
1189
1190    fn read_window<T, R>(
1191        &self,
1192        window: &WindowHandle<T>,
1193        read: impl FnOnce(View<T>, &AppContext) -> R,
1194    ) -> Result<R>
1195    where
1196        T: 'static,
1197    {
1198        let window = self
1199            .windows
1200            .get(window.id)
1201            .ok_or_else(|| anyhow!("window not found"))?
1202            .as_ref()
1203            .unwrap();
1204
1205        let root_view = window.root_view.clone().unwrap();
1206        let view = root_view
1207            .downcast::<T>()
1208            .map_err(|_| anyhow!("root view's type has changed"))?;
1209
1210        Ok(read(view, self))
1211    }
1212}
1213
1214/// These effects are processed at the end of each application update cycle.
1215pub(crate) enum Effect {
1216    Notify {
1217        emitter: EntityId,
1218    },
1219    Emit {
1220        emitter: EntityId,
1221        event_type: TypeId,
1222        event: Box<dyn Any>,
1223    },
1224    Refresh,
1225    NotifyGlobalObservers {
1226        global_type: TypeId,
1227    },
1228    Defer {
1229        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1230    },
1231}
1232
1233/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1234pub(crate) struct GlobalLease<G: 'static> {
1235    global: Box<dyn Any>,
1236    global_type: PhantomData<G>,
1237}
1238
1239impl<G: 'static> GlobalLease<G> {
1240    fn new(global: Box<dyn Any>) -> Self {
1241        GlobalLease {
1242            global,
1243            global_type: PhantomData,
1244        }
1245    }
1246}
1247
1248impl<G: 'static> Deref for GlobalLease<G> {
1249    type Target = G;
1250
1251    fn deref(&self) -> &Self::Target {
1252        self.global.downcast_ref().unwrap()
1253    }
1254}
1255
1256impl<G: 'static> DerefMut for GlobalLease<G> {
1257    fn deref_mut(&mut self) -> &mut Self::Target {
1258        self.global.downcast_mut().unwrap()
1259    }
1260}
1261
1262/// Contains state associated with an active drag operation, started by dragging an element
1263/// within the window or by dragging into the app from the underlying platform.
1264pub struct AnyDrag {
1265    pub view: AnyView,
1266    pub value: Box<dyn Any>,
1267    pub cursor_offset: Point<Pixels>,
1268}
1269
1270/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1271/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1272#[derive(Clone)]
1273pub struct AnyTooltip {
1274    pub view: AnyView,
1275    pub cursor_offset: Point<Pixels>,
1276}
1277
1278#[derive(Debug)]
1279pub struct KeystrokeEvent {
1280    pub keystroke: Keystroke,
1281    pub action: Option<Box<dyn Action>>,
1282}