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