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