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