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